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
|
/*-
* ============LICENSE_START=======================================================
* ONAP - SO
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.mso.bpmn.core.xml;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.openecomp.mso.logger.MsoLogger;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* XML transformation methods and other useful functions.
*/
public final class XmlTool {
private static final Map<String, Integer> ENTITIES = new HashMap<>();
private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.BPEL);
static {
ENTITIES.put("amp", 38);
ENTITIES.put("quot", 34);
ENTITIES.put("lt", 60);
ENTITIES.put("gt", 62);
}
/**
* Instantiation is not allowed.
*/
private XmlTool() {
}
/**
* Normalizes and formats XML. This method consolidates and moves all namespace
* declarations to the root element. The result will not have an XML prolog or
* a trailing newline.
* @param xml the XML to normalize
* @throws IOException
* @throws TransformerException
* @throws ParserConfigurationException
* @throws SAXException
* @throws XPathExpressionException
*/
public static String normalize(Object xml) throws IOException, TransformerException,
ParserConfigurationException, SAXException, XPathExpressionException {
if (xml == null) {
return null;
}
Source xsltSource = new StreamSource(new StringReader(
readResourceFile("normalize-namespaces.xsl")));
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder db = dbFactory.newDocumentBuilder();
InputSource source = new InputSource(new StringReader(String.valueOf(xml)));
Document doc = db.parse(source);
// Start of code to remove whitespace outside of tags
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate(
"//text()[normalize-space()='']", doc, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
node.getParentNode().removeChild(node);
}
// End of code to remove whitespace outside of tags
// the factory pattern supports different XSLT processors
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(xsltSource);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
return writer.toString().trim();
}
/**
* Encodes a value so it can be used inside an XML text element.
* @param s the string to encode
* @return the encoded string
*/
public static String encode(Object value) {
if (value == null) {
return null;
}
String s = String.valueOf(value);
StringBuilder out = new StringBuilder();
boolean modified = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
out.append("<");
modified = true;
} else if (c == '>') {
out.append(">");
modified = true;
} else if (c == '&') {
out.append("&");
modified = true;
} else if (c < 32 || c > 126) {
out.append("&#" + (int)c + ";");
modified = true;
} else {
out.append(c);
}
}
if (modified) {
return out.toString();
} else {
return s;
}
}
/**
* Encodes a value so it can be used inside an XML attribute.
* @param s the string to encode
* @return the encoded string
*/
public static String encodeAttr(Object value) {
if (value == null) {
return null;
}
String s = String.valueOf(value);
StringBuilder out = new StringBuilder();
boolean modified = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '<') {
out.append("<");
modified = true;
} else if (c == '>') {
out.append(">");
modified = true;
} else if (c == '"') {
out.append(""");
modified = true;
} else if (c == '&') {
out.append("&");
modified = true;
} else if (c < 32 || c > 126) {
out.append("&#" + (int)c + ";");
modified = true;
} else {
out.append(c);
}
}
if (modified) {
return out.toString();
} else {
return s;
}
}
/**
* Decodes XML entities in a string value
* @param value a value with embedded XML entities
* @return the decoded string
*/
public static String decode(Object value) {
if (value == null) {
return null;
}
String s = String.valueOf(value);
StringBuilder out = new StringBuilder(s.length());
int ampIndex = s.indexOf("&");
int lastEnd = 0;
while (ampIndex >= 0) {
int nextAmpIndex = s.indexOf("&", ampIndex + 1);
int nextSemiIndex = s.indexOf(";", ampIndex + 1);
if (nextSemiIndex != -1 && (nextAmpIndex == -1 || nextSemiIndex < nextAmpIndex)) {
int code = -1;
String entity = s.substring(ampIndex + 1, nextSemiIndex);
try {
if (entity.startsWith("#")) {
code = Integer.parseInt(entity.substring(1), 10);
} else {
if (ENTITIES.containsKey(entity)) {
code = ENTITIES.get(entity);
}
}
} catch (NumberFormatException x) {
// Do nothing
}
out.append(s.substring(lastEnd, ampIndex));
lastEnd = nextSemiIndex + 1;
if (code >= 0 && code <= 0xffff) {
out.append((char) code);
} else {
out.append("&");
out.append(entity);
out.append(";");
}
}
ampIndex = nextAmpIndex;
}
out.append(s.substring(lastEnd));
return out.toString();
}
/**
* Removes the preamble, if present, from an XML document.
* @param xml the XML document
* @return a possibly modified document
*/
public static String removePreamble(Object xml) {
if (xml == null) {
return null;
}
return String.valueOf(xml).replaceAll("(<\\?[^<]*\\?>\\s*[\\r\\n]*)?", "");
}
/**
* Removes namespaces and namespace declarations from an XML document.
* @param xml the XML document
* @return a possibly modified document
*/
public static String removeNamespaces(Object xml) {
if (xml == null) {
LOGGER.debug("removeNamespaces input object is null , returning null");
return null;
}
String text = String.valueOf(xml);
// remove xmlns declaration
text = text.replaceAll("xmlns.*?(\"|\').*?(\"|\')", "");
// remove opening tag prefix
text = text.replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
// remove closing tags prefix
text = text.replaceAll("(</)(\\w+:)(.*?>)", "$1$3");
// remove extra spaces left when xmlns declarations are removed
text = text.replaceAll("\\s+>", ">");
return text;
}
/**
* Reads the specified resource file and return the contents as a string.
* @param file Name of the resource file
* @return the contents of the resource file as a String
* @throws IOException if there is a problem reading the file
*/
private static String readResourceFile(String file) throws IOException {
try (InputStream stream = XmlTool.class.getClassLoader().getResourceAsStream(file);
Reader reader = new InputStreamReader(stream, "UTF-8")) {
StringBuilder out = new StringBuilder();
char[] buf = new char[1024];
int n;
while ((n = reader.read(buf)) >= 0) {
out.append(buf, 0, n);
}
return out.toString();
} catch (Exception e) {
LOGGER.debug("Exception at readResourceFile stream: " + e);
return null;
}
}
/**
* Parses the XML document String for the first occurrence of the specified element tag.
* If found, the value associated with that element tag is replaced with the new value
* and a String containing the modified XML document is returned. If the XML passed is
* null or the element tag is not found in the document, null will be returned.
* @param xml String containing the original XML document.
* @param elementTag String containing the tag of the element to be modified.
* @param newValue String containing the new value to be used to modify the corresponding element.
* @return the contents of the modified XML document as a String or null/empty if the modification failed.
* @throws IOException, TransformerException, ParserConfigurationException, SAXException
*/
public static Optional<String> modifyElement(String xml, String elementTag, String newValue) throws IOException, TransformerException,
ParserConfigurationException, SAXException {
if (xml == null || xml.isEmpty()) {
// no XML content to be modified, return empty
return Optional.empty();
}
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder db = dbFactory.newDocumentBuilder();
InputSource source = new InputSource(new StringReader(xml));
Document doc = db.parse(source);
Node modNode = doc.getElementsByTagName(elementTag).item(0);
if (modNode == null) {
// did not find the specified element to be modified, return empty
//System.out.println("Did not find element tag " + elementTag + " in XML");
return Optional.empty();
} else {
modNode.setTextContent(newValue);
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
// return the modified String representation of the XML
return Optional.of(writer.toString().trim());
}
}
|