]> git.basschouten.com Git - openhab-addons.git/blob
57b520ed2c74b5c6ab4f691b3db4bd091efa8f4a
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.stream.Collectors;
21 import java.util.stream.IntStream;
22
23 import javax.xml.parsers.DocumentBuilder;
24 import javax.xml.parsers.DocumentBuilderFactory;
25 import javax.xml.parsers.ParserConfigurationException;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
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     private final Logger logger = LoggerFactory.getLogger(StatusFileInterpreter.class);
48     private final String hostname;
49     private @Nullable Document doc;
50     private final Ipx800EventListener listener;
51
52     public static enum StatusEntry {
53         VERSION,
54         CONFIG_MAC;
55     }
56
57     public StatusFileInterpreter(String hostname, Ipx800EventListener listener) {
58         this.hostname = hostname;
59         this.listener = listener;
60     }
61
62     public void read() {
63         try {
64             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
65             // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
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             DocumentBuilder builder = factory.newDocumentBuilder();
72             String statusPage = HttpUtil.executeUrl("GET", String.format(URL_TEMPLATE, hostname), 5000);
73             InputStream inputStream = new ByteArrayInputStream(statusPage.getBytes());
74             Document document = builder.parse(inputStream);
75             document.getDocumentElement().normalize();
76             doc = document;
77             pushDatas();
78             inputStream.close();
79         } catch (IOException | SAXException | ParserConfigurationException e) {
80             logger.warn("Unable to read IPX800 status page : {}", e.getMessage());
81             doc = null;
82         }
83     }
84
85     private void pushDatas() {
86         Element root = getRoot();
87         if (root != null) {
88             PortDefinition.asStream().forEach(portDefinition -> {
89                 List<Node> xmlNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName());
90                 xmlNodes.forEach(xmlNode -> {
91                     String sPortNum = xmlNode.getNodeName().replace(portDefinition.getNodeName(), "");
92                     int portNum = Integer.parseInt(sPortNum) + 1;
93                     double value = Double.parseDouble(xmlNode.getTextContent().replace("dn", "1").replace("up", "0"));
94                     listener.dataReceived(String.format("%s%d", portDefinition.getPortName(), portNum), value);
95                 });
96             });
97         }
98     }
99
100     public String getElement(StatusEntry entry) {
101         Element root = getRoot();
102         if (root != null) {
103             return root.getElementsByTagName(entry.name().toLowerCase()).item(0).getTextContent();
104         } else {
105             return "";
106         }
107     }
108
109     private List<Node> getMatchingNodes(NodeList nodeList, String criteria) {
110         return IntStream.range(0, nodeList.getLength()).boxed().map(nodeList::item)
111                 .filter(node -> node.getNodeName().startsWith(criteria))
112                 .sorted(Comparator.comparing(o -> o.getNodeName())).collect(Collectors.toList());
113     }
114
115     public int getMaxNumberofNodeType(PortDefinition portDefinition) {
116         Element root = getRoot();
117         if (root != null) {
118             List<Node> filteredNodes = getMatchingNodes(root.getChildNodes(), portDefinition.getNodeName());
119             return filteredNodes.size();
120         }
121         return 0;
122     }
123
124     private @Nullable Element getRoot() {
125         if (doc == null) {
126             read();
127         }
128         if (doc != null) {
129             return doc.getDocumentElement();
130         }
131         return null;
132     }
133 }