Search in sources :

Example 41 with Source

use of org.exist.source.Source in project exist by eXist-db.

the class XQuery method execute.

public Sequence execute(final DBBroker broker, final CompiledXQuery expression, Sequence contextSequence, final Properties outputProperties, final boolean resetContext) throws XPathException, PermissionDeniedException {
    // check execute permissions
    if (expression.getContext().getSource() instanceof DBSource) {
        ((DBSource) expression.getContext().getSource()).validate(Permission.EXECUTE);
    }
    final long start = System.currentTimeMillis();
    final XQueryContext context = expression.getContext();
    expression.reset();
    if (resetContext) {
        // context.setBroker(broker);
        context.getWatchDog().reset();
    }
    if (context.requireDebugMode()) {
        final Debuggee debuggee = broker.getBrokerPool().getDebuggee();
        if (debuggee != null) {
            debuggee.joint(expression);
        }
    }
    // do any preparation before execution
    context.prepareForExecution();
    final Subject callingUser = broker.getCurrentSubject();
    // if setUid or setGid, become Effective User
    EffectiveSubject effectiveSubject = null;
    final Source src = expression.getContext().getSource();
    if (src instanceof DBSource) {
        final DBSource dbSrc = (DBSource) src;
        final Permission perm = dbSrc.getPermissions();
        if (perm.isSetUid()) {
            if (perm.isSetGid()) {
                // setUid and SetGid
                effectiveSubject = new EffectiveSubject(perm.getOwner(), perm.getGroup());
            } else {
                // just setUid
                effectiveSubject = new EffectiveSubject(perm.getOwner());
            }
        } else if (perm.isSetGid()) {
            // just setGid, so we use the current user as the effective user
            effectiveSubject = new EffectiveSubject(callingUser, perm.getGroup());
        }
    }
    try {
        if (effectiveSubject != null) {
            // switch to effective user (e.g. setuid/setgid)
            broker.pushSubject(effectiveSubject);
        }
        context.getProfiler().traceQueryStart();
        broker.getBrokerPool().getProcessMonitor().queryStarted(context.getWatchDog());
        try {
            // support for XQuery 3.0 - declare context item :=
            if (contextSequence == null) {
                if (context.getContextItemDeclartion() != null) {
                    contextSequence = context.getContextItemDeclartion().eval(null, null);
                }
            }
            final Sequence result = expression.eval(contextSequence);
            if (LOG.isDebugEnabled()) {
                final NumberFormat nf = NumberFormat.getNumberInstance();
                LOG.debug("Execution took {} ms", nf.format(System.currentTimeMillis() - start));
            }
            if (outputProperties != null) {
                // must be done before context.reset!
                context.checkOptions(outputProperties);
            }
            return result;
        } finally {
            context.getProfiler().traceQueryEnd(context);
            // track query stats before context is reset
            broker.getBrokerPool().getProcessMonitor().queryCompleted(context.getWatchDog());
            expression.reset();
            if (resetContext) {
                context.reset();
            }
        }
    } finally {
        if (effectiveSubject != null) {
            broker.popSubject();
        }
    }
}
Also used : EffectiveSubject(org.exist.security.EffectiveSubject) Debuggee(org.exist.debuggee.Debuggee) Permission(org.exist.security.Permission) DBSource(org.exist.source.DBSource) Sequence(org.exist.xquery.value.Sequence) Subject(org.exist.security.Subject) EffectiveSubject(org.exist.security.EffectiveSubject) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) FileSource(org.exist.source.FileSource) NumberFormat(java.text.NumberFormat)

Example 42 with Source

use of org.exist.source.Source in project exist by eXist-db.

the class RpcConnection method executeT.

