Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
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 0576682
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
17 changes: 15 additions & 2 deletions restx-i18n/src/main/java/restx/i18n/DefaultMessages.java
@@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand Down
Expand Up @@ -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;
}

Expand Down

0 comments on commit 0576682

Please sign in to comment.