-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathStructuredNode.java
426 lines (390 loc) · 14.4 KB
/
StructuredNode.java
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
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.kernel.xml;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Value;
import sirius.kernel.health.Exceptions;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.namespace.NamespaceContext;
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 java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Represents a structured node, which is part of a {@link StructuredInput}.
* <p>
* This is basically a XML node which can be queried using xpath.
*/
public class StructuredNode {
private static final XPathFactory XPATH = XPathFactory.newInstance();
private final Node node;
private final NamespaceContext namespaceContext;
/**
* Wraps the given node
*
* @param root the node to wrap
*/
protected StructuredNode(@Nonnull Node root, NamespaceContext namespaceContext) {
this.node = root;
this.namespaceContext = namespaceContext;
}
/**
* Wraps the given W3C node into a structured node.
*
* @param node the node to wrap
* @return a wrapped instance of the given node
*/
@Nonnull
public static StructuredNode of(@Nonnull Node node) {
return new StructuredNode(node, null);
}
/**
* Wraps the given W3C node into a structured node.
*
* @param node the node to wrap
* @param namespaceContext the context to use in order to resolve namespace prefixes
* @return a wrapped instance of the given node
*/
@Nonnull
public static StructuredNode of(@Nonnull Node node, @Nullable NamespaceContext namespaceContext) {
return new StructuredNode(node, namespaceContext);
}
/**
* Returns the current nodes name.
*
* @return returns the name of the node represented by this object
*/
@Nonnull
public String getNodeName() {
return node.getNodeName();
}
/**
* Returns the underlying W3C Node.
*
* @return the underlying node
*/
@Nonnull
public Node getNode() {
return node;
}
/**
* Determines if the underlying node is actually an instance of the given class.
*
* @param type the class to check for
* @param <N> the node type to check for
* @return <tt>true</tt> if the underlying node is an instance of the given class, <tt>false</tt> otherwise
*/
public <N extends Node> boolean is(Class<N> type) {
return type.isInstance(node);
}
/**
* Returns the underlying node casted to the given type.
* <p>
* Used {@link #is(Class)} to check if the node actually is an instance of the target class. Otherwise a
* <tt>ClassCastException</tt> will be thrown.
*
* @param type the target class for the cast
* @param <N> the node type to cast to
* @return the underlying node casted to the target type.
* @throws java.lang.ClassCastException if the underlying node isn't an instance of the given class.
*/
@SuppressWarnings("unchecked")
public <N extends Node> N as(Class<N> type) {
return (N) node;
}
/**
* Returns a list of all children of this DOM node.
*
* @return a list containing all children of this node. If no children exist, an empty list will be returned.
*/
@Nonnull
public List<StructuredNode> getChildren() {
NodeList result = node.getChildNodes();
List<StructuredNode> resultList = new ArrayList<>(result.getLength());
for (int i = 0; i < result.getLength(); i++) {
resultList.add(new StructuredNode(result.item(i), namespaceContext));
}
return resultList;
}
/**
* Returns a map of all attribute values of this DOM node with their names as keys.
*
* @return a map containing all attributes of this node. If no attributes exist, an empty map will be returned.
*/
@Nonnull
public Map<String, String> getAttributes() {
Map<String, String> attributes = new HashMap<>();
NamedNodeMap result = node.getAttributes();
if (result != null) {
for (int i = 0; i < result.getLength(); i++) {
attributes.put(result.item(i).getNodeName(), result.item(i).getNodeValue());
}
}
return attributes;
}
/**
* Returns the value of the attribute with the given name.
*
* @param name the name of the attribute to read
* @return a {@link Value} filled with the attribute value if an attribute exists for the given name, an empty
* {@link Value} otherwise.
*/
@Nonnull
public Value getAttribute(String name) {
NamedNodeMap attributes = getNode().getAttributes();
if (attributes != null) {
Node attribute = attributes.getNamedItem(name);
if (attribute != null) {
return Value.of(attribute.getNodeValue());
}
}
return Value.EMPTY;
}
/**
* Returns a given node at the relative path.
*
* @param xpath the xpath used to retrieve the resulting node
* @return the node returned by the given xpath expression
* @throws IllegalArgumentException if an invalid xpath was given
*/
@Nullable
public StructuredNode queryNode(String xpath) {
try {
Node result = (Node) compile(xpath).evaluate(node, XPathConstants.NODE);
if (result == null) {
return null;
}
return new StructuredNode(result, namespaceContext);
} catch (XPathExpressionException exception) {
throw new IllegalArgumentException(exception);
}
}
private XPathExpression compile(String xpath) throws XPathExpressionException {
XPath xPathInstance = XPATH.newXPath();
if (namespaceContext != null) {
xPathInstance.setNamespaceContext(namespaceContext);
}
return xPathInstance.compile(xpath);
}
/**
* Returns a list of nodes at the relative path.
*
* @param xpath the xpath used to retrieve the resulting nodes
* @return the list of nodes returned by the given xpath expression
* @throws IllegalArgumentException if an invalid xpath was given
*/
@Nonnull
public List<StructuredNode> queryNodeList(String xpath) {
try {
NodeList result = (NodeList) compile(xpath).evaluate(node, XPathConstants.NODESET);
List<StructuredNode> resultList = new ArrayList<>(result.getLength());
for (int i = 0; i < result.getLength(); i++) {
resultList.add(new StructuredNode(result.item(i), namespaceContext));
}
return resultList;
} catch (XPathExpressionException exception) {
throw new IllegalArgumentException(exception);
}
}
/**
* Returns the property at the given relative path as string.
* <p>
* Note that this method will return an untrimmed string and also <tt>null</tt> if no value is present.
*
* @param path the xpath used to retrieve property
* @return a string representation of the value returned by the given xpath expression or <tt>null</tt> if no value
* is present
* @throws IllegalArgumentException if an invalid xpath was given
* @see #queryString(String)
*/
@Nullable
public String queryRawString(String path) {
try {
Object result = compile(path).evaluate(node, XPathConstants.NODE);
if (result == null) {
return null;
}
if (result instanceof Node child) {
return child.getTextContent();
}
return result.toString();
} catch (XPathExpressionException exception) {
throw new IllegalArgumentException(exception);
}
}
/**
* Returns the property at the given relative path as trimmed string.
* <p>
* Note that this method will return <tt>null</tt> if no value is present.
*
* @param path the xpath used to retrieve property
* @return a trimmed string representation of the value returned by the given xpath expression or <tt>null</tt>
* if no value is present
* @throws IllegalArgumentException if an invalid xpath was given
* @see #queryRawString(String)
*/
@Nullable
public String queryString(String path) {
// The internal call to Value.asOptionalString will perform a trim but still yield null if the original
// value is null
return Value.of(queryRawString(path)).asOptionalString().orElse(null);
}
/**
* Queries a {@link sirius.kernel.commons.Value} by evaluating the given xpath.
*
* @param path the xpath used to retrieve property.
* @return a Value wrapping the value returned by the given xpath expression. Note that string values are
* automatically trimmed.
* @throws java.lang.IllegalArgumentException if an invalid xpath was given
* @see #queryRawValue(String)
*/
@Nonnull
public Value queryValue(String path) {
return Value.of(queryString(path));
}
/**
* Queries a {@link sirius.kernel.commons.Value} by evaluating the given xpath.
*
* @param path the xpath used to retrieve property.
* @return a Value wrapping the value returned by the given xpath expression. Note that this will return the
* unmodified (untrimmed) contents wrapped as value.
* @throws java.lang.IllegalArgumentException if an invalid xpath was given
* @see #queryValue(String)
*/
@Nonnull
public Value queryRawValue(String path) {
return Value.of(queryRawString(path));
}
/**
* Queries a string via the given XPath. All XML is converted to a string.
*
* @param path the xpath used to retrieve the xml sub tree
* @return a string representing the xml sub-tree returned by the given xpath expression
* @throws IllegalArgumentException if an invalid xpath was given
*/
@Nullable
public String queryXMLString(String path) {
return queryXMLString(path, true);
}
/**
* Queries a string via the given XPath. All inner XML is converted to a string.
*
* @param path the xpath used to retrieve the xml sub tree
* @return a string representing the xml sub-tree returned by the given xpath expression
* @throws IllegalArgumentException if an invalid xpath was given
*/
@Nullable
public String queryInnerXMLString(String path) {
return queryXMLString(path, false);
}
@Nullable
private String queryXMLString(String path, boolean includeOuter) {
try {
XPath xpath = XPATH.newXPath();
Object result = xpath.evaluate(path, node, XPathConstants.NODE);
if (result == null) {
return null;
}
if (result instanceof Node child) {
return serializeNodeAsXML(child, includeOuter);
}
return result.toString().trim();
} catch (XPathExpressionException exception) {
throw new IllegalArgumentException(exception);
}
}
private String serializeNodeAsXML(Node result, boolean includeOuter) {
try {
StringWriter writer = new StringWriter();
XMLGenerator.writeXML(result, writer, StandardCharsets.UTF_8.name(), true, includeOuter);
return writer.toString();
} catch (Exception exception) {
Exceptions.handle(exception);
return null;
}
}
/**
* Checks whether a node or non-empty content is reachable via the given
* XPath.
*
* @param path the xpath to be checked
* @return <tt>true</tt> if a node or non empty property was found, <tt>false</tt> otherwise
* @throws IllegalArgumentException if an invalid xpath was given
*/
public boolean isFilled(String path) {
return Strings.isFilled(queryString(path));
}
/**
* Checks whether a node is not reachable or has empty content via the given
* XPath.
*
* @param path the xpath to be checked
* @return <tt>true</tt> if no node or a empty property was found, <tt>false</tt> otherwise
* @throws IllegalArgumentException if an invalid xpath was given
*/
public boolean isEmpty(String path) {
return Strings.isEmpty(queryString(path));
}
/**
* Iterates through the sub-tree and invokes the given handler for each child node.
*
* @param nodeHandler the handler invoked for each child element
*/
public void visitNodes(Consumer<StructuredNode> nodeHandler) {
visit(nodeHandler, null);
}
/**
* Iterates through the sub-tree and invokes the given handler for each text node.
*
* @param textNodeHandler the handler invoked for each text node
*/
public void visitTexts(Consumer<Node> textNodeHandler) {
visit(null, textNodeHandler);
}
/**
* Iterates through the sub-tree and invokes the appropriate handler for each child node.
*
* @param nodeHandler the handler invoked for each element node
* @param textNodeHandler the handler invoked for each text node
*/
public void visit(@Nullable Consumer<StructuredNode> nodeHandler, @Nullable Consumer<Node> textNodeHandler) {
if (node.getNodeType() == Node.TEXT_NODE) {
if (textNodeHandler != null) {
textNodeHandler.accept(node);
}
} else if (node.getNodeType() == Node.ELEMENT_NODE) {
if (nodeHandler != null) {
nodeHandler.accept(this);
}
getChildren().forEach(c -> c.visit(nodeHandler, textNodeHandler));
}
}
@Override
public String toString() {
try {
StringWriter writer = new StringWriter();
XMLGenerator.writeXML(node, writer, StandardCharsets.UTF_8.name(), true);
return writer.toString();
} catch (Exception exception) {
Exceptions.handle(exception);
return node.toString();
}
}
}