Search in sources :

Example 1 with ValidationReport

use of org.exist.validation.ValidationReport in project exist by eXist-db.

the class Jaxv method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2 && args.length != 3) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final ValidationReport report = new ValidationReport();
    StreamSource instance = null;
    StreamSource[] grammars = null;
    String schemaLang = XMLConstants.W3C_XML_SCHEMA_NS_URI;
    try {
        report.start();
        // Get inputstream for instance document
        instance = Shared.getStreamSource(args[0].itemAt(0), context);
        // Validate using resource speciefied in second parameter
        grammars = Shared.getStreamSource(args[1], context);
        // Check input
        for (final StreamSource grammar : grammars) {
            final String grammarUrl = grammar.getSystemId();
            if (grammarUrl != null && !grammarUrl.endsWith(".xsd") && !grammarUrl.endsWith(".rng")) {
                throw new XPathException("Only XML schemas (.xsd) and RELAXNG grammars (.rng) are supported" + ", depending on the used XML parser.");
            }
        }
        // Fetch third argument if available, and override defailt value
        if (args.length == 3) {
            schemaLang = args[2].getStringValue();
        }
        // Get language specific factory
        SchemaFactory factory = null;
        try {
            factory = SchemaFactory.newInstance(schemaLang);
        } catch (final IllegalArgumentException ex) {
            final String msg = "Schema language '" + schemaLang + "' is not supported. " + ex.getMessage();
            LOG.error(msg);
            throw new XPathException(msg);
        }
        // Create grammar
        final Schema schema = factory.newSchema(grammars);
        // Setup validator
        final Validator validator = schema.newValidator();
        validator.setErrorHandler(report);
        // Perform validation
        validator.validate(instance);
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeStreamSource(instance);
        Shared.closeStreamSources(grammars);
    }
    // Create response
    if (isCalledAs("jaxv")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxv-report") */
    {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            return result;
        } finally {
            context.popDocumentContext();
        }
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) MalformedURLException(java.net.MalformedURLException) NodeImpl(org.exist.dom.memtree.NodeImpl) XPathException(org.exist.xquery.XPathException) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) Validator(javax.xml.validation.Validator)

Example 2 with ValidationReport

use of org.exist.validation.ValidationReport in project exist by eXist-db.

