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

changeset 112
206e91a8dd18
parent 109
1e852be12654
equal deleted inserted replaced
111:cb128bae1161 112:206e91a8dd18
1 package de.unixwork.uwproj; 1 package de.unixwork.uwproj;
2 2
3 import org.apache.velocity.VelocityContext; 3 import org.apache.velocity.VelocityContext;
4 import org.apache.velocity.app.VelocityEngine; 4 import org.apache.velocity.app.VelocityEngine;
5 import org.xml.sax.SAXException; 5 import org.xml.sax.SAXParseException;
6 6
7 import javax.xml.XMLConstants; 7 import javax.xml.XMLConstants;
8 import javax.xml.parsers.DocumentBuilderFactory; 8 import javax.xml.parsers.DocumentBuilderFactory;
9 import javax.xml.transform.dom.DOMSource;
10 import javax.xml.transform.stream.StreamSource; 9 import javax.xml.transform.stream.StreamSource;
11 import javax.xml.validation.SchemaFactory; 10 import javax.xml.validation.SchemaFactory;
12 import java.io.*; 11 import java.io.*;
13 import java.nio.file.Files; 12 import java.nio.file.Files;
14 import java.nio.file.Path; 13 import java.nio.file.Path;
29 // Create the XSD validator 28 // Create the XSD validator
30 final var factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 29 final var factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
31 final var schema = factory.newSchema(new StreamSource(xsdResource)); 30 final var schema = factory.newSchema(new StreamSource(xsdResource));
32 final var validator = schema.newValidator(); 31 final var validator = schema.newValidator();
33 32
33 // Validate the XML as stream (DOM validation cannot output line numbers in error message)
34 validator.validate(new StreamSource(new File(fileName)));
35
34 // Load the DOM from the input file 36 // Load the DOM from the input file
35 final var dom = DocumentBuilderFactory. 37 final var dom = DocumentBuilderFactory.
36 newDefaultNSInstance(). 38 newDefaultNSInstance().
37 newDocumentBuilder(). 39 newDocumentBuilder().
38 parse(fileName). 40 parse(fileName).
39 getDocumentElement(); 41 getDocumentElement();
40 42
41 // Validate the XML
42 validator.validate(new DOMSource(dom));
43
44 // Parse the XML 43 // Parse the XML
45 return new Project(dom); 44 return new Project(dom);
46 } catch (SAXException saxerror) { 45 } catch (SAXParseException saxerror) {
47 System.err.println(saxerror.getMessage()); 46 System.err.printf("Parse error in line %d, column %d: %s",
47 saxerror.getLineNumber(),
48 saxerror.getColumnNumber(),
49 saxerror.getMessage());
48 throw new RuntimeException("XML validation failed."); 50 throw new RuntimeException("XML validation failed.");
49 } catch (Exception e) { 51 } catch (Exception e) {
50 throw new RuntimeException(e); 52 throw new RuntimeException(e);
51 } 53 }
52 } 54 }

mercurial