Search in sources :

Example 66 with XQueryContext

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

the class GetRunningXQueries method getRunningXQueries.

private Sequence getRunningXQueries() throws XPathException {
    Sequence xmlResponse = null;
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("xqueries", NAMESPACE_URI, PREFIX), null);
        // Add all the running xqueries
        final XQueryWatchDog[] watchdogs = getContext().getBroker().getBrokerPool().getProcessMonitor().getRunningXQueries();
        for (XQueryWatchDog watchdog : watchdogs) {
            final XQueryContext context = watchdog.getContext();
            getRunningXQuery(builder, context, watchdog);
        }
        builder.endElement();
        xmlResponse = (NodeValue) builder.getDocument().getDocumentElement();
        return (xmlResponse);
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) XQueryWatchDog(org.exist.xquery.XQueryWatchDog)

Example 67 with XQueryContext

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

the class KillRunningXQuery method killXQuery.

private void killXQuery(Sequence[] args) throws XPathException {
    int id = 0;
    long waittime = 0;
    // determine the query id to kill
    if (args.length == 1) {
        if (!args[0].isEmpty()) {
            id = ((NumericValue) args[0].itemAt(0)).getInt();
        }
    }
    // determine the wait time
    if (args.length == 2) {
        if (!args[1].isEmpty()) {
            waittime = ((NumericValue) args[1].itemAt(0)).getLong();
        }
    }
    if (id != 0) {
        final XQueryWatchDog[] watchdogs = getContext().getBroker().getBrokerPool().getProcessMonitor().getRunningXQueries();
        for (XQueryWatchDog watchdog : watchdogs) {
            final XQueryContext context = watchdog.getContext();
            if (id == context.hashCode()) {
                if (!watchdog.isTerminating()) {
                    watchdog.kill(waittime);
                }
                break;
            }
        }
    }
}
Also used : XQueryContext(org.exist.xquery.XQueryContext) XQueryWatchDog(org.exist.xquery.XQueryWatchDog)

Example 68 with XQueryContext

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

the class AuditTrailSessionListener method executeXQuery.

private void executeXQuery(String xqueryResourcePath) {
    if (xqueryResourcePath != null && xqueryResourcePath.length() > 0) {
        xqueryResourcePath = xqueryResourcePath.trim();
        try {
            final BrokerPool pool = BrokerPool.getInstance();
            final Subject sysSubject = pool.getSecurityManager().getSystemSubject();
            try (final DBBroker broker = pool.get(Optional.of(sysSubject))) {
                if (broker == null) {
                    LOG.error("Unable to retrieve DBBroker for {}", sysSubject.getName());
                    return;
                }
                final XmldbURI pathUri = XmldbURI.create(xqueryResourcePath);
                try (final LockedDocument lockedResource = broker.getXMLResource(pathUri, LockMode.READ_LOCK)) {
                    final Source source;
                    if (lockedResource != null) {
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("Resource [{}] exists.", xqueryResourcePath);
                        }
                        source = new DBSource(broker, (BinaryDocument) lockedResource.getDocument(), true);
                    } else {
                        LOG.error("Resource [{}] does not exist.", xqueryResourcePath);
                        return;
                    }
                    final XQuery xquery = pool.getXQueryService();
                    if (xquery == null) {
                        LOG.error("broker unable to retrieve XQueryService");
                        return;
                    }
                    final XQueryPool xqpool = pool.getXQueryPool();
                    CompiledXQuery compiled = xqpool.borrowCompiledXQuery(broker, source);
                    final XQueryContext context;
                    if (compiled == null) {
                        context = new XQueryContext(broker.getBrokerPool());
                    } else {
                        context = compiled.getContext();
                        context.prepareForReuse();
                    }
                    context.setStaticallyKnownDocuments(new XmldbURI[] { pathUri });
                    context.setBaseURI(new AnyURIValue(pathUri.toString()));
                    if (compiled == null) {
                        compiled = xquery.compile(context, source);
                    } else {
                        compiled.getContext().updateContext(context);
                        context.getWatchDog().reset();
                    }
                    final Properties outputProperties = new Properties();
                    try {
                        final long startTime = System.currentTimeMillis();
                        final Sequence result = xquery.execute(broker, compiled, null, outputProperties);
                        final long queryTime = System.currentTimeMillis() - startTime;
                        if (LOG.isTraceEnabled()) {
                            LOG.trace("XQuery execution results: {} in {}ms.", result.toString(), queryTime);
                        }
                    } finally {
                        context.runCleanupTasks();
                        xqpool.returnCompiledXQuery(source, compiled);
                    }
                }
            }
        } catch (final Exception e) {
            LOG.error("Exception while executing [{}] script", xqueryResourcePath, e);
        }
    }
}
Also used : CompiledXQuery(org.exist.xquery.CompiledXQuery) XQuery(org.exist.xquery.XQuery) CompiledXQuery(org.exist.xquery.CompiledXQuery) AnyURIValue(org.exist.xquery.value.AnyURIValue) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) Properties(java.util.Properties) Subject(org.exist.security.Subject) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) BinaryDocument(org.exist.dom.persistent.BinaryDocument) XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) LockedDocument(org.exist.dom.persistent.LockedDocument) DBSource(org.exist.source.DBSource) BrokerPool(org.exist.storage.BrokerPool) XmldbURI(org.exist.xmldb.XmldbURI)