the class Jaxp method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    XMLEntityResolver entityResolver = null;
    GrammarPool grammarPool = null;
    final ValidationReport report = new ValidationReport();
    ContentHandler contenthandler = null;
    MemTreeBuilder instanceBuilder = null;
    InputSource instance = null;
    if (isCalledAs("jaxp-parse")) {
        instanceBuilder = context.getDocumentBuilder();
        // (namespace?)
        contenthandler = new DocumentBuilderReceiver(instanceBuilder, true);
    } else {
        contenthandler = new ValidationContentHandler();
    }
    try {
        report.start();
        // Get initialized parser
        final XMLReader xmlReader = getXMLReader();
        // Setup validation reporting
        xmlReader.setContentHandler(contenthandler);
        xmlReader.setErrorHandler(report);
        // Get inputstream for instance document
        instance = Shared.getInputSource(args[0].itemAt(0), context);
        // Handle catalog
        if (args.length == 2) {
            LOG.debug("No Catalog specified");
        } else if (args[2].isEmpty()) {
            // Use system catalog
            LOG.debug("Using system catalog.");
            final Configuration config = brokerPool.getConfiguration();
            entityResolver = (eXistXMLCatalogResolver) config.getProperty(XMLReaderObjectFactory.CATALOG_RESOLVER);
            setXmlReaderEnitityResolver(xmlReader, entityResolver);
        } else {
            // Get URL for catalog
            final String[] catalogUrls = Shared.getUrls(args[2]);
            final String singleUrl = catalogUrls[0];
            if (singleUrl.endsWith("/")) {
                // Search grammar in collection specified by URL. Just one collection is used.
                LOG.debug("Search for grammar in {}", singleUrl);
                entityResolver = new SearchResourceResolver(catalogUrls[0], brokerPool);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else if (singleUrl.endsWith(".xml")) {
                LOG.debug("Using catalogs {}", getStrings(catalogUrls));
                entityResolver = new eXistXMLCatalogResolver();
                ((eXistXMLCatalogResolver) entityResolver).setCatalogList(catalogUrls);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else {
                LOG.error("Catalog URLs should end on / or .xml");
            }
        }
        // Use grammarpool
        final boolean useCache = ((BooleanValue) args[1].itemAt(0)).getValue();
        if (useCache) {
            LOG.debug("Grammar caching enabled.");
            final Configuration config = brokerPool.getConfiguration();
            grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
        }
        // Jaxp document
        LOG.debug("Start parsing document");
        xmlReader.parse(instance);
        LOG.debug("Stopped parsing document");
        // Distill namespace from document
        if (contenthandler instanceof ValidationContentHandler) {
            report.setNamespaceUri(((ValidationContentHandler) contenthandler).getNamespaceUri());
        }
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final IOException ex) {
        LOG.error(ex.getCause());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeInputSource(instance);
    }
    // Create response
    if (isCalledAs("jaxp")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxp-report or jaxp-parse ") */
    {
        if (report.getThrowable() != null) {
            throw new XPathException(report.getThrowable().getMessage(), report.getThrowable());
        }
        if (contenthandler instanceof DocumentBuilderReceiver) {
            // DocumentBuilderReceiver dbr = (DocumentBuilderReceiver) contenthandler;
            return instanceBuilder.getDocument().getNode(0);
        } else {
            context.pushDocumentContext();
            try {
                final MemTreeBuilder builder = context.getDocumentBuilder();
                return Shared.writeReport(report, builder);
            } finally {
                context.popDocumentContext();
            }
        }
    }
}
Also used : ValidationContentHandler(org.exist.validation.ValidationContentHandler) InputSource(org.xml.sax.InputSource) SearchResourceResolver(org.exist.validation.resolver.SearchResourceResolver) MalformedURLException(java.net.MalformedURLException) org.exist.validation.resolver.eXistXMLCatalogResolver(org.exist.validation.resolver.eXistXMLCatalogResolver) Configuration(org.exist.util.Configuration) XPathException(org.exist.xquery.XPathException) XMLEntityResolver(org.apache.xerces.xni.parser.XMLEntityResolver) GrammarPool(org.exist.validation.GrammarPool) IOException(java.io.IOException) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) ContentHandler(org.xml.sax.ContentHandler) ValidationContentHandler(org.exist.validation.ValidationContentHandler) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) XMLReader(org.xml.sax.XMLReader)

Example 3 with ValidationReport

use of org.exist.validation.ValidationReport in project exist by eXist-db.

the class Parse method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (args[0].getItemCount() == 0) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final String xmlContent = args[0].itemAt(0).getStringValue();
    if (xmlContent.isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final StringReader reader = new StringReader(xmlContent);
    final ValidationReport report = new ValidationReport();
    final SAXAdapter adapter = new SAXAdapter(context);
    XMLReader xr = null;
    try {
        final InputSource src = new InputSource(reader);
        final Optional<Either<Throwable, XMLReader>> maybeReaderInst = HtmlToXmlParser.getHtmlToXmlParser(context.getBroker().getConfiguration());
        if (maybeReaderInst.isPresent()) {
            final Either<Throwable, XMLReader> readerInst = maybeReaderInst.get();
            if (readerInst.isLeft()) {
                final String msg = "Unable to parse HTML to XML please ensure the parser is configured in conf.xml and is present on the classpath";
                final Throwable t = readerInst.left().get();
                LOG.error(msg, t);
                throw new XPathException(this, ErrorCodes.EXXQDY0002, t);
            } else {
                xr = readerInst.right().get();
            }
        } else {
            throw new XPathException(this, ErrorCodes.EXXQDY0002, "There is no HTML to XML parser configured in conf.xml");
        }
        xr.setErrorHandler(report);
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
        xr.parse(src);
    } catch (final SAXException e) {
        logger.debug("Error while parsing XML: {}", e.getMessage(), e);
    } catch (final IOException e) {
        throw new XPathException(this, ErrorCodes.EXXQDY0002, "Error while parsing XML: " + e.getMessage(), args[0], e);
    } finally {
        if (!isCalledAs("parse-html") && xr != null) {
            context.getBroker().getBrokerPool().getParserPool().returnXMLReader(xr);
        }
    }
    if (report.isValid()) {
        return adapter.getDocument();
    } else {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            throw new XPathException(this, ErrorCodes.EXXQDY0002, report.toString(), result);
        } finally {
            context.popDocumentContext();
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) NodeImpl(org.exist.dom.memtree.NodeImpl) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) StringReader(java.io.StringReader) SAXAdapter(org.exist.dom.memtree.SAXAdapter) Either(com.evolvedbinary.j8fu.Either) XMLReader(org.xml.sax.XMLReader)

