Search in sources :

Example 16 with NodeValue

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

the class LocalXMLResource method getContentAsSAX.

@Override
public void getContentAsSAX(final ContentHandler handler) throws XMLDBException {
    // case 1: content is an external DOM node
    if (root != null && !(root instanceof NodeValue)) {
        try {
            final String option = collection.getProperty(Serializer.GENERATE_DOC_EVENTS, "false");
            final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
            try {
                streamer.setContentHandler(handler);
                streamer.setLexicalHandler(lexicalHandler);
                streamer.serialize(root, option.equalsIgnoreCase("true"));
            } finally {
                SerializerPool.getInstance().returnObject(streamer);
            }
        } catch (final Exception e) {
            throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, e.getMessage(), e);
        }
    } else {
        withDb((broker, transaction) -> {
            try {
                // case 2: content is an atomic value
                if (value != null) {
                    value.toSAX(broker, handler, getProperties());
                // case 3: content is an internal node or a document
                } else {
                    final Serializer serializer = broker.borrowSerializer();
                    try {
                        serializer.setUser(user);
                        serializer.setProperties(getProperties());
                        serializer.setSAXHandlers(handler, lexicalHandler);
                        if (root != null) {
                            serializer.toSAX((NodeValue) root);
                        } else if (proxy != null) {
                            serializer.toSAX(proxy);
                        } else {
                            read(broker, transaction).apply((document, broker1, transaction1) -> {
                                try {
                                    serializer.toSAX(document);
                                    return null;
                                } catch (final SAXException e) {
                                    throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage(), e);
                                }
                            });
                        }
                    } finally {
                        broker.returnSerializer(serializer);
                    }
                }
                return null;
            } catch (final SAXException e) {
                throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage(), e);
            }
        });
    }
}
Also used : Tuple3(com.evolvedbinary.j8fu.tuple.Tuple3) StoredNode(org.exist.dom.persistent.StoredNode) Txn(org.exist.storage.txn.Txn) SAXSerializer(org.exist.util.serializer.SAXSerializer) net.sf.cglib.proxy(net.sf.cglib.proxy) BrokerPool(org.exist.storage.BrokerPool) TransformerException(javax.xml.transform.TransformerException) NodeProxy(org.exist.dom.persistent.NodeProxy) AtomicValue(org.exist.xquery.value.AtomicValue) MimeType(org.exist.util.MimeType) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) StringValue(org.exist.xquery.value.StringValue) LexicalHandler(org.xml.sax.ext.LexicalHandler) SerializerPool(org.exist.util.serializer.SerializerPool) AttrImpl(org.exist.dom.memtree.AttrImpl) Subject(org.exist.security.Subject) Node(org.w3c.dom.Node) NodeValue(org.exist.xquery.value.NodeValue) org.xml.sax(org.xml.sax) DocumentImpl(org.exist.dom.memtree.DocumentImpl) NodeImpl(org.exist.dom.memtree.NodeImpl) DOMSerializer(org.exist.util.serializer.DOMSerializer) XMLResource(org.xmldb.api.modules.XMLResource) Method(java.lang.reflect.Method) Path(java.nio.file.Path) Nullable(javax.annotation.Nullable) XMLDBException(org.xmldb.api.base.XMLDBException) NodeList(org.w3c.dom.NodeList) Properties(java.util.Properties) UTF_8(java.nio.charset.StandardCharsets.UTF_8) DOMStreamer(org.exist.util.serializer.DOMStreamer) StringWriter(java.io.StringWriter) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) DocumentType(org.w3c.dom.DocumentType) Stream(java.util.stream.Stream) XMLUtil(org.exist.dom.persistent.XMLUtil) NodeId(org.exist.numbering.NodeId) DBBroker(org.exist.storage.DBBroker) Serializer(org.exist.storage.serializers.Serializer) Optional(java.util.Optional) ErrorCodes(org.xmldb.api.base.ErrorCodes) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) XPathException(org.exist.xquery.XPathException) NodeValue(org.exist.xquery.value.NodeValue) DOMStreamer(org.exist.util.serializer.DOMStreamer) XMLDBException(org.xmldb.api.base.XMLDBException) TransformerException(javax.xml.transform.TransformerException) XMLDBException(org.xmldb.api.base.XMLDBException) IOException(java.io.IOException) XPathException(org.exist.xquery.XPathException) SAXSerializer(org.exist.util.serializer.SAXSerializer) DOMSerializer(org.exist.util.serializer.DOMSerializer) Serializer(org.exist.storage.serializers.Serializer)

