Search in sources :

Example 21 with NodeProxy

use of org.exist.dom.persistent.NodeProxy in project exist by eXist-db.

the class DocUtils method getDocumentByPathFromDB.

private static Sequence getDocumentByPathFromDB(final XQueryContext context, final String path) throws XPathException, PermissionDeniedException {
    // check if the loaded documents should remain locked
    final LockMode lockType = context.lockDocumentsOnLoad() ? LockMode.WRITE_LOCK : LockMode.READ_LOCK;
    try {
        final XmldbURI baseURI = context.getBaseURI().toXmldbURI();
        final XmldbURI pathUri;
        if (baseURI != null && !(baseURI.equals("") || baseURI.equals("/db"))) {
            // relative collection Path: add the current base URI
            pathUri = baseURI.resolveCollectionPath(XmldbURI.xmldbUriFor(path, false));
        } else {
            pathUri = XmldbURI.xmldbUriFor(path, false);
        }
        // relative collection Path: add the current module call URI if applicable
        final XmldbURI resourceUri = Optional.ofNullable(context.getModuleLoadPath()).filter(moduleLoadPath -> !moduleLoadPath.isEmpty()).flatMap(moduleLoadPath -> Try(() -> XmldbURI.xmldbUriFor(moduleLoadPath)).toOption()).map(moduleLoadPath -> moduleLoadPath.resolveCollectionPath(pathUri)).orElse(pathUri);
        // try to open the document and acquire a lock
        try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(resourceUri, lockType)) {
            if (lockedDoc == null) {
                return Sequence.EMPTY_SEQUENCE;
            } else {
                final DocumentImpl doc = lockedDoc.getDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.READ)) {
                    throw new PermissionDeniedException("Insufficient privileges to read resource " + path);
                }
                if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                    throw new XPathException("Document " + path + " is a binary resource, not an XML document. Please consider using the function util:binary-doc() to retrieve a reference to it.");
                }
                return new NodeProxy(doc);
            }
        }
    } catch (final URISyntaxException e) {
        throw new XPathException(e);
    }
}
Also used : LockMode(org.exist.storage.lock.Lock.LockMode) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) BrokerPool(org.exist.storage.BrokerPool) XMLReaderPool(org.exist.util.XMLReaderPool) ErrorCodes(org.exist.xquery.ErrorCodes) NodeProxy(org.exist.dom.persistent.NodeProxy) PermissionDeniedException(org.exist.security.PermissionDeniedException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) XMLReader(org.xml.sax.XMLReader) Source(org.exist.source.Source) java.net(java.net) Namespaces(org.exist.Namespaces) Document(org.w3c.dom.Document) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) Permission(org.exist.security.Permission) XQueryContext(org.exist.xquery.XQueryContext) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) LockedDocument(org.exist.dom.persistent.LockedDocument) AnyURIValue(org.exist.xquery.value.AnyURIValue) IOException(java.io.IOException) Try(com.evolvedbinary.j8fu.Try.Try) URLSource(org.exist.source.URLSource) SAXException(org.xml.sax.SAXException) SourceFactory(org.exist.source.SourceFactory) Optional(java.util.Optional) Sequence(org.exist.xquery.value.Sequence) Pattern(java.util.regex.Pattern) SAXAdapter(org.exist.dom.memtree.SAXAdapter) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) XPathException(org.exist.xquery.XPathException) LockedDocument(org.exist.dom.persistent.LockedDocument) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockMode(org.exist.storage.lock.Lock.LockMode) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) XmldbURI(org.exist.xmldb.XmldbURI)

Example 22 with NodeProxy

use of org.exist.dom.persistent.NodeProxy in project exist by eXist-db.

the class ArrayListValueSequence method toNodeSet.

