Search in sources :

Example 1 with NodeImpl

use of org.exist.dom.memtree.NodeImpl in project exist by eXist-db.

the class RESTServer method declareExternalAndXQJVariables.

private void declareExternalAndXQJVariables(final XQueryContext context, final ElementImpl variables) throws XPathException {
    final ValueSequence varSeq = new ValueSequence();
    variables.selectChildren(new NameTest(Type.ELEMENT, new QName(Variable.xmlKey(), Namespaces.EXIST_NS)), varSeq);
    for (final SequenceIterator i = varSeq.iterate(); i.hasNext(); ) {
        final ElementImpl variable = (ElementImpl) i.nextItem();
        // get the QName of the variable
        final ElementImpl qname = (ElementImpl) variable.getFirstChild(new NameTest(Type.ELEMENT, new QName("qname", Namespaces.EXIST_NS)));
        String localname = null, prefix = null, uri = null;
        NodeImpl child = (NodeImpl) qname.getFirstChild();
        while (child != null) {
            if ("localname".equals(child.getLocalName())) {
                localname = child.getStringValue();
            } else if ("namespace".equals(child.getLocalName())) {
                uri = child.getStringValue();
            } else if ("prefix".equals(child.getLocalName())) {
                prefix = child.getStringValue();
            }
            child = (NodeImpl) child.getNextSibling();
        }
        if (uri != null && prefix != null) {
            context.declareNamespace(prefix, uri);
        }
        if (localname == null) {
            continue;
        }
        final QName q;
        if (prefix != null && localname != null) {
            q = new QName(localname, uri, prefix);
        } else {
            q = new QName(localname, uri, XMLConstants.DEFAULT_NS_PREFIX);
        }
        // get serialized sequence
        final NodeImpl value = variable.getFirstChild(new NameTest(Type.ELEMENT, Marshaller.ROOT_ELEMENT_QNAME));
        final Sequence sequence;
        try {
            sequence = value == null ? Sequence.EMPTY_SEQUENCE : Marshaller.demarshall(value);
        } catch (final XMLStreamException xe) {
            throw new XPathException(xe.toString());
        }
        // now declare variable
        if (prefix != null) {
            context.declareVariable(q.getPrefix() + ":" + q.getLocalPart(), sequence);
        } else {
            context.declareVariable(q.getLocalPart(), sequence);
        }
    }
}
Also used : ElementImpl(org.exist.dom.memtree.ElementImpl) NodeImpl(org.exist.dom.memtree.NodeImpl) XMLStreamException(javax.xml.stream.XMLStreamException) QName(org.exist.dom.QName)

Example 2 with NodeImpl

use of org.exist.dom.memtree.NodeImpl in project exist by eXist-db.

the class LocationStep method applyPredicate.

/**
 * The method <code>applyPredicate</code>
 *
 * @param outerSequence   a <code>Sequence</code> value
 * @param contextSequence a <code>Sequence</code> value
 * @return a <code>Sequence</code> value
 * @throws XPathException if an error occurs
 */
private Sequence applyPredicate(Sequence outerSequence, final Sequence contextSequence) throws XPathException {
    if (contextSequence == null) {
        return Sequence.EMPTY_SEQUENCE;
    }
    if (predicates == null || !applyPredicate || (!(contextSequence instanceof VirtualNodeSet) && contextSequence.isEmpty())) // Nothing to apply
    {
        return contextSequence;
    }
    Sequence result;
    final Predicate pred = predicates[0];
    // is required.
    if (abbreviatedStep && (pred.getExecutionMode() == Predicate.ExecutionMode.POSITIONAL || !contextSequence.isPersistentSet())) {
        result = new ValueSequence();
        ((ValueSequence) result).keepUnOrdered(unordered);
        if (contextSequence.isPersistentSet()) {
            final NodeSet contextSet = contextSequence.toNodeSet();
            outerSequence = contextSet.getParents(-1);
            for (final SequenceIterator i = outerSequence.iterate(); i.hasNext(); ) {
                final NodeValue node = (NodeValue) i.nextItem();
                final Sequence newContextSeq = contextSet.selectParentChild((NodeSet) node, NodeSet.DESCENDANT, getExpressionId());
                final Sequence temp = processPredicate(outerSequence, newContextSeq);
                result.addAll(temp);
            }
        } else {
            final MemoryNodeSet nodes = contextSequence.toMemNodeSet();
            outerSequence = nodes.getParents(new AnyNodeTest());
            for (final SequenceIterator i = outerSequence.iterate(); i.hasNext(); ) {
                final NodeValue node = (NodeValue) i.nextItem();
                final InMemoryNodeSet newSet = new InMemoryNodeSet();
                ((NodeImpl) node).selectChildren(test, newSet);
                final Sequence temp = processPredicate(outerSequence, newSet);
                result.addAll(temp);
            }
        }
    } else {
        result = processPredicate(outerSequence, contextSequence);
    }
    return result;
}
Also used : InMemoryNodeSet(org.exist.dom.memtree.InMemoryNodeSet) InMemoryNodeSet(org.exist.dom.memtree.InMemoryNodeSet) NodeImpl(org.exist.dom.memtree.NodeImpl) InMemoryNodeSet(org.exist.dom.memtree.InMemoryNodeSet)

