-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathPluralFormHelper.java
More file actions
299 lines (248 loc) · 9.09 KB
/
PluralFormHelper.java
File metadata and controls
299 lines (248 loc) · 9.09 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
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
package com.ilib;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PluralFormHelper {
public static final File root = new File("locale");
public static final File pluralsJSON = new File("plurals.json");
protected static final Pattern commandParser = Pattern.compile("(\\w*)(\\(([^(]+?)\\))");
protected static final String VALUE_REPLACER = "(?<=[^\\w\\\\])n(?=(,|\\)))";
private static final String TRUE_VALUE = "true";
private static final String OTHER_PLURAL = "other";
private static final String COMMA = ",";
private static final String ENCODING = "utf-8";
private static final String EMPTY = "";
public static final class PluralRule {
static final String OPENED_BRACKET = "(";
static final String CLOSED_BRACKET = ")";
String functionName = null;
PluralRule[] inheritors;
public PluralRule() {
functionName = EMPTY;
}
public PluralRule(String name) {
this.functionName = name;
}
public void addAncestors(int number) {
inheritors = new PluralRule[number];
for (int i = 0; i < inheritors.length; ++i)
inheritors[i] = new PluralRule();
}
public boolean hasAncestors() {
return (inheritors != null) ? (inheritors.length > 0) : false;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(functionName);
if (hasAncestors()) {
if (!functionName.isEmpty()) builder.append(OPENED_BRACKET);
for (int i = 0; i < inheritors.length; i++) {
builder.append(inheritors[i].toString());
if (i < inheritors.length - 1) builder.append(COMMA);
}
if (!functionName.isEmpty()) builder.append(CLOSED_BRACKET);
}
return builder.toString();
}
}
protected Map<String,String> forms = null;
public PluralFormHelper(String localeSpec) {
// load the plural forms from the same jar file as this code
Locale locale = Locale.forLanguageTag(localeSpec);
String language = locale.getLanguage();
String path = root + "/" + language + "/" + pluralsJSON;
ClassLoader cl = this.getClass().getClassLoader();
forms = getPluralForms(cl.getResourceAsStream(path));
}
public Map<String,String> getForms() {
return forms;
}
public <K> String getPluralKey(int value) {
String resultPlural = OTHER_PLURAL;
StringBuilder builder = new StringBuilder();
if ( !forms.isEmpty() ) {
for (String callItem : forms.keySet()) {
builder.setLength(0);
builder.append(forms.get(callItem).toString().replaceAll(VALUE_REPLACER, String.valueOf(value)));
matchPluralForm(builder);
if ( (builder.toString()).equals(TRUE_VALUE) ) {
return callItem;
}
}
}
return resultPlural;
}
/**
*
* @param file
* @return a map containing the plural forms encoded in the file
*/
public static Map<String, String> getPluralForms(InputStream is) {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(is, ENCODING)); ) {
String currentLine = null;
while ( (currentLine = reader.readLine()) != null ) {
builder.append(currentLine);
}
} catch (Exception e) {
System.err.println("Could not load plurals file.");
return null;
}
Map<String, String> pluralForms = new HashMap<>();
if ( builder.length() > 0 ) {
try {
JSONObject jsonObject = new JSONObject(builder.toString());
Iterator<String> it = jsonObject.keys();
String key;
while ( it.hasNext() ) {
key = it.next();
PluralRule call = new PluralRule();
scanJsonParts(jsonObject.get(key), call);
pluralForms.put(key, call.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return pluralForms;
}
/**
*
* @param value
* @param plurals
* @return the key for a value in the plurals map
*/
public static <K> String getPluralKey(int value, Map<String, K> plurals) {
String resultPlural = OTHER_PLURAL;
StringBuilder builder = new StringBuilder();
if ( !plurals.isEmpty() ) {
for (String callItem : plurals.keySet()) {
builder.setLength(0);
builder.append(plurals.get(callItem).toString().replaceAll(VALUE_REPLACER, String.valueOf(value)));
matchPluralForm(builder);
if ( (builder.toString()).equals(TRUE_VALUE) ) {
return callItem;
}
}
}
return resultPlural;
}
protected static void scanJsonParts(Object jsonPart, PluralRule call) throws JSONException {
if (jsonPart != null && !jsonPart.toString().isEmpty()) {
if (jsonPart instanceof JSONObject) {
if (((JSONObject)jsonPart).length() > 0) {
JSONObject castToJSONObject = ((JSONObject)jsonPart);
call.addAncestors(castToJSONObject.length());
Iterator<String> it = ((JSONObject)jsonPart).keys();
String key;
int k = 0;
while ( it.hasNext() ) {
key = it.next();
Object jsonValue = null;
try {
jsonValue = castToJSONObject.get(key);
call.inheritors[k].functionName = key;
scanJsonParts(jsonValue, call.inheritors[k]);
} catch (JSONException e) {
e.printStackTrace();
}
++k;
}
}
}
else if (jsonPart instanceof JSONArray) {
if (((JSONArray)jsonPart).length() > 0) {
call.addAncestors(((JSONArray)jsonPart).length());
for (int i = 0; i < ((JSONArray)jsonPart).length(); i++) {
try {
Object item = ((JSONArray)jsonPart).get(i);
if (item instanceof JSONObject || item instanceof JSONArray) {
scanJsonParts(item, call.inheritors[i]);
}
else {
if (item instanceof Integer || item instanceof String) {
call.inheritors[i].functionName = item.toString();
} else
System.err.println(" wrong item: " + item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
else {
throw new JSONException("Undefined json item found: " + jsonPart);
}
}
}
protected static void matchPluralForm(StringBuilder builder) {
String command = builder.toString();
Matcher matcher = commandParser.matcher(command);
while (matcher.find()) {
final String replacement = matcher.group(0);
String result = invokeFunction(matcher.group(1), matcher.group(3).split(COMMA));
command = command.replace(replacement, result);
matcher = commandParser.matcher(command);
}
builder.setLength(0);
builder.append(command);
}
protected static String invokeFunction(String methodName, String[] params) {
String result = EMPTY;
switch (methodName) {
case "and":
if (params.length == 2)
result = String.valueOf( Boolean.valueOf(params[0]) && Boolean.valueOf(params[1]) );
break;
case "or":
if (params.length == 2)
result = String.valueOf( Boolean.valueOf(params[0]) || Boolean.valueOf(params[1]) );
break;
case "eq":
if (params.length == 2)
result = String.valueOf( Integer.valueOf(params[0]) == Integer.valueOf(params[1]) );
break;
case "isnot":
if (params.length == 2)
result = String.valueOf( Integer.valueOf(params[0]) != Integer.valueOf(params[1]) );
break;
case "inrange":
if (params.length == 3)
result = String.valueOf( inrange(Integer.valueOf(params[0]), Integer.valueOf(params[1]), Integer.valueOf(params[2])) );
break;
case "notin":
if (params.length == 3)
result = String.valueOf( notin(Integer.valueOf(params[0]), Integer.valueOf(params[1]), Integer.valueOf(params[2])) );
break;
case "mod":
if (params.length == 2)
result = String.valueOf( Integer.valueOf(params[0]) % Integer.valueOf(params[1]) );
break;
case "within":
if (params.length == 3)
result = String.valueOf( inrange(Integer.valueOf(params[0]), Integer.valueOf(params[1]), Integer.valueOf(params[2])) );
break;
default:
break;
}
return result;
}
protected static boolean inrange(int actual, int leftRange, int rightRange) {
return (actual >= leftRange && actual <= rightRange);
}
protected static boolean notin(int actual, int leftRange, int rightRange) {
return !inrange(actual, leftRange, rightRange);
}
}