Search in sources :

Example 91 with XPathException

use of org.exist.xquery.XPathException 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 92 with XPathException

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

the class AccountStatusFunction method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final DBBroker broker = getContext().getBroker();
    final Subject currentUser = broker.getCurrentSubject();
    final SecurityManager securityManager = broker.getBrokerPool().getSecurityManager();
    final String username = args[0].getStringValue();
    if (isCalledAs(qnIsAccountEnabled.getLocalPart())) {
        if (!currentUser.hasDbaRole() && !currentUser.getName().equals(username)) {
            throw new XPathException("You must be a DBA or be enquiring about your own account!");
        }
        final Account account = securityManager.getAccount(username);
        return (account == null) ? BooleanValue.FALSE : new BooleanValue(account.isEnabled());
    } else if (isCalledAs(qnSetAccountEnabled.getLocalPart())) {
        if (!currentUser.hasDbaRole()) {
            throw new XPathException("You must be a DBA to change the status of an account!");
        }
        final boolean enable = args[1].effectiveBooleanValue();
        final Account account = securityManager.getAccount(username);
        account.setEnabled(enable);
        try {
            account.save(broker);
            return Sequence.EMPTY_SEQUENCE;
        } catch (final ConfigurationException | PermissionDeniedException ce) {
            throw new XPathException(ce.getMessage(), ce);
        }
    } else {
        throw new XPathException("Unknown function");
    }
}
Also used : Account(org.exist.security.Account) DBBroker(org.exist.storage.DBBroker) SecurityManager(org.exist.security.SecurityManager) XPathException(org.exist.xquery.XPathException) BooleanValue(org.exist.xquery.value.BooleanValue) Subject(org.exist.security.Subject)

Example 93 with XPathException

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

the class DocUtils method getDocumentByPathFromDB.

private static Sequence getDocumentByPathFromDB(final XQueryContext context, final String path) throws XPathException, PermissionDeniedException {
    // check if the loaded documents should remain locked
    final LockMode lockType = context.lockDocumentsOnLoad() ? LockMode.WRITE_LOCK : LockMode.READ_LOCK;
    try {
        final XmldbURI baseURI = context.getBaseURI().toXmldbURI();
        final XmldbURI pathUri;
        if (baseURI != null && !(baseURI.equals("") || baseURI.equals("/db"))) {
            // relative collection Path: add the current base URI
            pathUri = baseURI.resolveCollectionPath(XmldbURI.xmldbUriFor(path, false));
        } else {
            pathUri = XmldbURI.xmldbUriFor(path, false);
        }
        // relative collection Path: add the current module call URI if applicable
        final XmldbURI resourceUri = Optional.ofNullable(context.getModuleLoadPath()).filter(moduleLoadPath -> !moduleLoadPath.isEmpty()).flatMap(moduleLoadPath -> Try(() -> XmldbURI.xmldbUriFor(moduleLoadPath)).toOption()).map(moduleLoadPath -> moduleLoadPath.resolveCollectionPath(pathUri)).orElse(pathUri);
        // try to open the document and acquire a lock
        try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(resourceUri, lockType)) {
            if (lockedDoc == null) {
                return Sequence.EMPTY_SEQUENCE;
            } else {
                final DocumentImpl doc = lockedDoc.getDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.READ)) {
                    throw new PermissionDeniedException("Insufficient privileges to read resource " + path);
                }
                if (doc.getResourceType() == DocumentImpl.BINARY_FILE) {
                    throw new XPathException("Document " + path + " is a binary resource, not an XML document. Please consider using the function util:binary-doc() to retrieve a reference to it.");
                }
                return new NodeProxy(doc);
            }
        }
    } catch (final URISyntaxException e) {
        throw new XPathException(e);
    }
}
Also used : LockMode(org.exist.storage.lock.Lock.LockMode) SAXNotSupportedException(org.xml.sax.SAXNotSupportedException) BrokerPool(org.exist.storage.BrokerPool) XMLReaderPool(org.exist.util.XMLReaderPool) ErrorCodes(org.exist.xquery.ErrorCodes) NodeProxy(org.exist.dom.persistent.NodeProxy) PermissionDeniedException(org.exist.security.PermissionDeniedException) SAXNotRecognizedException(org.xml.sax.SAXNotRecognizedException) XMLReader(org.xml.sax.XMLReader) Source(org.exist.source.Source) java.net(java.net) Namespaces(org.exist.Namespaces) Document(org.w3c.dom.Document) XmldbURI(org.exist.xmldb.XmldbURI) DocumentImpl(org.exist.dom.persistent.DocumentImpl) Permission(org.exist.security.Permission) XQueryContext(org.exist.xquery.XQueryContext) Nullable(javax.annotation.Nullable) InputSource(org.xml.sax.InputSource) LockedDocument(org.exist.dom.persistent.LockedDocument) AnyURIValue(org.exist.xquery.value.AnyURIValue) IOException(java.io.IOException) Try(com.evolvedbinary.j8fu.Try.Try) URLSource(org.exist.source.URLSource) SAXException(org.xml.sax.SAXException) SourceFactory(org.exist.source.SourceFactory) Optional(java.util.Optional) Sequence(org.exist.xquery.value.Sequence) Pattern(java.util.regex.Pattern) SAXAdapter(org.exist.dom.memtree.SAXAdapter) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) XPathException(org.exist.xquery.XPathException) LockedDocument(org.exist.dom.persistent.LockedDocument) PermissionDeniedException(org.exist.security.PermissionDeniedException) LockMode(org.exist.storage.lock.Lock.LockMode) DocumentImpl(org.exist.dom.persistent.DocumentImpl) NodeProxy(org.exist.dom.persistent.NodeProxy) XmldbURI(org.exist.xmldb.XmldbURI)

