#
Junjie
1 天以前 2d2fd991826837d7189cc488aee6f309a6f5e216
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package com.zy.common.i18n;
 
import com.core.common.Cools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.context.i18n.LocaleContextHolder;
 
import java.io.File;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
 
@Service
public class I18nMessageService {
 
    private static final String MESSAGE_BUNDLE = "messages";
    private static final String LEGACY_BUNDLE = "legacy";
 
    private final Map<String, CacheEntry> cache = new ConcurrentHashMap<>();
 
    @Autowired
    private I18nProperties properties;
 
    public Locale getCurrentLocale() {
        Locale locale = LocaleContextHolder.getLocale();
        return locale == null ? I18nLocaleUtils.defaultLocale(properties) : locale;
    }
 
    public Locale resolveLocale(String requested) {
        return I18nLocaleUtils.resolveLocale(requested, properties);
    }
 
    public String getDefaultLocaleTag() {
        return properties.getDefaultLocale();
    }
 
    public List<String> getSupportedLocaleTags() {
        return properties.getSupportedLocales();
    }
 
    public String getMessage(String key, Object... args) {
        return getMessage(key, getCurrentLocale(), args);
    }
 
    public String getMessage(String key, Locale locale, Object... args) {
        if (Cools.isEmpty(key)) {
            return "";
        }
        Locale resolvedLocale = locale == null ? I18nLocaleUtils.defaultLocale(properties) : locale;
        String value = mergedBundle(resolvedLocale, MESSAGE_BUNDLE).get(key);
        if (value == null && !I18nLocaleUtils.isDefaultLocale(resolvedLocale, properties)) {
            value = mergedBundle(I18nLocaleUtils.defaultLocale(properties), MESSAGE_BUNDLE).get(key);
        }
        if (value == null) {
            return key;
        }
        return args == null || args.length == 0 ? value : MessageFormat.format(value, args);
    }
 
    public boolean hasMessage(String key, Locale locale) {
        return mergedBundle(locale == null ? I18nLocaleUtils.defaultLocale(properties) : locale, MESSAGE_BUNDLE).containsKey(key);
    }
 
    public Map<String, String> getMessages(Locale locale) {
        return new LinkedHashMap<>(mergedBundle(locale, MESSAGE_BUNDLE));
    }
 
    public Map<String, String> getLegacyMessages(Locale locale) {
        return new LinkedHashMap<>(mergedBundle(locale, LEGACY_BUNDLE));
    }
 
    public String translateLegacy(String text) {
        return translateLegacy(text, getCurrentLocale());
    }
 
    public String translateLegacy(String text, Locale locale) {
        if (Cools.isEmpty(text)) {
            return text;
        }
        Locale resolvedLocale = locale == null ? I18nLocaleUtils.defaultLocale(properties) : locale;
        if (I18nLocaleUtils.isDefaultLocale(resolvedLocale, properties)) {
            return text;
        }
        Map<String, String> bundle = mergedBundle(resolvedLocale, LEGACY_BUNDLE);
        String direct = directTranslate(text, bundle);
        if (!text.equals(direct)) {
            return direct;
        }
        String regex = regexTranslate(text, bundle);
        if (!text.equals(regex)) {
            return regex;
        }
        return fragmentTranslate(text, bundle);
    }
 
    public String resolveResourceText(String fallbackName, String code, Long id) {
        Locale locale = getCurrentLocale();
        String key = resourceKey(code, id);
        if (hasMessage(key, locale)) {
            return getMessage(key, locale);
        }
        if (!I18nLocaleUtils.isDefaultLocale(locale, properties)) {
            String humanized = I18nLocaleUtils.humanizeCode(code);
            if (!Cools.isEmpty(humanized)) {
                return humanized;
            }
        }
        return fallbackName;
    }
 
    public String resolvePermissionText(String fallbackName, String action, Long id) {
        Locale locale = getCurrentLocale();
        String key = permissionKey(action, id);
        if (hasMessage(key, locale)) {
            return getMessage(key, locale);
        }
        if (!I18nLocaleUtils.isDefaultLocale(locale, properties)) {
            String humanized = I18nLocaleUtils.humanizeCode(action);
            if (!Cools.isEmpty(humanized)) {
                return humanized;
            }
        }
        return fallbackName;
    }
 
    public String resourceKey(String code, Long id) {
        return "resource." + normalizeKey(code, id, "resource");
    }
 
    public String permissionKey(String action, Long id) {
        return "permission." + normalizeKey(action, id, "permission");
    }
 
