Search in sources :

Example 56 with DocumentImpl

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

the class Serializer method setStylesheet.

/**
 *  Plug an XSL stylesheet into the processing pipeline.
 *  All output will be passed to this stylesheet.
 *
 * @param doc the document
 * @param stylesheet the stylesheet
 *
 * @throws TransformerConfigurationException if the stylesheet cannot be set
 */
public void setStylesheet(Document doc, String stylesheet) throws TransformerConfigurationException {
    if (stylesheet == null) {
        templates = null;
        return;
    }
    final long start = System.currentTimeMillis();
    xslHandler = null;
    XmldbURI stylesheetUri = null;
    URI externalUri = null;
    try {
        stylesheetUri = XmldbURI.xmldbUriFor(stylesheet);
        if (!stylesheetUri.toCollectionPathURI().equals(stylesheetUri)) {
            externalUri = stylesheetUri.getXmldbURI();
        }
    } catch (final URISyntaxException e) {
        // could be an external URI!
        try {
            externalUri = new URI(stylesheet);
        } catch (final URISyntaxException ee) {
            throw new IllegalArgumentException("Stylesheet URI could not be parsed: " + ee.getMessage());
        }
    }
    // does stylesheet point to an external resource?
    if (externalUri != null) {
        final StreamSource source = new StreamSource(externalUri.toString());
        this.templates = factory.get().newTemplates(source);
    // read stylesheet from the database
    } else {
        // current collection and normalize
        if (doc != null && doc instanceof DocumentImpl) {
            stylesheetUri = ((DocumentImpl) doc).getCollection().getURI().resolveCollectionPath(stylesheetUri).normalizeCollectionPath();
        }
        // load stylesheet from eXist
        DocumentImpl xsl = null;
        try {
            xsl = broker.getResource(stylesheetUri, Permission.READ);
        } catch (final PermissionDeniedException e) {
            throw new TransformerConfigurationException("permission denied to read " + stylesheetUri);
        }
        if (xsl == null) {
            throw new TransformerConfigurationException("stylesheet not found: " + stylesheetUri);
        }
        // TODO: use xmldbURI
        if (xsl.getCollection() != null) {
            factory.get().setURIResolver(new InternalURIResolver(xsl.getCollection().getURI().toString()));
        }
        // save handlers
        Receiver oldReceiver = receiver;
        // compile stylesheet
        factory.get().setErrorListener(new ErrorListener());
        final TemplatesHandler handler = factory.get().newTemplatesHandler();
        receiver = new ReceiverToSAX(handler);
        try {
            this.serializeToReceiver(xsl, true);
            templates = handler.getTemplates();
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
        // restore handlers
        receiver = oldReceiver;
        factory.get().setURIResolver(null);
    }
    LOG.debug("compiling stylesheet took {}", System.currentTimeMillis() - start);
    if (templates != null) {
        xslHandler = factory.get().newTransformerHandler(templates);
        try {
            xslHandler.startDocument();
            documentStarted = true;
        } catch (final SAXException e) {
            throw new TransformerConfigurationException(e.getMessage(), e);
        }
    }
    // xslHandler.getTransformer().setOutputProperties(outputProperties);
    checkStylesheetParams();
}
Also used : TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) StreamSource(javax.xml.transform.stream.StreamSource) Receiver(org.exist.util.serializer.Receiver) TemplatesHandler(javax.xml.transform.sax.TemplatesHandler) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmldbURI(org.exist.xmldb.XmldbURI)

Example 57 with DocumentImpl

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

the class NativeStructuralIndexWorker method scanIndex.

/**
 * Collect index statistics. Used by functions like util:index-keys.
 *
 * @param context the xquery context
 * @param docs The documents to which the index entries belong
 * @param contextSet ignored by this index
 * @param hints Some "hints" for retrieving the index entries. See such hints in
 * {@link org.exist.indexing.OrderedValuesIndex} and {@link org.exist.indexing.QNamedKeysIndex}.
 * @return the matching occurrences
 */