Example 94 with XPathException

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

the class DocUtils method getFromDynamicallyAvailableDocuments.

@Nullable
private static Sequence getFromDynamicallyAvailableDocuments(final XQueryContext context, final String path) throws XPathException {
    try {
        URI uri = new URI(path);
        if (!uri.isAbsolute()) {
            final AnyURIValue baseXdmUri = context.getBaseURI();
            if (baseXdmUri != null && !baseXdmUri.equals(AnyURIValue.EMPTY_URI)) {
                URI baseUri = baseXdmUri.toURI();
                if (!baseUri.toString().endsWith("/")) {
                    baseUri = new URI(baseUri.toString() + '/');
                }
                uri = baseUri.resolve(uri);
            }
        }
        return context.getDynamicallyAvailableDocument(uri.toString());
    } catch (final URISyntaxException e) {
        throw new XPathException(context.getRootExpression(), ErrorCodes.FODC0005, e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) AnyURIValue(org.exist.xquery.value.AnyURIValue) XmldbURI(org.exist.xmldb.XmldbURI) Nullable(javax.annotation.Nullable)

Example 95 with XPathException

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

the class Insert method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.AbstractExpression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    if (contextItem != null) {
        contextSequence = contextItem.toSequence();
    }
    Sequence contentSeq = value.eval(contextSequence);
    if (contentSeq.isEmpty()) {
        throw new XPathException(this, Messages.getMessage(Error.UPDATE_EMPTY_CONTENT));
    }
    final Sequence inSeq = select.eval(contextSequence);
    /* If we try and Insert a node at an invalid location,
         * trap the error in a context variable,
         * this is then accessible from xquery via. the context extension module - deliriumsky
         * TODO: This trapping could be expanded further - basically where XPathException is thrown from thiss class
         * TODO: Maybe we could provide more detailed messages in the trap, e.g. couldnt insert node `xyz` into `abc` becuase... this would be nicer for the end user of the xquery application 
         */
    if (!Type.subTypeOf(inSeq.getItemType(), Type.NODE)) {
        // Indicate the failure to perform this update by adding it to the sequence in the context variable XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR
        ValueSequence prevUpdateErrors = null;
        final XPathException xpe = new XPathException(this, Messages.getMessage(Error.UPDATE_SELECT_TYPE));
        final Object ctxVarObj = context.getAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR);
        if (ctxVarObj == null) {
            prevUpdateErrors = new ValueSequence();
        } else {
            prevUpdateErrors = (ValueSequence) XPathUtil.javaObjectToXPath(ctxVarObj, context);
        }
        prevUpdateErrors.add(new StringValue(xpe.getMessage()));
        context.setAttribute(XQueryContext.XQUERY_CONTEXTVAR_XQUERY_UPDATE_ERROR, prevUpdateErrors);
        if (!inSeq.isEmpty()) {
            // TODO: should we trap this instead of throwing an exception - deliriumsky?
            throw xpe;
        }
    }
    if (!inSeq.isEmpty()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Found: {} nodes", inSeq.getItemCount());
        }
        context.pushInScopeNamespaces();
        contentSeq = deepCopy(contentSeq);
        // start a transaction
        try (final Txn transaction = getTransaction()) {
            final StoredNode[] ql = selectAndLock(transaction, inSeq);
            final NotificationService notifier = context.getBroker().getBrokerPool().getNotificationService();
            final NodeList contentList = seq2nodeList(contentSeq);
            for (final StoredNode node : ql) {
                final DocumentImpl doc = node.getOwnerDocument();
                if (!doc.getPermissions().validate(context.getSubject(), Permission.WRITE)) {
                    throw new PermissionDeniedException("User '" + context.getSubject().getName() + "' does not have permission to write to the document '" + doc.getDocumentURI() + "'!");
                }
                // update the document
                if (mode == INSERT_APPEND) {
                    node.appendChildren(transaction, contentList, -1);
                } else {
                    final NodeImpl parent = (NodeImpl) getParent(node);
                    switch(mode) {
                        case INSERT_BEFORE:
                            parent.insertBefore(transaction, contentList, node);
                            break;
                        case INSERT_AFTER:
                            parent.insertAfter(transaction, contentList, node);
                            break;
                    }
                }
                doc.setLastModified(System.currentTimeMillis());
                modifiedDocuments.add(doc);
                context.getBroker().storeXMLResource(transaction, doc);
                notifier.notifyUpdate(doc, UpdateListener.UPDATE);
            }
            finishTriggers(transaction);
            // commit the transaction
            transaction.commit();
        } catch (final PermissionDeniedException | EXistException | LockException | TriggerException e) {
            throw new XPathException(this, e.getMessage(), e);
        } finally {
            unlockDocuments();
            context.popInScopeNamespaces();
        }
    }
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().end(this, "", Sequence.EMPTY_SEQUENCE);
    }
    return Sequence.EMPTY_SEQUENCE;
}
Also used : NodeImpl(org.exist.dom.persistent.NodeImpl) XPathException(org.exist.xquery.XPathException) NodeList(org.w3c.dom.NodeList) NotificationService(org.exist.storage.NotificationService) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) Txn(org.exist.storage.txn.Txn) EXistException(org.exist.EXistException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) LockException(org.exist.util.LockException) ValueSequence(org.exist.xquery.value.ValueSequence) PermissionDeniedException(org.exist.security.PermissionDeniedException) StringValue(org.exist.xquery.value.StringValue) TriggerException(org.exist.collections.triggers.TriggerException) StoredNode(org.exist.dom.persistent.StoredNode)

Aggregations

XPathException (org.exist.xquery.XPathException)306 Sequence (org.exist.xquery.value.Sequence)86 IOException (java.io.IOException)61 SAXException (org.xml.sax.SAXException)43 StringValue (org.exist.xquery.value.StringValue)40 PermissionDeniedException (org.exist.security.PermissionDeniedException)34 NodeValue (org.exist.xquery.value.NodeValue)34 DBBroker (org.exist.storage.DBBroker)32 IntegerValue (org.exist.xquery.value.IntegerValue)32 ValueSequence (org.exist.xquery.value.ValueSequence)27 Item (org.exist.xquery.value.Item)26 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)24 EXistException (org.exist.EXistException)23 Path (java.nio.file.Path)22 XmldbURI (org.exist.xmldb.XmldbURI)22 BrokerPool (org.exist.storage.BrokerPool)21 Txn (org.exist.storage.txn.Txn)21 XQueryContext (org.exist.xquery.XQueryContext)21 Element (org.w3c.dom.Element)21 XQuery (org.exist.xquery.XQuery)20