@Override
public Map<String, Object> executeT(final String pathToQuery, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
    final long startTime = System.currentTimeMillis();
    final Optional<String> sortBy = Optional.ofNullable(parameters.get(RpcAPI.SORT_EXPR)).map(Object::toString);
    return this.<Map<String, Object>>readDocument(XmldbURI.createInternal(pathToQuery)).apply((document, broker, transaction) -> {
        final BinaryDocument xquery = (BinaryDocument) document;
        if (xquery.getResourceType() != DocumentImpl.BINARY_FILE) {
            throw new EXistException("Document " + pathToQuery + " is not a binary resource");
        }
        if (!xquery.getPermissions().validate(user, Permission.READ | Permission.EXECUTE)) {
            throw new PermissionDeniedException("Insufficient privileges to access resource");
        }
        final Source source = new DBSource(broker, xquery, true);
        try {
            final Map<String, Object> rpcResponse = this.<Map<String, Object>>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> queryResultToTypedRpcResponse(startTime, doQuery(broker, compiledQuery, null, parameters), sortBy));
            return rpcResponse;
        } catch (final XPathException e) {
            throw new EXistException(e);
        }
    });
}
Also used : DBSource(org.exist.source.DBSource) PermissionDeniedException(org.exist.security.PermissionDeniedException) EXistException(org.exist.EXistException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource)

Example 43 with Source

use of org.exist.source.Source in project exist by eXist-db.

the class RpcConnection method queryPT.

private Map<String, Object> queryPT(final String xquery, final XmldbURI docUri, final String s_id, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
    final Source source = new StringSource(xquery);
    final Optional<String> sortBy = Optional.ofNullable(parameters.get(RpcAPI.SORT_EXPR)).map(Object::toString);
    return withDb((broker, transaction) -> {
        final long startTime = System.currentTimeMillis();
        final NodeSet nodes;
        if (docUri != null && s_id != null) {
            nodes = this.<NodeSet>readDocument(broker, transaction, docUri).apply((document, broker1, transaction1) -> {
                final Object[] docs = new Object[1];
                docs[0] = docUri.toString();
                parameters.put(RpcAPI.STATIC_DOCUMENTS, docs);
                if (s_id.length() > 0) {
                    final NodeId nodeId = factory.getBrokerPool().getNodeFactory().createFromString(s_id);
                    final NodeProxy node = new NodeProxy(document, nodeId);
                    final NodeSet nodeSet = new ExtArrayNodeSet(1);
                    nodeSet.add(node);
                    return nodeSet;
                } else {
                    return null;
                }
            });
        } else {
            nodes = null;
        }
        try {
            final Map<String, Object> rpcResponse = this.<Map<String, Object>>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> queryResultToTypedRpcResponse(startTime, doQuery(broker, compiledQuery, nodes, parameters), sortBy));
            return rpcResponse;
        } catch (final XPathException e) {
            throw new EXistException(e);
        }
    });
}
Also used : Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2) LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) ValidationReport(org.exist.validation.ValidationReport) EXistOutputKeys(org.exist.storage.serializers.EXistOutputKeys) StringSource(org.exist.source.StringSource) TemporaryFileManager(org.exist.util.io.TemporaryFileManager) URISyntaxException(java.net.URISyntaxException) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock) Modification(org.exist.xupdate.Modification) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmlRpcDocumentFunction(org.exist.xmlrpc.function.XmlRpcDocumentFunction) org.xmldb.api.base(org.xmldb.api.base) java.nio.file(java.nio.file) EXistSchemaType(org.exist.security.EXistSchemaType) org.exist.xquery(org.exist.xquery) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) Version(org.exist.Version) PreserveType(org.exist.storage.DBBroker.PreserveType) SerializerPool(org.exist.util.serializer.SerializerPool) Namespaces(org.exist.Namespaces) SchemaType(org.exist.security.SchemaType) DigestType(org.exist.util.crypto.digest.DigestType) Collection(org.exist.collections.Collection) NodeImpl(org.exist.dom.memtree.NodeImpl) SystemTaskJob(org.exist.scheduler.SystemTaskJob) SystemTaskJobImpl(org.exist.scheduler.impl.SystemTaskJobImpl) ACEAider(org.exist.security.internal.aider.ACEAider) AttributesImpl(org.xml.sax.helpers.AttributesImpl) PermissionFactory(org.exist.security.PermissionFactory) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) GroupAider(org.exist.security.internal.aider.GroupAider) java.util.concurrent(java.util.concurrent) AXSchemaType(org.exist.security.AXSchemaType) SupplierE(com.evolvedbinary.j8fu.function.SupplierE) StandardOpenOption(java.nio.file.StandardOpenOption) GuardedBy(javax.annotation.concurrent.GuardedBy) StandardCharsets(java.nio.charset.StandardCharsets) SecurityManager(org.exist.security.SecurityManager) Logger(org.apache.logging.log4j.Logger) XUpdateProcessor(org.exist.xupdate.XUpdateProcessor) LockManager(org.exist.storage.lock.LockManager) SAXException(org.xml.sax.SAXException) ShutdownTask(org.exist.scheduler.impl.ShutdownTask) Restore(org.exist.backup.Restore) SAXSerializer(org.exist.util.serializer.SAXSerializer) java.util(java.util) QName(org.exist.dom.QName) org.exist.xquery.value(org.exist.xquery.value) org.exist.dom.persistent(org.exist.dom.persistent) Function2E(com.evolvedbinary.j8fu.function.Function2E) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) XmlRpcCollectionFunction(org.exist.xmlrpc.function.XmlRpcCollectionFunction) LockedDocumentMap(org.exist.storage.lock.LockedDocumentMap) Account(org.exist.security.Account) Source(org.exist.source.Source) org.exist.storage(org.exist.storage) ACLPermission(org.exist.security.ACLPermission) Charset(java.nio.charset.Charset) DBSource(org.exist.source.DBSource) Subject(org.exist.security.Subject) XmldbURI(org.exist.xmldb.XmldbURI) EXistException(org.exist.EXistException) Validator(org.exist.validation.Validator) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) RestoreListener(org.exist.backup.restore.listener.RestoreListener) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Group(org.exist.security.Group) Backup(org.exist.backup.Backup) XmlRpcFunction(org.exist.xmlrpc.function.XmlRpcFunction) Sync(org.exist.storage.sync.Sync) OutputKeys(javax.xml.transform.OutputKeys) UserAider(org.exist.security.internal.aider.UserAider) Function3E(com.evolvedbinary.j8fu.function.Function3E) CollectionConfigurationManager(org.exist.collections.CollectionConfigurationManager) MessageDigest(org.exist.util.crypto.digest.MessageDigest) HTTPUtils(org.exist.xquery.util.HTTPUtils) DocumentType(org.w3c.dom.DocumentType) Lock(java.util.concurrent.locks.Lock) java.io(java.io) NodeId(org.exist.numbering.NodeId) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) CollectionConfigurationException(org.exist.collections.CollectionConfigurationException) XmldbURL(org.exist.protocolhandler.xmldb.XmldbURL) org.exist.util(org.exist.util) Serializer(org.exist.storage.serializers.Serializer) BEGIN_PROTECTED_MAX_LOCKING_RETRIES(org.exist.xmldb.EXistXPathQueryService.BEGIN_PROTECTED_MAX_LOCKING_RETRIES) EmbeddedInputStream(org.exist.protocolhandler.embedded.EmbeddedInputStream) XmlRpcCompiledXQueryFunction(org.exist.xmlrpc.function.XmlRpcCompiledXQueryFunction) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) LogManager(org.apache.logging.log4j.LogManager) EXistException(org.exist.EXistException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource) NodeId(org.exist.numbering.NodeId) StringSource(org.exist.source.StringSource)

