use of org.exist.xquery.XPathException 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);
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class TestDataGenerator method generate.
public Path[] generate(final DBBroker broker, final Collection collection, final String xqueryContent) throws SAXException {
try {
final DocumentSet docs = collection.allDocs(broker, new DefaultDocumentSet(), true);
final XQuery service = broker.getBrokerPool().getXQueryService();
final XQueryContext context = new XQueryContext(broker.getBrokerPool());
context.declareVariable("filename", "");
context.declareVariable("count", "0");
context.setStaticallyKnownDocuments(docs);
final String query = IMPORT + xqueryContent;
final CompiledXQuery compiled = service.compile(context, query);
for (int i = 0; i < count; i++) {
generatedFiles[i] = Files.createTempFile(prefix, ".xml");
context.declareVariable("filename", generatedFiles[i].getFileName().toString());
context.declareVariable("count", new Integer(i));
final Sequence results = service.execute(broker, compiled, Sequence.EMPTY_SEQUENCE);
final Serializer serializer = broker.borrowSerializer();
try (final Writer out = Files.newBufferedWriter(generatedFiles[i], StandardCharsets.UTF_8)) {
final SAXSerializer sax = new SAXSerializer(out, outputProps);
serializer.setSAXHandlers(sax, sax);
for (final SequenceIterator iter = results.iterate(); iter.hasNext(); ) {
final Item item = iter.nextItem();
if (!Type.subTypeOf(item.getType(), Type.NODE)) {
continue;
}
serializer.toSAX((NodeValue) item);
}
} finally {
broker.returnSerializer(serializer);
}
}
} catch (final XPathException | PermissionDeniedException | LockException | IOException e) {
LOG.error(e.getMessage(), e);
throw new SAXException(e.getMessage(), e);
}
return generatedFiles;
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class YearMonthDurationValue method div.
public ComputableValue div(ComputableValue other) throws XPathException {
if (other.getType() == Type.YEAR_MONTH_DURATION) {
return new IntegerValue(getValue()).div(new IntegerValue(((YearMonthDurationValue) other).getValue()));
}
if (other instanceof NumericValue) {
if (((NumericValue) other).isNaN()) {
throw new XPathException(ErrorCodes.FOCA0005, "Operand is not a number");
}
if (((NumericValue) other).isInfinite()) {
return new YearMonthDurationValue("P0M");
}
// If $arg2 is positive or negative zero, the result overflows and is handled as discussed in 10.1.1 Limits and Precision
if (((NumericValue) other).isZero()) {
throw new XPathException(ErrorCodes.FODT0002, "Division by zero overflow");
}
}
final BigDecimal divisor = numberToBigDecimal(other, "Can not divide xdt:yearMonthDuration by '" + Type.getTypeName(other.getType()) + "'");
final boolean isDivisorNegative = divisor.signum() < 0;
final YearMonthDurationValue quotient = fromDecimalMonths(new BigDecimal(monthsValueSigned()).divide(divisor.abs(), 0, (isDivisorNegative) ? BigDecimal.ROUND_HALF_DOWN : BigDecimal.ROUND_HALF_UP));
if (isDivisorNegative) {
return quotient.negate();
}
return new YearMonthDurationValue(quotient.getCanonicalDuration());
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class RemoveIndex method eval.
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
// Get first parameter, this is the document
final String path = args[0].itemAt(0).getStringValue();
// Retrieve document from database
try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(XmldbURI.xmldbUriFor(path), LockMode.READ_LOCK)) {
// Verify the document actually exists
if (lockedDoc == null) {
throw new XPathException("Document " + path + " does not exist.");
}
// Retrieve Lucene
LuceneIndexWorker index = (LuceneIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(LuceneIndex.ID);
// Note: code order is important here,
index.setDocument(lockedDoc.getDocument(), ReindexMode.REMOVE_BINARY);
index.flush();
} catch (Exception ex) {
// PermissionDeniedException
throw new XPathException(ex);
}
// Return nothing [status would be nice]
return Sequence.EMPTY_SEQUENCE;
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class XMLToQuery method fuzzyQuery.
private Query fuzzyQuery(String field, Element node) throws XPathException {
int maxEdits = FuzzyQuery.defaultMaxEdits;
String attr = node.getAttribute("max-edits");
if (attr != null && !attr.isEmpty()) {
try {
maxEdits = Integer.parseInt(attr);
if (maxEdits < 0 || maxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE) {
throw new XPathException("Query parameter max-edits must by <= " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE);
}
} catch (NumberFormatException e) {
throw new XPathException("Query parameter 'max-edits' should be an integer value. Got: " + attr);
}
}
return new FuzzyQuery(new Term(field, getText(node)), maxEdits);
}
Aggregations