@Override
public NodeSet toNodeSet() throws XPathException {
    if (isEmpty) {
        return NodeSet.EMPTY_SET;
    }
    // for this method to work, all items have to be nodes
    if (itemType != Type.ANY_TYPE && Type.subTypeOf(itemType, Type.NODE)) {
        final NodeSet set = new NewArrayNodeSet();
        for (int i = 0; i <= values.size(); i++) {
            NodeValue v = (NodeValue) values.get(i);
            if (v.getImplementationType() != NodeValue.PERSISTENT_NODE) {
                // found an in-memory document
                final DocumentImpl doc;
                if (v.getType() == Type.DOCUMENT) {
                    doc = (DocumentImpl) v;
                } else {
                    doc = ((NodeImpl) v).getOwnerDocument();
                }
                if (doc == null) {
                    continue;
                }
                // make this document persistent: doc.makePersistent()
                // returns a map of all root node ids mapped to the corresponding
                // persistent node. We scan the current sequence and replace all
                // in-memory nodes with their new persistent node objects.
                final DocumentImpl expandedDoc = doc.expandRefs(null);
                final org.exist.dom.persistent.DocumentImpl newDoc = expandedDoc.makePersistent();
                if (newDoc != null) {
                    NodeId rootId = newDoc.getBrokerPool().getNodeFactory().createInstance();
                    for (int j = i; j <= values.size(); j++) {
                        v = (NodeValue) values.get(j);
                        if (v.getImplementationType() != NodeValue.PERSISTENT_NODE) {
                            NodeImpl node = (NodeImpl) v;
                            final Document nodeOwnerDoc;
                            if (node.getNodeType() == Node.DOCUMENT_NODE) {
                                nodeOwnerDoc = (Document) node;
                            } else {
                                nodeOwnerDoc = node.getOwnerDocument();
                            }
                            if (nodeOwnerDoc == doc) {
                                if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                                    node = expandedDoc.getAttribute(node.getNodeNumber());
                                } else {
                                    node = expandedDoc.getNode(node.getNodeNumber());
                                }
                                NodeId nodeId = node.getNodeId();
                                if (nodeId == null) {
                                    throw new XPathException("Internal error: nodeId == null");
                                }
                                if (node.getNodeType() == Node.DOCUMENT_NODE) {
                                    nodeId = rootId;
                                } else {
                                    nodeId = rootId.append(nodeId);
                                }
                                final NodeProxy p = new NodeProxy(newDoc, nodeId, node.getNodeType());
                                // replace the node by the NodeProxy
                                values.set(j, p);
                                setHasChanged();
                            }
                        }
                    }
                    set.add((NodeProxy) values.get(i));
                }
            } else {
                set.add((NodeProxy) v);
            }
        }
        // }
        return set;
    } else {
        throw new XPathException("Type error: the sequence cannot be converted into" + " a node set. Item type is " + Type.getTypeName(itemType));
    }
}
Also used : NodeSet(org.exist.dom.persistent.NodeSet) NewArrayNodeSet(org.exist.dom.persistent.NewArrayNodeSet) NewArrayNodeSet(org.exist.dom.persistent.NewArrayNodeSet) NodeImpl(org.exist.dom.memtree.NodeImpl) XPathException(org.exist.xquery.XPathException) Document(org.w3c.dom.Document) DocumentImpl(org.exist.dom.memtree.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) NodeId(org.exist.numbering.NodeId)

Example 23 with NodeProxy

use of org.exist.dom.persistent.NodeProxy in project exist by eXist-db.

the class MarshallerTest method nodes.

@Test
public void nodes() throws EXistException, PermissionDeniedException, SAXException, XPathException, XMLStreamException {
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
        DocumentImpl doc = (DocumentImpl) broker.getXMLResource(TEST_COLLECTION_URI.append("test.xml"));
        NodeProxy p = new NodeProxy(doc, pool.getNodeFactory().createFromString("1.1"));
        StringWriter writer = new StringWriter();
        SAXSerializer serializer = new SAXSerializer(writer, new Properties());
        Marshaller.marshall(broker, p, serializer);
        String serialized = writer.toString();
        Sequence seq = Marshaller.demarshall(broker, new StringReader(serialized));
        assertTrue(Type.subTypeOf(seq.getItemType(), Type.NODE));
        NodeValue n = (NodeValue) seq.itemAt(0);
        writer = new StringWriter();
        serializer.reset();
        serializer.setOutput(writer, new Properties());
        n.toSAX(broker, serializer, new Properties());
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) StringWriter(java.io.StringWriter) StringReader(java.io.StringReader) SAXSerializer(org.exist.util.serializer.SAXSerializer) Properties(java.util.Properties) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 24 with NodeProxy

use of org.exist.dom.persistent.NodeProxy in project exist by eXist-db.

the class ExceptTest method persistent_except_memtree.

/**
 * Tests the XQuery `except` operator against a
 * persistent node on the left and an in-memory node on the right
 */
