]> git.basschouten.com Git - openhab-addons.git/blob
5305221272549620a76ed2a874b86f009e18fd64
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.ecovacs.internal.api.util;
14
15 import java.io.StringReader;
16 import java.util.Optional;
17
18 import javax.xml.xpath.XPath;
19 import javax.xml.xpath.XPathConstants;
20 import javax.xml.xpath.XPathExpressionException;
21 import javax.xml.xpath.XPathFactory;
22
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.w3c.dom.Node;
26 import org.w3c.dom.NodeList;
27 import org.xml.sax.InputSource;
28
29 /**
30  * @author Danny Baumann - Initial contribution
31  */
32 @NonNullByDefault
33 public class XPathUtils {
34     private static @Nullable XPathFactory factory;
35
36     public static Node getFirstXPathMatch(String xml, String xpathExpression) throws DataParsingException {
37         NodeList nodes = getXPathMatches(xml, xpathExpression);
38         if (nodes.getLength() == 0) {
39             throw new DataParsingException("No nodes matching expression " + xpathExpression + " in XML " + xml);
40         }
41         return nodes.item(0);
42     }
43
44     public static Optional<Node> getFirstXPathMatchOpt(String xml, String xpathExpression) throws DataParsingException {
45         NodeList nodes = getXPathMatches(xml, xpathExpression);
46         return nodes.getLength() == 0 ? Optional.empty() : Optional.of(nodes.item(0));
47     }
48
49     public static NodeList getXPathMatches(String xml, String xpathExpression) throws DataParsingException {
50         try {
51             InputSource source = new InputSource(new StringReader(xml));
52             return (NodeList) newXPath().evaluate(xpathExpression, source, XPathConstants.NODESET);
53         } catch (XPathExpressionException e) {
54             throw new DataParsingException(e);
55         }
56     }
57
58     @SuppressWarnings("null") // null annotations don't recognize FACTORY can not be null in return statement
59     private static XPath newXPath() {
60         synchronized (XPathUtils.class) {
61             if (factory == null) {
62                 factory = XPathFactory.newInstance();
63             }
64             return factory.newXPath();
65         }
66     }
67 }