-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathI18n.java
More file actions
94 lines (77 loc) · 2.54 KB
/
I18n.java
File metadata and controls
94 lines (77 loc) · 2.54 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package graphql.i18n;
import graphql.Internal;
import graphql.VisibleForTesting;
import java.text.MessageFormat;
import java.util.List;
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 {
Parsing,
Scalars,
Validation,
Execution,
General;
private final String baseName;
BundleType() {
this.baseName = "i18n." + this.name();
}
}
private final ResourceBundle resourceBundle;
private final Locale locale;
@VisibleForTesting
protected I18n(BundleType bundleType, Locale locale) {
assertNotNull(bundleType);
assertNotNull(locale);
this.locale = 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 Locale getLocale() {
return locale;
}
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
*/
public String msg(String msgKey, Object... msgArgs) {
return msgImpl(msgKey, msgArgs);
}
/**
* 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
*/
public String msg(String msgKey, List<Object> msgArgs) {
return msgImpl(msgKey, msgArgs.toArray());
}
private String msgImpl(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);
}
return new MessageFormat(msgPattern).format(msgArgs);
}
}