]> git.basschouten.com Git - openhab-addons.git/blob
242254b9d415c16ba1717b05c851be4c40780c3b
[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.ihc.internal.ws.projectfile;
14
15 import java.io.ByteArrayInputStream;
16 import java.io.File;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27
28 import org.openhab.binding.ihc.internal.ws.datatypes.WSProjectInfo;
29 import org.openhab.binding.ihc.internal.ws.exeptions.IhcExecption;
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.NodeList;
35 import org.xml.sax.SAXException;
36
37 /**
38  * Generic methods related to IHC / ELKO project file handling.
39  *
40  * @author Pauli Anttila - Initial contribution
41  */
42 public class ProjectFileUtils {
43     private static final Logger LOGGER = LoggerFactory.getLogger(ProjectFileUtils.class);
44
45     /**
46      * Read IHC project file from local file.
47      *
48      * @param filePath File to read.
49      * @return XML document.
50      * @throws IhcExecption when file read fails.
51      */
52     public static Document readFromFile(String filePath) throws IhcExecption {
53         File fXmlFile = new File(filePath);
54         DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
55         try {
56             // see https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
57             dbFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
58             dbFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
59             dbFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
60             dbFactory.setXIncludeAware(false);
61             dbFactory.setExpandEntityReferences(false);
62             DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
63             return dBuilder.parse(fXmlFile);
64         } catch (IOException | ParserConfigurationException | SAXException e) {
65             throw new IhcExecption(e);
66         }
67     }
68
69     /**
70      * Save IHC project file to local file.
71      *
72      * @param filePath File path.
73      * @param data Data to write
74      * @throws IhcExecption when file write fails.
75      */
76     public static void saveToFile(String filePath, byte[] data) throws IhcExecption {
77         try {
78             try (FileOutputStream stream = new FileOutputStream(filePath)) {
79                 stream.write(data);
80                 stream.flush();
81             }
82         } catch (IOException e) {
83             throw new IhcExecption(e);
84         }
85     }
86
87     /**
88      * Convert bytes to XML document.
89      *
90      * @return XML document or null if conversion fails.
91      */
92     public static Document converteBytesToDocument(byte[] data) {
93         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
94         factory.setNamespaceAware(true);
95         try {
96             DocumentBuilder builder = factory.newDocumentBuilder();
97             return builder.parse(new ByteArrayInputStream(data));
98         } catch (ParserConfigurationException | SAXException | IOException e) {
99             LOGGER.warn("Error occured when trying to convert data to XML, reason {}", e.getMessage());
100         }
101         return null;
102     }
103
104     /**
105      * Compare XML document header information to project info.
106      *
107      * @return true if information is equal and false if not.
108      */
109     public static boolean projectEqualsToControllerProject(Document projectfile, WSProjectInfo projectInfo) {
110         if (projectInfo != null) {
111             try {
112                 NodeList nodes = projectfile.getElementsByTagName("modified");
113                 if (nodes.getLength() == 1) {
114                     Element node = (Element) nodes.item(0);
115                     int year = Integer.parseInt(node.getAttribute("year"));
116                     int month = Integer.parseInt(node.getAttribute("month"));
117                     int day = Integer.parseInt(node.getAttribute("day"));
118                     int hour = Integer.parseInt(node.getAttribute("hour"));
119                     int minute = Integer.parseInt(node.getAttribute("minute"));
120
121                     LOGGER.debug("Project file from file, date: {}.{}.{} {}:{}", year, month, day, hour, minute);
122                     LOGGER.debug("Project file in controller, date: {}.{}.{} {}:{}",
123                             projectInfo.getLastmodified().getYear(),
124                             projectInfo.getLastmodified().getMonthWithJanuaryAsOne(),
125                             projectInfo.getLastmodified().getDay(), projectInfo.getLastmodified().getHours(),
126                             projectInfo.getLastmodified().getMinutes());
127
128                     if (projectInfo.getLastmodified().getYear() == year
129                             && projectInfo.getLastmodified().getMonthWithJanuaryAsOne() == month
130                             && projectInfo.getLastmodified().getDay() == day
131                             && projectInfo.getLastmodified().getHours() == hour
132                             && projectInfo.getLastmodified().getMinutes() == minute) {
133                         return true;
134                     }
135                 }
136             } catch (RuntimeException e) {
137                 LOGGER.debug("Error occured during project file date comparasion, reason {}.", e.getMessage(), e);
138                 // There is no documentation available for XML content. This is part of inessential feature, so do
139                 // nothing, but return false
140             }
141         }
142         return false;
143     }
144
145     /**
146      * Parse all enum values from IHC project file.
147      *
148      * @param doc IHC project file in XML format.
149      * @return enum dictionary.
150      */
151     public static Map<Integer, List<IhcEnumValue>> parseEnums(Document doc) {
152         Map<Integer, List<IhcEnumValue>> enumDictionary = new HashMap<>();
153         if (doc != null) {
154             NodeList nodes = doc.getElementsByTagName("enum_definition");
155
156             // iterate enum definitions from project
157             for (int i = 0; i < nodes.getLength(); i++) {
158                 Element element = (Element) nodes.item(i);
159
160                 int typedefId = Integer.parseInt(element.getAttribute("id").replace("_0x", ""), 16);
161                 String enumName = element.getAttribute("name");
162
163                 List<IhcEnumValue> enumValues = new ArrayList<>();
164
165                 NodeList name = element.getElementsByTagName("enum_value");
166
167                 for (int j = 0; j < name.getLength(); j++) {
168                     Element val = (Element) name.item(j);
169                     int id = Integer.parseInt(val.getAttribute("id").replace("_0x", ""), 16);
170                     String n = val.getAttribute("name");
171                     IhcEnumValue enumVal = new IhcEnumValue(id, n);
172                     enumValues.add(enumVal);
173                 }
174
175                 LOGGER.debug("Enum values found: typedefId={}, name={}: {}", typedefId, enumName, enumValues);
176                 enumDictionary.put(typedefId, enumValues);
177             }
178         }
179         return enumDictionary;
180     }
181 }