LanguageUtil.java
3.34 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
/*
* Decompiled with CFR 0_118.
*/
package com.day.cq.commons;
import com.day.cq.commons.Language;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LanguageUtil {
public static final Set<String> ISO_LANGUAGES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(Locale.getISOLanguages())));
public static final Set<String> ISO_COUNTRIES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(Locale.getISOCountries())));
public static final String PSEUDO_LANGUAGE = "zz";
private static final Pattern SINGLE_CODE = Pattern.compile("/([a-zA-Z]{2})(/|$)");
private static final Pattern LANGUAGE_AND_COUNTRY = Pattern.compile("/([a-zA-Z]{2,3}[_-][a-zA-Z]{2,3})(/|$)");
public static Locale getLocale(String code) {
Language l = LanguageUtil.getLanguage(code);
return l == null ? null : l.getLocale();
}
public static Language getLanguage(String code) {
if (code == null) {
return null;
}
code = code.replaceAll("-", "_");
String lang = null;
String country = "";
if (code.length() == 2) {
lang = code.toLowerCase();
} else if (code.length() == 5 && code.charAt(2) == '_') {
lang = code.substring(0, 2);
country = code.substring(3);
}
if (lang == null) {
return null;
}
if (!"zz".equalsIgnoreCase(lang) && !ISO_LANGUAGES.contains(lang.toLowerCase())) {
return null;
}
if (country.length() > 0 && !ISO_COUNTRIES.contains(country.toUpperCase()) && !"zz".equalsIgnoreCase(lang)) {
return null;
}
return new Language(lang, country);
}
public static String getLanguageRoot(String path) {
if (path == null || path.length() == 0 || path.equals("/")) {
return null;
}
String root = null;
String strPrefix = "";
String strTempPath = path;
Matcher m = LANGUAGE_AND_COUNTRY.matcher(path);
while (m.find() && root == null) {
String code = m.group(1);
if (LanguageUtil.getLocale(code) != null) {
root = strPrefix + strTempPath.substring(0, m.end(1));
}
String strTempPrefix = strTempPath.substring(0, m.end(1));
strPrefix = strPrefix + strTempPrefix;
strTempPath = strTempPath.substring(strTempPrefix.length());
m = LANGUAGE_AND_COUNTRY.matcher(strTempPath);
}
if (root == null) {
int pos = -1;
String last = null;
Matcher sm = SINGLE_CODE.matcher(path);
while (sm.find()) {
String code = sm.group(1);
if (last == null && LanguageUtil.getLocale(code) != null) {
last = code;
pos = sm.end(1);
} else if (last != null && LanguageUtil.getLocale(code + "_" + last) != null) {
pos = sm.end(1);
break;
}
sm.region(sm.end(1), path.length());
}
if (pos > 0) {
root = path.substring(0, pos);
}
}
return root;
}
}