-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathI18n.java
More file actions
72 lines (58 loc) · 1.99 KB
/
Copy pathI18n.java
File metadata and controls
72 lines (58 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package graphql.i18n;
import graphql.Internal;
import graphql.VisibleForTesting;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import static graphql.Assert.assertNotNull;
import static graphql.Assert.assertShouldNeverHappen;
@Internal
public class I18n {
/**
* This enum is a type safe way to control what resource bundle to load from
*/
public enum BundleType {
Validation,
Execution,
General;
private final String baseName;
BundleType() {
this.baseName = "i18n." + this.name();
}
}
private final ResourceBundle resourceBundle;
@VisibleForTesting
protected I18n(BundleType bundleType, Locale locale) {
assertNotNull(bundleType);
assertNotNull(locale);
// load the resource bundle with this classes class loader - to help avoid confusion in complicated worlds
// like OSGI
this.resourceBundle = ResourceBundle.getBundle(bundleType.baseName, locale, I18n.class.getClassLoader());
}
public ResourceBundle getResourceBundle() {
return resourceBundle;
}
public static I18n i18n(BundleType bundleType, Locale locale) {
return new I18n(bundleType, locale);
}
/**
* Creates an I18N message using the key and arguments
*
* @param msgKey the key in the underlying message bundle
* @param msgArgs the message arguments
*
* @return the formatted I18N message
*/
@SuppressWarnings("UnnecessaryLocalVariable")
public String msg(String msgKey, Object... msgArgs) {
String msgPattern = null;
try {
msgPattern = resourceBundle.getString(msgKey);
} catch (MissingResourceException e) {
assertShouldNeverHappen("There must be a resource bundle key called %s", msgKey);
}
String formattedMsg = new MessageFormat(msgPattern).format(msgArgs);
return formattedMsg;
}
}