Search in sources :

Example 21 with XQueryPool

use of org.exist.storage.XQueryPool in project exist by eXist-db.

the class ClearXQueryCache method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        throw new XPathException(this, "Only DBA can call clear-xquery-cache function.");
    }
    final DBBroker broker = context.getBroker();
    final XQuery xquery = broker.getBrokerPool().getXQueryService();
    final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
    pool.clear();
    return Sequence.EMPTY_SEQUENCE;
}
Also used : XQueryPool(org.exist.storage.XQueryPool) DBBroker(org.exist.storage.DBBroker) XPathException(org.exist.xquery.XPathException) XQuery(org.exist.xquery.XQuery)

Example 22 with XQueryPool

use of org.exist.storage.XQueryPool in project exist by eXist-db.

the class RESTServer method executeXProc.

/**
 * Directly execute an XProc stored as a XML document in the database.
 *
 * @throws PermissionDeniedException
 */
private void executeXProc(final DBBroker broker, final Txn transaction, final DocumentImpl resource, final HttpServletRequest request, final HttpServletResponse response, final Properties outputProperties, final String servletPath, final String pathInfo) throws XPathException, BadRequestException, PermissionDeniedException {
    final URLSource source = new URLSource(this.getClass().getResource("run-xproc.xq"));
    final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
    CompiledXQuery compiled = null;
    try {
        final XQuery xquery = broker.getBrokerPool().getXQueryService();
        compiled = pool.borrowCompiledXQuery(broker, source);
        XQueryContext context;
        if (compiled == null) {
            context = new XQueryContext(broker.getBrokerPool());
        } else {
            context = compiled.getContext();
            context.prepareForReuse();
        }
        context.declareVariable("pipeline", resource.getURI().toString());
        final String stdin = request.getParameter("stdin");
        context.declareVariable("stdin", stdin == null ? "" : stdin);
        final String debug = request.getParameter("debug");
        context.declareVariable("debug", debug == null ? "0" : "1");
        final String bindings = request.getParameter("bindings");
        context.declareVariable("bindings", bindings == null ? "<bindings/>" : bindings);
        final String autobind = request.getParameter("autobind");
        context.declareVariable("autobind", autobind == null ? "0" : "1");
        final String options = request.getParameter("options");
        context.declareVariable("options", options == null ? "<options/>" : options);
        // TODO: don't hardcode this?
        context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(resource.getCollection().getURI()).toString());
        context.setStaticallyKnownDocuments(new XmldbURI[] { resource.getCollection().getURI() });
        final HttpRequestWrapper reqw = declareVariables(context, null, request, response);
        reqw.setServletPath(servletPath);
        reqw.setPathInfo(pathInfo);
        final long compilationTime;
        if (compiled == null) {
            try {
                final long compilationStart = System.currentTimeMillis();
                compiled = xquery.compile(context, source);
                compilationTime = System.currentTimeMillis() - compilationStart;
            } catch (final IOException e) {
                throw new BadRequestException("Failed to read query from " + source.getURL(), e);
            }
        } else {
            compilationTime = 0;
        }
        try {
            final long executeStart = System.currentTimeMillis();
            final Sequence result = xquery.execute(broker, compiled, null, outputProperties);
            writeResults(response, broker, transaction, result, -1, 1, false, outputProperties, false, compilationTime, System.currentTimeMillis() - executeStart);
        } finally {
            context.runCleanupTasks();
        }
    } finally {
        if (compiled != null) {
            pool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : XQueryPool(org.exist.storage.XQueryPool) URLSource(org.exist.source.URLSource) HttpRequestWrapper(org.exist.http.servlets.HttpRequestWrapper)

Example 23 with XQueryPool

use of org.exist.storage.XQueryPool in project exist by eXist-db.

the class RESTServer method search.

/**
 * TODO: pass request and response objects to XQuery.
 *
 * @param broker the database broker
 * @param transaction the database transaction
 * @param query the XQuery
 * @param path the path of the request
 * @param namespaces any XQuery namespace bindings
 * @param variables any XQuery variable bindings
 * @param howmany the number of items in the results to return
 * @param start the start position in the results to return
 * @param typed whether the result nodes should be typed
 * @param outputProperties the serialization properties
 * @param wrap true to wrap the result of the XQuery in an exist:result
 * @param cache whether to cache the results
 * @param request the request
 * @param response the response
 *
 * @throws BadRequestException if a bad request is made
 * @throws PermissionDeniedException if the request has insufficient permissions
 * @throws XPathException if the XQuery raises an error
 */
protected void search(final DBBroker broker, final Txn transaction, final String query, final String path, final List<Namespace> namespaces, final ElementImpl variables, final int howmany, final int start, final boolean typed, final Properties outputProperties, final boolean wrap, final boolean cache, final HttpServletRequest request, final HttpServletResponse response) throws BadRequestException, PermissionDeniedException, XPathException {
    if (xquerySubmission == EXistServlet.FeatureEnabled.FALSE) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    } else if (xquerySubmission == EXistServlet.FeatureEnabled.AUTHENTICATED_USERS_ONLY) {
        final Subject currentSubject = broker.getCurrentSubject();
        if (!currentSubject.isAuthenticated() || currentSubject.getId() == RealmImpl.GUEST_GROUP_ID) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    final String sessionIdParam = outputProperties.getProperty(Serializer.PROPERTY_SESSION_ID);
    if (sessionIdParam != null) {
        try {
            final int sessionId = Integer.parseInt(sessionIdParam);
            if (sessionId > -1) {
                final Sequence cached = sessionManager.get(query, sessionId);
                if (cached != null) {
                    LOG.debug("Returning cached query result");
                    writeResults(response, broker, transaction, cached, howmany, start, typed, outputProperties, wrap, 0, 0);
                } else {
                    LOG.debug("Cached query result not found. Probably timed out. Repeating query.");
                }
            }
        } catch (final NumberFormatException e) {
            throw new BadRequestException("Invalid session id passed in query request: " + sessionIdParam);
        }
    }
    final XmldbURI pathUri = XmldbURI.createInternal(path);
    final Source source = new StringSource(query);
    final XQueryPool pool = broker.getBrokerPool().getXQueryPool();
    CompiledXQuery compiled = null;
    try {
        final XQuery xquery = broker.getBrokerPool().getXQueryService();
        compiled = pool.borrowCompiledXQuery(broker, source);
        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()));
        declareNamespaces(context, namespaces);
        declareVariables(context, variables, request, response);
        final long compilationTime;
        if (compiled == null) {
            final long compilationStart = System.currentTimeMillis();
            compiled = xquery.compile(context, source);
            compilationTime = System.currentTimeMillis() - compilationStart;
        } else {
            compiled.getContext().updateContext(context);
            context.getWatchDog().reset();
            compilationTime = 0;
        }
        try {
            final long executeStart = System.currentTimeMillis();
            final Sequence resultSequence = xquery.execute(broker, compiled, null, outputProperties);
            final long executionTime = System.currentTimeMillis() - executeStart;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found {} in {}ms.", resultSequence.getItemCount(), executionTime);
            }
            if (cache) {
                final int sessionId = sessionManager.add(query, resultSequence);
                outputProperties.setProperty(Serializer.PROPERTY_SESSION_ID, Integer.toString(sessionId));
                if (!response.isCommitted()) {
                    response.setIntHeader("X-Session-Id", sessionId);
                }
            }
            writeResults(response, broker, transaction, resultSequence, howmany, start, typed, outputProperties, wrap, compilationTime, executionTime);
        } finally {
            context.runCleanupTasks();
        }
    } catch (final IOException e) {
        throw new BadRequestException(e.getMessage(), e);
    } finally {
        if (compiled != null) {
            pool.returnCompiledXQuery(source, compiled);
        }
    }
}
Also used : Subject(org.exist.security.Subject) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource) URLSource(org.exist.source.URLSource) XQueryPool(org.exist.storage.XQueryPool) StringSource(org.exist.source.StringSource) XmldbURI(org.exist.xmldb.XmldbURI)

Example 24 with XQueryPool

use of org.exist.storage.XQueryPool 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)

Aggregations

XQueryPool (org.exist.storage.XQueryPool)24 XQuery (org.exist.xquery.XQuery)15 CompiledXQuery (org.exist.xquery.CompiledXQuery)14 BrokerPool (org.exist.storage.BrokerPool)10 XQueryContext (org.exist.xquery.XQueryContext)10 Source (org.exist.source.Source)9 DBBroker (org.exist.storage.DBBroker)8 IOException (java.io.IOException)7 StringSource (org.exist.source.StringSource)7 DBSource (org.exist.source.DBSource)6 XmldbURI (org.exist.xmldb.XmldbURI)6 Sequence (org.exist.xquery.value.Sequence)6 EXistException (org.exist.EXistException)3 URLSource (org.exist.source.URLSource)3 InputSource (org.xml.sax.InputSource)3 Path (java.nio.file.Path)2 Optional (java.util.Optional)2 UnsynchronizedByteArrayOutputStream (org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)2 Collection (org.exist.collections.Collection)2 BinaryDocument (org.exist.dom.persistent.BinaryDocument)2