use of org.exist.xquery.XQueryContext 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.XQueryContext in project exist by eXist-db.
the class Compile method eval.
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
// get the query expression
final String expr = args[0].getStringValue();
if (expr.trim().isEmpty()) {
return new EmptySequence();
}
context.pushNamespaceContext();
logger.debug("eval: {}", expr);
// TODO(pkaminsk2): why replicate XQuery.compile here?
String error = null;
ErrorCodes.ErrorCode code = null;
int line = -1;
int column = -1;
final XQueryContext pContext = new XQueryContext(context.getBroker().getBrokerPool());
if (getArgumentCount() == 2 && args[1].hasOne()) {
pContext.setModuleLoadPath(args[1].getStringValue());
}
final XQueryLexer lexer = new XQueryLexer(pContext, new StringReader(expr));
final XQueryParser parser = new XQueryParser(lexer);
// shares the context of the outer expression
final XQueryTreeParser astParser = new XQueryTreeParser(pContext);
try {
parser.xpath();
if (parser.foundErrors()) {
logger.debug(parser.getErrorMessage());
throw new XPathException(this, "error found while executing expression: " + parser.getErrorMessage());
}
final AST ast = parser.getAST();
final PathExpr path = new PathExpr(pContext);
astParser.xpath(ast, path);
if (astParser.foundErrors()) {
throw astParser.getLastException();
}
path.analyze(new AnalyzeContextInfo());
} catch (final RecognitionException | TokenStreamException e) {
error = e.toString();
} catch (final XPathException e) {
line = e.getLine();
column = e.getColumn();
code = e.getCode();
error = e.getDetailMessage();
} catch (final Exception e) {
error = e.getMessage();
} finally {
context.popNamespaceContext();
pContext.reset(false);
}
if (isCalledAs("compile")) {
return error == null ? Sequence.EMPTY_SEQUENCE : new StringValue(error);
} else {
return response(pContext, error, code, line, column);
}
}
use of org.exist.xquery.XQueryContext 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.XQueryContext in project exist by eXist-db.
the class IdFunctionTest method sameRealAndEffectiveUsers.
/**
* Test of eval method, of class IdFunction.
* when real and effective users are the same
*/
@Test
public void sameRealAndEffectiveUsers() throws XPathException, XpathException {
final XQueryContext mckContext = createMockBuilder(XQueryContext.class).addMockedMethod("pushDocumentContext").addMockedMethod("getDocumentBuilder", new Class[0]).addMockedMethod("popDocumentContext").addMockedMethod("getRealUser").addMockedMethod("getEffectiveUser").createMock();
final Subject mckUser = EasyMock.createMock(Subject.class);
final String username = "user1";
mckContext.pushDocumentContext();
expectLastCall().once();
expect(mckContext.getDocumentBuilder()).andReturn(new MemTreeBuilder());
mckContext.popDocumentContext();
expectLastCall().once();
expect(mckContext.getRealUser()).andReturn(mckUser).times(2);
expect(mckUser.getName()).andReturn(username);
expect(mckUser.getGroups()).andReturn(new String[] { "group1", "group2" });
expect(mckUser.getId()).andReturn(1);
expect(mckContext.getEffectiveUser()).andReturn(mckUser);
expect(mckUser.getId()).andReturn(1);
replay(mckUser, mckContext);
final IdFunction idFunctions = new IdFunction(mckContext, IdFunction.FNS_ID);
final Sequence result = idFunctions.eval(new Sequence[] { Sequence.EMPTY_SEQUENCE }, null);
assertEquals(1, result.getItemCount());
final XpathEngine xpathEngine = XMLUnit.newXpathEngine();
final Map<String, String> namespaces = new HashMap<>();
namespaces.put("sm", "http://exist-db.org/xquery/securitymanager");
xpathEngine.setNamespaceContext(new SimpleNamespaceContext(namespaces));
final DocumentImpl resultDoc = (DocumentImpl) result.itemAt(0);
final String actualRealUsername = xpathEngine.evaluate("/sm:id/sm:real/sm:username", resultDoc);
assertEquals(username, actualRealUsername);
final String actualEffectiveUsername = xpathEngine.evaluate("/sm:id/sm:effective/sm:username", resultDoc);
assertEquals("", actualEffectiveUsername);
verify(mckUser, mckContext);
}
use of org.exist.xquery.XQueryContext in project exist by eXist-db.
the class AbstractFieldConfig method compile.
protected CompiledXQuery compile(DBBroker broker, String code) {
final XQuery xquery = broker.getBrokerPool().getXQueryService();
final XQueryContext context = new XQueryContext(broker.getBrokerPool());
try {
return xquery.compile(context, code);
} catch (XPathException | PermissionDeniedException e) {
LOG.error("Failed to compile expression: {}: {}", code, e.getMessage(), e);
isValid = false;
return null;
}
}
Aggregations