Sat, 27 Jan 2024 14:28:09 +0100
adds schema validation - fixes #291
src/main/java/de/unixwork/uwproj/Main.java | file | annotate | diff | comparison | revisions | |
src/main/java/de/unixwork/uwproj/Project.java | file | annotate | diff | comparison | revisions |
--- a/src/main/java/de/unixwork/uwproj/Main.java Sat Jan 27 12:29:50 2024 +0100 +++ b/src/main/java/de/unixwork/uwproj/Main.java Sat Jan 27 14:28:09 2024 +0100 @@ -2,7 +2,13 @@ import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; +import org.xml.sax.SAXException; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.SchemaFactory; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; @@ -19,8 +25,27 @@ public final static String OUT_FILE_DEFAULT = "configure"; static Project loadProjectFile(String fileName) { - try { - return new Project(new File(fileName)); + try (final var xsdResource = Objects.requireNonNull(Main.class.getClassLoader().getResourceAsStream("make/uwproj.xsd"))) { + // Create the XSD validator + final var factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + final var schema = factory.newSchema(new StreamSource(xsdResource)); + final var validator = schema.newValidator(); + + // Load the DOM from the input file + final var dom = DocumentBuilderFactory. + newDefaultNSInstance(). + newDocumentBuilder(). + parse(fileName). + getDocumentElement(); + + // Validate the XML + validator.validate(new DOMSource(dom)); + + // Parse the XML + return new Project(dom); + } catch (SAXException saxerror) { + System.err.println(saxerror.getMessage()); + throw new RuntimeException("XML validation failed."); } catch (Exception e) { throw new RuntimeException(e); }
--- a/src/main/java/de/unixwork/uwproj/Project.java Sat Jan 27 12:29:50 2024 +0100 +++ b/src/main/java/de/unixwork/uwproj/Project.java Sat Jan 27 14:28:09 2024 +0100 @@ -22,12 +22,7 @@ private final Set<String> lang; - public Project(File file) throws Exception { - var root = DocumentBuilderFactory. - newDefaultNSInstance(). - newDocumentBuilder(). - parse(file). - getDocumentElement(); + public Project(Element root) throws Exception { NodeList dependency_nodes = root.getElementsByTagName("dependency"); NodeList target_nodes = root.getElementsByTagName("target"); NodeList config_nodes = root.getElementsByTagName("config");