public Occurrences[] scanIndex(XQueryContext context, DocumentSet docs, NodeSet contextSet, Map hints) {
    final Map<String, Occurrences> occurrences = new TreeMap<>();
    for (final Iterator<DocumentImpl> i = docs.getDocumentIterator(); i.hasNext(); ) {
        final DocumentImpl doc = i.next();
        final List<QName> qnames = getQNamesForDoc(doc);
        for (final QName qname : qnames) {
            final String name;
            if (qname.getNameType() == ElementValue.ATTRIBUTE) {
                name = "@" + qname.getLocalPart();
            } else {
                name = qname.getLocalPart();
            }
            final byte[] fromKey = computeKey(qname.getNameType(), qname, doc.getDocId());
            final byte[] toKey = computeKey(qname.getNameType(), qname, doc.getDocId() + 1);
            final IndexQuery query = new IndexQuery(IndexQuery.RANGE, new Value(fromKey), new Value(toKey));
            try (final ManagedLock<ReentrantLock> btreeLock = index.lockManager.acquireBtreeReadLock(index.btree.getLockName())) {
                index.btree.query(query, (value, pointer) -> {
                    Occurrences oc = occurrences.get(name);
                    if (oc == null) {
                        oc = new Occurrences(name);
                        occurrences.put(name, oc);
                        oc.addDocument(doc);
                        oc.addOccurrences(1);
                    } else {
                        oc.addOccurrences(1);
                        oc.addDocument(doc);
                    }
                    return true;
                });
            } catch (final LockException e) {
                NativeStructuralIndex.LOG.warn("Failed to lock structural index: {}", e.getMessage(), e);
            } catch (final Exception e) {
                NativeStructuralIndex.LOG.warn("Exception caught while reading structural index for document {}: {}", doc.getURI(), e.getMessage(), e);
            }
        }
    }
    final Occurrences[] result = new Occurrences[occurrences.size()];
    int i = 0;
    for (Occurrences occ : occurrences.values()) {
        result[i++] = occ;
    }
    return result;
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) IndexQuery(org.exist.storage.btree.IndexQuery) QName(org.exist.dom.QName) Occurrences(org.exist.util.Occurrences) DocumentImpl(org.exist.dom.persistent.DocumentImpl) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) DatabaseConfigurationException(org.exist.util.DatabaseConfigurationException) LockException(org.exist.util.LockException) Value(org.exist.storage.btree.Value)

Example 58 with DocumentImpl

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

the class XPathUtil method getNode.

/**
 * Converts an XMLResource into a NodeProxy.
 *
 * @param broker The DBBroker to use to access the database
 * @param xres The XMLResource to convert
 * @return A NodeProxy for accessing the content represented by xres
 * @throws XPathException if an XMLDBException is encountered
 */
public static final NodeProxy getNode(DBBroker broker, XMLResource xres) throws XPathException {
    if (xres instanceof LocalXMLResource) {
        final LocalXMLResource lres = (LocalXMLResource) xres;
        try {
            return lres.getNode();
        } catch (final XMLDBException xe) {
            throw new XPathException("Failed to convert LocalXMLResource to node: " + xe.getMessage());
        }
    }
    DocumentImpl document;
    try {
        document = broker.getCollection(XmldbURI.xmldbUriFor(xres.getParentCollection().getName())).getDocument(broker, XmldbURI.xmldbUriFor(xres.getDocumentId()));
    } catch (final URISyntaxException xe) {
        throw new XPathException(xe);
    } catch (final XMLDBException xe) {
        throw new XPathException("Failed to get document for RemoteXMLResource: " + xe.getMessage());
    } catch (final PermissionDeniedException pde) {
        throw new XPathException("Failed to get document: " + pde.getMessage());
    }
    final NodeId nodeId = broker.getBrokerPool().getNodeFactory().createFromString(((RemoteXMLResource) xres).getNodeId());
    return new NodeProxy(document, nodeId);
}
Also used : LocalXMLResource(org.exist.xmldb.LocalXMLResource) NodeId(org.exist.numbering.NodeId) XMLDBException(org.xmldb.api.base.XMLDBException) PermissionDeniedException(org.exist.security.PermissionDeniedException) URISyntaxException(java.net.URISyntaxException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy)

Example 59 with DocumentImpl

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

the class FunDoc method registerUpdateListener.

protected void registerUpdateListener() {
    if (listener == null) {
        listener = new UpdateListener() {

            @Override
            public void documentUpdated(DocumentImpl document, int event) {
            // clear all
            }

            @Override
            public void unsubscribe() {
                FunDoc.this.listener = null;
            }

            public void nodeMoved(NodeId oldNodeId, NodeHandle newNode) {
            // not relevant
            }

            @Override
            public void debug() {
                logger.debug("UpdateListener: Line: {}: {}", getLine(), FunDoc.this.toString());
            }
        };
        context.registerUpdateListener(listener);
    }
}
Also used : NodeHandle(org.exist.dom.persistent.NodeHandle) NodeId(org.exist.numbering.NodeId) UpdateListener(org.exist.storage.UpdateListener) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Example 60 with DocumentImpl

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

the class FunInScopePrefixes method collectPrefixes.

