2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.ihc.internal.ws.projectfile;
15 import java.io.ByteArrayInputStream;
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;
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
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;
38 * Generic methods related to IHC / ELKO project file handling.
40 * @author Pauli Anttila - Initial contribution
42 public class ProjectFileUtils {
43 private static final Logger LOGGER = LoggerFactory.getLogger(ProjectFileUtils.class);
46 * Read IHC project file from local file.
48 * @param filePath File to read.
49 * @return XML document.
50 * @throws IhcExecption when file read fails.
52 public static Document readFromFile(String filePath) throws IhcExecption {
53 File fXmlFile = new File(filePath);
54 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
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);
70 * Save IHC project file to local file.
72 * @param filePath File path.
73 * @param data Data to write
74 * @throws IhcExecption when file write fails.
76 public static void saveToFile(String filePath, byte[] data) throws IhcExecption {
78 try (FileOutputStream stream = new FileOutputStream(filePath)) {
82 } catch (IOException e) {
83 throw new IhcExecption(e);
88 * Convert bytes to XML document.
90 * @return XML document or null if conversion fails.
92 public static Document converteBytesToDocument(byte[] data) {
93 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
94 factory.setNamespaceAware(true);
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());
105 * Compare XML document header information to project info.
107 * @return true if information is equal and false if not.
109 public static boolean projectEqualsToControllerProject(Document projectfile, WSProjectInfo projectInfo) {
110 if (projectInfo != null) {
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"));
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());
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) {
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
146 * Parse all enum values from IHC project file.
148 * @param doc IHC project file in XML format.
149 * @return enum dictionary.
151 public static Map<Integer, List<IhcEnumValue>> parseEnums(Document doc) {
152 Map<Integer, List<IhcEnumValue>> enumDictionary = new HashMap<>();
154 NodeList nodes = doc.getElementsByTagName("enum_definition");
156 // iterate enum definitions from project
157 for (int i = 0; i < nodes.getLength(); i++) {
158 Element element = (Element) nodes.item(i);
160 int typedefId = Integer.parseInt(element.getAttribute("id").replace("_0x", ""), 16);
161 String enumName = element.getAttribute("name");
163 List<IhcEnumValue> enumValues = new ArrayList<>();
165 NodeList name = element.getElementsByTagName("enum_value");
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);
175 LOGGER.debug("Enum values found: typedefId={}, name={}: {}", typedefId, enumName, enumValues);
176 enumDictionary.put(typedefId, enumValues);
179 return enumDictionary;