// Copyright © 2013 Solita Oy <www.solita.fi>
// This software is released under the MIT License.
// The license text is at http://opensource.org/licenses/MIT

package fi.solita.datatree.xml;

import fi.solita.datatree.Tree;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import java.io.*;

public class XmlSchemaValidator {

    public static void validate(Tree schema, Tree subject) throws Exception {
        // XXX: We cannot just convert the schema to a Document, because namespaces would not work.
        // As a workaround we convert the schema to bytes and then read it back, same as a regular XSD file.
        ByteArrayOutputStream schemaBytes = new ByteArrayOutputStream();
        XmlDocumentGenerator.toXml(schema, new StreamResult(schemaBytes));
//        XmlDocumentGenerator.toXml(schema, new StreamResult(new File("sample.xml")));

        Validator validator = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                .newSchema(new StreamSource(new ByteArrayInputStream(schemaBytes.toByteArray())))
                .newValidator();

        try {
            validator.validate(new DOMSource(XmlDocumentGenerator.toDocument(subject)));
        } catch (SAXException e) {
            throw new ValidationException(e);
        }
    }
}

@@ -283,16 +283,51 @@
 stants;%0A
+import javax.xml.transform.Source;%0A
 import j
@@ -560,16 +560,186 @@
 ption %7B%0A
+        validate(schema, new DOMSource(XmlDocumentGenerator.toDocument(subject)));%0A    %7D%0A%0A    public static void validate(Tree schema, Source subject) throws Exception %7B%0A
         
@@ -1175,16 +1175,202 @@
 ml%22)));%0A
+        validate(new StreamSource(new ByteArrayInputStream(schemaBytes.toByteArray())), subject);%0A    %7D%0A%0A    public static void validate(Source schema, Source subject) throws Exception %7B
 %0A       
@@ -1485,77 +1485,14 @@
 ema(
-new StreamSource(new ByteArrayInputStream(schemaBytes.toByteArray()))
+schema
 )%0A  
@@ -1522,17 +1522,16 @@
 ator();%0A
-%0A
         
@@ -1571,62 +1571,16 @@
 ate(
-new DOMSource(XmlDocumentGenerator.toDocument(
 subject)
 ));%0A
@@ -1571,26 +1571,24 @@
 ate(subject)
-))
 ;%0A        %7D 

split validation to more reusable operations