Example 4 with ValidationReport

use of org.exist.validation.ValidationReport in project exist by eXist-db.

the class ParsingFunctions method parse.

private Sequence parse(final String xmlContent, final Sequence[] args) throws XPathException {
    final SAXAdapter adapter = new FragmentSAXAdapter(context, isCalledAs("parse-xml-fragment"));
    final ValidationReport report = validate(xmlContent, adapter);
    if (report.isValid()) {
        return adapter.getDocument();
    } else {
        try {
            context.pushDocumentContext();
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            throw new XPathException(this, ErrorCodes.FODC0006, ErrorCodes.FODC0006.getDescription() + ": " + report.toString(), result);
        } finally {
            context.popDocumentContext();
        }
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) NodeImpl(org.exist.dom.memtree.NodeImpl) ValidationReport(org.exist.validation.ValidationReport) SAXAdapter(org.exist.dom.memtree.SAXAdapter)

Example 5 with ValidationReport

use of org.exist.validation.ValidationReport in project exist by eXist-db.

the class ParsingFunctions method validate.

private ValidationReport validate(final String xmlContent, final SAXAdapter saxAdapter) throws XPathException {
    final String xml;
    if (isCalledAs("parse-xml-fragment")) {
        xml = "<" + FRAGMENT_WRAPPER_NAME + ">" + xmlContent + "</" + FRAGMENT_WRAPPER_NAME + ">";
    } else {
        xml = xmlContent;
    }
    final ValidationReport report = new ValidationReport();
    try (final StringReader reader = new StringReader(xml)) {
        final InputSource src = new InputSource(reader);
        final XMLReaderPool parserPool = context.getBroker().getBrokerPool().getParserPool();
        XMLReader xr = null;
        try {
            xr = parserPool.borrowXMLReader();
            xr.setErrorHandler(report);
            xr.setContentHandler(saxAdapter);
            xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, saxAdapter);
            xr.parse(src);
        } catch (final SAXException e) {
            logger.debug("Error while parsing XML: {}", e.getMessage(), e);
        } catch (final IOException e) {
            throw new XPathException(this, ErrorCodes.FODC0006, ErrorCodes.FODC0006.getDescription() + ": " + e.getMessage(), new StringValue(xml), e);
        } finally {
            if (xr != null) {
                parserPool.returnXMLReader(xr);
            }
        }
    }
    return report;
}
Also used : InputSource(org.xml.sax.InputSource) ValidationReport(org.exist.validation.ValidationReport) StringReader(java.io.StringReader) IOException(java.io.IOException) XMLReaderPool(org.exist.util.XMLReaderPool) XMLReader(org.xml.sax.XMLReader) SAXException(org.xml.sax.SAXException)

Aggregations

ValidationReport (org.exist.validation.ValidationReport)6 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)5 NodeImpl (org.exist.dom.memtree.NodeImpl)4 InputSource (org.xml.sax.InputSource)4 IOException (java.io.IOException)3 MalformedURLException (java.net.MalformedURLException)3 BooleanValue (org.exist.xquery.value.BooleanValue)3 Sequence (org.exist.xquery.value.Sequence)3 ValueSequence (org.exist.xquery.value.ValueSequence)3 XMLReader (org.xml.sax.XMLReader)3 StringReader (java.io.StringReader)2 SAXAdapter (org.exist.dom.memtree.SAXAdapter)2 XPathException (org.exist.xquery.XPathException)2 SAXException (org.xml.sax.SAXException)2 Either (com.evolvedbinary.j8fu.Either)1 PropertyMapBuilder (com.thaiopensource.util.PropertyMapBuilder)1 SchemaReader (com.thaiopensource.validate.SchemaReader)1 ValidationDriver (com.thaiopensource.validate.ValidationDriver)1 CompactSchemaReader (com.thaiopensource.validate.rng.CompactSchemaReader)1 StreamSource (javax.xml.transform.stream.StreamSource)1