01: package org.kohsuke.rngom.util;
02:
03: import java.text.MessageFormat;
04: import java.util.MissingResourceException;
05: import java.util.ResourceBundle;
06:
07: /**
08: * Localizes messages.
09: */
10: public class Localizer {
11: private final Class cls;
12: private ResourceBundle bundle;
13: /**
14: * If non-null, any resources that weren't found in this localizer
15: * will be delegated to the parent.
16: */
17: private final Localizer parent;
18:
19: public Localizer(Class cls) {
20: this (null, cls);
21: }
22:
23: public Localizer(Localizer parent, Class cls) {
24: this .parent = parent;
25: this .cls = cls;
26: }
27:
28: private String getString(String key) {
29: try {
30: return getBundle().getString(key);
31: } catch (MissingResourceException e) {
32: // delegation
33: if (parent != null)
34: return parent.getString(key);
35: else
36: throw e;
37: }
38: }
39:
40: public String message(String key) {
41: return MessageFormat.format(getString(key), new Object[] {});
42: }
43:
44: public String message(String key, Object arg) {
45: return MessageFormat.format(getString(key),
46: new Object[] { arg });
47: }
48:
49: public String message(String key, Object arg1, Object arg2) {
50: return MessageFormat.format(getString(key), new Object[] {
51: arg1, arg2 });
52: }
53:
54: public String message(String key, Object[] args) {
55: return MessageFormat.format(getString(key), args);
56: }
57:
58: private ResourceBundle getBundle() {
59: if (bundle == null) {
60: String s = cls.getName();
61: int i = s.lastIndexOf('.');
62: if (i > 0)
63: s = s.substring(0, i + 1);
64: else
65: s = "";
66: bundle = ResourceBundle.getBundle(s + "Messages");
67: }
68: return bundle;
69: }
70: }
|