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