1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package ch.qos.cal10n;
24
25 import java.text.MessageFormat;
26 import java.util.Locale;
27 import java.util.Map;
28 import java.util.concurrent.ConcurrentHashMap;
29
30 import ch.qos.cal10n.util.AnnotationExtractor;
31 import ch.qos.cal10n.util.CAL10NPropertyResourceBundle;
32 import ch.qos.cal10n.util.PropertyResourceBundleFinder;
33
34
35
36
37
38
39
40
41
42
43 public class MessageConveyor implements IMessageConveyor {
44
45 final Locale locale;
46
47 final Map<String, CAL10NPropertyResourceBundle> cache = new ConcurrentHashMap<String, CAL10NPropertyResourceBundle>();
48
49
50
51
52
53
54 public MessageConveyor(Locale locale) {
55 this.locale = locale;
56 }
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 public <E extends Enum<?>> String getMessage(E key, Object... args) throws MessageConveyorException {
72
73 String declararingClassName = key.getDeclaringClass().getName();
74 CAL10NPropertyResourceBundle rb = cache.get(declararingClassName);
75 if (rb == null || rb.hasChanged()) {
76 rb = lookup(key);
77 cache.put(declararingClassName, rb);
78 }
79
80 String keyAsStr = key.toString();
81 String value = rb.getString(keyAsStr);
82 if (value == null) {
83 return "No key found for " + keyAsStr;
84 } else {
85 if (args == null || args.length == 0) {
86 return value;
87 } else {
88 return MessageFormat.format(value, args);
89 }
90 }
91 }
92
93 private <E extends Enum<?>> CAL10NPropertyResourceBundle lookup(E key) throws MessageConveyorException {
94 String baseName = AnnotationExtractor.getBaseName(key.getDeclaringClass());
95 if (baseName == null) {
96 throw new MessageConveyorException(
97 "Missing @BaseName annotation in enum type ["
98 + key.getClass().getName() + "]. See also "
99 + Cal10nConstants.MISSING_BN_ANNOTATION_URL);
100 }
101 CAL10NPropertyResourceBundle rb = PropertyResourceBundleFinder.getBundle(this.getClass()
102 .getClassLoader(), baseName, locale);
103
104 if(rb == null) {
105 throw new MessageConveyorException("Failed to locate resource bundle [" + baseName
106 + "] for locale [" + locale + "] for enum type [" + key.getDeclaringClass().getName()
107 + "]");
108 }
109 return rb;
110 }
111
112 public String getMessage(MessageParameterObj mpo) throws MessageConveyorException {
113 if (mpo == null) {
114 throw new IllegalArgumentException(
115 "MessageParameterObj argumument cannot be null");
116 }
117 return getMessage(mpo.getKey(), mpo.getArgs());
118 }
119
120 }