Skip to content

Commit 0576682

Browse files
committed
i18n - Caching resolved Messages keys for a given Locale, avoiding to rely on a complicated ResourceBundle resolution when retrieving Messages keys
1 parent 2afa00b commit 0576682

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

restx-i18n/src/main/java/restx/i18n/DefaultMessages.java

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package restx.i18n;
22

33
import com.google.common.base.Optional;
4+
import com.google.common.cache.CacheBuilder;
5+
import com.google.common.cache.CacheLoader;
6+
import com.google.common.cache.LoadingCache;
47
import com.google.common.collect.Ordering;
58
import com.google.common.io.Resources;
69
import com.samskivert.mustache.Mustache;
@@ -31,6 +34,13 @@
3134
public class DefaultMessages extends AbstractMessages implements Messages {
3235
private final String baseName;
3336
private final Charset charset;
37+
private final LoadingCache<Locale, Iterable<String>> cachedKeysByLocale = CacheBuilder.newBuilder().build(new CacheLoader<Locale, Iterable<String>>() {
38+
@Override
39+
public Iterable<String> load(Locale locale) throws Exception {
40+
Optional<ResourceBundle> bundle = getBundle(locale);
41+
return bundle.isPresent() ? Ordering.natural().sortedCopy(bundle.get().keySet()) : Collections.<String>emptySet();
42+
}
43+
});
3444

3545
public DefaultMessages(String baseName) {
3646
this(baseName, StandardCharsets.UTF_8);
@@ -56,8 +66,11 @@ public String getMessage(String key, MessageParams params, Locale locale) {
5666

5767
@Override
5868
public Iterable<String> keys(Locale locale) {
59-
Optional<ResourceBundle> bundle = getBundle(locale);
60-
return bundle.isPresent() ? Ordering.natural().sortedCopy(bundle.get().keySet()) : Collections.<String>emptySet();
69+
return cachedKeysByLocale.getUnchecked(locale);
70+
}
71+
72+
protected void invalidateCachedKeysFor(Locale locale) {
73+
cachedKeysByLocale.invalidate(locale);
6174
}
6275

6376
@Override

restx-i18n/src/main/java/restx/i18n/DefaultMutableMessages.java

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public MutableMessages setMessageTemplate(String key, String messageTemplate, Lo
3232
}
3333
MutablePropertyResourceBundle bundle = (MutablePropertyResourceBundle) b.get();
3434
bundle.setMessageTemplate(key, messageTemplate);
35+
invalidateCachedKeysFor(locale);
3536
return this;
3637
}
3738

0 commit comments

Comments
 (0)