1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.aikiit.fotorenamer.util;
17
18 import com.google.common.base.Strings;
19 import lombok.AccessLevel;
20 import lombok.NoArgsConstructor;
21 import org.apache.logging.log4j.LogManager;
22 import org.apache.logging.log4j.Logger;
23
24 import java.text.MessageFormat;
25 import java.util.Locale;
26 import java.util.MissingResourceException;
27 import java.util.ResourceBundle;
28
29
30
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 = "fotorenamer";
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("Your system emits the following l10n-properties: language={}, country={}", 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
85 public static Locale getLocale() {
86 if (LOCALE == null) {
87 LOG.warn("Returning fallback Locale for Germany - please make sure you've configured your environment correctly via system properties 'user.country'/'user.language'.");
88 return FALLBACK_LOCALE;
89 }
90 return LOCALE;
91 }
92
93
94
95
96
97 public static String getLanguage() {
98 return getLocale().getLanguage();
99 }
100
101
102
103
104
105
106
107
108
109 public static String getBundleString(final String key) {
110 LOG.debug("Retrieving key {}", key);
111 try {
112 return BUNDLE.getString(key);
113 } catch (MissingResourceException mre) {
114 LOG.error("Retrieving unknown key {}. Please fix your property files.", key);
115 return key;
116 }
117
118
119
120
121
122
123
124
125
126
127 }
128
129
130
131
132
133
134
135
136
137
138
139
140
141 public static String getParameterizedBundleString(final String key, final Object... parameters) {
142 LOG.debug("Applying {} parameters to {}", (parameters == null) ? null : parameters
143 .length, key);
144 FORMAT.applyPattern(getBundleString(key));
145 return FORMAT.format(parameters);
146 }
147
148
149
150
151
152
153
154 public static String removeCrLf(final String input) {
155 if (!Strings.isNullOrEmpty(input)) {
156 return input.replaceAll("[\r\n]", "");
157 }
158 return input;
159 }
160 }