]> git.basschouten.com Git - openhab-addons.git/blob
f4fe134bc2aae52216154f3e7f93f1253729a7c6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.insteon.internal.device;
14
15 import java.io.File;
16 import java.io.FileInputStream;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Map.Entry;
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.insteon.internal.device.DeviceType.FeatureGroup;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.w3c.dom.Document;
33 import org.w3c.dom.Element;
34 import org.w3c.dom.Node;
35 import org.w3c.dom.NodeList;
36 import org.xml.sax.SAXException;
37
38 /**
39  * Reads the device types from an xml file.
40  *
41  * @author Daniel Pfrommer - Initial contribution
42  * @author Bernd Pfrommer - openHAB 1 insteonplm binding
43  * @author Rob Nielsen - Port to openHAB 2 insteon binding
44  */
45 @NonNullByDefault
46 public class DeviceTypeLoader {
47     private static final Logger logger = LoggerFactory.getLogger(DeviceTypeLoader.class);
48     private Map<String, DeviceType> deviceTypes = new HashMap<>();
49     private static DeviceTypeLoader deviceTypeLoader = new DeviceTypeLoader();
50
51     private DeviceTypeLoader() {
52     } // private so nobody can call it
53
54     /**
55      * Finds the device type for a given product key
56      *
57      * @param aProdKey product key to search for
58      * @return the device type, or null if not found
59      */
60     public @Nullable DeviceType getDeviceType(String aProdKey) {
61         return (deviceTypes.get(aProdKey));
62     }
63
64     /**
65      * Must call loadDeviceTypesXML() before calling this function!
66      *
67      * @return currently known device types
68      */
69     public Map<String, DeviceType> getDeviceTypes() {
70         return (deviceTypes);
71     }
72
73     /**
74      * Reads the device types from input stream and stores them in memory for
75      * later access.
76      *
77      * @param in the input stream from which to read
78      */
79     public void loadDeviceTypesXML(InputStream in) throws ParserConfigurationException, SAXException, IOException {
80         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
81         // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
82         dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
83         dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
84         dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
85         dbFactory.setXIncludeAware(false);
86         dbFactory.setExpandEntityReferences(false);
87         DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
88         Document doc = dBuilder.parse(in);
89         doc.getDocumentElement().normalize();
90         Node root = doc.getDocumentElement();
91         NodeList nodes = root.getChildNodes();
92         for (int i = 0; i < nodes.getLength(); i++) {
93             Node node = nodes.item(i);
94             if (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals("device")) {
95                 processDevice((Element) node);
96             }
97         }
98     }
99
100     /**
101      * Reads the device types from file and stores them in memory for later access.
102      *
103      * @param aFileName The name of the file to read from
104      * @throws ParserConfigurationException
105      * @throws SAXException
106      * @throws IOException
107      */
108     public void loadDeviceTypesXML(String aFileName) throws ParserConfigurationException, SAXException, IOException {
109         File file = new File(aFileName);
110         InputStream in = new FileInputStream(file);
111         loadDeviceTypesXML(in);
112     }
113
114     /**
115      * Process device node
116      *
117      * @param e name of the element to process
118      * @throws SAXException
119      */
120     private void processDevice(Element e) throws SAXException {
121         String productKey = e.getAttribute("productKey");
122         if (productKey.equals("")) {
123             throw new SAXException("device in device_types file has no product key!");
124         }
125         if (deviceTypes.containsKey(productKey)) {
126             logger.warn("overwriting previous definition of device {}", productKey);
127             deviceTypes.remove(productKey);
128         }
129         DeviceType devType = new DeviceType(productKey);
130
131         NodeList nodes = e.getChildNodes();
132         for (int i = 0; i < nodes.getLength(); i++) {
133             Node node = nodes.item(i);
134             if (node.getNodeType() != Node.ELEMENT_NODE) {
135                 continue;
136             }
137             Element subElement = (Element) node;
138             if (subElement.getNodeName().equals("model")) {
139                 devType.setModel(subElement.getTextContent());
140             } else if (subElement.getNodeName().equals("description")) {
141                 devType.setDescription(subElement.getTextContent());
142             } else if (subElement.getNodeName().equals("feature")) {
143                 processFeature(devType, subElement);
144             } else if (subElement.getNodeName().equals("feature_group")) {
145                 processFeatureGroup(devType, subElement);
146             }
147             deviceTypes.put(productKey, devType);
148         }
149     }
150
151     private String processFeature(DeviceType devType, Element e) throws SAXException {
152         String name = e.getAttribute("name");
153         if (name.equals("")) {
154             throw new SAXException("feature " + e.getNodeName() + " has feature without name!");
155         }
156         if (!name.equals(name.toLowerCase())) {
157             throw new SAXException("feature name '" + name + "' must be lower case");
158         }
159         if (!devType.addFeature(name, e.getTextContent())) {
160             throw new SAXException("duplicate feature: " + name);
161         }
162         return (name);
163     }
164
165     private String processFeatureGroup(DeviceType devType, Element e) throws SAXException {
166         String name = e.getAttribute("name");
167         if (name.equals("")) {
168             throw new SAXException("feature group " + e.getNodeName() + " has no name attr!");
169         }
170         String type = e.getAttribute("type");
171         if (type.equals("")) {
172             throw new SAXException("feature group " + e.getNodeName() + " has no type attr!");
173         }
174         FeatureGroup fg = new FeatureGroup(name, type);
175         NodeList nodes = e.getChildNodes();
176         for (int i = 0; i < nodes.getLength(); i++) {
177             Node node = nodes.item(i);
178             if (node.getNodeType() != Node.ELEMENT_NODE) {
179                 continue;
180             }
181             Element subElement = (Element) node;
182             if (subElement.getNodeName().equals("feature")) {
183                 fg.addFeature(processFeature(devType, subElement));
184             } else if (subElement.getNodeName().equals("feature_group")) {
185                 fg.addFeature(processFeatureGroup(devType, subElement));
186             }
187         }
188         if (!devType.addFeatureGroup(name, fg)) {
189             throw new SAXException("duplicate feature group " + name);
190         }
191         return (name);
192     }
193
194     /**
195      * Helper function for debugging
196      */
197     private void logDeviceTypes() {
198         for (Entry<String, DeviceType> dt : getDeviceTypes().entrySet()) {
199             String msg = String.format("%-10s->", dt.getKey()) + dt.getValue();
200             logger.debug("{}", msg);
201         }
202     }
203
204     /**
205      * Singleton instance function, creates DeviceTypeLoader
206      *
207      * @return DeviceTypeLoader singleton reference
208      */
209     @Nullable
210     public static synchronized DeviceTypeLoader instance() {
211         if (deviceTypeLoader.getDeviceTypes().isEmpty()) {
212             InputStream input = DeviceTypeLoader.class.getResourceAsStream("/device_types.xml");
213             try {
214                 if (input != null) {
215                     deviceTypeLoader.loadDeviceTypesXML(input);
216                 } else {
217                     logger.warn("Resource stream is null, cannot read xml file.");
218                 }
219             } catch (ParserConfigurationException e) {
220                 logger.warn("parser config error when reading device types xml file: ", e);
221             } catch (SAXException e) {
222                 logger.warn("SAX exception when reading device types xml file: ", e);
223             } catch (IOException e) {
224                 logger.warn("I/O exception when reading device types xml file: ", e);
225             }
226         }
227         return deviceTypeLoader;
228     }
229 }