XliffDictImporter.java
20.2 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
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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* javax.jcr.Item
* javax.jcr.Node
* javax.jcr.NodeIterator
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Workspace
* javax.jcr.query.Query
* javax.jcr.query.QueryManager
* javax.jcr.query.QueryResult
* org.apache.jackrabbit.commons.JcrUtils
* org.apache.jackrabbit.commons.json.JsonHandler
* org.apache.jackrabbit.commons.json.JsonParser
* org.apache.jackrabbit.util.Text
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceMetadata
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.api.resource.ValueMap
* org.apache.sling.commons.json.JSONException
* org.apache.sling.commons.json.JSONObject
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.granite.i18n.impl.dict;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.jackrabbit.commons.json.JsonHandler;
import org.apache.jackrabbit.commons.json.JsonParser;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
public class XliffDictImporter
extends DefaultHandler {
private final Logger log = LoggerFactory.getLogger(XliffDictImporter.class);
private static final String LANGUAGE_MIXIN = "mix:language";
private static final String SLING_MESSAGE_MIXIN = "sling:Message";
private static final String SLING_KEY_PROP = "sling:key";
private static final String SLING_MESSAGE_PROP = "sling:message";
private TransUnit transUnit = null;
private State state = State.OTHER;
private final String path;
private final Session session;
private Map<String, Map<String, String>> storedTranslations = new HashMap<String, Map<String, String>>();
private Map<String, Map<String, String>> storedLowerCaseNodeNames = new HashMap<String, Map<String, String>>();
private int treeDepth;
private boolean overwrite;
private JSONObject jsonObject = null;
private Resource jsonFileResource = null;
private ResourceResolver resourceResolver = null;
public XliffDictImporter(Session session, String path, int treeDepth, boolean overwrite, ResourceResolver resourceResolver) {
this.session = session;
this.path = path;
this.treeDepth = treeDepth;
this.overwrite = overwrite;
this.resourceResolver = resourceResolver;
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private void checkAndCreateJsonObject(String targetLanguage) {
block16 : {
String lang = targetLanguage.replace("_", "-");
String[] langSplit = lang.split("-");
if (langSplit.length == 2 && langSplit[0].equals(langSplit[1])) {
lang = langSplit[0];
}
String languageNodeJsonPath = this.path + "/" + lang + ".json";
try {
if (!this.session.nodeExists(languageNodeJsonPath)) break block16;
this.jsonFileResource = this.resourceResolver.getResource(languageNodeJsonPath);
ValueMap properties = (ValueMap)this.jsonFileResource.adaptTo(ValueMap.class);
this.jsonObject = new JSONObject();
if (!((String)properties.get("jcr:mixinTypes", String.class)).equalsIgnoreCase("mix:language") || !properties.containsKey((Object)"jcr:language")) break block16;
JsonParser parser = new JsonParser(new JsonHandler(){
private String key;
public void key(String key) throws IOException {
this.key = key;
}
public void value(String value) throws IOException {
try {
XliffDictImporter.this.jsonObject.put(this.key, (Object)value);
}
catch (JSONException e) {
XliffDictImporter.this.log.error("error occurred while reading " + this.key + ":" + value + " pair");
}
}
public void object() throws IOException {
}
public void endObject() throws IOException {
}
public void array() throws IOException {
}
public void endArray() throws IOException {
}
public void value(boolean value) throws IOException {
}
public void value(long value) throws IOException {
}
public void value(double value) throws IOException {
}
});
InputStream stream = (InputStream)this.jsonFileResource.adaptTo(InputStream.class);
if (stream != null) {
String encoding = "utf-8";
ResourceMetadata metadata = this.jsonFileResource.getResourceMetadata();
if (metadata != null && metadata.getCharacterEncoding() != null) {
encoding = metadata.getCharacterEncoding();
}
try {
parser.parse(stream, encoding);
}
catch (IOException ioe) {
this.log.error("error occurred while reading json obejct from path : " + languageNodeJsonPath + "'" + ioe);
}
finally {
try {
stream.close();
}
catch (IOException ioe) {
this.log.error("error occurred while reading json obejct from path : " + languageNodeJsonPath + "'" + ioe);
}
}
}
this.log.error("error occurred while reading json obejct from path : " + languageNodeJsonPath);
}
catch (RepositoryException e) {
this.log.error("could not find json file at to '" + languageNodeJsonPath + "'", (Throwable)e);
}
}
}
private void updateJsonObject(TransUnit transUnit) {
String key = XliffDictImporter.getKey(transUnit.source, transUnit.comment);
try {
if (this.jsonObject.has(key)) {
String existingTranslation = (String)this.jsonObject.get(key);
if (transUnit.target.equals(existingTranslation)) {
this.log.info(transUnit.language + ": skipping repeated translation '" + transUnit.source + "' => '" + transUnit.target + "'" + XliffDictImporter.getCommentForLog(transUnit.comment) + "'");
return;
}
if (this.overwrite) {
this.log.info(transUnit.language + ": overwriting old translation for '" + transUnit.source + "', " + "existing translation: '" + existingTranslation + "', " + "new translation: '" + transUnit.target + "'" + XliffDictImporter.getCommentForLog(transUnit.comment) + "'");
} else {
this.log.info(transUnit.language + ": keeping old translation for '" + transUnit.source + "', " + "existing translation: '" + existingTranslation + "', " + "new translation: '" + transUnit.target + "'" + XliffDictImporter.getCommentForLog(transUnit.comment) + "'");
return;
}
}
this.jsonObject.put(key, (Object)transUnit.target);
}
catch (JSONException e) {
this.log.error("could not update the json object with key " + key + "'" + (Object)e);
}
}
private Map<String, String> getStoredTranslations(Node languageNode) throws RepositoryException {
String path = languageNode.getPath();
if (!this.storedTranslations.containsKey(path)) {
HashMap<String, String> translations = new HashMap<String, String>();
this.storedTranslations.put(path, translations);
String query = "/jcr:root" + languageNode.getPath() + "//*[@sling:message]";
QueryManager qm = languageNode.getSession().getWorkspace().getQueryManager();
NodeIterator messageNodes = qm.createQuery(query, "xpath").execute().getNodes();
while (messageNodes.hasNext()) {
Node node = messageNodes.nextNode();
try {
if (!node.isNodeType("sling:Message")) continue;
if (node.hasProperty("sling:key")) {
translations.put(node.getProperty("sling:key").getString(), node.getPath());
continue;
}
translations.put(node.getName(), node.getPath());
}
catch (Exception e) {
this.log.warn("Error while reading existing translation inside '" + path + "'", (Throwable)e);
}
}
}
return this.storedTranslations.get(path);
}
private Map<String, String> getStoredLowerCaseNodeNames(Node languageNode) throws RepositoryException {
String path = languageNode.getPath();
if (!this.storedLowerCaseNodeNames.containsKey(path)) {
HashMap<String, String> lowerCaseNodeNames = new HashMap<String, String>();
this.storedLowerCaseNodeNames.put(path, lowerCaseNodeNames);
String query = "/jcr:root" + languageNode.getPath() + "//*[@sling:message]";
QueryManager qm = languageNode.getSession().getWorkspace().getQueryManager();
NodeIterator messageNodes = qm.createQuery(query, "xpath").execute().getNodes();
while (messageNodes.hasNext()) {
Node node = messageNodes.nextNode();
lowerCaseNodeNames.put(node.getName().toLowerCase(), node.getName());
}
}
return this.storedLowerCaseNodeNames.get(path);
}
private static String getNodeName(String source) {
source = source.substring(0, (source = source.trim()).length() > 50 ? 50 : source.length());
source = source.replaceAll(":", "_");
source = source.replaceAll("/", "_");
source = source.replaceAll("<", "_");
source = source.replaceAll(">", "_");
return Text.escapeIllegalJcrChars((String)source);
}
private static String getKey(String source, String comment) {
if (comment != null) {
return source + " ((" + comment + "))";
}
return source;
}
private static String getCommentForLog(String comment) {
if (comment != null) {
return " (comment: " + comment + ")";
}
return "";
}
private String calculateFolderPath(String nodeName) {
StringBuilder path = new StringBuilder();
int i = 0;
for (int n = 0; n < nodeName.length() && i < this.treeDepth; ++n) {
char c = nodeName.charAt(n);
if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') && (c < '0' || c > '9')) continue;
path.append(Character.toLowerCase(c));
path.append("/");
++i;
}
path.append(nodeName);
return path.toString();
}
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
this.state = State.OTHER;
if (name.equalsIgnoreCase("trans-unit")) {
this.transUnit = new TransUnit();
} else if (name.equalsIgnoreCase("source")) {
this.state = State.SOURCE;
this.transUnit.source = null;
} else if (name.equalsIgnoreCase("target")) {
this.state = State.TARGET;
this.transUnit.language = attributes.getValue("xml:lang");
this.transUnit.target = null;
} else if (name.equalsIgnoreCase("context")) {
if ("comment".equalsIgnoreCase(attributes.getValue("context-type"))) {
this.state = State.COMMENT;
this.transUnit.comment = null;
}
} else if (name.equalsIgnoreCase("file")) {
this.checkAndCreateJsonObject(attributes.getValue("target-language"));
}
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (this.transUnit != null) {
switch (this.state) {
case SOURCE: {
if (this.transUnit.source != null) {
this.transUnit.source = this.transUnit.source + new String(ch, start, length);
break;
}
this.transUnit.source = new String(ch, start, length);
break;
}
case TARGET: {
if (this.transUnit.target != null) {
this.transUnit.target = this.transUnit.target + new String(ch, start, length);
break;
}
this.transUnit.target = new String(ch, start, length);
break;
}
case COMMENT: {
if (this.transUnit.comment != null) {
this.transUnit.comment = this.transUnit.comment + new String(ch, start, length);
break;
}
this.transUnit.comment = new String(ch, start, length);
}
}
}
}
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
@Override
public void endElement(String uri, String localName, String name) throws SAXException {
this.state = State.OTHER;
if (!name.equalsIgnoreCase("trans-unit")) return;
if (this.transUnit.source == null) return;
if (this.transUnit.source.length() == 0) return;
if (this.transUnit.target == null) return;
if (this.transUnit.target.length() == 0) return;
if (this.transUnit.language == null) return;
if (this.transUnit.language.length() == 0) {
return;
}
if (this.jsonObject != null) {
this.updateJsonObject(this.transUnit);
return;
}
String lang = this.transUnit.language.toLowerCase();
String[] langSplit = (lang = lang.replace("_", "-")).split("-");
if (langSplit.length == 2 && langSplit[0].equals(langSplit[1])) {
lang = langSplit[0];
}
String languageNodePath = this.path + "/" + lang;
Node languageNode = null;
try {
languageNode = JcrUtils.getOrCreateByPath((String)languageNodePath, (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (Session)this.session);
if (!languageNode.isNodeType("mix:language")) {
languageNode.addMixin("mix:language");
}
if (!languageNode.hasProperty("{http://www.jcp.org/jcr/1.0}language")) {
languageNode.setProperty("{http://www.jcp.org/jcr/1.0}language", lang);
}
String key = XliffDictImporter.getKey(this.transUnit.source, this.transUnit.comment);
Node messageNode = null;
Map<String, String> translations = this.getStoredTranslations(languageNode);
if (translations.containsKey(key)) {
messageNode = (Node)this.session.getItem(translations.get(key));
if (messageNode.hasProperty("sling:message")) {
String existingTranslation = messageNode.getProperty("sling:message").getString();
if (this.transUnit.target.equals(existingTranslation)) {
this.log.info(this.transUnit.language + ": skipping repeated translation '" + this.transUnit.source + "' => '" + this.transUnit.target + "'" + XliffDictImporter.getCommentForLog(this.transUnit.comment) + " :: '" + messageNode.getPath() + "'");
return;
}
if (!this.overwrite) {
this.log.info(this.transUnit.language + ": keeping old translation for '" + this.transUnit.source + "', " + "existing translation: '" + existingTranslation + "', " + "new translation: '" + this.transUnit.target + "'" + XliffDictImporter.getCommentForLog(this.transUnit.comment) + " :: '" + messageNode.getPath() + "'");
return;
}
this.log.info(this.transUnit.language + ": overwriting old translation for '" + this.transUnit.source + "', " + "existing translation: '" + existingTranslation + "', " + "new translation: '" + this.transUnit.target + "'" + XliffDictImporter.getCommentForLog(this.transUnit.comment) + " :: '" + messageNode.getPath() + "'");
} else {
this.log.warn("existing message node without translation (sling:message) found '" + messageNode.getPath() + "'");
}
}
Map<String, String> lowerCaseNodeNames = this.getStoredLowerCaseNodeNames(languageNode);
if (messageNode == null) {
String nodeNameHint = XliffDictImporter.getNodeName(this.transUnit.source);
if (lowerCaseNodeNames.containsKey(nodeNameHint.toLowerCase())) {
nodeNameHint = lowerCaseNodeNames.get(nodeNameHint.toLowerCase());
}
String pathHint = languageNode.getPath() + "/" + this.calculateFolderPath(nodeNameHint);
messageNode = JcrUtils.getOrCreateUniqueByPath((String)pathHint, (String)"{http://www.jcp.org/jcr/nt/1.0}folder", (Session)this.session);
}
this.log.info(this.transUnit.language + ": translating '" + this.transUnit.source + "' => '" + this.transUnit.target + "'" + XliffDictImporter.getCommentForLog(this.transUnit.comment) + " :: '" + messageNode.getPath() + "'");
if (!messageNode.isNodeType("sling:Message")) {
messageNode.addMixin("sling:Message");
}
if (!messageNode.getName().equals(key)) {
messageNode.setProperty("sling:key", key);
}
messageNode.setProperty("sling:message", this.transUnit.target);
translations.put(key, messageNode.getPath());
lowerCaseNodeNames.put(messageNode.getName().toLowerCase(), messageNode.getName());
return;
}
catch (RepositoryException e) {
this.log.error("could not add translation unit to '" + languageNodePath + "'", (Throwable)e);
}
}
@Override
public void endDocument() throws SAXException {
try {
if (this.jsonFileResource != null) {
((Node)this.jsonFileResource.adaptTo(Node.class)).getNode("jcr:content").setProperty("jcr:data", this.jsonObject.toString(10));
}
this.session.save();
}
catch (JSONException e) {
this.log.error("could not save xliff import", (Throwable)e);
}
catch (RepositoryException e) {
this.log.error("could not save xliff import", (Throwable)e);
}
}
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
private static enum State {
SOURCE,
TARGET,
COMMENT,
OTHER;
private State() {
}
}
private static class TransUnit {
String source;
String target;
String language;
String comment;
private TransUnit() {
}
}
}