src/main/java/de/unixwork/uwproj/Main.java

changeset 109
1e852be12654
parent 93
df47e083139b
child 112
206e91a8dd18
--- 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);
         }

mercurial