Package org.exist.validation

Examples of org.exist.validation.ValidationReport


            // Get inputstream
            // TODO DWES reconsider
            final InputStream is = new EmbeddedInputStream( new XmldbURL(docUri) );
           
            // Perform validation
            final ValidationReport report = validator.validate(is);
           
            // Return validation result
            isValid = report.isValid();
           
        } catch (final Throwable e) {
            handleException(e);
            return false;
        }
View Full Code Here


        return parse(src, context, args);
  }

    private Sequence parse(final InputSource src, XQueryContext theContext, Sequence[] args) throws XPathException {
        Sequence resultSequence;
        final ValidationReport report = new ValidationReport();
        final SAXAdapter adapter = new SAXAdapter(theContext);
        try {
            final SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
                     
            XMLReader xr = null;
           
            if (xr == null) {
                final SAXParser parser = factory.newSAXParser();
                xr = parser.getXMLReader();
            }
           
            xr.setErrorHandler(report);
            xr.setContentHandler(adapter);
            xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
            xr.parse(src);
           
        } catch (final ParserConfigurationException e) {
            throw new XPathException(this, ErrorCodes.EXXQDY0002, "Error while constructing XML parser: "  + e.getMessage(), args[0], e);
        } 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(),
                    args[0], e);
        }
       
        if (report.isValid()) {
            if (isCalledAs("parse-xml-fragment")) {
                resultSequence = new ValueSequence();
                NodeList children = adapter.getDocument().getDocumentElement().getChildNodes();
                for (int i = 0, il = children.getLength(); i < il; i++) {
                    Node child = children.item(i);
                    resultSequence.add((NodeValue)child);
                }
               
                return resultSequence;
            } else {
                return (DocumentImpl) adapter.getDocument();
            }
        } else {
            final MemTreeBuilder builder = theContext.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            throw new XPathException(this, ErrorCodes.FODC0006, ErrorCodes.FODC0006.getDescription() + ": " + report.toString(), result);
        }
    }
View Full Code Here

        if (args.length != 1 && args.length != 2) {
            return Sequence.EMPTY_SEQUENCE;
        }

        InputStream is = null;
        ValidationReport report = new ValidationReport();

        try { // args[0]
            is = Shared.getInputStream(args[0].itemAt(0), context);

            if(args.length == 1) {
                // Validate using system catalog
                report=validator.validate(is);

            } else {
                // Validate using resource specified in second parameter
                final String url=Shared.getUrl(args[1].itemAt(0));

                report=validator.validate(is, url);
            }


        } catch (final MalformedURLException ex) {
            LOG.error(ex.getMessage());
            report.setException(ex);

        } catch (final IOException ex) {
            LOG.error(ex);
            report.setException(ex);

        } catch (final Throwable ex) {
            LOG.error(ex);
            report.setException(ex);

        } finally {
            // Force release stream
            if(is != null){
                try {
                    is.close();
                } catch (final Exception ex) {
                    LOG.debug("Attemted to close stream. ignore.", ex);
                }
            }
        }

        // Create response
        if (isCalledAs("validate") || isCalledAs("jing")) {
            final Sequence result = new ValueSequence();
            result.add(new BooleanValue(report.isValid()));
            return result;

        } else  /* isCalledAs("validate-report") || isCalledAs("jing-report") */{
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
View Full Code Here

        if (args.length != && 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") */ {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
View Full Code Here

        final String xmlContent = args[0].itemAt(0).getStringValue();
        if (xmlContent.length() == 0) {
            return Sequence.EMPTY_SEQUENCE;
        }
        final StringReader reader = new StringReader(xmlContent);
        final ValidationReport report = new ValidationReport();
        final SAXAdapter adapter = new SAXAdapter(context);
        try {
            final SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            final InputSource src = new InputSource(reader);

            XMLReader xr = null;
            if (isCalledAs("parse-html")) {
                try {
                    final Class<?> clazz = Class.forName( "org.cyberneko.html.parsers.SAXParser" );
                    xr = (XMLReader) clazz.newInstance();
                    //do not modify the case of elements and attributes
                    xr.setProperty("http://cyberneko.org/html/properties/names/elems", "match");
                    xr.setProperty("http://cyberneko.org/html/properties/names/attrs", "no-change");
                } catch (final Exception e) {
                    logger.warn("Could not instantiate neko HTML parser for function util:parse-html, falling back to " +
                            "default XML parser.", e);
                }
            }
            if (xr == null) {
                final SAXParser parser = factory.newSAXParser();
                xr = parser.getXMLReader();
            }

            xr.setErrorHandler(report);
            xr.setContentHandler(adapter);
            xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
            xr.parse(src);
        } catch (final ParserConfigurationException e) {
            throw new XPathException(this, ErrorCodes.EXXQDY0002, "Error while constructing XML parser: " + e.getMessage(), args[0], e);
        } 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);
        }
       
        if (report.isValid())
          {return (DocumentImpl) adapter.getDocument();}
        else {
          final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
        throw new XPathException(this, ErrorCodes.EXXQDY0002, report.toString(), result);
        }
    }
View Full Code Here

            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();
            contenthandler = new DocumentBuilderReceiver(instanceBuilder, true); // (namespace?)

        } 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.GRAMMER_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 ((DocumentImpl) instanceBuilder.getDocument()).getNode(0);
View Full Code Here

        // Check input parameters
        if (args.length != 2) {
            return Sequence.EMPTY_SEQUENCE;
        }

        final ValidationReport report = new ValidationReport();
        InputSource instance=null;
        InputSource grammar =null;

        try {
            report.start();

            // Get inputstream of XML instance document
            instance=Shared.getInputSource(args[0].itemAt(0), context);

            // Validate using resource specified in second parameter
            grammar = Shared.getInputSource(args[1].itemAt(0), context);

            // Special setup for compact notation
            final String grammarUrl = grammar.getSystemId();
            final SchemaReader schemaReader
                    = ( (grammarUrl != null) && (grammarUrl.endsWith(".rnc")) )
                    ? CompactSchemaReader.getInstance() : null;

            // Setup validation properties. see Jing interface
            final PropertyMapBuilder properties = new PropertyMapBuilder();
            ValidateProperty.ERROR_HANDLER.put(properties, report);
           
            // Register resolver for xmldb:exist:/// embedded URLs
            final ExistResolver resolver = new ExistResolver(brokerPool);
            ValidateProperty.URI_RESOLVER.put(properties, resolver);
            ValidateProperty.ENTITY_RESOLVER.put(properties, resolver);

            // Setup driver
            final ValidationDriver driver = new ValidationDriver(properties.toPropertyMap(), schemaReader);

            // Load schema
            driver.loadSchema(grammar);

            // Validate XML instance
            driver.validate(instance);
           
        } catch (final MalformedURLException ex) {
            LOG.error(ex.getMessage());
            report.setException(ex);

        } catch (final IOException ex) {
            LOG.error(ex);
            report.setException(ex);

        } catch (final Throwable ex) {
            LOG.error(ex);
            report.setException(ex);

        } finally {
            Shared.closeInputSource(instance);
            Shared.closeInputSource(grammar);
            report.stop();
        }

        // Create response
        if (isCalledAs("jing")) {
            final Sequence result = new ValueSequence();
            result.add(new BooleanValue(report.isValid()));
            return result;

        } else  /* isCalledAs("jing-report") */{
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
View Full Code Here

TOP

Related Classes of org.exist.validation.ValidationReport

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.