Search in sources :

Example 1 with NodeValue

use of org.exist.xquery.value.NodeValue in project exist by eXist-db.

the class NodeId method eval.

/* (non-Javadoc)
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final NodeValue docNode = (NodeValue) args[0].itemAt(0);
    org.exist.numbering.NodeId nodeId;
    if (docNode.getImplementationType() == NodeValue.IN_MEMORY_NODE) {
        nodeId = ((NodeImpl) docNode).getNodeId();
    } else {
        nodeId = ((NodeProxy) docNode).getNodeId();
    }
    return new StringValue(nodeId.toString());
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) StringValue(org.exist.xquery.value.StringValue)

Example 2 with NodeValue

use of org.exist.xquery.value.NodeValue in project exist by eXist-db.

the class Expand method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    // apply serialization options set on the XQuery context
    final Properties serializeOptions = new Properties();
    serializeOptions.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
    serializeOptions.setProperty(EXistOutputKeys.HIGHLIGHT_MATCHES, "elements");
    if (getArgumentCount() == 2) {
        final String serOpts = args[1].getStringValue();
        final String[] contents = Option.tokenize(serOpts);
        for (String content : contents) {
            final String[] pair = Option.parseKeyValuePair(content);
            if (pair == null) {
                throw new XPathException(this, "Found invalid serialization option: " + content);
            }
            logger.debug("Setting serialization property: {} = {}", pair[0], pair[1]);
            serializeOptions.setProperty(pair[0], pair[1]);
        }
    } else {
        context.checkOptions(serializeOptions);
    }
    context.pushDocumentContext();
    try {
        final InMemoryNodeSet result = new InMemoryNodeSet();
        final MemTreeBuilder builder = new MemTreeBuilder(getContext());
        final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
        int attrNr = -1;
        for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
            final NodeValue next = (NodeValue) i.nextItem();
            final short nodeType = ((INodeHandle) next).getNodeType();
            builder.startDocument();
            if (nodeType == Node.ATTRIBUTE_NODE) {
                // NOTE: Attributes nodes need special handling as they cannot be directly serialized via SAX to a ContentHandler
                final Attr attr = (Attr) next.getNode();
                String ns = attr.getNamespaceURI();
                if (ns == null || ns.isEmpty()) {
                    ns = XMLConstants.NULL_NS_URI;
                }
                attrNr = builder.addAttribute(new QName(attr.getLocalName(), ns), attr.getValue());
            } else {
                next.toSAX(context.getBroker(), receiver, serializeOptions);
            }
            builder.endDocument();
            if (Node.DOCUMENT_NODE == nodeType) {
                result.add(builder.getDocument());
            } else if (Node.ATTRIBUTE_NODE == nodeType) {
                result.add(builder.getDocument().getAttribute(attrNr));
            } else {
                result.add(builder.getDocument().getNode(1));
            }
            builder.reset(getContext());
        }
        return result;
    } catch (final SAXException e) {
        throw new XPathException(this, e);
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) INodeHandle(org.exist.dom.INodeHandle) QName(org.exist.dom.QName) InMemoryNodeSet(org.exist.dom.memtree.InMemoryNodeSet) Properties(java.util.Properties) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Attr(org.w3c.dom.Attr) SAXException(org.xml.sax.SAXException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SequenceIterator(org.exist.xquery.value.SequenceIterator)

Example 3 with NodeValue

use of org.exist.xquery.value.NodeValue in project exist by eXist-db.

the class GetFragmentBetween method eval.

/**
 * Get the fragment between two elements (normally milestone elements) of a document
 *
 * @param contextSequence 1. first node (e.g. pb[10])  2. second node (e.g.: pb[11]) 3. pathCompletion:
 *                        open and closing tags before and after the fragment are appended (Default: true)
 *                        4. Display the namespace of the root node of the fragment (Default: false)
 * @return the fragment between the two nodes
 *
 * @throws XPathException in case of dynamic error
 */
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final Node ms1Node = ((NodeValue) args[0].itemAt(0)).getNode();
    final Optional<Node> ms2Node;
    if (args[1].isEmpty()) {
        ms2Node = Optional.empty();
    } else {
        ms2Node = Optional.of(((NodeValue) args[1].itemAt(0)).getNode());
    }
    final boolean pathCompletion;
    if (args[2].isEmpty()) {
        // default
        pathCompletion = true;
    } else {
        pathCompletion = args[2].itemAt(0).atomize().effectiveBooleanValue();
    }
    final boolean displayRootNamespace;
    if (args[3].isEmpty()) {
        // default
        displayRootNamespace = false;
    } else {
        displayRootNamespace = args[3].itemAt(0).atomize().effectiveBooleanValue();
    }
    // fetch the fragment between the two milestones
    final StringBuilder fragment = getFragmentBetween(ms1Node, ms2Node);
    if (pathCompletion) {
        final String msFromPathName = getNodeXPath(ms1Node.getParentNode(), displayRootNamespace);
        final String openElementsOfMsFrom = pathName2XmlTags(msFromPathName, "open");
        final String closingElementsOfMsTo;
        if (ms2Node.isPresent()) {
            final String msToPathName = getNodeXPath(ms2Node.get().getParentNode(), displayRootNamespace);
            closingElementsOfMsTo = pathName2XmlTags(msToPathName, "close");
        } else {
            closingElementsOfMsTo = "";
        }
        fragment.insert(0, openElementsOfMsFrom);
        fragment.append(closingElementsOfMsTo);
    }
    return new StringValue(fragment.toString());
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) StoredNode(org.exist.dom.persistent.StoredNode) Node(org.w3c.dom.Node) StringValue(org.exist.xquery.value.StringValue)

