Skip to content

Commit

Permalink
Use separately defined Key as composite key in StaticMessageSource
Browse files Browse the repository at this point in the history
  • Loading branch information
stsypanov committed Feb 21, 2019
1 parent 25d7f09 commit 68eb1d6
Showing 1 changed file with 29 additions and 7 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -36,21 +36,20 @@
*/
public class StaticMessageSource extends AbstractMessageSource {

/** Map from 'code + locale' keys to message Strings. */
private final Map<String, String> messages = new HashMap<>();
private final Map<Key, String> messages = new HashMap<>();

private final Map<String, MessageFormat> cachedMessageFormats = new HashMap<>();
private final Map<Key, MessageFormat> cachedMessageFormats = new HashMap<>();


@Override
protected String resolveCodeWithoutArguments(String code, Locale locale) {
return this.messages.get(code + '_' + locale.toString());
return this.messages.get(new Key(code, locale));
}

@Override
@Nullable
protected MessageFormat resolveCode(String code, Locale locale) {
String key = code + '_' + locale.toString();
Key key = new Key(code, locale);
String msg = this.messages.get(key);
if (msg == null) {
return null;
Expand All @@ -75,7 +74,7 @@ public void addMessage(String code, Locale locale, String msg) {
Assert.notNull(code, "Code must not be null");
Assert.notNull(locale, "Locale must not be null");
Assert.notNull(msg, "Message must not be null");
this.messages.put(code + '_' + locale.toString(), msg);
this.messages.put(new Key(code, locale), msg);
if (logger.isDebugEnabled()) {
logger.debug("Added message [" + msg + "] for code [" + code + "] and Locale [" + locale + "]");
}
Expand All @@ -98,4 +97,27 @@ public String toString() {
return getClass().getName() + ": " + this.messages;
}

private static final class Key {
private final String code;
private final Locale locale;

private Key(String code, Locale locale) {
this.code = code;
this.locale = locale;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Key key = (Key) o;
return code.equals(key.code) && locale.equals(key.locale);
}

@Override
public int hashCode() {
return 31 * code.hashCode() + locale.hashCode();
}
}

}

0 comments on commit 68eb1d6

Please sign in to comment.