    private Map<String, String> mergedBundle(Locale locale, String bundleName) {
        Locale resolvedLocale = locale == null ? I18nLocaleUtils.defaultLocale(properties) : locale;
        LinkedHashMap<String, String> merged = new LinkedHashMap<>();
        Locale defaultLocale = I18nLocaleUtils.defaultLocale(properties);
        merged.putAll(loadBundle(defaultLocale, bundleName));
        if (!I18nLocaleUtils.toTag(defaultLocale).equalsIgnoreCase(I18nLocaleUtils.toTag(resolvedLocale))) {
            merged.putAll(loadBundle(resolvedLocale, bundleName));
        }
        return merged;
    }
 
    private Map<String, String> loadBundle(Locale locale, String bundleName) {
        String localeTag = I18nLocaleUtils.toTag(locale);
        String cacheKey = localeTag + ":" + bundleName;
        CacheEntry cacheEntry = cache.get(cacheKey);
        File externalFile = externalBundle(localeTag, bundleName);
        long refreshMillis = Math.max(1, properties.getRefreshSeconds()) * 1000L;
        long externalLastModified = externalFile.exists() ? externalFile.lastModified() : -1L;
        if (cacheEntry != null
                && (System.currentTimeMillis() - cacheEntry.loadedAt) < refreshMillis
                && cacheEntry.externalLastModified == externalLastModified) {
            return cacheEntry.values;
        }
        synchronized (cache.computeIfAbsent(cacheKey, key -> new CacheEntry())) {
            CacheEntry latest = cache.get(cacheKey);
            if (latest != null
                    && (System.currentTimeMillis() - latest.loadedAt) < refreshMillis
                    && latest.externalLastModified == externalLastModified) {
                return latest.values;
            }
            LinkedHashMap<String, String> values = new LinkedHashMap<>();
            readClasspathBundle(values, localeTag, bundleName);
            readExternalBundle(values, externalFile);
            CacheEntry updated = new CacheEntry();
            updated.values = values;
            updated.loadedAt = System.currentTimeMillis();
            updated.externalLastModified = externalLastModified;
            cache.put(cacheKey, updated);
            return updated.values;
        }
    }
 
    private void readClasspathBundle(Map<String, String> values, String localeTag, String bundleName) {
        ClassPathResource resource = new ClassPathResource("i18n/" + localeTag + "/" + bundleName + ".properties");
        if (!resource.exists()) {
            return;
        }
        try (InputStream inputStream = resource.getInputStream()) {
            loadProperties(values, inputStream);
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load classpath i18n bundle: " + resource.getPath(), ex);
        }
    }
 
    private void readExternalBundle(Map<String, String> values, File file) {
        if (!file.exists() || !file.isFile()) {
            return;
        }
        try (InputStream inputStream = new FileInputStream(file)) {
            loadProperties(values, inputStream);
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load external i18n bundle: " + file.getAbsolutePath(), ex);
        }
    }
 