@Test
public void persistent_except_memtree() throws XPathException, NoSuchMethodException {
    final XQueryContext mockContext = createMock(XQueryContext.class);
    final PathExpr mockLeft = createMock(PathExpr.class);
    final PathExpr mockRight = createMock(PathExpr.class);
    final Sequence mockContextSequence = createMock(Sequence.class);
    final Item mockContextItem = createMock(Item.class);
    final Profiler mockProfiler = createMock(Profiler.class);
    final DocumentImpl mockPersistentDoc = createMock(DocumentImpl.class);
    final NodeProxy mockPersistentNode = createMockBuilder(NodeProxy.class).withConstructor(DocumentImpl.class, NodeId.class).withArgs(mockPersistentDoc, new DLN(1)).addMockedMethods(NodeProxy.class.getMethod("isEmpty", new Class[] {}), NodeProxy.class.getMethod("getItemType", new Class[] {}), NodeProxy.class.getMethod("equals", new Class[] { Object.class })).createMock();
    expect(mockContext.nextExpressionId()).andReturn(1);
    expect(mockContext.getProfiler()).andReturn(mockProfiler);
    // persistent node
    expect(mockLeft.eval(mockContextSequence, mockContextItem)).andReturn(mockPersistentNode);
    // memtree node
    expect(mockRight.eval(mockContextSequence, mockContextItem)).andReturn((org.exist.dom.memtree.ElementImpl) createInMemoryDocument().getDocumentElement());
    expect(mockPersistentNode.isEmpty()).andReturn(false);
    expect(mockPersistentNode.getItemType()).andReturn(Type.NODE);
    expect(mockContext.getProfiler()).andReturn(mockProfiler);
    replay(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
    // test
    final Except except = new Except(mockContext, mockLeft, mockRight);
    final Sequence result = except.eval(mockContextSequence, mockContextItem);
    assertEquals(1, ((ValueSequence) result).size());
    verify(mockPersistentDoc, mockPersistentNode, mockRight, mockLeft, mockContext);
}
Also used : DLN(org.exist.numbering.DLN) NodeId(org.exist.numbering.NodeId) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) Test(org.junit.Test)

Example 25 with NodeProxy

use of org.exist.dom.persistent.NodeProxy in project exist by eXist-db.

the class ValueSequenceTest method sortInDocumentOrder.

@Test
public void sortInDocumentOrder() throws EXistException, PermissionDeniedException, AuthenticationException {
    final ValueSequence seq = new ValueSequence(true);
    seq.keepUnOrdered(true);
    // in-memory doc
    final MemTreeBuilder memtree = new MemTreeBuilder();
    memtree.startDocument();
    memtree.startElement(new QName("m1", XMLConstants.NULL_NS_URI), null);
    memtree.startElement(new QName("m2", XMLConstants.NULL_NS_URI), null);
    memtree.characters("test data");
    memtree.endElement();
    memtree.endElement();
    memtree.endDocument();
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final Subject admin = pool.getSecurityManager().authenticate("admin", "");
    try (final DBBroker broker = pool.get(Optional.of(admin))) {
        // persistent doc
        final Collection sysCollection = broker.getCollection(SecurityManager.SECURITY_COLLECTION_URI);
        final DocumentImpl doc = sysCollection.getDocument(broker, XmldbURI.create("config.xml"));
        final NodeProxy docProxy = new NodeProxy(doc);
        final NodeProxy nodeProxy = new NodeProxy(doc, ((NodeImpl) doc.getFirstChild()).getNodeId());
        seq.add(memtree.getDocument());
        seq.add(docProxy);
        seq.add((org.exist.dom.memtree.NodeImpl) memtree.getDocument().getFirstChild());
        seq.add(nodeProxy);
        // call sort
        seq.sortInDocumentOrder();
    }
}
Also used : DBBroker(org.exist.storage.DBBroker) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) Collection(org.exist.collections.Collection) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) BrokerPool(org.exist.storage.BrokerPool)

Aggregations

NodeProxy (org.exist.dom.persistent.NodeProxy)79 DocumentImpl (org.exist.dom.persistent.DocumentImpl)18 Sequence (org.exist.xquery.value.Sequence)17 NodeSet (org.exist.dom.persistent.NodeSet)16 NodeId (org.exist.numbering.NodeId)16 XPathException (org.exist.xquery.XPathException)16 IOException (java.io.IOException)12 NewArrayNodeSet (org.exist.dom.persistent.NewArrayNodeSet)10 PermissionDeniedException (org.exist.security.PermissionDeniedException)10 LockException (org.exist.util.LockException)10 NodeValue (org.exist.xquery.value.NodeValue)10 Node (org.w3c.dom.Node)9 Document (org.w3c.dom.Document)8 SAXException (org.xml.sax.SAXException)8 NodeImpl (org.exist.dom.memtree.NodeImpl)7 ExtArrayNodeSet (org.exist.dom.persistent.ExtArrayNodeSet)7 SequenceIterator (org.exist.xquery.value.SequenceIterator)7 ReentrantLock (java.util.concurrent.locks.ReentrantLock)6 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)6 Match (org.exist.dom.persistent.Match)6