Search in sources :

Example 1 with SearchResourceResolver

use of org.exist.validation.resolver.SearchResourceResolver 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 2 with SearchResourceResolver

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

the class Validator method validateParse.

/**
 *  Validate XML data from reader using specified grammar.
 *
 * @param grammarUrl   User supplied path to grammar.
 * @param stream XML input.
 * @return Validation report containing all validation info.
 */
public ValidationReport validateParse(InputStream stream, String grammarUrl) {
    logger.debug("Start validation.");
    final ValidationReport report = new ValidationReport();
    final ValidationContentHandler contenthandler = new ValidationContentHandler();
    try {
        final XMLReader xmlReader = getXMLReader(contenthandler, report);
        if (grammarUrl == null) {
            // Scenario 1 : no params - use system catalog
            logger.debug("Validation using system catalog.");
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_ENTITYRESOLVER, systemCatalogResolver);
        } else if (grammarUrl.endsWith(".xml")) {
            // Scenario 2 : path to catalog (xml)
            logger.debug("Validation using user specified catalog '{}'.", grammarUrl);
            final eXistXMLCatalogResolver resolver = new eXistXMLCatalogResolver();
            resolver.setCatalogList(new String[] { grammarUrl });
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_ENTITYRESOLVER, resolver);
        } else if (grammarUrl.endsWith("/")) {
            // Scenario 3 : path to collection ("/"): search.
            logger.debug("Validation using searched grammar, start from '{}'.", grammarUrl);
            final SearchResourceResolver resolver = new SearchResourceResolver(grammarUrl, brokerPool);
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_ENTITYRESOLVER, resolver);
        } else {
            // Scenario 4 : path to grammar (xsd, dtd) specified.
            logger.debug("Validation using specified grammar '{}'.", grammarUrl);
            final AnyUriResolver resolver = new AnyUriResolver(grammarUrl);
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_ENTITYRESOLVER, resolver);
        }
        logger.debug("Validation started.");
        report.start();
        final InputSource source = new InputSource(stream);
        xmlReader.parse(source);
        logger.debug("Validation stopped.");
        report.stop();
        report.setNamespaceUri(contenthandler.getNamespaceUri());
        if (!report.isValid()) {
            logger.debug("Document is not valid.");
        }
    } catch (final ParserConfigurationException | SAXException | IOException ex) {
        logger.error(ex);
        report.setThrowable(ex);
    } finally {
        report.stop();
        logger.debug("Validation performed in {} msec.", report.getValidationDuration());
    }
    return report;
}
Also used : SearchResourceResolver(org.exist.validation.resolver.SearchResourceResolver) InputSource(org.xml.sax.InputSource) org.exist.validation.resolver.eXistXMLCatalogResolver(org.exist.validation.resolver.eXistXMLCatalogResolver) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) AnyUriResolver(org.exist.validation.resolver.AnyUriResolver) XMLReader(org.xml.sax.XMLReader) SAXException(org.xml.sax.SAXException)

Aggregations

IOException (java.io.IOException)2 SearchResourceResolver (org.exist.validation.resolver.SearchResourceResolver)2 org.exist.validation.resolver.eXistXMLCatalogResolver (org.exist.validation.resolver.eXistXMLCatalogResolver)2 InputSource (org.xml.sax.InputSource)2 XMLReader (org.xml.sax.XMLReader)2 MalformedURLException (java.net.MalformedURLException)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 XMLEntityResolver (org.apache.xerces.xni.parser.XMLEntityResolver)1 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)1 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)1 Configuration (org.exist.util.Configuration)1 GrammarPool (org.exist.validation.GrammarPool)1 ValidationContentHandler (org.exist.validation.ValidationContentHandler)1 ValidationReport (org.exist.validation.ValidationReport)1 AnyUriResolver (org.exist.validation.resolver.AnyUriResolver)1 XPathException (org.exist.xquery.XPathException)1 BooleanValue (org.exist.xquery.value.BooleanValue)1 Sequence (org.exist.xquery.value.Sequence)1 ValueSequence (org.exist.xquery.value.ValueSequence)1 ContentHandler (org.xml.sax.ContentHandler)1