Permalink
Browse files

i18n - Caching resolved Messages keys for a given Locale, avoiding to…

… rely on a complicated ResourceBundle resolution when retrieving Messages keys
  • Loading branch information...
fcamblor committed Nov 21, 2016
1 parent 2afa00b commit 0576682d98ff0842c8310f793018e19e08d7d166
@@ -1,6 +1,9 @@
package restx.i18n;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Ordering;
import com.google.common.io.Resources;
import com.samskivert.mustache.Mustache;
@@ -31,6 +34,13 @@
public class DefaultMessages extends AbstractMessages implements Messages {
private final String baseName;
private final Charset charset;
private final LoadingCache<Locale, Iterable<String>> cachedKeysByLocale = CacheBuilder.newBuilder().build(new CacheLoader<Locale, Iterable<String>>() {
@Override
public Iterable<String> load(Locale locale) throws Exception {
Optional<ResourceBundle> bundle = getBundle(locale);
return bundle.isPresent() ? Ordering.natural().sortedCopy(bundle.get().keySet()) : Collections.<String>emptySet();
}
});
public DefaultMessages(String baseName) {
this(baseName, StandardCharsets.UTF_8);
@@ -56,8 +66,11 @@ public String getMessage(String key, MessageParams params, Locale locale) {
@Override
public Iterable<String> keys(Locale locale) {
Optional<ResourceBundle> bundle = getBundle(locale);
return bundle.isPresent() ? Ordering.natural().sortedCopy(bundle.get().keySet()) : Collections.<String>emptySet();
return cachedKeysByLocale.getUnchecked(locale);
}
protected void invalidateCachedKeysFor(Locale locale) {
cachedKeysByLocale.invalidate(locale);
}
@Override
@@ -32,6 +32,7 @@ public MutableMessages setMessageTemplate(String key, String messageTemplate, Lo
}
MutablePropertyResourceBundle bundle = (MutablePropertyResourceBundle) b.get();
bundle.setMessageTemplate(key, messageTemplate);
invalidateCachedKeysFor(locale);
return this;
}

0 comments on commit 0576682

Please sign in to comment.