use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class XQueryStartupTrigger method executeQuery.
/**
* Execute xquery on path
*
* @param broker eXist database broker
* @param path path to query, formatted as xmldb:exist:///db/...
*/
private void executeQuery(DBBroker broker, String path) {
XQueryContext context = null;
try {
// Get path to xquery
Source source = SourceFactory.getSource(broker, null, path, false);
if (source == null) {
LOG.info("No XQuery found at '{}'", path);
} else {
// Setup xquery service
XQuery service = broker.getBrokerPool().getXQueryService();
context = new XQueryContext(broker.getBrokerPool());
// Allow use of modules with relative paths
String moduleLoadPath = StringUtils.substringBeforeLast(path, "/");
context.setModuleLoadPath(moduleLoadPath);
// Compile query
CompiledXQuery compiledQuery = service.compile(context, source);
LOG.info("Starting XQuery at '{}'", path);
// Finish preparation
context.prepareForExecution();
// Execute
Sequence result = service.execute(broker, compiledQuery, null);
// Log results
LOG.info("Result XQuery: '{}'", result.getStringValue());
}
} catch (Throwable t) {
// Dirty, catch it all
LOG.error("An error occurred during preparation/execution of the XQuery script {}: {}", path, t.getMessage(), t);
} finally {
if (context != null) {
context.runCleanupTasks();
}
}
}
use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class Launcher method checkInstalledApps.
private void checkInstalledApps() {
try {
final BrokerPool pool = BrokerPool.getInstance();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
final XQuery xquery = pool.getXQueryService();
final Sequence pkgs = xquery.execute(broker, "repo:list()", null);
for (final SequenceIterator i = pkgs.iterate(); i.hasNext(); ) {
final ExistRepository.Notification notification = new ExistRepository.Notification(ExistRepository.Action.INSTALL, i.nextItem().getStringValue());
final Optional<ExistRepository> expathRepo = pool.getExpathRepo();
if (expathRepo.isPresent()) {
update(expathRepo.get(), notification);
utilityPanel.update(expathRepo.get(), notification);
}
expathRepo.orElseThrow(() -> new EXistException("EXPath repository is not available."));
}
}
} catch (final EXistException | XPathException | PermissionDeniedException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
}
}
use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class SequenceConstructor method eval.
@Override
public Sequence eval(final Sequence contextSequence, final 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());
}
}
final ValueSequence result = new ValueSequence();
result.keepUnOrdered(unordered);
for (final Expression step : steps) {
context.pushDocumentContext();
try {
final Sequence temp = step.eval(contextSequence, contextItem);
if (temp != null && !temp.isEmpty()) {
result.addAll(temp);
}
} finally {
context.popDocumentContext();
}
}
if (context.getProfiler().isEnabled()) {
context.getProfiler().end(this, "", result);
}
return result;
}
use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class Predicate method selectByPosition.
/**
* @param outerSequence the outer sequence
* @param contextSequence the context sequence
* @param mode the mode
* @param innerSeq the inner sequence
*
* @return The result of the positional evaluation of the predicate.
*
* @throws XPathException if an error occurs
*/
private Sequence selectByPosition(final Sequence outerSequence, final Sequence contextSequence, final int mode, final Sequence innerSeq) throws XPathException {
if (outerSequence != null && !outerSequence.isEmpty() && Type.subTypeOf(contextSequence.getItemType(), Type.NODE) && contextSequence.isPersistentSet() && outerSequence.isPersistentSet()) {
final Sequence result = new NewArrayNodeSet();
final NodeSet contextSet = contextSequence.toNodeSet();
switch(mode) {
case Constants.CHILD_AXIS:
case Constants.ATTRIBUTE_AXIS:
case Constants.DESCENDANT_AXIS:
case Constants.DESCENDANT_SELF_AXIS:
case Constants.DESCENDANT_ATTRIBUTE_AXIS:
{
final NodeSet outerNodeSet = outerSequence.toNodeSet();
// TODO: in some cases, especially with in-memory nodes,
// outerSequence.toNodeSet() will generate a document
// which will be different from the one(s) in contextSet
// ancestors will thus be empty :-(
// A special treatment of VirtualNodeSet does not seem to be
// required anymore
final Sequence ancestors = outerNodeSet.selectAncestors(contextSet, true, getExpressionId());
if (contextSet.getDocumentSet().intersection(outerNodeSet.getDocumentSet()).getDocumentCount() == 0) {
LOG.info("contextSet and outerNodeSet don't share any document");
}
final NewArrayNodeSet temp = new NewArrayNodeSet();
for (final SequenceIterator i = ancestors.iterate(); i.hasNext(); ) {
NodeProxy p = (NodeProxy) i.nextItem();
ContextItem contextNode = p.getContext();
temp.reset();
while (contextNode != null) {
if (contextNode.getContextId() == getExpressionId()) {
temp.add(contextNode.getNode());
}
contextNode = contextNode.getNextDirect();
}
p.clearContext(getExpressionId());
// TODO : understand why we sort here...
temp.sortInDocumentOrder();
for (final SequenceIterator j = innerSeq.iterate(); j.hasNext(); ) {
final NumericValue v = (NumericValue) j.nextItem();
// Non integers return... nothing, not even an error !
if (!v.hasFractionalPart() && !v.isZero()) {
// ... whereas we don't want a sorted array here
// TODO : rename this method as getInDocumentOrder ? -pb
p = temp.get(v.getInt() - 1);
if (p != null) {
result.add(p);
}
// TODO : does null make sense here ? Well... sometimes ;-)
}
}
}
break;
}
default:
for (final SequenceIterator i = outerSequence.iterate(); i.hasNext(); ) {
NodeProxy p = (NodeProxy) i.nextItem();
Sequence temp;
boolean reverseAxis = true;
switch(mode) {
case Constants.ANCESTOR_AXIS:
temp = contextSet.selectAncestors(p, false, Expression.IGNORE_CONTEXT);
break;
case Constants.ANCESTOR_SELF_AXIS:
temp = contextSet.selectAncestors(p, true, Expression.IGNORE_CONTEXT);
break;
case Constants.PARENT_AXIS:
// TODO : understand why the contextSet is not involved
// here
// NodeProxy.getParent returns a *theoretical* parent
// which is *not* guaranteed to be in the context set !
temp = p.getParents(Expression.NO_CONTEXT_ID);
break;
case Constants.PRECEDING_AXIS:
temp = contextSet.selectPreceding(p, Expression.IGNORE_CONTEXT);
break;
case Constants.PRECEDING_SIBLING_AXIS:
temp = contextSet.selectPrecedingSiblings(p, Expression.IGNORE_CONTEXT);
break;
case Constants.FOLLOWING_SIBLING_AXIS:
temp = contextSet.selectFollowingSiblings(p, Expression.IGNORE_CONTEXT);
reverseAxis = false;
break;
case Constants.FOLLOWING_AXIS:
temp = contextSet.selectFollowing(p, Expression.IGNORE_CONTEXT);
reverseAxis = false;
break;
case Constants.SELF_AXIS:
temp = p;
reverseAxis = false;
break;
default:
throw new IllegalArgumentException("Tried to test unknown axis");
}
if (!temp.isEmpty()) {
for (final SequenceIterator j = innerSeq.iterate(); j.hasNext(); ) {
final NumericValue v = (NumericValue) j.nextItem();
// Non integers return... nothing, not even an error !
if (!v.hasFractionalPart() && !v.isZero()) {
final int pos = (reverseAxis ? temp.getItemCount() - v.getInt() : v.getInt() - 1);
// Other positions are ignored
if (pos >= 0 && pos < temp.getItemCount()) {
final NodeProxy t = (NodeProxy) temp.itemAt(pos);
// for the current context: filter out those
// context items not selected by the positional predicate
ContextItem ctx = t.getContext();
t.clearContext(Expression.IGNORE_CONTEXT);
while (ctx != null) {
if (ctx.getContextId() == outerContextId) {
if (ctx.getNode().getNodeId().equals(p.getNodeId())) {
t.addContextNode(outerContextId, ctx.getNode());
}
} else {
t.addContextNode(ctx.getContextId(), ctx.getNode());
}
ctx = ctx.getNextDirect();
}
result.add(t);
}
}
}
}
}
}
return result;
} else {
final boolean reverseAxis = Type.subTypeOf(contextSequence.getItemType(), Type.NODE) && (mode == Constants.ANCESTOR_AXIS || mode == Constants.ANCESTOR_SELF_AXIS || mode == Constants.PARENT_AXIS || mode == Constants.PRECEDING_AXIS || mode == Constants.PRECEDING_SIBLING_AXIS);
final Set<NumericValue> set = new TreeSet<>();
final ValueSequence result = new ValueSequence();
for (final SequenceIterator i = innerSeq.iterate(); i.hasNext(); ) {
final NumericValue v = (NumericValue) i.nextItem();
// Non integers return... nothing, not even an error !
if (!v.hasFractionalPart() && !v.isZero()) {
final int pos = (reverseAxis ? contextSequence.getItemCount() - v.getInt() : v.getInt() - 1);
// Other positions are ignored
if (pos >= 0 && pos < contextSequence.getItemCount() && !set.contains(v)) {
result.add(contextSequence.itemAt(pos));
set.add(v);
}
}
}
return result;
}
}
use of org.exist.xquery.value.Sequence in project exist by eXist-db.
the class GeneralComparison method genericCompare.
protected Sequence genericCompare(Sequence ls, Sequence contextSequence, Item contextItem) throws XPathException {
final long start = System.currentTimeMillis();
final Sequence rs = getRight().eval(contextSequence, contextItem);
final Collator collator = getCollator(contextSequence);
Sequence result = BooleanValue.FALSE;
if (ls.isEmpty() && rs.isEmpty()) {
result = BooleanValue.valueOf(compareAtomic(collator, AtomicValue.EMPTY_VALUE, AtomicValue.EMPTY_VALUE));
} else if (ls.isEmpty() && !rs.isEmpty()) {
for (final SequenceIterator i2 = Atomize.atomize(rs).iterate(); i2.hasNext(); ) {
if (compareAtomic(collator, AtomicValue.EMPTY_VALUE, i2.nextItem().atomize())) {
result = BooleanValue.TRUE;
break;
}
}
} else if (!ls.isEmpty() && rs.isEmpty()) {
for (final SequenceIterator i1 = Atomize.atomize(ls).iterate(); i1.hasNext(); ) {
final AtomicValue lv = i1.nextItem().atomize();
if (compareAtomic(collator, lv, AtomicValue.EMPTY_VALUE)) {
result = BooleanValue.TRUE;
break;
}
}
} else if (ls.hasOne() && rs.hasOne() && ls.itemAt(0).getType() != Type.ARRAY && rs.itemAt(0).getType() != Type.ARRAY) {
result = BooleanValue.valueOf(compareAtomic(collator, ls.itemAt(0).atomize(), rs.itemAt(0).atomize()));
} else {
for (final SequenceIterator i1 = Atomize.atomize(ls).iterate(); i1.hasNext(); ) {
final AtomicValue lv = i1.nextItem().atomize();
if (rs.isEmpty()) {
if (compareAtomic(collator, lv, AtomicValue.EMPTY_VALUE)) {
result = BooleanValue.TRUE;
break;
}
} else if (rs.hasOne() && rs.itemAt(0).getType() != Type.ARRAY) {
if (compareAtomic(collator, lv, rs.itemAt(0).atomize())) {
// return early if we are successful, continue otherwise
result = BooleanValue.TRUE;
break;
}
} else {
for (final SequenceIterator i2 = Atomize.atomize(rs).iterate(); i2.hasNext(); ) {
if (compareAtomic(collator, lv, i2.nextItem().atomize())) {
result = BooleanValue.TRUE;
break;
}
}
}
}
}
if (context.getProfiler().traceFunctions()) {
context.getProfiler().traceIndexUsage(context, PerformanceStats.RANGE_IDX_TYPE, this, PerformanceStats.NO_INDEX, System.currentTimeMillis() - start);
}
return (result);
}
Aggregations