use of org.exist.xquery.XPathException in project exist by eXist-db.
the class Jaxp method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
XMLEntityResolver entityResolver = null;
GrammarPool grammarPool = null;
final ValidationReport report = new ValidationReport();
ContentHandler contenthandler = null;
MemTreeBuilder instanceBuilder = null;
InputSource instance = null;
if (isCalledAs("jaxp-parse")) {
instanceBuilder = context.getDocumentBuilder();
// (namespace?)
contenthandler = new DocumentBuilderReceiver(instanceBuilder, true);
} else {
contenthandler = new ValidationContentHandler();
}
try {
report.start();
// Get initialized parser
final XMLReader xmlReader = getXMLReader();
// Setup validation reporting
xmlReader.setContentHandler(contenthandler);
xmlReader.setErrorHandler(report);
// Get inputstream for instance document
instance = Shared.getInputSource(args[0].itemAt(0), context);
// Handle catalog
if (args.length == 2) {
LOG.debug("No Catalog specified");
} else if (args[2].isEmpty()) {
// Use system catalog
LOG.debug("Using system catalog.");
final Configuration config = brokerPool.getConfiguration();
entityResolver = (eXistXMLCatalogResolver) config.getProperty(XMLReaderObjectFactory.CATALOG_RESOLVER);
setXmlReaderEnitityResolver(xmlReader, entityResolver);
} else {
// Get URL for catalog
final String[] catalogUrls = Shared.getUrls(args[2]);
final String singleUrl = catalogUrls[0];
if (singleUrl.endsWith("/")) {
// Search grammar in collection specified by URL. Just one collection is used.
LOG.debug("Search for grammar in {}", singleUrl);
entityResolver = new SearchResourceResolver(catalogUrls[0], brokerPool);
setXmlReaderEnitityResolver(xmlReader, entityResolver);
} else if (singleUrl.endsWith(".xml")) {
LOG.debug("Using catalogs {}", getStrings(catalogUrls));
entityResolver = new eXistXMLCatalogResolver();
((eXistXMLCatalogResolver) entityResolver).setCatalogList(catalogUrls);
setXmlReaderEnitityResolver(xmlReader, entityResolver);
} else {
LOG.error("Catalog URLs should end on / or .xml");
}
}
// Use grammarpool
final boolean useCache = ((BooleanValue) args[1].itemAt(0)).getValue();
if (useCache) {
LOG.debug("Grammar caching enabled.");
final Configuration config = brokerPool.getConfiguration();
grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
}
// Jaxp document
LOG.debug("Start parsing document");
xmlReader.parse(instance);
LOG.debug("Stopped parsing document");
// Distill namespace from document
if (contenthandler instanceof ValidationContentHandler) {
report.setNamespaceUri(((ValidationContentHandler) contenthandler).getNamespaceUri());
}
} catch (final MalformedURLException ex) {
LOG.error(ex.getMessage());
report.setException(ex);
} catch (final IOException ex) {
LOG.error(ex.getCause());
report.setException(ex);
} catch (final Throwable ex) {
LOG.error(ex);
report.setException(ex);
} finally {
report.stop();
Shared.closeInputSource(instance);
}
// Create response
if (isCalledAs("jaxp")) {
final Sequence result = new ValueSequence();
result.add(new BooleanValue(report.isValid()));
return result;
} else /* isCalledAs("jaxp-report or jaxp-parse ") */
{
if (report.getThrowable() != null) {
throw new XPathException(report.getThrowable().getMessage(), report.getThrowable());
}
if (contenthandler instanceof DocumentBuilderReceiver) {
// DocumentBuilderReceiver dbr = (DocumentBuilderReceiver) contenthandler;
return instanceBuilder.getDocument().getNode(0);
} else {
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
return Shared.writeReport(report, builder);
} finally {
context.popDocumentContext();
}
}
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class ModuleInfo method eval.
/* (non-Javadoc)
* @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
*/
@SuppressWarnings("unchecked")
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if ("get-module-description".equals(getSignature().getName().getLocalPart())) {
final String uri = args[0].getStringValue();
final Module[] modules = context.getModules(uri);
if (isEmpty(modules)) {
throw new XPathException(this, "No module found matching namespace URI: " + uri);
}
final Sequence result = new ValueSequence();
for (final Module module : modules) {
result.add(new StringValue(module.getDescription()));
}
return result;
} else if ("is-module-registered".equals(getSignature().getName().getLocalPart())) {
final String uri = args[0].getStringValue();
final Module[] modules = context.getModules(uri);
return new BooleanValue(modules != null && modules.length > 0);
} else if ("mapped-modules".equals(getSignature().getName().getLocalPart())) {
final ValueSequence resultSeq = new ValueSequence();
for (final Iterator<String> i = context.getMappedModuleURIs(); i.hasNext(); ) {
resultSeq.add(new StringValue(i.next()));
}
return resultSeq;
} else if ("is-module-mapped".equals(getSignature().getName().getLocalPart())) {
final String uri = args[0].getStringValue();
return new BooleanValue(((Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP)).get(uri) != null);
} else if ("map-module".equals(getSignature().getName().getLocalPart())) {
if (!context.getSubject().hasDbaRole()) {
final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
logger.error("Invalid user", xPathException);
throw xPathException;
}
final String namespace = args[0].getStringValue();
final String location = args[1].getStringValue();
final Map<String, String> moduleMap = (Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP);
moduleMap.put(namespace, location);
return Sequence.EMPTY_SEQUENCE;
} else if ("unmap-module".equals(getSignature().getName().getLocalPart())) {
if (!context.getSubject().hasDbaRole()) {
final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
logger.error("Invalid user", xPathException);
throw xPathException;
}
final String namespace = args[0].getStringValue();
final Map<String, String> moduleMap = (Map<String, String>) context.getBroker().getConfiguration().getProperty(XQueryContext.PROPERTY_STATIC_MODULE_MAP);
moduleMap.remove(namespace);
return Sequence.EMPTY_SEQUENCE;
} else if ("get-module-info".equals(getSignature().getName().getLocalPart())) {
context.pushDocumentContext();
try {
final MemTreeBuilder builder = context.getDocumentBuilder();
builder.startElement(MODULES_QNAME, null);
if (getArgumentCount() == 1) {
final Module[] modules = context.getModules(args[0].getStringValue());
if (modules != null) {
outputModules(builder, modules);
}
} else {
for (final Iterator<Module> i = context.getRootModules(); i.hasNext(); ) {
final Module module = i.next();
outputModule(builder, module);
}
}
return builder.getDocument().getNode(1);
} finally {
context.popDocumentContext();
}
} else {
final ValueSequence resultSeq = new ValueSequence();
final XQueryContext tempContext = new XQueryContext(context.getBroker().getBrokerPool());
for (final Iterator<Module> i = tempContext.getRootModules(); i.hasNext(); ) {
final Module module = i.next();
resultSeq.add(new StringValue(module.getNamespaceURI()));
}
if (tempContext.getRepository().isPresent()) {
for (final URI uri : tempContext.getRepository().get().getJavaModules()) {
resultSeq.add(new StringValue(uri.toString()));
}
}
return resultSeq;
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class Expand method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
if (args[0].isEmpty()) {
return Sequence.EMPTY_SEQUENCE;
}
// apply serialization options set on the XQuery context
final Properties serializeOptions = new Properties();
serializeOptions.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
serializeOptions.setProperty(EXistOutputKeys.HIGHLIGHT_MATCHES, "elements");
if (getArgumentCount() == 2) {
final String serOpts = args[1].getStringValue();
final String[] contents = Option.tokenize(serOpts);
for (String content : contents) {
final String[] pair = Option.parseKeyValuePair(content);
if (pair == null) {
throw new XPathException(this, "Found invalid serialization option: " + content);
}
logger.debug("Setting serialization property: {} = {}", pair[0], pair[1]);
serializeOptions.setProperty(pair[0], pair[1]);
}
} else {
context.checkOptions(serializeOptions);
}
context.pushDocumentContext();
try {
final InMemoryNodeSet result = new InMemoryNodeSet();
final MemTreeBuilder builder = new MemTreeBuilder(getContext());
final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
int attrNr = -1;
for (final SequenceIterator i = args[0].iterate(); i.hasNext(); ) {
final NodeValue next = (NodeValue) i.nextItem();
final short nodeType = ((INodeHandle) next).getNodeType();
builder.startDocument();
if (nodeType == Node.ATTRIBUTE_NODE) {
// NOTE: Attributes nodes need special handling as they cannot be directly serialized via SAX to a ContentHandler
final Attr attr = (Attr) next.getNode();
String ns = attr.getNamespaceURI();
if (ns == null || ns.isEmpty()) {
ns = XMLConstants.NULL_NS_URI;
}
attrNr = builder.addAttribute(new QName(attr.getLocalName(), ns), attr.getValue());
} else {
next.toSAX(context.getBroker(), receiver, serializeOptions);
}
builder.endDocument();
if (Node.DOCUMENT_NODE == nodeType) {
result.add(builder.getDocument());
} else if (Node.ATTRIBUTE_NODE == nodeType) {
result.add(builder.getDocument().getAttribute(attrNr));
} else {
result.add(builder.getDocument().getNode(1));
}
builder.reset(getContext());
}
return result;
} catch (final SAXException e) {
throw new XPathException(this, e);
} finally {
context.popDocumentContext();
}
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class XMLDBAbstractCollectionManipulator method eval.
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
if (0 == args.length) {
throw new XPathException(this, "Expected a collection as the argument " + (paramNumber + 1) + ".");
}
final boolean collectionNeedsClose = false;
Collection collection = null;
final Item item = args[paramNumber].itemAt(0);
if (Type.subTypeOf(item.getType(), Type.NODE)) {
final NodeValue node = (NodeValue) item;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found node");
}
if (node.getImplementationType() == NodeValue.PERSISTENT_NODE) {
final org.exist.collections.Collection internalCol = ((NodeProxy) node).getOwnerDocument().getCollection();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Found node");
}
try {
// TODO: use xmldbURI
collection = getLocalCollection(context, internalCol.getURI().toString());
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Loaded collection {}", collection.getName());
}
} catch (final XMLDBException e) {
throw new XPathException(this, "Failed to access collection: " + internalCol.getURI(), e);
}
} else {
return Sequence.EMPTY_SEQUENCE;
}
}
if (collection == null) {
// Otherwise, just extract the name as a string:
final String collectionURI = args[paramNumber].getStringValue();
if (collectionURI != null) {
try {
collection = getCollection(context, collectionURI, Optional.empty(), Optional.empty());
} catch (final XMLDBException xe) {
if (errorIfAbsent) {
throw new XPathException(this, "Could not locate collection: " + collectionURI, xe);
}
collection = null;
}
}
if (collection == null && errorIfAbsent) {
throw new XPathException(this, "Unable to find collection: " + collectionURI);
}
}
Sequence s = Sequence.EMPTY_SEQUENCE;
try {
s = evalWithCollection(collection, args, contextSequence);
} finally {
if (collectionNeedsClose && collection != null) {
try {
collection.close();
} catch (final Exception e) {
throw new XPathException(this, "Unable to close collection", e);
}
}
}
return s;
}
use of org.exist.xquery.XPathException in project exist by eXist-db.
the class XMLDBDefragment 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[] args, Sequence contextSequence) throws XPathException {
// Get nodes
final NodeSet nodes = args[0].toNodeSet();
final DocumentSet docs = nodes.getDocumentSet();
try {
if (args.length > 1) {
// Use supplied parameter
final int splitCount = ((IntegerValue) args[1].itemAt(0)).getInt();
Modification.checkFragmentation(context, docs, splitCount);
} else {
// Use conf.xml configured value or -1 if not existent
Modification.checkFragmentation(context, docs);
}
} catch (final LockException | EXistException e) {
logger.error("An error occurred while defragmenting documents: {}", e.getMessage());
throw new XPathException(this, "An error occurred while defragmenting documents: " + e.getMessage(), e);
}
return Sequence.EMPTY_SEQUENCE;
}
Aggregations