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();
}
}
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");
}
}
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);
}
}
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);
}
}
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;
}
Aggregations