Example 69 with XQueryContext

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

the class Shared method getStreamSource.

public static StreamSource getStreamSource(Item item, XQueryContext context) throws XPathException, IOException {
    final StreamSource streamSource = new StreamSource();
    if (item.getType() == Type.JAVA_OBJECT) {
        LOG.debug("Streaming Java object");
        final Object obj = ((JavaObjectValue) item).getObject();
        if (!(obj instanceof File)) {
            throw new XPathException("Passed java object should be a File");
        }
        final File inputFile = (File) obj;
        final InputStream is = new FileInputStream(inputFile);
        streamSource.setInputStream(is);
        streamSource.setSystemId(inputFile.toURI().toURL().toString());
    } else if (item.getType() == Type.ANY_URI) {
        LOG.debug("Streaming xs:anyURI");
        // anyURI provided
        String url = item.getStringValue();
        // Fix URL
        if (url.startsWith("/")) {
            url = "xmldb:exist://" + url;
        }
        final InputStream is = new URL(url).openStream();
        streamSource.setInputStream(is);
        streamSource.setSystemId(url);
    } else if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
        LOG.debug("Streaming element or document node");
        if (item instanceof NodeProxy) {
            final NodeProxy np = (NodeProxy) item;
            final String url = "xmldb:exist://" + np.getOwnerDocument().getBaseURI();
            LOG.debug("Document detected, adding URL {}", url);
            streamSource.setSystemId(url);
        }
        // Node provided
        final DBBroker broker = context.getBroker();
        final ConsumerE<ConsumerE<Serializer, IOException>, IOException> withSerializerFn = fn -> {
            final Serializer serializer = broker.borrowSerializer();
            try {
                fn.accept(serializer);
            } finally {
                broker.returnSerializer(serializer);
            }
        };
        final NodeValue node = (NodeValue) item;
        final InputStream is = new NodeInputStream(context.getBroker().getBrokerPool(), withSerializerFn, node);
        streamSource.setInputStream(is);
    } else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
        LOG.debug("Streaming base64 binary");
        final BinaryValue binary = (BinaryValue) item;
        final byte[] data = binary.toJavaObject(byte[].class);
        final InputStream is = new UnsynchronizedByteArrayInputStream(data);
        streamSource.setInputStream(is);
        if (item instanceof Base64BinaryDocument) {
            final Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
            final String url = "xmldb:exist://" + b64doc.getUrl();
            LOG.debug("Base64BinaryDocument detected, adding URL {}", url);
            streamSource.setSystemId(url);
        }
    } else {
        LOG.error("Wrong item type {}", Type.getTypeName(item.getType()));
        throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
    }
    return streamSource;
}
Also used : ValidationReport(org.exist.validation.ValidationReport) URL(java.net.URL) StreamSource(javax.xml.transform.stream.StreamSource) SequenceIterator(org.exist.xquery.value.SequenceIterator) NodeProxy(org.exist.dom.persistent.NodeProxy) Base64BinaryDocument(org.exist.xquery.value.Base64BinaryDocument) ArrayList(java.util.ArrayList) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) NodeValue(org.exist.xquery.value.NodeValue) Item(org.exist.xquery.value.Item) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) NodeImpl(org.exist.dom.memtree.NodeImpl) XQueryContext(org.exist.xquery.XQueryContext) AttributesImpl(org.xml.sax.helpers.AttributesImpl) InputSource(org.xml.sax.InputSource) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) BinaryValue(org.exist.xquery.value.BinaryValue) ValidationReportItem(org.exist.validation.ValidationReportItem) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) File(java.io.File) Logger(org.apache.logging.log4j.Logger) JavaObjectValue(org.exist.xquery.value.JavaObjectValue) DBBroker(org.exist.storage.DBBroker) Serializer(org.exist.storage.serializers.Serializer) Sequence(org.exist.xquery.value.Sequence) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) LogManager(org.apache.logging.log4j.LogManager) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) StreamSource(javax.xml.transform.stream.StreamSource) BinaryValue(org.exist.xquery.value.BinaryValue) IOException(java.io.IOException) NodeProxy(org.exist.dom.persistent.NodeProxy) FileInputStream(java.io.FileInputStream) URL(java.net.URL) DBBroker(org.exist.storage.DBBroker) Base64BinaryDocument(org.exist.xquery.value.Base64BinaryDocument) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) JavaObjectValue(org.exist.xquery.value.JavaObjectValue) File(java.io.File) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) Serializer(org.exist.storage.serializers.Serializer)

