DOMParser.java
2.74 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
/*
* Decompiled with CFR 0_118.
*/
package com.day.cq.searchpromote.xml;
import com.day.cq.searchpromote.SearchPromoteException;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class DOMParser {
public Element parseXML(InputSource xml) throws SearchPromoteException {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
String FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
factory.setFeature(FEATURE, true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(xml);
return document.getDocumentElement();
}
catch (ParserConfigurationException e) {
throw new SearchPromoteException("Unable to create XML parser", e);
}
catch (SAXParseException e) {
throw new SearchPromoteException("XML syntax error. (Line: " + e.getLineNumber() + " Column: " + e.getColumnNumber() + ")", e);
}
catch (SAXException e) {
throw new SearchPromoteException("XML syntax error. ", e);
}
catch (IOException e) {
throw new SearchPromoteException("XML could not be read.", e);
}
}
protected Element getElement(Element parent, String name, boolean required) throws SearchPromoteException {
NodeList children = parent.getChildNodes();
Element found = null;
for (int i = 0; i < children.getLength(); ++i) {
Node child = children.item(i);
if (child.getNodeType() != 1 || !name.equals(child.getNodeName())) continue;
if (found != null) {
throw new SearchPromoteException("Duplicate configuration element " + name + " in " + parent.getNodeName() + ".");
}
found = (Element)child;
}
if (required && found == null) {
throw new SearchPromoteException("Configuration element " + name + " not found in " + parent.getNodeName() + ".");
}
return found;
}
protected String getAttribute(Element element, String name) throws SearchPromoteException {
Attr attribute = element.getAttributeNode(name);
if (attribute != null) {
return attribute.getValue();
}
throw new SearchPromoteException("Configuration attribute " + name + " not found in " + element.getNodeName() + ".");
}
}