    private void loadProperties(Map<String, String> values, InputStream inputStream) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                parsePropertyLine(values, line);
            }
        }
    }
 
    private void parsePropertyLine(Map<String, String> values, String line) {
        if (line == null) {
            return;
        }
        String trimmed = line.trim();
        if (trimmed.isEmpty() || trimmed.startsWith("#") || trimmed.startsWith("!")) {
            return;
        }
        int separatorIndex = findSeparator(line);
        String rawKey = separatorIndex >= 0 ? line.substring(0, separatorIndex) : line;
        String rawValue = separatorIndex >= 0 ? line.substring(separatorIndex + 1) : "";
        while (!rawValue.isEmpty() && Character.isWhitespace(rawValue.charAt(0))) {
            rawValue = rawValue.substring(1);
        }
        String key = unescapePropertyToken(rawKey);
        String value = unescapePropertyToken(rawValue);
        if (!key.isEmpty()) {
            values.put(key, value);
        }
    }
 
    private int findSeparator(String line) {
        boolean escaping = false;
        for (int i = 0; i < line.length(); i++) {
            char ch = line.charAt(i);
            if (escaping) {
                escaping = false;
                continue;
            }
            if (ch == '\\') {
                escaping = true;
                continue;
            }
            if (ch == '=' || ch == ':') {
                return i;
            }
        }
        return -1;
    }
 
    private String unescapePropertyToken(String text) {
        StringBuilder builder = new StringBuilder(text.length());
        boolean escaping = false;
        for (int i = 0; i < text.length(); i++) {
            char ch = text.charAt(i);
            if (!escaping) {
                if (ch == '\\') {
                    escaping = true;
                } else {
                    builder.append(ch);
                }
                continue;
            }
            switch (ch) {
                case 't':
                    builder.append('\t');
                    break;
                case 'r':
                    builder.append('\r');
                    break;
                case 'n':
                    builder.append('\n');
                    break;
                case 'f':
                    builder.append('\f');
                    break;
                case 'u':
                    if (i + 4 < text.length()) {
                        String hex = text.substring(i + 1, i + 5);
                        try {
                            builder.append((char) Integer.parseInt(hex, 16));
                            i += 4;
                            break;
                        } catch (NumberFormatException ex) {
                            builder.append('u');
                            break;
                        }
                    }
                    builder.append('u');
                    break;
                default:
                    builder.append(ch);
                    break;
            }
            escaping = false;
        }
        if (escaping) {
            builder.append('\\');
        }
        return builder.toString();
    }
 
    private File externalBundle(String localeTag, String bundleName) {
        return new File(properties.getPackPath(), localeTag + File.separator + bundleName + ".properties");
    }
 
    private String directTranslate(String text, Map<String, String> bundle) {
        String trimmed = text.trim();
        String translated = bundle.get(trimmed);
        if (translated == null) {
            return text;
        }
        return preserveOuterWhitespace(text, translated);
    }
 
    private String regexTranslate(String text, Map<String, String> bundle) {
        String trimmed = text == null ? "" : text.trim();
        for (Map.Entry<String, String> entry : bundle.entrySet()) {
            String key = entry.getKey();
            if (Cools.isEmpty(key) || !key.startsWith("regex:")) {
                continue;
            }
            String patternText = key.substring("regex:".length());
            if (Cools.isEmpty(patternText)) {
                continue;
            }
            try {
                Pattern pattern = Pattern.compile(patternText);
                if (!trimmed.isEmpty()) {
                    Matcher trimmedMatcher = pattern.matcher(trimmed);
                    if (trimmedMatcher.matches()) {
                        return preserveOuterWhitespace(text, trimmedMatcher.replaceAll(entry.getValue()));
                    }
                }
                Matcher matcher = pattern.matcher(text);
                if (matcher.find()) {
                    return matcher.replaceAll(entry.getValue());
                }
            } catch (PatternSyntaxException ex) {
                // Ignore invalid regex entries so a bad pack does not break all translations.
            }
        }
        return text;
    }
 
    private String fragmentTranslate(String text, Map<String, String> bundle) {
        List<Map.Entry<String, String>> entries = new ArrayList<>(bundle.entrySet());
        entries.sort((left, right) -> Integer.compare(right.getKey().length(), left.getKey().length()));
        String result = text;
        for (Map.Entry<String, String> entry : entries) {
            if (Cools.isEmpty(entry.getKey())
                    || entry.getKey().length() < 2
                    || entry.getKey().startsWith("regex:")
                    || entry.getKey().equals(entry.getValue())) {
                continue;
            }
            result = result.replace(entry.getKey(), entry.getValue());
        }
        return result;
    }
 
    private String preserveOuterWhitespace(String original, String translated) {
        String trimmed = original == null ? "" : original.trim();
        if (trimmed.isEmpty()) {
            return translated;
        }
        int leading = original.indexOf(trimmed);
        int trailing = original.length() - leading - trimmed.length();
        StringBuilder builder = new StringBuilder();
        if (leading > 0) {
            builder.append(original, 0, leading);
        }
        builder.append(translated);
        if (trailing > 0) {
            builder.append(original.substring(original.length() - trailing));
        }
        return builder.toString();
    }
 
    private String normalizeKey(String raw, Long id, String prefix) {
        if (Cools.isEmpty(raw)) {
            return prefix + "." + (id == null ? "unknown" : id);
        }
        String normalized = raw.replaceAll("\\.html", "");
        normalized = normalized.replaceAll("[^A-Za-z0-9]+", ".");
        normalized = normalized.replaceAll("\\.+", ".");
        normalized = normalized.replaceAll("^\\.|\\.$", "");
        if (Cools.isEmpty(normalized)) {
            return prefix + "." + (id == null ? "unknown" : id);
        }
        return normalized;
    }
 
    private static class CacheEntry {
        private Map<String, String> values = new LinkedHashMap<>();
        private long loadedAt;
        private long externalLastModified = -1L;
    }
}