Search in sources :

Example 91 with QName

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

the class ExampleFunctions method sayHello.

/**
 * Creates an XML document like <hello>name</hello>.
 *
 * @param name An optional name, if empty then "stranger" is used.
 *
 * @return An XML document
 */
private DocumentImpl sayHello(final Optional<StringValue> name) throws XPathException {
    try {
        final MemTreeBuilder builder = new MemTreeBuilder(context);
        builder.startDocument();
        builder.startElement(new QName("hello"), null);
        builder.characters(name.map(StringValue::toString).orElse("stranger"));
        builder.endElement();
        builder.endDocument();
        return builder.getDocument();
    } catch (final QName.IllegalQNameException e) {
        throw new XPathException(this, e.getMessage(), e);
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) StringValue(org.exist.xquery.value.StringValue)

Example 92 with QName

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

the class Directory method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
        logger.error("Invalid user", xPathException);
        throw xPathException;
    }
    final String inputPath = args[0].getStringValue();
    final Path directoryPath = FileModuleHelper.getFile(inputPath);
    if (logger.isDebugEnabled()) {
        logger.debug("Listing matching files in directory: {}", directoryPath.toAbsolutePath().toString());
    }
    if (!Files.isDirectory(directoryPath)) {
        throw new XPathException(this, "'" + inputPath + "' does not point to a valid directory.");
    }
    // Get list of files, null if baseDir does not point to a directory
    context.pushDocumentContext();
    try (final Stream<Path> scannedFiles = Files.list(directoryPath)) {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("list", null, null), null);
        scannedFiles.forEach(entry -> {
            if (logger.isDebugEnabled()) {
                logger.debug("Found: {}", entry.toAbsolutePath().toString());
            }
            String entryType = "unknown";
            if (Files.isRegularFile(entry)) {
                entryType = "file";
            } else if (Files.isDirectory(entry)) {
                entryType = "directory";
            }
            builder.startElement(new QName(entryType, NAMESPACE_URI, PREFIX), null);
            builder.addAttribute(new QName("name", null, null), FileUtils.fileName(entry));
            try {
                if (Files.isRegularFile(entry)) {
                    final Long sizeLong = Files.size(entry);
                    String sizeString = Long.toString(sizeLong);
                    String humanSize = getHumanSize(sizeLong, sizeString);
                    builder.addAttribute(new QName("size", null, null), sizeString);
                    builder.addAttribute(new QName("human-size", null, null), humanSize);
                }
                builder.addAttribute(new QName("modified", null, null), new DateTimeValue(new Date(Files.getLastModifiedTime(entry).toMillis())).getStringValue());
                builder.addAttribute(new QName("hidden", null, null), new BooleanValue(Files.isHidden(entry)).getStringValue());
                builder.addAttribute(new QName("canRead", null, null), new BooleanValue(Files.isReadable(entry)).getStringValue());
                builder.addAttribute(new QName("canWrite", null, null), new BooleanValue(Files.isWritable(entry)).getStringValue());
            } catch (final IOException | XPathException ioe) {
                LOG.warn(ioe);
            }
            builder.endElement();
        });
        builder.endElement();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } catch (final IOException ioe) {
        throw new XPathException(this, ioe);
    } finally {
        context.popDocumentContext();
    }
}
Also used : Path(java.nio.file.Path) NodeValue(org.exist.xquery.value.NodeValue) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) IOException(java.io.IOException) Date(java.util.Date) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue)

Example 93 with QName

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

the class NativeStructuralIndexWorker method removeDocument.

protected void removeDocument(DocumentImpl docToRemove) {
    if (index.btree == null) {
        return;
    }
    final List<QName> qnames = getQNamesForDoc(docToRemove);
    for (final QName qname : qnames) {
        final byte[] fromKey = computeKey(qname.getNameType(), qname, docToRemove.getDocId());
        final byte[] toKey = computeKey(qname.getNameType(), qname, docToRemove.getDocId() + 1);
        final IndexQuery query = new IndexQuery(IndexQuery.RANGE, new Value(fromKey), new Value(toKey));
        try (final ManagedLock<ReentrantLock> btreeLock = index.lockManager.acquireBtreeWriteLock(index.btree.getLockName())) {
            index.btree.remove(query, null);
        } 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 removing structural index for document {}: {}", docToRemove.getURI(), e.getMessage(), e);
        }
    }
    removeQNamesForDoc(docToRemove);
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) IndexQuery(org.exist.storage.btree.IndexQuery) LockException(org.exist.util.LockException) QName(org.exist.dom.QName) Value(org.exist.storage.btree.Value) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) DatabaseConfigurationException(org.exist.util.DatabaseConfigurationException)

Example 94 with QName

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

the class NativeStructuralIndexWorker method removeSome.

protected void removeSome() {
    if (pending.size() == 0) {
        return;
    }
    try {
        for (final Map.Entry<QName, List<NodeProxy>> entry : pending.entrySet()) {
            final QName qname = entry.getKey();
            try (final ManagedLock<ReentrantLock> btreeLock = index.lockManager.acquireBtreeWriteLock(index.btree.getLockName())) {
                final List<NodeProxy> nodes = entry.getValue();
                for (final NodeProxy proxy : nodes) {
                    final NodeId nodeId = proxy.getNodeId();
                    final byte[] key = computeKey(qname.getNameType(), qname, document.getDocId(), nodeId);
                    index.btree.removeValue(new Value(key));
                }
            } 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 writing to structural index: {}", e.getMessage(), e);
            }
        }
    } finally {
        pending.clear();
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) QName(org.exist.dom.QName) NodeProxy(org.exist.dom.persistent.NodeProxy) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockException(org.exist.util.LockException) DatabaseConfigurationException(org.exist.util.DatabaseConfigurationException) LockException(org.exist.util.LockException) NodeId(org.exist.numbering.NodeId) Value(org.exist.storage.btree.Value) NodeList(org.w3c.dom.NodeList)

Example 95 with QName

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

Aggregations

QName (org.exist.dom.QName)271 Test (org.junit.Test)54 Sequence (org.exist.xquery.value.Sequence)39 DBBroker (org.exist.storage.DBBroker)31 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)28 IOException (java.io.IOException)23 Document (org.w3c.dom.Document)23 DocumentSet (org.exist.dom.persistent.DocumentSet)20 Text (org.w3c.dom.Text)20 AttributesImpl (org.xml.sax.helpers.AttributesImpl)18 NameTest (org.exist.xquery.NameTest)17 XPathException (org.exist.xquery.XPathException)17 BrokerPool (org.exist.storage.BrokerPool)15 IllegalQNameException (org.exist.dom.QName.IllegalQNameException)13 Node (org.w3c.dom.Node)12 ReentrantLock (java.util.concurrent.locks.ReentrantLock)11 NodeSet (org.exist.dom.persistent.NodeSet)11 SAXException (org.xml.sax.SAXException)11 DefaultDocumentSet (org.exist.dom.persistent.DefaultDocumentSet)10 MutableDocumentSet (org.exist.dom.persistent.MutableDocumentSet)10