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
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.api.utils;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.io.IOUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* XML Parsing tool using XPATH. It's recommended to use StaxParser when parsing big XML files.
*
* @since 1.10
* @deprecated since 5.6 plugins should use their own dependencies
*/
@Deprecated
public class XpathParser {
private static final String CAN_NOT_PARSE_XML = "can not parse xml : ";
private Element root = null;
private Document doc = null;
private DocumentBuilder builder;
private XPath xpath;
private Map<String, XPathExpression> compiledExprs = new HashMap<>();
public XpathParser() {
DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance();
try {
bf.setFeature("http://apache.org/xml/features/validation/schema", false);
bf.setFeature("http://xml.org/sax/features/external-general-entities", false);
bf.setFeature("http://xml.org/sax/features/validation", false);
bf.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
bf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
bf.setFeature("http://apache.org/xml/features/allow-java-encodings", true);
} catch (ParserConfigurationException e) {
Logger log = Loggers.get(this.getClass().getName());
log.error("Error occured during features set up.", e);
}
try {
bf.setNamespaceAware(false);
bf.setValidating(false);
builder = bf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new XmlParserException("can not create a XML parser", e);
}
}
public void parse(@Nullable File file) {
if (file == null || !file.exists()) {
throw new XmlParserException("File not found : " + file);
}
BufferedReader buffer = null;
try {
buffer = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
parse(buffer);
} catch (IOException e) {
throw new XmlParserException("can not parse the file " + file.getAbsolutePath(), e);
} finally {
IOUtils.closeQuietly(buffer);
}
}
public void parse(InputStream stream) {
BufferedReader buffer = null;
try {
buffer = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
parse(buffer);
} catch (IOException e) {
throw new XmlParserException("can not parse the stream", e);
} finally {
IOUtils.closeQuietly(buffer);
}
}
private void parse(BufferedReader buffer) throws IOException {
parse(IOUtils.toString(buffer));
}
public void parse(String xml) {
try {
String fixedXml = fixUnicodeChar(xml);
doc = builder.parse(new ByteArrayInputStream(fixedXml.getBytes(StandardCharsets.UTF_8)));
XPathFactory factory = XPathFactory.newInstance();
xpath = factory.newXPath();
} catch (IOException | SAXException e) {
throw new XmlParserException(CAN_NOT_PARSE_XML + xml, e);
}
}
public Element getRoot() {
if (root == null && doc != null) {
root = doc.getDocumentElement();
}
return root;
}
public Document getDocument() {
return doc;
}
public Element getChildElement(Element base, String elementName) {
NodeList childrens = base.getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
Node nde = childrens.item(i);
if (nde.getNodeType() == Node.ELEMENT_NODE) {
return (Element) nde;
}
}
return null;
}
public Element getChildElement(String elementName) {
NodeList childrens = getRoot().getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
Node nde = childrens.item(i);
if (nde.getNodeType() == Node.ELEMENT_NODE) {
return (Element) nde;
}
}
return null;
}
public List<Element> getChildElements(String elementName) {
List<Element> rtrVal = new ArrayList<>();
NodeList childrens = getRoot().getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
Node nde = childrens.item(i);
if (nde.getNodeType() == Node.ELEMENT_NODE) {
rtrVal.add((Element) nde);
}
}
return rtrVal;
}
public List<Element> getChildElements(Element base, String elementName) {
List<Element> rtrVal = new ArrayList<>();
NodeList childrens = base.getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
Node nde = childrens.item(i);
if (nde.getNodeType() == Node.ELEMENT_NODE) {
rtrVal.add((Element) nde);
}
}
return rtrVal;
}
public String getChildElementValue(Element base, String elementName) {
NodeList childrens = base.getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
if (childrens.item(i).getNodeType() == Node.ELEMENT_NODE) {
return childrens.item(i).getFirstChild().getNodeValue();
}
}
return null;
}
public String getElementValue(Node base) {
if (base.getNextSibling() != null && base.getNextSibling().getNodeType() == Node.TEXT_NODE) {
return base.getNextSibling().getNodeValue();
} else if (base.getFirstChild() != null && base.getFirstChild().getNodeType() == Node.TEXT_NODE) {
return base.getFirstChild().getNodeValue();
}
return null;
}
public String getChildElementValue(String elementName) {
NodeList childrens = getRoot().getElementsByTagName(elementName);
for (int i = 0; i < childrens.getLength(); i++) {
if (childrens.item(i).getNodeType() == Node.ELEMENT_NODE) {
return childrens.item(i).getFirstChild().getNodeValue();
}
}
return null;
}
public Object executeXPath(Node node, QName qname, String xPathExpression) {
XPathExpression expr = compiledExprs.get(xPathExpression);
try {
if (expr == null) {
expr = xpath.compile(xPathExpression);
compiledExprs.put(xPathExpression, expr);
}
return expr.evaluate(node, qname);
} catch (XPathExpressionException e) {
throw new XmlParserException("Unable to evaluate xpath expression :" + xPathExpression, e);
}
}
public String executeXPath(String xPathExpression) {
return (String) executeXPath(doc, XPathConstants.STRING, xPathExpression);
}
public String executeXPath(Node node, String xPathExpression) {
return (String) executeXPath(node, XPathConstants.STRING, xPathExpression);
}
public NodeList executeXPathNodeList(String xPathExpression) {
return (NodeList) executeXPath(doc, XPathConstants.NODESET, xPathExpression);
}
public NodeList executeXPathNodeList(Node node, String xPathExpression) {
return (NodeList) executeXPath(node, XPathConstants.NODESET, xPathExpression);
}
public Node executeXPathNode(Node node, String xPathExpression) {
return (Node) executeXPath(node, XPathConstants.NODE, xPathExpression);
}
/**
* Fix the error occured when parsing a string containing unicode character
* Example : {@code &u20ac;} will be replaced by {@code €}
*/
protected String fixUnicodeChar(String text) {
String unicode = "&u";
StringBuilder replace = new StringBuilder(text);
if (text.indexOf(unicode) >= 0) {
Pattern p = Pattern.compile("&u([0-9a-fA-F]{1,4});");
Matcher m = p.matcher(replace.toString());
int nbFind = 0;
while (m.find()) {
// Add one index each time because we add one character each time (&u -> &#x)
replace.replace(m.start() + nbFind, m.end() + nbFind, "&#x" + m.group(1) + ";");
nbFind++;
}
}
return replace.toString();
}
}
|