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.AnnotationExtractorViaEnumClass;
31 import ch.qos.cal10n.util.CAL10NBundle;
32 import ch.qos.cal10n.util.CAL10NBundleFinderByClassloader;
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, CAL10NBundle> cache = new ConcurrentHashMap<String, CAL10NBundle>();
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 public <E extends Enum<?>> String getMessage(E key, Object... args)
70 throws MessageConveyorException {
71
72 Class<? extends Enum<?>> declaringClass = key.getDeclaringClass();
73
74 String declaringClassName = declaringClass.getName();
75 CAL10NBundle rb = cache.get(declaringClassName);
76 if (rb == null || rb.hasChanged()) {
77 rb = lookupResourceBundleByEnumClassAndLocale(declaringClass);
78 cache.put(declaringClassName, rb);
79 }
80
81 String keyAsStr = key.toString();
82 String value = rb.getString(keyAsStr);
83 if (value == null) {
84 return "No key found for " + keyAsStr;
85 } else {
86 if (args == null || args.length == 0) {
87 return value;
88 } else {
89 return MessageFormat.format(value, args);
90 }
91 }
92 }
93
94 private <E extends Enum<?>> CAL10NBundle lookupResourceBundleByEnumClassAndLocale(Class<E> declaringClass)
95 throws MessageConveyorException {
96
97 AnnotationExtractorViaEnumClass annotationExtractor = new AnnotationExtractorViaEnumClass(declaringClass);
98
99 String baseName = annotationExtractor.getBaseName();
100 if (baseName == null) {
101 throw new MessageConveyorException(
102 "Missing @BaseName annotation in enum type ["
103 + declaringClass.getName() + "]. See also "
104 + CAL10NConstants.MISSING_BN_ANNOTATION_URL);
105 }
106
107 String charset = annotationExtractor.extractCharset(locale);
108
109
110
111 CAL10NBundleFinderByClassloader cal10NBundleFinderByClassloader = new CAL10NBundleFinderByClassloader(declaringClass.getClassLoader());
112 CAL10NBundle rb = cal10NBundleFinderByClassloader.getBundle(
113 baseName, locale, charset);
114
115 if (rb == null) {
116 throw new MessageConveyorException(
117 "Failed to locate resource bundle [" + baseName
118 + "] for locale [" + locale + "] for enum type ["
119 + declaringClass.getName() + "]");
120 }
121 return rb;
122 }
123
124 public String getMessage(MessageParameterObj mpo)
125 throws MessageConveyorException {
126 if (mpo == null) {
127 throw new IllegalArgumentException(
128 "MessageParameterObj argumument cannot be null");
129 }
130 return getMessage(mpo.getKey(), mpo.getArgs());
131 }
132 }