Example 17 with NodeValue

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

the class GetRunningJobs method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        throw (new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to get the list of running jobs"));
    }
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("jobs", NAMESPACE_URI, PREFIX), null);
        final BrokerPool brokerPool = context.getBroker().getBrokerPool();
        final ProcessMonitor monitor = brokerPool.getProcessMonitor();
        final ProcessMonitor.JobInfo[] jobs = monitor.runningJobs();
        for (ProcessMonitor.JobInfo job : jobs) {
            final Thread process = job.getThread();
            final Date startDate = new Date(job.getStartTime());
            builder.startElement(new QName("job", NAMESPACE_URI, PREFIX), null);
            builder.addAttribute(new QName("id", null, null), process.getName());
            builder.addAttribute(new QName("action", null, null), job.getAction());
            builder.addAttribute(new QName("start", null, null), new DateTimeValue(startDate).getStringValue());
            builder.addAttribute(new QName("info", null, null), job.getAddInfo().toString());
            builder.endElement();
        }
        builder.endElement();
        builder.endDocument();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) ProcessMonitor(org.exist.storage.ProcessMonitor) BrokerPool(org.exist.storage.BrokerPool) Date(java.util.Date)

Example 18 with NodeValue

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

the class EXIUtils method getInputStream.

protected static InputStream getInputStream(Item item, XQueryContext context) throws XPathException, MalformedURLException, IOException {
    switch(item.getType()) {
        case Type.ANY_URI:
            LOG.debug("Streaming xs:anyURI");
            // anyURI provided
            String url = item.getStringValue();
            // Fix URL
            if (url.startsWith("/")) {
                url = "xmldb:exist://" + url;
            }
            return new URL(url).openStream();
        case Type.ELEMENT:
        case Type.DOCUMENT:
            LOG.debug("Streaming element or document node");
            /*
            if (item instanceof NodeProxy) {
                NodeProxy np = (NodeProxy) item;
                String url = "xmldb:exist://" + np.getDocument().getBaseURI();
                LOG.debug("Document detected, adding URL " + url);
                streamSource.setSystemId(url);
            }
            */
            // Node provided
            final ConsumerE<ConsumerE<Serializer, IOException>, IOException> withSerializerFn = fn -> {
                final Serializer serializer = context.getBroker().borrowSerializer();
                try {
                    fn.accept(serializer);
                } finally {
                    context.getBroker().returnSerializer(serializer);
                }
            };
            NodeValue node = (NodeValue) item;
            return new NodeInputStream(context.getBroker().getBrokerPool(), withSerializerFn, node);
        default:
            LOG.error("Wrong item type {}", Type.getTypeName(item.getType()));
            throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) Logger(org.apache.logging.log4j.Logger) NodeValue(org.exist.xquery.value.NodeValue) Serializer(org.exist.storage.serializers.Serializer) Item(org.exist.xquery.value.Item) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) LogManager(org.apache.logging.log4j.LogManager) XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) InputStream(java.io.InputStream) NodeValue(org.exist.xquery.value.NodeValue) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) XPathException(org.exist.xquery.XPathException) IOException(java.io.IOException) URL(java.net.URL) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) Serializer(org.exist.storage.serializers.Serializer)

Example 19 with NodeValue

use of org.exist.xquery.value.NodeValue 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 20 with NodeValue

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

the class FunAnalyzeString method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("analyze-string-result", Function.BUILTIN_FUNCTION_NS), null);
        String input = "";
        if (!args[0].isEmpty()) {
            input = args[0].itemAt(0).getStringValue();
        }
        if (input != null && !input.isEmpty()) {
            final String pattern = args[1].itemAt(0).getStringValue();
            String flags = "";
            if (args.length == 3) {
                flags = args[2].itemAt(0).getStringValue();
            }
            analyzeString(builder, input, pattern, flags);
        }
        builder.endElement();
        builder.endDocument();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName)

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