Example 3 with NodeImpl

use of org.exist.dom.memtree.NodeImpl in project exist by eXist-db.

the class GrammarTooling method eval.

/**
 * @see org.exist.xquery.BasicFunction#eval(Sequence[], Sequence)
 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final GrammarPool grammarpool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
    if (isCalledAs("clear-grammar-cache")) {
        final Sequence result = new ValueSequence();
        final int before = countTotalNumberOfGrammar(grammarpool);
        LOG.debug("Clearing {} grammars", before);
        clearGrammarPool(grammarpool);
        final int after = countTotalNumberOfGrammar(grammarpool);
        LOG.debug("Remained {} grammars", after);
        final int delta = before - after;
        result.add(new IntegerValue(delta));
        return result;
    } else if (isCalledAs("show-grammar-cache")) {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = writeReport(grammarpool, builder);
            return result;
        } finally {
            context.popDocumentContext();
        }
    } else if (isCalledAs("pre-parse-grammar")) {
        if (args[0].isEmpty()) {
            return Sequence.EMPTY_SEQUENCE;
        }
        // Setup for XML schema support only
        final XMLGrammarPreparser parser = new XMLGrammarPreparser();
        parser.registerPreparser(TYPE_XSD, null);
        final List<Grammar> allGrammars = new ArrayList<>();
        // iterate through the argument sequence and parse url
        for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
            String url = i.nextItem().getStringValue();
            // Fix database urls
            if (url.startsWith("/")) {
                url = "xmldb:exist://" + url;
            }
            LOG.debug("Parsing {}", url);
            // parse XSD grammar
            try {
                if (url.endsWith(".xsd")) {
                    final InputStream is = new URL(url).openStream();
                    final XMLInputSource xis = new XMLInputSource(null, url, url, is, null);
                    final Grammar schema = parser.preparseGrammar(TYPE_XSD, xis);
                    is.close();
                    allGrammars.add(schema);
                } else {
                    throw new XPathException(this, "Only XMLSchemas can be preparsed.");
                }
            } catch (final Exception ex) {
                LOG.debug(ex);
                throw new XPathException(this, ex);
            }
        }
        LOG.debug("Successfully parsed {} grammars.", allGrammars.size());
        // Send all XSD grammars to grammarpool
        Grammar[] grammars = new Grammar[allGrammars.size()];
        grammars = allGrammars.toArray(grammars);
        grammarpool.cacheGrammars(TYPE_XSD, grammars);
        // Construct result to end user
        final ValueSequence result = new ValueSequence();
        for (final Grammar one : grammars) {
            result.add(new StringValue(one.getGrammarDescription().getNamespace()));
        }
        return result;
    } else {
        // oh oh
        LOG.error("function not found error");
        throw new XPathException(this, "function not found");
    }
}
Also used : NodeImpl(org.exist.dom.memtree.NodeImpl) XMLInputSource(org.apache.xerces.xni.parser.XMLInputSource) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) IntegerValue(org.exist.xquery.value.IntegerValue) ArrayList(java.util.ArrayList) GrammarPool(org.exist.validation.GrammarPool) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) Grammar(org.apache.xerces.xni.grammars.Grammar) URL(java.net.URL) XPathException(org.exist.xquery.XPathException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XMLGrammarPreparser(org.apache.xerces.parsers.XMLGrammarPreparser) SequenceIterator(org.exist.xquery.value.SequenceIterator) ValueSequence(org.exist.xquery.value.ValueSequence) StringValue(org.exist.xquery.value.StringValue)

Example 4 with NodeImpl

use of org.exist.dom.memtree.NodeImpl 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 5 with NodeImpl

use of org.exist.dom.memtree.NodeImpl 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)

Aggregations

NodeImpl (org.exist.dom.memtree.NodeImpl)53 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)14 XPathException (org.exist.xquery.XPathException)9 DocumentImpl (org.exist.dom.memtree.DocumentImpl)8 Sequence (org.exist.xquery.value.Sequence)8 SAXException (org.xml.sax.SAXException)8 SAXAdapter (org.exist.dom.memtree.SAXAdapter)6 NodeProxy (org.exist.dom.persistent.NodeProxy)6 ValueSequence (org.exist.xquery.value.ValueSequence)6 IOException (java.io.IOException)5 Document (org.w3c.dom.Document)5 InputSource (org.xml.sax.InputSource)5 StringReader (java.io.StringReader)4 QName (org.exist.dom.QName)4 SequenceIterator (org.exist.xquery.value.SequenceIterator)4 XMLReader (org.xml.sax.XMLReader)4 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)3 NodeSet (org.exist.dom.persistent.NodeSet)3 NodeId (org.exist.numbering.NodeId)3 ValidationReport (org.exist.validation.ValidationReport)3