]> git.basschouten.com Git - openhab-addons.git/blob
421a5cc69678bb95454a60c4d19e462f365f88b7
[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.gce.internal.model;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.Comparator;
19 import java.util.List;
20 import java.util.Optional;
21 import java.util.stream.Collectors;
22 import java.util.stream.IntStream;
23
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.openhab.binding.gce.internal.handler.Ipx800EventListener;
30 import org.openhab.core.io.net.http.HttpUtil;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.w3c.dom.Document;
34 import org.w3c.dom.Element;
35 import org.w3c.dom.Node;
36 import org.w3c.dom.NodeList;
37 import org.xml.sax.SAXException;
38
39 /**
40  * This class takes care of interpreting the status.xml file
41  *
42  * @author GaĆ«l L'hopital - Initial contribution
43  */
44 @NonNullByDefault
45 public class StatusFileInterpreter {
46     private static final String URL_TEMPLATE = "http://%s/globalstatus.xml";
47
48     private final Logger logger = LoggerFactory.getLogger(StatusFileInterpreter.class);
49     private final DocumentBuilder builder;
50     private final String url;
51     private final Ipx800EventListener listener;
52
53     private Optional<Document> doc = Optional.empty();
54
55     public enum StatusEntry {
56         VERSION,
57         CONFIG_MAC
58     }
59
60     public StatusFileInterpreter(String hostname, Ipx800EventListener listener) {
61         this.url = String.format(URL_TEMPLATE, hostname);
62         this.listener = listener;
63         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
64         // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
65         try {
66             factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
67             factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
68             factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
69             factory.setXIncludeAware(false);
70             factory.setExpandEntityReferences(false);
71             builder = factory.newDocumentBuilder();
72         } catch (ParserConfigurationException e) {
73             logger.warn("Error initializing StatusFileInterpreter :{}", e.getMessage());
74             throw new IllegalArgumentException(e);
75         }
76     }
77
78     public void read() {
79         try {
80             String statusPage = HttpUtil.executeUrl("GET", url, 5000);
81             InputStream inputStream = new ByteArrayInputStream(statusPage.getBytes());
82             Document document = builder.parse(inputStream);
83             document.getDocumentElement().normalize();
84             inputStream.close();
85             this.doc = Optional.of(document);
86             pushDatas();
87         } catch (IOException | SAXException e) {
88             logger.warn("Unable to read IPX800 status page : {}", e.getMessage());
89         }
90     }
91
92     private void pushDatas() {
93         getRoot().ifPresent(root -> {
94             PortDefinition.asStream().forEach(portDefinition -> {
95                 List<Node> xmlNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName());
96                 xmlNodes.forEach(xmlNode -> {
97                     String sPortNum = xmlNode.getNodeName().replace(portDefinition.getNodeName(), "");
98                     int portNum = Integer.parseInt(sPortNum) + 1;
99                     double value = Double.parseDouble(xmlNode.getTextContent().replace("dn", "1").replace("up", "0"));
100                     listener.dataReceived(String.format("%s%d", portDefinition.getPortName(), portNum), value);
101                 });
102             });
103         });
104     }
105
106     public String getElement(StatusEntry entry) {
107         return getRoot().map(root -> root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent())
108                 .orElse("");
109     }
110
111     private List<Node> getMatchingNodes(NodeList nodeList, String criteria) {
112         return IntStream.range(0, nodeList.getLength()).boxed().map(nodeList::item)
113                 .filter(node -> node.getNodeName().startsWith(criteria)).sorted(Comparator.comparing(Node::getNodeName))
114                 .collect(Collectors.toList());
115     }
116
117     public int getMaxNumberofNodeType(PortDefinition portDefinition) {
118         return getRoot().map(root -> getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName()).size())
119                 .orElse(0);
120     }
121
122     private Optional<Element> getRoot() {
123         if (doc.isEmpty()) {
124             read();
125         }
126         return Optional.ofNullable(doc.map(Document::getDocumentElement).orElse(null));
127     }
128 }