1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
package org.apache.any23.validator; |
19 | |
|
20 | |
import org.apache.any23.extractor.html.DomUtils; |
21 | |
import org.w3c.dom.Attr; |
22 | |
import org.w3c.dom.Document; |
23 | |
import org.w3c.dom.NamedNodeMap; |
24 | |
import org.w3c.dom.Node; |
25 | |
|
26 | |
import java.net.URI; |
27 | |
import java.util.List; |
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
|
35 | |
public class DefaultDOMDocument implements DOMDocument { |
36 | |
|
37 | |
private URI documentURI; |
38 | |
|
39 | |
private Document document; |
40 | |
|
41 | 0 | public DefaultDOMDocument(URI documentURI, Document document) { |
42 | 0 | if(documentURI == null) { |
43 | 0 | throw new NullPointerException("documentURI cannot be null."); |
44 | |
} |
45 | 0 | if(document == null) { |
46 | 0 | throw new NullPointerException("document cannot be null."); |
47 | |
} |
48 | 0 | this.documentURI = documentURI; |
49 | 0 | this.document = document; |
50 | 0 | } |
51 | |
|
52 | |
public URI getDocumentURI() { |
53 | 0 | return documentURI; |
54 | |
} |
55 | |
|
56 | |
public Document getOriginalDocument() { |
57 | 0 | return document; |
58 | |
} |
59 | |
|
60 | |
public List<Node> getNodes(String xPath) { |
61 | 0 | return DomUtils.findAll(document, xPath); |
62 | |
} |
63 | |
|
64 | |
public Node getNode(String xPath) { |
65 | 0 | List<Node> nodes = DomUtils.findAll(document, xPath); |
66 | 0 | if(nodes.size() == 0) { |
67 | 0 | throw new IllegalArgumentException( |
68 | |
String.format("Cannot find node at XPath '%s'", xPath) |
69 | |
); |
70 | |
} |
71 | 0 | if(nodes.size() > 1) { |
72 | 0 | throw new IllegalArgumentException( |
73 | |
String.format("The given XPath '%s' corresponds to more than one node.", xPath) |
74 | |
); |
75 | |
} |
76 | 0 | return nodes.get(0); |
77 | |
} |
78 | |
|
79 | |
public void addAttribute(String xPath, String attrName, String attrValue) { |
80 | 0 | Node node = getNode(xPath); |
81 | 0 | NamedNodeMap namedNodeMap = node.getAttributes(); |
82 | 0 | Attr attr = document.createAttribute(attrName); |
83 | 0 | attr.setNodeValue(attrValue); |
84 | 0 | namedNodeMap.setNamedItem(attr); |
85 | 0 | } |
86 | |
|
87 | |
public List<Node> getNodesWithAttribute(String attrName) { |
88 | 0 | return DomUtils.findAllByAttributeName(document, attrName); |
89 | |
} |
90 | |
|
91 | |
} |