Example 70 with XQueryContext

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

the class XQueryCompiler method compile.

public static CompiledXQuery compile(final DBBroker broker, final DocumentImpl document) throws RestXqServiceCompilationException {
    try {
        if (document instanceof BinaryDocument) {
            if (document.getMimeType().equals(XQUERY_MIME_TYPE)) {
                // compile the query
                final XQueryContext context = new XQueryContext(broker.getBrokerPool());
                final DBSource source = new DBSource(broker, (BinaryDocument) document, true);
                // set the module load path for any module imports that are relative
                context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + source.getDocumentPath().removeLastSegment());
                return broker.getBrokerPool().getXQueryService().compile(context, source);
            } else {
                throw new RestXqServiceCompilationException("Invalid mimetype '" + document.getMimeType() + "' for XQuery: " + document.getURI().toString());
            }
        } else {
            throw new RestXqServiceCompilationException("Invalid document location for XQuery: " + document.getURI().toString());
        }
    } catch (XPathException xpe) {
        throw new RestXqServiceCompilationException("Unable to compile XQuery: " + document.getURI().toString() + ": " + xpe.getMessage(), xpe);
    } catch (IOException ioe) {
        throw new RestXqServiceCompilationException("Unable to access XQuery: " + document.getURI().toString() + ": " + ioe.getMessage(), ioe);
    } catch (PermissionDeniedException pde) {
        throw new RestXqServiceCompilationException("Permission to access XQuery denied: " + document.getURI().toString() + ": " + pde.getMessage(), pde);
    }
}
Also used : BinaryDocument(org.exist.dom.persistent.BinaryDocument) XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) DBSource(org.exist.source.DBSource) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

Aggregations

XQueryContext (org.exist.xquery.XQueryContext)70 CompiledXQuery (org.exist.xquery.CompiledXQuery)37 Sequence (org.exist.xquery.value.Sequence)34 XQuery (org.exist.xquery.XQuery)33 DBBroker (org.exist.storage.DBBroker)24 Test (org.junit.Test)23 XPathException (org.exist.xquery.XPathException)18 BrokerPool (org.exist.storage.BrokerPool)17 IOException (java.io.IOException)11 Source (org.exist.source.Source)10 XQueryPool (org.exist.storage.XQueryPool)10 Node (org.w3c.dom.Node)10 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)8 PermissionDeniedException (org.exist.security.PermissionDeniedException)8 AnyURIValue (org.exist.xquery.value.AnyURIValue)8 URI (java.net.URI)7 StringValue (org.exist.xquery.value.StringValue)7 InputSource (org.xml.sax.InputSource)7 EXistException (org.exist.EXistException)6 QName (org.exist.dom.QName)6