XMLUtils.java
26.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.forms.common.service.FormDataXMLProviderRegistry
* com.adobe.granite.resourceresolverhelper.ResourceResolverHelper
* javax.jcr.Binary
* javax.jcr.Node
* javax.jcr.PathNotFoundException
* javax.jcr.Property
* javax.jcr.RepositoryException
* org.apache.commons.io.IOUtils
* org.apache.commons.lang3.StringUtils
* org.apache.sling.api.resource.NonExistingResource
* org.apache.sling.api.resource.Resource
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.commons.json.JSONException
* org.apache.sling.commons.json.JSONObject
* org.apache.sling.commons.json.xml.XML
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.adobe.aemds.guide.utils;
import com.adobe.aemds.guide.service.GuideException;
import com.adobe.forms.common.service.FormDataXMLProviderRegistry;
import com.adobe.granite.resourceresolverhelper.ResourceResolverHelper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.jcr.Binary;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.json.xml.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentFragment;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
public class XMLUtils {
private static Logger logger = LoggerFactory.getLogger(XMLUtils.class);
public static final String xmlSkeleton = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<afData>\n <afUnboundData>\n <data></data>\n </afUnboundData>\n <afBoundData>\n <data xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"></data>\n </afBoundData>\n</afData>\n";
public static boolean checkIfStringHasIndexOperator(String bindRef) {
boolean bContainsIndex = false;
if (StringUtils.contains((CharSequence)bindRef, (CharSequence)"[")) {
bContainsIndex = true;
}
return bContainsIndex;
}
public static String extractXsdRootElement(JSONObject guideJson) {
String xsdRootEl = "";
try {
if (guideJson.has("xsdRootElement")) {
xsdRootEl = guideJson.getString("xsdRootElement");
} else {
logger.debug("Unable to find xsdRootElement in guide JSON");
}
}
catch (JSONException ex) {
logger.debug("Unable to read xsdRootElement from guide JSON", (Throwable)ex);
}
return xsdRootEl;
}
public static String getXSDRootBindRef(JSONObject jsonObject, String xsdRoot) throws JSONException {
String effectiveBindRef = "";
if (XMLUtils.isXsd(jsonObject)) {
effectiveBindRef = XMLUtils.getRelativeXpath(jsonObject.optString("bindRef", ""), xsdRoot);
}
return effectiveBindRef;
}
public static String getRelativeXpath(String bindRef, String root) {
String xpath = "";
if (StringUtils.isNotBlank((CharSequence)bindRef)) {
xpath = bindRef;
if (XMLUtils.isValidXsdRoot(root) && xpath.matches("/" + root + "(?:/.+)?") || StringUtils.equals((CharSequence)root, (CharSequence)"?")) {
xpath = xpath.replaceFirst("^/[^/]+", "");
}
}
return StringUtils.removeStart((String)xpath, (String)"/");
}
public static String getXMLfromXsdDom(Element doc) {
return XMLUtils.getXMLfromXsdDom(doc, false);
}
public static String getXMLfromXsdDom(Element doc, Boolean omitXmlDeclaration) {
String xsdValue = "";
try {
if (doc != null) {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty("omit-xml-declaration", omitXmlDeclaration != false ? "yes" : "no");
trans.setOutputProperty("method", "xml");
trans.setOutputProperty("indent", "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
xsdValue = sw.toString();
}
}
catch (Exception e) {
throw new GuideException(e);
}
return xsdValue;
}
public static void addChildNodesOfParentUnderRoot(org.w3c.dom.Node parent, org.w3c.dom.Node root) {
Document document = root.getOwnerDocument();
NodeList children = parent.getChildNodes();
int length = children.getLength();
for (int i = 0; i < length; ++i) {
org.w3c.dom.Node child = children.item(i);
if (child.getNodeType() != 1) continue;
root.appendChild(document.importNode(child, true));
}
}
public static String getDorDataXmlPart(Document dorDoc, Document doc, String excludeFromDorIfHidden, boolean bSetXfaNameSpace) {
try {
Element nakedExcludeFromDoRXml;
Element nakedBoundXml;
org.w3c.dom.Node root = null;
if (bSetXfaNameSpace) {
root = dorDoc.createElement("data");
XMLUtils.setXfaNameSpace((Element)root);
} else {
root = dorDoc.importNode(XMLUtils.getBoundDataXmlElement(doc), false);
}
Element nakedUnBoundXml = XMLUtils.getUnboundDataXmlElement(doc);
if (nakedUnBoundXml != null) {
XMLUtils.addChildNodesOfParentUnderRoot(nakedUnBoundXml, root);
}
if ((nakedBoundXml = XMLUtils.getBoundDataXmlElement(doc)) != null) {
XMLUtils.addChildNodesOfParentUnderRoot(nakedBoundXml, root);
}
if ((nakedExcludeFromDoRXml = XMLUtils.getSubmissionInfoDataXmlElement(doc, "excludeFromDoR")) != null) {
root.appendChild(dorDoc.importNode(nakedExcludeFromDoRXml, true));
}
return XMLUtils.getXMLfromXsdDom((Element)root);
}
catch (Exception e) {
throw new GuideException("Error in getting dor data xml " + e.getMessage(), e);
}
}
public static Element getSubmissionInfoDataXmlElement(Document doc, String submitInfoPart) {
try {
if (XMLUtils.isWrappedXml(doc)) {
XPath xPath = XPathFactory.newInstance().newXPath();
String xPathString = "afSubmissionInfo";
xPathString = submitInfoPart != null && submitInfoPart.length() > 0 ? xPathString + "/" + submitInfoPart : xPathString + "/*";
org.w3c.dom.Node afSubmissionInfo = (org.w3c.dom.Node)xPath.evaluate(xPathString, doc.getDocumentElement(), XPathConstants.NODE);
return (Element)afSubmissionInfo;
}
return null;
}
catch (Exception e) {
throw new GuideException("Error in getting bound xml part" + e.getMessage(), e);
}
}
public static String getSubmissionInfoDataXmlPart(Document doc, String submitInfoPart) {
return XMLUtils.getXMLfromXsdDom(XMLUtils.getSubmissionInfoDataXmlElement(doc, submitInfoPart));
}
public static void setXfaNameSpace(Element data) {
if (data != null) {
data.setAttribute("xmlns:xfa", "http://www.xfa.org/schema/xfa-data/1.0/");
}
}
public static String getBoundDataXmlPart(Document doc) {
return XMLUtils.getXMLfromXsdDom(XMLUtils.getBoundDataXmlElement(doc));
}
public static Element getBoundDataXmlElement(Document doc) {
try {
if (XMLUtils.isWrappedXml(doc)) {
XPath xPath = XPathFactory.newInstance().newXPath();
org.w3c.dom.Node afBoundData = (org.w3c.dom.Node)xPath.evaluate("afBoundData/*", doc.getDocumentElement(), XPathConstants.NODE);
return (Element)afBoundData;
}
return doc.getDocumentElement();
}
catch (Exception e) {
throw new GuideException("Error in getting bound xml part" + e.getMessage(), e);
}
}
public static String getUnboundDataXmlPart(Document doc) {
return XMLUtils.getXMLfromXsdDom(XMLUtils.getUnboundDataXmlElement(doc));
}
public static Element getUnboundDataXmlElement(Document doc) {
try {
if (XMLUtils.isWrappedXml(doc)) {
XPath xPath = XPathFactory.newInstance().newXPath();
org.w3c.dom.Node afUnboundData = (org.w3c.dom.Node)xPath.evaluate("afUnboundData/*", doc.getDocumentElement(), XPathConstants.NODE);
return (Element)afUnboundData;
}
return doc.getDocumentElement();
}
catch (Exception e) {
throw new GuideException("Error in getting unbound xml part" + e.getMessage(), e);
}
}
public static JSONObject getMapOfUnboundData(Document doc) {
JSONObject xmlJSONObj = null;
try {
String jsonStr = XML.toJSONObject((String)XMLUtils.getUnboundDataXmlPart(doc).trim()).toString().replaceAll("(\\\\r)?\\\\n", "\\\\n");
xmlJSONObj = new JSONObject(jsonStr);
}
catch (Exception e) {
throw new GuideException("Error in getting map of unbound data" + e.getMessage(), e);
}
return xmlJSONObj;
}
public static String getPrefillXmlWithoutBoundPart(Document doc) {
try {
if (XMLUtils.isWrappedXml(doc)) {
XPath xPath = XPathFactory.newInstance().newXPath();
org.w3c.dom.Node afBoundData = (org.w3c.dom.Node)xPath.evaluate("afBoundData", doc.getDocumentElement(), XPathConstants.NODE);
if (afBoundData != null) {
doc.getDocumentElement().removeChild(afBoundData);
}
return XMLUtils.getXMLfromXsdDom(doc.getDocumentElement());
}
return XMLUtils.getXMLfromXsdDom(doc.getDocumentElement());
}
catch (Exception e) {
throw new GuideException("Error in getting bound xml part" + e.getMessage(), e);
}
}
public static String getXMLFromDom(Document doc, String tagName) {
try {
XPath xPath = XPathFactory.newInstance().newXPath();
org.w3c.dom.Node xmlNode = (org.w3c.dom.Node)xPath.evaluate(tagName + "/*", doc.getDocumentElement(), XPathConstants.NODE);
return XMLUtils.getXMLfromXsdDom((Element)xmlNode);
}
catch (Exception e) {
throw new GuideException("Error in Getting XML of the element <" + tagName + "> From DOM", e);
}
}
@Deprecated
public static InputStream getDataRefInputStream(String dataRef, FormDataXMLProviderRegistry formDataXMLProviderRegistry, ResourceResolverHelper resourceResolverHelper) {
String xml = null;
try {
if (dataRef.startsWith("crx://")) {
Resource fileResource = resourceResolverHelper.getResourceResolver().resolve(dataRef.substring(6));
Node jcrNode = (Node)fileResource.adaptTo(Node.class);
Node jcrContent = jcrNode.getNode("jcr:content");
InputStream is = jcrContent.getProperty("jcr:data").getBinary().getStream();
return is;
}
if (!(dataRef.startsWith("https://") || dataRef.startsWith("http://") || dataRef.startsWith("file://"))) {
xml = formDataXMLProviderRegistry.getDataXMLFromService(dataRef);
logger.info("[AEMForm] XML Recieved from Prefill Service = " + xml);
if (xml != null && xml.length() > 0) {
return new ByteArrayInputStream(xml.getBytes("UTF-8"));
}
return null;
}
URL url = new URL(dataRef);
InputStream in = url.openStream();
return in;
}
catch (PathNotFoundException e) {
logger.error("[AEMForm] unable to locate Data XML in the repository " + dataRef + ": " + e.getMessage(), (Throwable)e);
}
catch (RepositoryException e) {
logger.error("[AEMForm] Exception while reading Data XML in the repository " + dataRef + ": " + e.getMessage(), (Throwable)e);
}
catch (UnsupportedEncodingException e) {
logger.error("[AEMForm] Unable to read xml using UTF-8 encoding for the " + dataRef + "," + xml + ": " + e.getMessage(), (Throwable)e);
}
catch (MalformedURLException e) {
logger.error("[AEMForm] Malformed URL passed for getting the xml " + dataRef + ": " + e.getMessage(), (Throwable)e);
}
catch (IOException e) {
logger.error("[AEMForm] Unable to read from the dataRef URL " + dataRef + ": " + e.getMessage(), (Throwable)e);
}
return null;
}
@Deprecated
public static Document exportDocumentFromDataRef(String dataRef, DocumentBuilder builder, FormDataXMLProviderRegistry formDataXMLProviderRegistry, ResourceResolverHelper resourceResolverHelper) throws Exception {
Document doc = null;
if (dataRef.startsWith("crx://")) {
Resource fileResource = resourceResolverHelper.getResourceResolver().resolve(dataRef.substring(6));
if (fileResource instanceof NonExistingResource) {
return null;
}
Node jcrNode = (Node)fileResource.adaptTo(Node.class);
Node jcrContent = jcrNode.getNode("jcr:content");
InputStream is = jcrContent.getProperty("jcr:data").getBinary().getStream();
byte[] fileBytes = IOUtils.toByteArray((InputStream)is);
is.close();
doc = builder.parse(new ByteArrayInputStream(fileBytes));
} else if (!(dataRef.startsWith("https://") || dataRef.startsWith("http://") || dataRef.startsWith("file://"))) {
InputSource inputSource = new InputSource(new StringReader(formDataXMLProviderRegistry.getDataXMLFromService(dataRef)));
doc = builder.parse(inputSource);
}
if (doc == null) {
URL url = new URL(dataRef);
InputStream in = url.openStream();
doc = builder.parse(in);
in.close();
}
return doc;
}
public static org.w3c.dom.Node createNode(Document dataDoc, XPath xPath, org.w3c.dom.Node node, String path) throws XPathExpressionException {
Document document = dataDoc;
String[] pathTokens = path.split("/");
org.w3c.dom.Node currentNode = node;
int pathTokensSize = pathTokens.length;
for (int i = 0; i < pathTokensSize; ++i) {
Element elNode;
String pathToken = pathTokens[i];
boolean isLastToken = i == pathTokensSize - 1;
org.w3c.dom.Node newNode = (org.w3c.dom.Node)xPath.evaluate(pathToken, currentNode, XPathConstants.NODE);
if (newNode == null) {
if (pathToken.charAt(0) == '@') {
Attr newAttribute = document.createAttribute(pathToken.substring(1));
((Element)currentNode).setAttributeNode(newAttribute);
newNode = newAttribute;
} else if ("text()".equals(pathToken)) {
Text textNode = document.createTextNode(null);
currentNode.appendChild(textNode);
newNode = textNode;
} else {
if (XMLUtils.checkIfStringHasIndexOperator(pathToken)) {
pathToken = StringUtils.substringBefore((String)pathToken, (String)"[");
}
elNode = document.createElement(pathToken);
currentNode.appendChild(elNode);
newNode = elNode;
}
} else if (isLastToken && pathToken.charAt(0) != '@' && !"text()".equals(pathToken)) {
elNode = document.createElement(pathToken);
currentNode.appendChild(elNode);
newNode = elNode;
}
currentNode = newNode;
}
return currentNode;
}
public static void addToDocument(Document dataDoc, XPath xPath, org.w3c.dom.Node currentNode, String path, String value) {
try {
org.w3c.dom.Node toUpdate = (org.w3c.dom.Node)xPath.evaluate(path, currentNode, XPathConstants.NODE);
if (toUpdate == null) {
toUpdate = XMLUtils.createNode(dataDoc, xPath, currentNode, path);
}
switch (toUpdate.getNodeType()) {
case 2: {
((Attr)toUpdate).setValue(value);
break;
}
case 1: {
toUpdate.setTextContent(value);
break;
}
case 3: {
toUpdate.setNodeValue(value);
break;
}
}
}
catch (XPathExpressionException ex) {
logger.warn("Invalid Xpath Syntax: " + path, (Throwable)ex);
}
catch (Exception e) {
logger.error(e.getMessage(), (Throwable)e);
throw new GuideException(e);
}
}
public static boolean isXsd(JSONObject obj) {
String bindRef = obj.optString("bindRef");
return StringUtils.isNotBlank((CharSequence)bindRef) && StringUtils.startsWith((CharSequence)bindRef, (CharSequence)"/");
}
public static boolean isWrappedXml(Document doc) {
try {
return "afData".equals(doc.getDocumentElement().getTagName());
}
catch (Exception e) {
logger.debug("Error while trying to check document root tag : " + e.getMessage(), (Throwable)e);
return false;
}
}
public static boolean isWrappedXmlStr(String docStr) {
if (StringUtils.isNotBlank((CharSequence)docStr)) {
try {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(docStr)));
return XMLUtils.isWrappedXml(doc);
}
catch (SAXException e) {
logger.error("Error while parsing Guide Prefill Xml String : " + e.getMessage(), (Throwable)e);
}
catch (IOException e) {
logger.error("Error while parsing Guide Prefill Xml String : " + e.getMessage(), (Throwable)e);
}
catch (ParserConfigurationException e) {
logger.error("Error while parsing Guide Prefill Xml String : " + e.getMessage(), (Throwable)e);
}
}
return false;
}
public static boolean isValidXsdRoot(String root) {
return StringUtils.isNotBlank((CharSequence)root) && root.matches("[a-zA-Z].*");
}
public static Document getEmptySubmitDoc() {
Document doc = XMLUtils.strToDoc("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<afData>\n <afUnboundData>\n <data></data>\n </afUnboundData>\n <afBoundData>\n <data xmlns:xfa=\"http://www.xfa.org/schema/xfa-data/1.0/\"></data>\n </afBoundData>\n</afData>\n");
if (!(doc instanceof Document)) {
logger.debug("Unable to Generate Empty Xml Doc");
return null;
}
return doc;
}
public static String getChildBoundRootXpath(String fsRoot, String bindRefPrefix, String childRoot) {
String xpath = "";
if (StringUtils.isBlank((CharSequence)bindRefPrefix)) {
if (XMLUtils.isValidXsdRoot(childRoot) && !StringUtils.equals((CharSequence)fsRoot, (CharSequence)childRoot)) {
xpath = childRoot;
}
} else {
xpath = XMLUtils.getRelativeXpath(bindRefPrefix, fsRoot);
}
return xpath;
}
public static Object evaluateXPath(String xPathQuery, org.w3c.dom.Node contextNode, QName type) {
try {
if (StringUtils.isBlank((CharSequence)xPathQuery)) {
return contextNode;
}
XPathFactory xpFactory = XPathFactory.newInstance();
XPath xPath = xpFactory.newXPath();
return xPath.evaluate(xPathQuery, contextNode, type);
}
catch (XPathExpressionException e) {
logger.debug("Unable to evaluate XPath" + xPathQuery, (Throwable)e);
return null;
}
}
public static void copyChildren(org.w3c.dom.Node source, org.w3c.dom.Node target) {
if (source == null || target == null) {
return;
}
Document destination = target.getOwnerDocument();
DocumentFragment container = destination.createDocumentFragment();
NodeList children = source.getChildNodes();
int length = children.getLength();
for (int i = 0; i < length; ++i) {
container.appendChild(destination.importNode(children.item(i), true));
}
target.appendChild(container);
}
public static Document getChildXmlDoc(Element fsUnBoundDataRoot, Element fsBoundDataRoot, String childBoundRootXpath, boolean keepBoundPart) {
Document childDoc = XMLUtils.getEmptySubmitDoc();
XMLUtils.copyChildren(fsUnBoundDataRoot, XMLUtils.getUnboundDataXmlElement(childDoc));
if (keepBoundPart) {
Element childBoundRoot = (Element)XMLUtils.evaluateXPath(childBoundRootXpath, fsBoundDataRoot, XPathConstants.NODE);
if (childBoundRoot == null) {
childBoundRoot = fsBoundDataRoot;
}
XMLUtils.copyChildren(childBoundRoot, XMLUtils.getBoundDataXmlElement(childDoc));
}
return childDoc;
}
public static void createAttachmentTag(Document document, org.w3c.dom.Node fileComponentNode, JSONObject jsonObject) {
try {
JSONObject commentsJson;
Element fileAttachments = document.createElement("fileAttachment");
fileComponentNode.appendChild(fileAttachments);
fileAttachments.setTextContent(jsonObject.getString("files"));
JSONObject items = jsonObject.getJSONObject("items");
if (items.has("comment") && (commentsJson = items.getJSONObject("comment")).has("_value")) {
Element comments = document.createElement("comment");
comments.setTextContent(commentsJson.getString("_value"));
fileComponentNode.appendChild(comments);
}
}
catch (Exception e) {
logger.error("Error in creating file attachment tag", (Throwable)e);
}
}
public static String docToStr(Document doc) {
String xmlStr = "";
try {
if (doc != null) {
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty("omit-xml-declaration", "no");
trans.setOutputProperty("method", "xml");
trans.setOutputProperty("indent", "yes");
trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(2));
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
xmlStr = sw.toString();
}
}
catch (Exception e) {
logger.error("Exception while converting document to xml", (Throwable)e);
}
return xmlStr;
}
public static Document strToDoc(String xmlStr) {
Document doc = null;
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
doc = dBuilder.parse(new InputSource(new StringReader(xmlStr)));
doc.getDocumentElement().normalize();
}
catch (Exception e) {
logger.debug("Unable to Generate Xml Doc from String : " + xmlStr, (Throwable)e);
}
return doc;
}
public static List<String> extractAttachmentNames(Document doc) {
ArrayList<String> attachmentNames = new ArrayList<String>();
NodeList attachments = (NodeList)XMLUtils.evaluateXPath("//fileAttachment", doc.getDocumentElement(), XPathConstants.NODESET);
if (attachments != null) {
int length = attachments.getLength();
for (int i = 0; i < length; ++i) {
String[] fileNames;
Element attachment = (Element)attachments.item(i);
String combinedNames = attachment.getTextContent();
if (!StringUtils.isNotBlank((CharSequence)combinedNames) || (fileNames = combinedNames.split("\\r?\\n")) == null || fileNames.length <= 0) continue;
attachmentNames.addAll(Arrays.asList(fileNames));
}
}
return attachmentNames;
}
}