1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package de.aikiit.spamprotector.util;
19
20 import com.google.common.base.Strings;
21 import lombok.AccessLevel;
22 import lombok.NoArgsConstructor;
23 import org.apache.logging.log4j.LogManager;
24 import org.apache.logging.log4j.Logger;
25
26 import java.text.MessageFormat;
27 import java.util.Arrays;
28 import java.util.Locale;
29 import java.util.MissingResourceException;
30 import java.util.ResourceBundle;
31
32
33
34
35
36 @NoArgsConstructor(access = AccessLevel.PRIVATE)
37 public final class LocalizationHelper {
38
39
40
41
42 private static final Logger LOG =
43 LogManager.getLogger(LocalizationHelper.class);
44
45
46
47
48 private static final String BASE_NAME = "spamprotector";
49 private static final Locale FALLBACK_LOCALE = Locale.GERMANY;
50
51 private static ResourceBundle BUNDLE;
52 private static Locale LOCALE;
53 private static MessageFormat FORMAT;
54
55 static {
56 setLocale();
57 }
58
59
60
61
62 public static void setLocale() {
63 String userLanguage = System.getProperty("user.language");
64 String userCountry = System.getProperty("user.country");
65
66 LOG.info(String.format("Your system emits the following l10n-properties: language=%s, country=%s", userLanguage, userCountry));
67
68 if (Strings.isNullOrEmpty(userLanguage) || Strings.isNullOrEmpty(userCountry)) {
69 LOCALE = FALLBACK_LOCALE;
70 LOG.info("Falling back to locale " + LOCALE);
71 } else {
72 LOCALE = new Locale(userLanguage, userCountry);
73 LOG.info("Setting locale to " + LOCALE);
74 }
75
76 BUNDLE = ResourceBundle.getBundle(BASE_NAME, LOCALE);
77 FORMAT = new MessageFormat("");
78 FORMAT.setLocale(LOCALE);
79 }
80
81
82
83
84 public static Locale getLocale() {
85 if (LOCALE == null) {
86 LOG.warn("Returning fallback Locale for Germany - please make sure you've configured your environment correctly via system properties 'user.country'/'user.language'.");
87 return FALLBACK_LOCALE;
88 }
89 return LOCALE;
90 }
91
92
93
94
95 public static String getLanguage() {
96 return getLocale().getLanguage();
97 }
98
99
100
101
102
103
104
105
106
107 public static String getBundleString(final String key) {
108 LOG.debug("Retrieving key " + key);
109 try {
110 return BUNDLE.getString(key);
111 } catch (MissingResourceException mre) {
112 LOG.error("Retrieving unknown key " + key + ". Please fix your property files.");
113 return key;
114 }
115 }
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130 public static String getParameterizedBundleString(final String key, final Object... parameters) {
131 LOG.debug("Applying " + ((parameters == null) ? null : Arrays.toString(parameters)) + " parameters to " + key);
132 FORMAT.applyPattern(getBundleString(key));
133 return FORMAT.format(parameters);
134 }
135
136 }