use of org.exist.xquery.value.SequenceIterator in project exist by eXist-db.
the class Deployment method installAndDeploy.
/**
* Install and deploy a give xar archive. Dependencies are installed from
* the PackageLoader.
*
* @param broker the broker to use
* @param transaction the transaction for this deployment task
* @param xar the .xar file to install
* @param loader package loader to use
* @param enforceDeps when set to true, the method will throw an exception if a dependency could not be resolved
* or an older version of the required dependency is installed and needs to be replaced.
* @return the collection path to which the package was deployed or Optional.empty if not deployed
* @throws PackageException if package installation failed
* @throws IOException in case of an IO error
*/
public Optional<String> installAndDeploy(final DBBroker broker, final Txn transaction, final XarSource xar, final PackageLoader loader, boolean enforceDeps) throws PackageException, IOException {
final Optional<DocumentImpl> descriptor = getDescriptor(broker, xar);
if (!descriptor.isPresent()) {
throw new PackageException("Missing descriptor from package: " + xar.getURI());
}
final DocumentImpl document = descriptor.get();
final ElementImpl root = (ElementImpl) document.getDocumentElement();
final String name = root.getAttribute("name");
final String pkgVersion = root.getAttribute("version");
final Optional<ExistRepository> repo = broker.getBrokerPool().getExpathRepo();
if (repo.isPresent()) {
final Packages packages = repo.get().getParentRepo().getPackages(name);
if (packages != null && (!enforceDeps || pkgVersion.equals(packages.latest().getVersion()))) {
LOG.info("Application package {} already installed. Skipping.", name);
final Package pkg = packages.latest();
return Optional.of(getTargetCollection(broker, pkg, getPackageDir(pkg)));
}
InMemoryNodeSet deps;
try {
deps = findElements(root, DEPENDENCY_ELEMENT);
for (final SequenceIterator i = deps.iterate(); i.hasNext(); ) {
final Element dependency = (Element) i.nextItem();
final String pkgName = dependency.getAttribute("package");
final String processor = dependency.getAttribute("processor");
final String versionStr = dependency.getAttribute("version");
final String semVer = dependency.getAttribute("semver");
final String semVerMin = dependency.getAttribute("semver-min");
final String semVerMax = dependency.getAttribute("semver-max");
PackageLoader.Version version = null;
if (semVer != null) {
version = new PackageLoader.Version(semVer, true);
} else if (semVerMax != null || semVerMin != null) {
version = new PackageLoader.Version(semVerMin, semVerMax);
} else if (pkgVersion != null) {
version = new PackageLoader.Version(versionStr, false);
}
if (processor != null && processor.equals(PROCESSOR_NAME) && version != null) {
checkProcessorVersion(version);
} else if (pkgName != null) {
LOG.info("Package {} depends on {}", name, pkgName);
boolean isInstalled = false;
if (repo.get().getParentRepo().getPackages(pkgName) != null) {
LOG.debug("Package {} already installed", pkgName);
Packages pkgs = repo.get().getParentRepo().getPackages(pkgName);
// check if installed package matches required version
if (pkgs != null) {
if (version != null) {
Package latest = pkgs.latest();
DependencyVersion depVersion = version.getDependencyVersion();
if (depVersion.isCompatible(latest.getVersion())) {
isInstalled = true;
} else {
LOG.debug("Package {} needs to be upgraded", pkgName);
if (enforceDeps) {
throw new PackageException("Package requires version " + version.toString() + " of package " + pkgName + ". Installed version is " + latest.getVersion() + ". Please upgrade!");
}
}
} else {
isInstalled = true;
}
if (isInstalled) {
LOG.debug("Package {} already installed", pkgName);
}
}
}
if (!isInstalled && loader != null) {
final XarSource depFile = loader.load(pkgName, version);
if (depFile != null) {
installAndDeploy(broker, transaction, depFile, loader);
} else {
if (enforceDeps) {
LOG.warn("Missing dependency: package {} could not be resolved. This error is not fatal, but the package may not work as expected", pkgName);
} else {
throw new PackageException("Missing dependency: package " + pkgName + " could not be resolved.");
}
}
}
}
}
} catch (final XPathException e) {
throw new PackageException("Invalid descriptor found in " + xar.getURI());
}
// installing the xar into the expath repo
LOG.info("Installing package {}", xar.getURI());
final UserInteractionStrategy interact = new BatchUserInteraction();
final org.expath.pkg.repo.Package pkg = repo.get().getParentRepo().installPackage(xar, true, interact);
final ExistPkgInfo info = (ExistPkgInfo) pkg.getInfo("exist");
if (info != null && !info.getJars().isEmpty()) {
ClasspathHelper.updateClasspath(broker.getBrokerPool(), pkg);
}
broker.getBrokerPool().getXQueryPool().clear();
final String pkgName = pkg.getName();
// signal status
broker.getBrokerPool().reportStatus("Installing app: " + pkg.getAbbrev());
repo.get().reportAction(ExistRepository.Action.INSTALL, pkg.getName());
LOG.info("Deploying package {}", pkgName);
return deploy(broker, transaction, pkgName, repo, null);
}
// Totally unnecessary to do the above if repo is unavailable.
return Optional.empty();
}
use of org.exist.xquery.value.SequenceIterator in project exist by eXist-db.
the class DatabaseResources method getAllResults.
/**
* Convert sequence into list of strings.
*
* @param sequence Result of query.
* @return List containing String objects.
*/
public List<String> getAllResults(Sequence sequence) {
List<String> result = new ArrayList<>();
try {
final SequenceIterator i = sequence.iterate();
while (i.hasNext()) {
final String path = i.nextItem().getStringValue();
result.add(path);
}
} catch (final XPathException ex) {
logger.error("xQuery issue.", ex);
result = null;
}
return result;
}
use of org.exist.xquery.value.SequenceIterator in project exist by eXist-db.
the class FunMin method eval.
/* (non-Javadoc)
* @see org.exist.xquery.Expression#eval(org.exist.dom.persistent.DocumentSet, 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());
}
}
boolean computableProcessing = false;
Sequence result;
final Sequence arg = getArgument(0).eval(contextSequence, contextItem);
if (arg.isEmpty()) {
result = Sequence.EMPTY_SEQUENCE;
} else {
// TODO : test if a range index is defined *iff* it is compatible with the collator
final Collator collator = getCollator(contextSequence, contextItem, 2);
final SequenceIterator iter = arg.unorderedIterator();
AtomicValue min = null;
while (iter.hasNext()) {
final Item item = iter.nextItem();
if (item instanceof QNameValue) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(item.getType()), arg);
}
AtomicValue value = item.atomize();
// Duration values must either all be xs:yearMonthDuration values or must all be xs:dayTimeDuration values.
if (Type.subTypeOf(value.getType(), Type.DURATION)) {
value = ((DurationValue) value).wrap();
if (value.getType() == Type.YEAR_MONTH_DURATION) {
if (min != null && min.getType() != Type.YEAR_MONTH_DURATION) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), value);
}
} else if (value.getType() == Type.DAY_TIME_DURATION) {
if (min != null && min.getType() != Type.DAY_TIME_DURATION) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), value);
}
} else {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(value.getType()), value);
}
// Any value of type xdt:untypedAtomic is cast to xs:double
} else if (value.getType() == Type.UNTYPED_ATOMIC) {
value = value.convertTo(Type.DOUBLE);
}
if (min == null) {
min = value;
} else {
if (Type.getCommonSuperType(min.getType(), value.getType()) == Type.ATOMIC) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), value);
}
// Any value of type xdt:untypedAtomic is cast to xs:double
if (value.getType() == Type.ATOMIC) {
value = value.convertTo(Type.DOUBLE);
}
// Numeric tests
if (Type.subTypeOfUnion(value.getType(), Type.NUMBER)) {
// Don't mix comparisons
if (!Type.subTypeOfUnion(min.getType(), Type.NUMBER)) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), min);
}
if (((NumericValue) value).isNaN()) {
// Type NaN correctly
value = value.promote(min);
if (value.getType() == Type.FLOAT) {
min = FloatValue.NaN;
} else {
min = DoubleValue.NaN;
}
// although result will be NaN, we need to continue on order to type correctly
continue;
}
min = min.promote(value);
}
// Ugly test
if (value instanceof ComputableValue) {
if (!(min instanceof ComputableValue)) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), min);
}
// Type value correctly
value = value.promote(min);
min = min.min(collator, value);
computableProcessing = true;
} else {
if (computableProcessing) {
throw new XPathException(this, ErrorCodes.FORG0006, "Cannot compare " + Type.getTypeName(min.getType()) + " and " + Type.getTypeName(value.getType()), value);
}
if (Collations.compare(collator, value.getStringValue(), min.getStringValue()) < 0) {
min = value;
}
}
}
}
result = min;
}
if (context.getProfiler().isEnabled()) {
context.getProfiler().end(this, "", result);
}
return result;
}
use of org.exist.xquery.value.SequenceIterator in project exist by eXist-db.
the class FunRoot method eval.
/* (non-Javadoc)
* @see org.exist.xquery.Expression#eval(org.exist.dom.persistent.DocumentSet, 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());
}
}
Sequence seq;
Sequence result;
Item item;
if (contextItem != null) {
contextSequence = contextItem.toSequence();
}
if (contextSequence == null || contextSequence.isEmpty()) {
result = Sequence.EMPTY_SEQUENCE;
}
// If we have one argumment, we take it into account
if (getSignature().getArgumentCount() > 0) {
seq = getArgument(0).eval(contextSequence, contextItem);
} else // Otherwise, we take the context sequence and we iterate over it
{
seq = contextSequence;
}
if (seq == null) {
throw new XPathException(this, ErrorCodes.XPDY0002, "Undefined context item");
}
if (seq.isPersistentSet()) {
result = new ExtArrayNodeSet(seq.getItemCount());
} else {
result = new ValueSequence(seq.getItemCount());
}
for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
item = i.nextItem();
if (!Type.subTypeOf(item.getType(), Type.NODE)) {
throw new XPathException(this, ErrorCodes.XPTY0004, "Item is not a node; got '" + item + "'", seq);
}
final Sequence s = item.toSequence();
if (s.isPersistentSet()) {
final NodeProxy p = s.toNodeSet().get(0);
result.add(new NodeProxy(p.getOwnerDocument()));
} else {
if (seq.hasOne() && item.getType() == Type.ATTRIBUTE) {
result.add(item);
} else if (item.getType() == Type.DOCUMENT) {
result.add((DocumentImpl) item);
} else {
result.add(((NodeImpl) item).getOwnerDocument());
}
}
}
if (context.getProfiler().isEnabled()) {
context.getProfiler().end(this, "", result);
}
return result;
}
use of org.exist.xquery.value.SequenceIterator in project exist by eXist-db.
the class XUpdateProcessor method startElement.
@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
// save accumulated character content
if (inModification && charBuf.length() > 0) {
// String normalized = charBuf.toString();
final String normalized = preserveWhitespace ? charBuf.toString() : charBuf.toString().trim();
if (!normalized.isEmpty()) {
final Text text = doc.createTextNode(charBuf.toString());
final Element last = stack.peek();
if (last == null) {
// LOG.debug("appending text to fragment: " + text.getData());
contents.add(text);
} else {
last.appendChild(text);
}
}
charBuf.setLength(0);
}
if (namespaceURI.equals(XUPDATE_NS)) {
String select = null;
switch(localName) {
case MODIFICATIONS:
startModifications(atts);
return;
case VARIABLE:
// variable declaration
startVariableDecl(atts);
return;
case IF:
if (inModification) {
throw new SAXException("xupdate:if is not allowed inside a modification");
}
select = atts.getValue("test");
final Conditional cond = new Conditional(broker, documentSet, select, namespaces, variables);
conditionals.push(cond);
return;
case VALUE_OF:
if (!inModification) {
throw new SAXException("xupdate:value-of is not allowed outside a modification");
}
break;
case APPEND:
case INSERT_BEFORE:
case INSERT_AFTER:
case REMOVE:
case RENAME:
case UPDATE:
case REPLACE:
if (inModification) {
throw new SAXException("nested modifications are not allowed");
}
select = atts.getValue("select");
if (select == null) {
throw new SAXException(localName + " requires a select attribute");
}
doc = builder.newDocument();
contents = new NodeListImpl();
inModification = true;
break;
case ELEMENT:
case ATTRIBUTE:
case TEXT:
case PROCESSING_INSTRUCTION:
case COMMENT:
if (!inModification) {
throw new SAXException("creation elements are only allowed inside " + "a modification");
}
charBuf.setLength(0);
break;
default:
throw new SAXException("Unknown XUpdate element: " + qName);
}
// start a new modification section
switch(localName) {
case APPEND:
final String child = atts.getValue("child");
modification = new Append(broker, documentSet, select, child, namespaces, variables);
break;
case UPDATE:
modification = new Update(broker, documentSet, select, namespaces, variables);
break;
case INSERT_BEFORE:
modification = new Insert(broker, documentSet, select, Insert.INSERT_BEFORE, namespaces, variables);
break;
case INSERT_AFTER:
modification = new Insert(broker, documentSet, select, Insert.INSERT_AFTER, namespaces, variables);
break;
case REMOVE:
modification = new Remove(broker, documentSet, select, namespaces, variables);
break;
case RENAME:
modification = new Rename(broker, documentSet, select, namespaces, variables);
break;
case REPLACE:
modification = new Replace(broker, documentSet, select, namespaces, variables);
break;
// process commands for node creation
case ELEMENT:
{
String name = atts.getValue("name");
if (name == null) {
throw new SAXException("element requires a name attribute");
}
final int p = name.indexOf(':');
String namespace = null;
String prefix = "";
if (p != Constants.STRING_NOT_FOUND) {
prefix = name.substring(0, p);
if (name.length() == p + 1) {
throw new SAXException("illegal prefix in qname: " + name);
}
name = name.substring(p + 1);
namespace = atts.getValue("namespace");
if (namespace == null) {
namespace = namespaces.get(prefix);
}
if (namespace == null) {
throw new SAXException("no namespace defined for prefix " + prefix);
}
}
Element elem;
if (namespace != null && !namespace.isEmpty()) {
elem = doc.createElementNS(namespace, name);
elem.setPrefix(prefix);
} else {
elem = doc.createElement(name);
}
final Element last = stack.peek();
if (last == null) {
contents.add(elem);
} else {
last.appendChild(elem);
}
stack.push(elem);
this.setWhitespaceHandling(elem);
break;
}
case ATTRIBUTE:
{
final String name = atts.getValue("name");
if (name == null) {
throw new SAXException("attribute requires a name attribute");
}
final int p = name.indexOf(':');
String namespace = null;
if (p != Constants.STRING_NOT_FOUND) {
final String prefix = name.substring(0, p);
if (name.length() == p + 1) {
throw new SAXException("illegal prefix in qname: " + name);
}
namespace = atts.getValue("namespace");
if (namespace == null) {
namespace = namespaces.get(prefix);
}
if (namespace == null) {
throw new SAXException("no namespace defined for prefix " + prefix);
}
}
Attr attrib = namespace != null && !namespace.isEmpty() ? doc.createAttributeNS(namespace, name) : doc.createAttribute(name);
if (stack.isEmpty()) {
for (int i = 0; i < contents.getLength(); i++) {
final Node n = contents.item(i);
String ns = n.getNamespaceURI();
final String nname = ns == null ? n.getNodeName() : n.getLocalName();
if (ns == null) {
ns = XMLConstants.NULL_NS_URI;
}
// check for duplicate attributes
if (n.getNodeType() == Node.ATTRIBUTE_NODE && nname.equals(name) && ns.equals(namespace)) {
throw new SAXException("The attribute " + attrib.getNodeName() + " cannot be specified twice");
}
}
contents.add(attrib);
} else {
final Element last = stack.peek();
if (namespace != null && last.hasAttributeNS(namespace, name) || namespace == null && last.hasAttribute(name)) {
throw new SAXException("The attribute " + attrib.getNodeName() + " cannot be specified " + "twice on the same element");
}
if (namespace != null) {
last.setAttributeNodeNS(attrib);
} else {
last.setAttributeNode(attrib);
}
}
inAttribute = true;
currentNode = attrib;
// process value-of
break;
}
case VALUE_OF:
select = atts.getValue("select");
if (select == null) {
throw new SAXException("value-of requires a select attribute");
}
final Sequence seq = processQuery(select);
if (LOG.isDebugEnabled()) {
LOG.debug("Found {} items for value-of", seq.getItemCount());
}
Item item;
try {
for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
item = i.nextItem();
if (Type.subTypeOf(item.getType(), Type.NODE)) {
final Node node = NodeSetHelper.copyNode(doc, ((NodeValue) item).getNode());
final Element last = stack.peek();
if (last == null) {
contents.add(node);
} else {
last.appendChild(node);
}
} else {
final String value = item.getStringValue();
characters(value.toCharArray(), 0, value.length());
}
}
} catch (final XPathException e) {
throw new SAXException(e.getMessage(), e);
}
break;
}
} else if (inModification) {
final Element elem = namespaceURI != null && !namespaceURI.isEmpty() ? doc.createElementNS(namespaceURI, qName) : doc.createElement(qName);
Attr a;
for (int i = 0; i < atts.getLength(); i++) {
final String name = atts.getQName(i);
final String nsURI = atts.getURI(i);
if (name.startsWith("xmlns")) {
// Why are these showing up? They are supposed to be stripped out?
} else {
a = nsURI != null ? doc.createAttributeNS(nsURI, name) : doc.createAttribute(name);
a.setValue(atts.getValue(i));
if (nsURI != null) {
elem.setAttributeNodeNS(a);
} else {
elem.setAttributeNode(a);
}
}
}
final Element last = stack.peek();
if (last == null) {
contents.add(elem);
} else {
last.appendChild(elem);
}
stack.push(elem);
this.setWhitespaceHandling(elem);
}
}
Aggregations