Example 44 with Source

use of org.exist.source.Source in project exist by eXist-db.

the class RpcConnection method queryP.

/**
 * @deprecated Use {@link #queryPT(String, XmldbURI, String, Map)} instead.
 * @param xpath the query to execute
 * @param docUri the document to query
 * @param s_id an id
 * @param parameters map of options
 * @return the result of the query
 * @throws EXistException if an internal error occurs
 * @throws PermissionDeniedException If the current user is not allowed to perform this action
 */
private Map<String, Object> queryP(final String xpath, final XmldbURI docUri, final String s_id, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
    final Source source = new StringSource(xpath);
    final Optional<String> sortBy = Optional.ofNullable(parameters.get(RpcAPI.SORT_EXPR)).map(Object::toString);
    return withDb((broker, transaction) -> {
        final long startTime = System.currentTimeMillis();
        final NodeSet nodes;
        if (docUri != null && s_id != null) {
            nodes = this.<NodeSet>readDocument(broker, transaction, docUri).apply((document, broker1, transaction1) -> {
                final Object[] docs = new Object[1];
                docs[0] = docUri.toString();
                parameters.put(RpcAPI.STATIC_DOCUMENTS, docs);
                if (s_id.length() > 0) {
                    final NodeId nodeId = factory.getBrokerPool().getNodeFactory().createFromString(s_id);
                    final NodeProxy node = new NodeProxy(document, nodeId);
                    final NodeSet nodeSet = new ExtArrayNodeSet(1);
                    nodeSet.add(node);
                    return nodeSet;
                } else {
                    return null;
                }
            });
        } else {
            nodes = null;
        }
        try {
            final Map<String, Object> rpcResponse = this.<Map<String, Object>>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> queryResultToRpcResponse(startTime, doQuery(broker, compiledQuery, nodes, parameters), sortBy));
            return rpcResponse;
        } catch (final XPathException e) {
            throw new EXistException(e);
        }
    });
}
Also used : Tuple2(com.evolvedbinary.j8fu.tuple.Tuple2) LockMode(org.exist.storage.lock.Lock.LockMode) Txn(org.exist.storage.txn.Txn) ValidationReport(org.exist.validation.ValidationReport) EXistOutputKeys(org.exist.storage.serializers.EXistOutputKeys) StringSource(org.exist.source.StringSource) TemporaryFileManager(org.exist.util.io.TemporaryFileManager) URISyntaxException(java.net.URISyntaxException) ManagedCollectionLock(org.exist.storage.lock.ManagedCollectionLock) Modification(org.exist.xupdate.Modification) PermissionDeniedException(org.exist.security.PermissionDeniedException) XmlRpcDocumentFunction(org.exist.xmlrpc.function.XmlRpcDocumentFunction) org.xmldb.api.base(org.xmldb.api.base) java.nio.file(java.nio.file) EXistSchemaType(org.exist.security.EXistSchemaType) org.exist.xquery(org.exist.xquery) Tuple(com.evolvedbinary.j8fu.tuple.Tuple.Tuple) Version(org.exist.Version) PreserveType(org.exist.storage.DBBroker.PreserveType) SerializerPool(org.exist.util.serializer.SerializerPool) Namespaces(org.exist.Namespaces) SchemaType(org.exist.security.SchemaType) DigestType(org.exist.util.crypto.digest.DigestType) Collection(org.exist.collections.Collection) NodeImpl(org.exist.dom.memtree.NodeImpl) SystemTaskJob(org.exist.scheduler.SystemTaskJob) SystemTaskJobImpl(org.exist.scheduler.impl.SystemTaskJobImpl) ACEAider(org.exist.security.internal.aider.ACEAider) AttributesImpl(org.xml.sax.helpers.AttributesImpl) PermissionFactory(org.exist.security.PermissionFactory) ManagedDocumentLock(org.exist.storage.lock.ManagedDocumentLock) GroupAider(org.exist.security.internal.aider.GroupAider) java.util.concurrent(java.util.concurrent) AXSchemaType(org.exist.security.AXSchemaType) SupplierE(com.evolvedbinary.j8fu.function.SupplierE) StandardOpenOption(java.nio.file.StandardOpenOption) GuardedBy(javax.annotation.concurrent.GuardedBy) StandardCharsets(java.nio.charset.StandardCharsets) SecurityManager(org.exist.security.SecurityManager) Logger(org.apache.logging.log4j.Logger) XUpdateProcessor(org.exist.xupdate.XUpdateProcessor) LockManager(org.exist.storage.lock.LockManager) SAXException(org.xml.sax.SAXException) ShutdownTask(org.exist.scheduler.impl.ShutdownTask) Restore(org.exist.backup.Restore) SAXSerializer(org.exist.util.serializer.SAXSerializer) java.util(java.util) QName(org.exist.dom.QName) org.exist.xquery.value(org.exist.xquery.value) org.exist.dom.persistent(org.exist.dom.persistent) Function2E(com.evolvedbinary.j8fu.function.Function2E) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) XmlRpcCollectionFunction(org.exist.xmlrpc.function.XmlRpcCollectionFunction) LockedDocumentMap(org.exist.storage.lock.LockedDocumentMap) Account(org.exist.security.Account) Source(org.exist.source.Source) org.exist.storage(org.exist.storage) ACLPermission(org.exist.security.ACLPermission) Charset(java.nio.charset.Charset) DBSource(org.exist.source.DBSource) Subject(org.exist.security.Subject) XmldbURI(org.exist.xmldb.XmldbURI) EXistException(org.exist.EXistException) Validator(org.exist.validation.Validator) Permission(org.exist.security.Permission) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) RestoreListener(org.exist.backup.restore.listener.RestoreListener) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Group(org.exist.security.Group) Backup(org.exist.backup.Backup) XmlRpcFunction(org.exist.xmlrpc.function.XmlRpcFunction) Sync(org.exist.storage.sync.Sync) OutputKeys(javax.xml.transform.OutputKeys) UserAider(org.exist.security.internal.aider.UserAider) Function3E(com.evolvedbinary.j8fu.function.Function3E) CollectionConfigurationManager(org.exist.collections.CollectionConfigurationManager) MessageDigest(org.exist.util.crypto.digest.MessageDigest) HTTPUtils(org.exist.xquery.util.HTTPUtils) DocumentType(org.w3c.dom.DocumentType) Lock(java.util.concurrent.locks.Lock) java.io(java.io) NodeId(org.exist.numbering.NodeId) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) CollectionConfigurationException(org.exist.collections.CollectionConfigurationException) XmldbURL(org.exist.protocolhandler.xmldb.XmldbURL) org.exist.util(org.exist.util) Serializer(org.exist.storage.serializers.Serializer) BEGIN_PROTECTED_MAX_LOCKING_RETRIES(org.exist.xmldb.EXistXPathQueryService.BEGIN_PROTECTED_MAX_LOCKING_RETRIES) EmbeddedInputStream(org.exist.protocolhandler.embedded.EmbeddedInputStream) XmlRpcCompiledXQueryFunction(org.exist.xmlrpc.function.XmlRpcCompiledXQueryFunction) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) LogManager(org.apache.logging.log4j.LogManager) EXistException(org.exist.EXistException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource) NodeId(org.exist.numbering.NodeId) StringSource(org.exist.source.StringSource)