Example 4 with NodeValue

use of org.exist.xquery.value.NodeValue in project exist by eXist-db.

the class XMLDBAbstractCollectionManipulator method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (0 == args.length) {
        throw new XPathException(this, "Expected a collection as the argument " + (paramNumber + 1) + ".");
    }
    final boolean collectionNeedsClose = false;
    Collection collection = null;
    final Item item = args[paramNumber].itemAt(0);
    if (Type.subTypeOf(item.getType(), Type.NODE)) {
        final NodeValue node = (NodeValue) item;
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Found node");
        }
        if (node.getImplementationType() == NodeValue.PERSISTENT_NODE) {
            final org.exist.collections.Collection internalCol = ((NodeProxy) node).getOwnerDocument().getCollection();
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Found node");
            }
            try {
                // TODO: use xmldbURI
                collection = getLocalCollection(context, internalCol.getURI().toString());
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Loaded collection {}", collection.getName());
                }
            } catch (final XMLDBException e) {
                throw new XPathException(this, "Failed to access collection: " + internalCol.getURI(), e);
            }
        } else {
            return Sequence.EMPTY_SEQUENCE;
        }
    }
    if (collection == null) {
        // Otherwise, just extract the name as a string:
        final String collectionURI = args[paramNumber].getStringValue();
        if (collectionURI != null) {
            try {
                collection = getCollection(context, collectionURI, Optional.empty(), Optional.empty());
            } catch (final XMLDBException xe) {
                if (errorIfAbsent) {
                    throw new XPathException(this, "Could not locate collection: " + collectionURI, xe);
                }
                collection = null;
            }
        }
        if (collection == null && errorIfAbsent) {
            throw new XPathException(this, "Unable to find collection: " + collectionURI);
        }
    }
    Sequence s = Sequence.EMPTY_SEQUENCE;
    try {
        s = evalWithCollection(collection, args, contextSequence);
    } finally {
        if (collectionNeedsClose && collection != null) {
            try {
                collection.close();
            } catch (final Exception e) {
                throw new XPathException(this, "Unable to close collection", e);
            }
        }
    }
    return s;
}
Also used : Item(org.exist.xquery.value.Item) NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) InTxnLocalCollection(org.exist.xmldb.txn.bridge.InTxnLocalCollection) LocalCollection(org.exist.xmldb.LocalCollection) Collection(org.xmldb.api.base.Collection) XMLDBException(org.xmldb.api.base.XMLDBException) Sequence(org.exist.xquery.value.Sequence) XMLDBException(org.xmldb.api.base.XMLDBException) XPathException(org.exist.xquery.XPathException)

Example 5 with NodeValue

use of org.exist.xquery.value.NodeValue in project exist by eXist-db.

the class XMLDBXUpdate method evalWithCollection.

/* (non-Javadoc)
	 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
	 */
public Sequence evalWithCollection(Collection c, Sequence[] args, Sequence contextSequence) throws XPathException {
    final NodeValue data = (NodeValue) args[1].itemAt(0);
    final StringWriter writer = new StringWriter();
    final Properties properties = new Properties();
    properties.setProperty(OutputKeys.INDENT, "yes");
    final DOMSerializer serializer = new ExtendedDOMSerializer(context.getBroker(), writer, properties);
    try {
        serializer.serialize(data.getNode());
    } catch (final TransformerException e) {
        logger.debug("Exception while serializing XUpdate document", e);
        throw new XPathException(this, "Exception while serializing XUpdate document: " + e.getMessage(), e);
    }
    final String xupdate = writer.toString();
    long modifications = 0;
    try {
        final XUpdateQueryService service = (XUpdateQueryService) c.getService("XUpdateQueryService", "1.0");
        logger.debug("Processing XUpdate request: {}", xupdate);
        modifications = service.update(xupdate);
    } catch (final XMLDBException e) {
        throw new XPathException(this, "Exception while processing xupdate: " + e.getMessage(), e);
    }
    context.getRootExpression().resetState(false);
    return new IntegerValue(modifications);
}
Also used : ExtendedDOMSerializer(org.exist.util.serializer.ExtendedDOMSerializer) NodeValue(org.exist.xquery.value.NodeValue) ExtendedDOMSerializer(org.exist.util.serializer.ExtendedDOMSerializer) DOMSerializer(org.exist.util.serializer.DOMSerializer) StringWriter(java.io.StringWriter) XUpdateQueryService(org.xmldb.api.modules.XUpdateQueryService) XPathException(org.exist.xquery.XPathException) IntegerValue(org.exist.xquery.value.IntegerValue) XMLDBException(org.xmldb.api.base.XMLDBException) Properties(java.util.Properties) TransformerException(javax.xml.transform.TransformerException)

Aggregations

NodeValue (org.exist.xquery.value.NodeValue)52 XPathException (org.exist.xquery.XPathException)35 Sequence (org.exist.xquery.value.Sequence)21 Item (org.exist.xquery.value.Item)17 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)16 Node (org.w3c.dom.Node)15 NodeProxy (org.exist.dom.persistent.NodeProxy)11 IOException (java.io.IOException)10 QName (org.exist.dom.QName)10 Element (org.w3c.dom.Element)7 SAXException (org.xml.sax.SAXException)7 Properties (java.util.Properties)6 SequenceIterator (org.exist.xquery.value.SequenceIterator)6 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)5 BrokerPool (org.exist.storage.BrokerPool)5 DBBroker (org.exist.storage.DBBroker)5 StringValue (org.exist.xquery.value.StringValue)5 Path (java.nio.file.Path)4 NodeImpl (org.exist.dom.memtree.NodeImpl)4 Serializer (org.exist.storage.serializers.Serializer)4