public static Map<String, String> collectPrefixes(XQueryContext context, NodeValue nodeValue) {
    final Map<String, String> prefixes = new LinkedHashMap<>();
    prefixes.put("xml", Namespaces.XML_NS);
    final Map<String, String> inScopePrefixes = context.getInScopePrefixes();
    if (inScopePrefixes != null) {
        prefixes.putAll(inScopePrefixes);
    }
    if (nodeValue.getImplementationType() == NodeValue.PERSISTENT_NODE) {
        // NodeProxy proxy = (NodeProxy) node;
        Node node = nodeValue.getNode();
        if (context.preserveNamespaces()) {
            // Horrible hacks to work-around bad in-scope NS : we reconstruct a NS context !
            if (context.inheritNamespaces()) {
                // Grab ancestors' NS
                final Deque<Element> stack = new ArrayDeque<>();
                do {
                    stack.add((Element) node);
                    node = node.getParentNode();
                } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
                while (!stack.isEmpty()) {
                    collectNamespacePrefixes(stack.pop(), prefixes);
                }
            /*
					NodeSet ancestors = nodeValue.getAncestors(contextId, true);
					for (Iterator i = ancestors.iterator(); i.hasNext(); ) {
						proxy = (NodeProxy) i.next();
						collectNamespacePrefixes((ElementImpl)node, prefixes);
					}
					*/
            } else {
                // Grab self's NS
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    collectNamespacePrefixes((Element) node, prefixes);
                }
            }
        } else {
            // untested : copied from below
            if (context.inheritNamespaces()) {
                // get the top-most ancestor
                final Deque<Element> stack = new ArrayDeque<>();
                do {
                    if (node.getParentNode() == null || node.getParentNode() instanceof DocumentImpl) {
                        stack.add((Element) node);
                    }
                    node = node.getParentNode();
                } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
                while (!stack.isEmpty()) {
                    collectNamespacePrefixes(stack.pop(), prefixes);
                }
            }
        }
    } else {
        // In-memory node
        // NodeImpl nodeImpl = (NodeImpl) node;
        Node node = nodeValue.getNode();
        if (context.preserveNamespaces()) {
            // Horrible hacks to work-around bad in-scope NS : we reconstruct a NS context !
            if (context.inheritNamespaces()) {
                // Grab ancestors' NS
                final Deque<Element> stack = new ArrayDeque<>();
                do {
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        stack.add((Element) node);
                    }
                    node = node.getParentNode();
                } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
                while (!stack.isEmpty()) {
                    collectNamespacePrefixes(stack.pop(), prefixes);
                }
            } else {
                // Grab self's NS
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    collectNamespacePrefixes((Element) node, prefixes);
                }
            }
        } else {
            if (context.inheritNamespaces()) {
                // get the top-most ancestor
                final Deque<Element> stack = new ArrayDeque<>();
                do {
                    if (node.getParentNode() == null || node.getParentNode() instanceof org.exist.dom.memtree.DocumentImpl) {
                        stack.add((Element) node);
                    }
                    node = node.getParentNode();
                } while (node != null && node.getNodeType() == Node.ELEMENT_NODE);
                while (!stack.isEmpty()) {
                    collectNamespacePrefixes(stack.pop(), prefixes);
                }
            }
        }
    }
    // clean up
    String key = null;
    String value = null;
    for (final Entry<String, String> entry : prefixes.entrySet()) {
        key = entry.getKey();
        value = entry.getValue();
        if ((key == null || key.isEmpty()) && (value == null || value.isEmpty())) {
            prefixes.remove(key);
        }
    }
    return prefixes;
}
Also used : Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) DocumentImpl(org.exist.dom.persistent.DocumentImpl)

Aggregations

DocumentImpl (org.exist.dom.persistent.DocumentImpl)128 PermissionDeniedException (org.exist.security.PermissionDeniedException)51 Collection (org.exist.collections.Collection)40 LockedDocument (org.exist.dom.persistent.LockedDocument)39 Txn (org.exist.storage.txn.Txn)35 XmldbURI (org.exist.xmldb.XmldbURI)34 EXistException (org.exist.EXistException)27 LockException (org.exist.util.LockException)26 DBBroker (org.exist.storage.DBBroker)25 IOException (java.io.IOException)19 NodeProxy (org.exist.dom.persistent.NodeProxy)18 URISyntaxException (java.net.URISyntaxException)17 BrokerPool (org.exist.storage.BrokerPool)17 TransactionManager (org.exist.storage.txn.TransactionManager)17 Test (org.junit.Test)17 XPathException (org.exist.xquery.XPathException)16 NodeId (org.exist.numbering.NodeId)14 SAXException (org.xml.sax.SAXException)13 StoredNode (org.exist.dom.persistent.StoredNode)12 BinaryDocument (org.exist.dom.persistent.BinaryDocument)11