CQPagePreviewGenerator.java
12.8 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
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.translation.api.TranslationException
* com.adobe.granite.translation.api.TranslationService
* com.day.cq.wcm.api.Page
* com.day.cq.wcm.api.PageManager
* com.day.cq.wcm.contentsync.PageExporter
* javax.jcr.Node
* javax.jcr.Property
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.Value
* org.apache.commons.io.FileUtils
* org.apache.commons.lang3.StringUtils
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.commons.html.HtmlParser
* org.apache.sling.jcr.resource.JcrResourceUtil
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.cq.wcm.translation.impl;
import com.adobe.cq.wcm.translation.impl.CQPageTranslator;
import com.adobe.cq.wcm.translation.impl.TranslationRuleConfigurationFile;
import com.adobe.cq.wcm.translation.impl.TranslationUtils;
import com.adobe.cq.wcm.translation.impl.ZipUtil;
import com.adobe.granite.translation.api.TranslationException;
import com.adobe.granite.translation.api.TranslationService;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.contentsync.PageExporter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import java.util.UUID;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.html.HtmlParser;
import org.apache.sling.jcr.resource.JcrResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class CQPagePreviewGenerator
extends CQPageTranslator {
private static final String XML_PREPROCESSOR = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>";
private static String ATTR_NODE_PATH = "data-previewnodepath";
private static String ATTR_PROP_NAME = "data-previewpropertyname";
private static final Logger logger = LoggerFactory.getLogger(CQPagePreviewGenerator.class);
private String strUniqueID;
private String strTempFileParentPath;
private int iCount;
HashMap<String, ElementTextProperty> contentHashMap = null;
public CQPagePreviewGenerator(TranslationRuleConfigurationFile ruleFile) {
super(ruleFile, null);
}
public FileInputStream generatePreview(ResourceResolver resourceResolver, Page originalPage) {
try {
PageManager pageManager = (PageManager)resourceResolver.adaptTo(PageManager.class);
Node parentNode = ((Node)originalPage.adaptTo(Node.class)).getParent();
Session session = (Session)resourceResolver.adaptTo(Session.class);
this.strTempFileParentPath = "/var/contentsync/tmp/page/" + System.currentTimeMillis();
String strParentPath = this.strTempFileParentPath + parentNode.getPath();
String strTempPagePath = this.strTempFileParentPath + originalPage.getPath();
JcrResourceUtil.createPath((String)strParentPath, (String)"sling:Folder", (String)"cq:ContentSyncConfig", (Session)session, (boolean)false);
Page tempPage = pageManager.copy(originalPage, strTempPagePath, null, true, true);
this.init();
Node tempPageNode = (Node)tempPage.adaptTo(Node.class);
if (this.processTranslationNode(tempPageNode)) {
session.save();
}
File tempDir = File.createTempFile("preview", "zip");
tempDir.delete();
tempDir.mkdir();
String strParentFilePath = "/var/contentsync/tmp" + parentNode.getPath();
if (!session.itemExists(strParentFilePath)) {
JcrResourceUtil.createPath((String)strParentFilePath, (String)"sling:Folder", (String)"cq:ContentSyncConfig", (Session)session, (boolean)false);
}
String strZipFilePath = "/var/contentsync/tmp" + originalPage.getPath() + "_temp_" + System.currentTimeMillis() + ".zip";
String strOutputFilePath = tempDir.getAbsolutePath() + File.separator + "preview.zip";
PageExporter exporter = this.ruleFile.getPageExporter();
exporter.export(tempPage, resourceResolver, strZipFilePath);
Resource zipNode = resourceResolver.resolve(strZipFilePath);
File fileUnzipDir = new File(tempDir.getAbsolutePath() + File.separator + "unzip");
ZipUtil.unZipToDir(zipNode, fileUnzipDir.getAbsolutePath(), 0);
ArrayList<File> fileList = new ArrayList<File>();
ZipUtil.getAllFiles(fileUnzipDir, fileList, false);
for (File file : fileList) {
if (file.isDirectory()) continue;
this.patchFileContent(file);
}
ZipUtil.zipDirectory(fileUnzipDir, strOutputFilePath);
FileUtils.deleteDirectory((File)fileUnzipDir);
tempPageNode.remove();
session.save();
return new FileInputStream(strOutputFilePath);
}
catch (Exception ex) {
logger.error("Error while generating preview {}", (Throwable)ex);
return null;
}
}
@Override
protected ArrayList<String> getTranslatablePropertyListForNode(Node node) throws RepositoryException, IOException {
Resource resource;
String strCurrentNodePath = node.getPath();
if (strCurrentNodePath.indexOf(this.strTempFileParentPath) == 0 && (resource = this.resourceResolver.resolve(strCurrentNodePath = strCurrentNodePath.substring(this.strTempFileParentPath.length()))) != null) {
node = (Node)resource.adaptTo(Node.class);
}
return node != null ? this.ruleFile.getTranslatablePropertyListForNode(node) : null;
}
@Override
protected ArrayList<String> getLanguagePatchPropertyListForNode(Node node) throws RepositoryException, IOException {
Resource resource;
String strCurrentNodePath = node.getPath();
if (strCurrentNodePath.indexOf(this.strTempFileParentPath) == 0 && (resource = this.resourceResolver.resolve(strCurrentNodePath = strCurrentNodePath.substring(this.strTempFileParentPath.length()))) != null) {
node = (Node)resource.adaptTo(Node.class);
}
return node != null ? this.ruleFile.getLanguagePatchPropertyListForNode(node) : null;
}
private void patchFileContent(File file) {
String strFileExtension = TranslationUtils.getFileExtension(file.getAbsolutePath(), null);
if (!StringUtils.isEmpty((CharSequence)strFileExtension) && strFileExtension.compareToIgnoreCase(".html") == 0) {
try {
HtmlParser parser = this.ruleFile.getHTMLParser();
FileInputStream stream = new FileInputStream(file);
Document document = parser.parse(null, (InputStream)stream, "UTF-8");
org.w3c.dom.Node rootNode = document.getFirstChild();
this.processHTMLElement(rootNode);
stream.close();
String strOutput = TranslationUtils.convertDOMDocumentToString(document, false);
if (strOutput.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>") == 0) {
strOutput = strOutput.substring("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>".length());
}
strOutput = this.patchStringContent(strOutput);
OutputStreamWriter osw = new OutputStreamWriter((OutputStream)new FileOutputStream(file.getAbsoluteFile()), "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(strOutput);
bw.close();
}
catch (Exception e) {
logger.error("Error while patching file content {}", (Throwable)e);
}
}
}
private void processHTMLElement(org.w3c.dom.Node node) {
if (node != null) {
String nodeText;
ElementTextProperty textProp;
org.w3c.dom.Node parentNode;
if (node.getNodeType() == 3 && (textProp = this.getOriginalTextProperty(nodeText = node.getTextContent().trim())) != null && (parentNode = this.getParentTagNode(node)) != null) {
Element element = (Element)parentNode;
element.setAttribute(ATTR_NODE_PATH, textProp.strNodePath);
element.setAttribute(ATTR_PROP_NAME, textProp.strPropertyName);
}
NodeList childNodes = node.getChildNodes();
for (int index = 0; index < childNodes.getLength(); ++index) {
org.w3c.dom.Node childNode = childNodes.item(index);
this.processHTMLElement(childNode);
}
}
}
private org.w3c.dom.Node getParentTagNode(org.w3c.dom.Node node) {
while (node != null && node.getNodeType() != 1) {
node = node.getParentNode();
}
return node;
}
private String patchStringContent(String strOutput) {
for (String strKey : this.contentHashMap.keySet()) {
String strOriginalText = this.contentHashMap.get((Object)strKey).strOriginalText;
if (strOutput.indexOf(strKey) == -1) continue;
strOutput = strOutput.replaceAll(strKey, strOriginalText);
}
return strOutput;
}
private void init() {
this.strUniqueID = String.format("%s_%d", UUID.randomUUID().toString(), new Date().getTime());
this.contentHashMap = new HashMap();
this.iCount = 0;
}
@Override
protected boolean processNodeProperty(Node node, Property prop, String strPropertyName) throws TranslationException {
boolean bSave = false;
try {
String strNodePath = node.getPath();
Boolean bMultiValue = prop.isMultiple();
if (bMultiValue.booleanValue()) {
Value[] val_array = prop.getValues();
if (val_array != null && val_array.length > 0) {
ArrayList<String> strOutputArray = new ArrayList<String>();
for (int index = 0; index < val_array.length; ++index) {
Value value = val_array[index];
String strTranslationText = this.getTranslatableString(value);
if (StringUtils.isEmpty((CharSequence)strTranslationText)) continue;
strOutputArray.add(this.getPatchedString(strNodePath, strPropertyName, strTranslationText));
bSave = true;
}
String[] newVals = TranslationUtils.getStringArray(strOutputArray);
prop.setValue(newVals);
}
} else {
Value value = prop.getValue();
String strTranslationText = this.getTranslatableString(value);
if (!StringUtils.isEmpty((CharSequence)strTranslationText)) {
prop.setValue(this.getPatchedString(strNodePath, strPropertyName, strTranslationText));
bSave = true;
}
}
}
catch (Exception ex) {
logger.error("Error while processing node propery {}", (Throwable)ex);
}
return bSave;
}
private String getTranslatableString(Value value) throws IllegalStateException, RepositoryException {
if (value != null && value.getType() == 1) {
return value.getString();
}
return null;
}
private String getPatchedString(String strNodePath, String strPropertyName, String strOriginalText) {
++this.iCount;
String strKey = String.format("%s_%d", this.strUniqueID, this.iCount);
if (strNodePath.indexOf(this.strTempFileParentPath) == 0) {
strNodePath = strNodePath.substring(this.strTempFileParentPath.length());
}
this.contentHashMap.put(strKey, new ElementTextProperty(strNodePath, strPropertyName, strOriginalText));
return strKey;
}
private ElementTextProperty getOriginalTextProperty(String strKey) {
return this.contentHashMap.get(strKey);
}
class ElementTextProperty {
public String strNodePath;
public String strPropertyName;
public String strOriginalText;
public ElementTextProperty(String path, String propName, String originalText) {
this.strNodePath = path;
this.strPropertyName = propName;
this.strOriginalText = originalText;
}
}
}