Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.xmlcalabash.library;
  
 
Created by IntelliJ IDEA. User: ndw Date: Oct 22, 2008 Time: 11:06:11 AM To change this template use File | Settings | File Templates.
 
 
 public class ValidateWithSCH extends DefaultStep {
     private static final QName _assert_valid = new QName("""assert-valid");
     private static final QName _phase = new QName("""phase");
     private InputStream  skeleton = null;
     private ReadablePipe source = null;
     private ReadablePipe schema = null;
     private WritablePipe resultPipe = null;
     private WritablePipe reportPipe = null;
     private Hashtable<QName,RuntimeValueparams = new Hashtable<QName,RuntimeValue> ();
     private boolean schemaAware = false;


    
Creates a new instance of ValidateWithXSD
 
     public ValidateWithSCH(XProcRuntime runtimeXAtomicStep step) {
         super(runtime,step);
     }
 
     public void setInput(String portReadablePipe pipe) {
         if ("source".equals(port)) {
              = pipe;
         } else if ("schema".equals(port)) {
              = pipe;
         }
     }
 
     public void setOutput(String portWritablePipe pipe) {
         if ("result".equals(port)) {
              = pipe;
         } else if ("report".equals(port)) {
              = pipe;
         }
     }
 
     public void setParameter(QName nameRuntimeValue value) {
         .put(namevalue);
     }
 
     public void reset() {
         .resetReader();
         .resetReader();
         .resetWriter();
         .resetWriter();
     }
 
     public void run() throws SaxonApiException {
         super.run();
 
         XdmNode sourceXML = .read();
 
         // If we're dealing with a typed document, we must compile the XSLT in schema-aware mode
          = (sourceXML.getUnderlyingNode().getTypeAnnotation() != .);
 
         XdmNode schemaXML = .read();
 
         XsltCompiler compiler;
         XsltExecutable exec;
         XdmDestination result;
 
         // From http://www.schematron.com/
         // ...
         // So the basic processing now looks like this:
         //
        // xslt -stylesheet iso_dsdl_include.xsl  theSchema.sch > theSchema1.sch
        // xslt -stylesheet iso_abstract_expand.xsl  theSchema1.sch > theSchema2.sch
        // xslt -stylesheet iso_svrl_for_xsltn.xsl  theSchema2.sch > theSchema.xsl
        // xslt -stylesheet theSchema.xsl  myDocument.xml > myResult.xml
        // It would be nice to load these stylesheets only once, but sometimes (i.e. from RunTest),
        // there are different controllers involved and you can't do that.
        XdmNode theSchema1_sch = transform(schemaXMLgetSchematronXSLT("iso_dsdl_include.xsl"));
        XdmNode theSchema2_sch = transform(theSchema1_schgetSchematronXSLT("iso_abstract_expand.xsl"));
         = getClass().getResourceAsStream("/etc/schematron/iso_schematron_skeleton_for_saxon.xsl");
        if ( == null) {
            throw new UnsupportedOperationException("Failed to load iso_schematron_skeleton_for_saxon.xsl from JAR file.");
        }
        compiler = .getProcessor().newXsltCompiler();
        compiler.setSchemaAware();
        compiler.setURIResolver(new UResolver());
        exec = compiler.compile(getSchematronXSLT("iso_svrl_for_xslt2.xsl"));
        XsltTransformer schemaCompiler = exec.load();
        if (getOption() != null) {
            String phase = getOption().getString();
            schemaCompiler.setParameter(new QName("","phase"), new XdmAtomicValue(phase));
        }
        for (QName name : .keySet()) {
            RuntimeValue v = .get(name);
            schemaCompiler.setParameter(namenew XdmAtomicValue(v.getString()));
        }
        schemaCompiler.setInitialContextNode(theSchema2_sch);
        result = new XdmDestination();
        schemaCompiler.setDestination(result);
        schemaCompiler.transform();
        XdmNode compiledSchema = result.getXdmNode();
        XdmNode compiledRoot = S9apiUtils.getDocumentElement(compiledSchema);
        
        if (compiledRoot == null) {
            XdmNode schemaRoot = S9apiUtils.getDocumentElement(schemaXML);
            String root = schemaRoot == null ? "null" : schemaRoot.getNodeName().toString();
            throw new XProcException("p:validate-with-schematron failed to compile provided schema: " + root);
        }
        XsltTransformer transformer;
        compiler = .getProcessor().newXsltCompiler();
        compiler.setSchemaAware();
        exec = compiler.compile(compiledSchema.asSource());
        transformer = exec.load();
        transformer.setInitialContextNode(sourceXML);
        result = new XdmDestination();
        transformer.setDestination(result);
        transformer.transform();
        XdmNode report = result.getXdmNode();
        boolean failedAsserts = checkFailedAssert(report);
        if (failedAsserts && getOption(,false)) {
            throw XProcException.stepError(54);
        }
        .write(sourceXML);
        .write(report);
    }
    private boolean checkFailedAssert(XdmNode doc) {
        Hashtable<String,StringnsBindings = new Hashtable<String,String> ();
        nsBindings.put("svrl""http://purl.oclc.org/dsdl/svrl");
        String xpath = "//svrl:failed-assert";
        Vector<XdmItemresults = new Vector<XdmItem> ();
        try {
            XPathCompiler xcomp = .getProcessor().newXPathCompiler();
            xcomp.setBaseURI(.getNode().getBaseURI());
            for (String prefix : nsBindings.keySet()) {
                xcomp.declareNamespace(prefixnsBindings.get(prefix));
            }
            XPathExecutable xexec = null;
            try {
                xexec = xcomp.compile(xpath);
            } catch (SaxonApiException sae) {
                throw sae;
            }
            XPathSelector selector = xexec.load();
            selector.setContextItem(doc);
            try {
                Iterator<XdmItemvalues = selector.iterator();
                while (values.hasNext()) {
                    results.add(values.next());
                }
            } catch (SaxonApiUncheckedException saue) {
                Throwable sae = saue.getCause();
                if (sae instanceof XPathException) {
                    XPathException xe = (XPathExceptionsae;
                    if ("http://www.w3.org/2005/xqt-errors".equals(xe.getErrorCodeNamespace()) && "XPDY0002".equals(xe.getErrorCodeLocalPart())) {
                        throw XProcException.dynamicError(26, .getNode(), "Expression refers to context when none is available: " + xpath);
                    } else {
                        throw saue;
                    }
                } else {
                    throw saue;
                }
            }
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }
        return results.size() != 0;
    }
    private class UResolver implements URIResolver {
        public Source resolve(String hrefString basethrows TransformerException {
            if ("iso_schematron_skeleton_for_saxon.xsl".equals(href)) {
                return new SAXSource(new InputSource());
            } else {
                throw new XProcException(.getNode(), "Failed to resolve " + href + " from JAR file.");
            }
        }
    }
    private SAXSource getSchematronXSLT(String xslt) {
        InputStream instream = getClass().getResourceAsStream("/etc/schematron/" + xslt);
        if (instream == null) {
            throw new UnsupportedOperationException("Failed to load " + xslt + " from JAR file.");
        }
        return new SAXSource(new InputSource(instream));
    }
    private XdmNode transform(XdmNode sourceSAXSource stylesheetthrows SaxonApiException {
        XsltCompiler compiler = .getProcessor().newXsltCompiler();
        compiler.setSchemaAware();
        compiler.setURIResolver(new UResolver());
        XsltExecutable exec = compiler.compile(stylesheet);
        XsltTransformer schemaCompiler = exec.load();
        schemaCompiler.setInitialContextNode(source);
        XdmDestination result = new XdmDestination();
        schemaCompiler.setDestination(result);
        schemaCompiler.transform();
        return result.getXdmNode();
    }
New to GrepCode? Check out our FAQ X