Example 45 with Source

use of org.exist.source.Source in project exist by eXist-db.

the class RpcConnection method executeQuery.

@Override
public int executeQuery(final String xpath, final Map<String, Object> parameters) throws EXistException, PermissionDeniedException {
    return withDb((broker, transaction) -> {
        final Source source = new StringSource(xpath);
        final long startTime = System.currentTimeMillis();
        try {
            final QueryResult result = this.<QueryResult>compileQuery(broker, transaction, source, parameters).apply(compiledQuery -> doQuery(broker, compiledQuery, null, parameters));
            if (result.hasErrors()) {
                throw new EXistException(result.getException());
            }
            result.queryTime = System.currentTimeMillis() - startTime;
            return factory.resultSets.add(result);
        } catch (final XPathException e) {
            throw new EXistException(e);
        }
    });
}
Also used : StringSource(org.exist.source.StringSource) EXistException(org.exist.EXistException) StringSource(org.exist.source.StringSource) Source(org.exist.source.Source) DBSource(org.exist.source.DBSource) InputSource(org.xml.sax.InputSource)

Aggregations

Source (org.exist.source.Source)83 StringSource (org.exist.source.StringSource)62 Sequence (org.exist.xquery.value.Sequence)43 BrokerPool (org.exist.storage.BrokerPool)42 DBBroker (org.exist.storage.DBBroker)42 Txn (org.exist.storage.txn.Txn)40 Test (org.junit.Test)35 StringInputSource (org.exist.util.StringInputSource)32 DBSource (org.exist.source.DBSource)23 IOException (java.io.IOException)19 PermissionDeniedException (org.exist.security.PermissionDeniedException)19 InputSource (org.xml.sax.InputSource)15 EXistException (org.exist.EXistException)12 XmldbURI (org.exist.xmldb.XmldbURI)11 XQueryPool (org.exist.storage.XQueryPool)9 XQueryContext (org.exist.xquery.XQueryContext)9 FileSource (org.exist.source.FileSource)8 CompiledXQuery (org.exist.xquery.CompiledXQuery)8 XQuery (org.exist.xquery.XQuery)8 Collection (org.exist.collections.Collection)7