use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.
the class InspectFunction method eval.
@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
final FunctionReference ref = (FunctionReference) args[0].itemAt(0);
final FunctionSignature sig = ref.getSignature();
try {
context.pushDocumentContext();
final MemTreeBuilder builder = context.getDocumentBuilder();
final int nodeNr = InspectFunctionHelper.generateDocs(sig, null, builder);
return builder.getDocument().getNode(nodeNr);
} finally {
context.popDocumentContext();
}
}
use of org.exist.dom.memtree.MemTreeBuilder 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.dom.memtree.MemTreeBuilder 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.dom.memtree.MemTreeBuilder 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.dom.memtree.MemTreeBuilder in project exist by eXist-db.
the class ZipFileFunctions method extractEntries.
private Sequence extractEntries(XmldbURI uri) throws XPathException {
ZipFileSource zipFileSource = new ZipFileFromDb(uri);
ZipInputStream zis = null;
Sequence xmlResponse = null;
context.pushDocumentContext();
try {
MemTreeBuilder builder = context.getDocumentBuilder();
builder.startDocument();
builder.startElement(new QName("file", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
builder.addAttribute(new QName("href", null, null), uri.toString());
try {
zis = zipFileSource.getStream();
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
if (zipEntry.isDirectory()) {
builder.startElement(new QName("dir", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
builder.addAttribute(new QName("name", null, null), zipEntry.toString());
builder.endElement();
} else {
logger.debug("file: {}", zipEntry.getName());
builder.startElement(new QName("entry", ZipModule.NAMESPACE_URI, ZipModule.PREFIX), null);
builder.addAttribute(new QName("name", null, null), zipEntry.toString());
builder.endElement();
}
}
} catch (PermissionDeniedException pde) {
logger.error(pde.getMessage(), pde);
throw new XPathException("Permission denied to read the source zip");
} catch (IOException ioe) {
logger.error(ioe.getMessage(), ioe);
throw new XPathException("IO exception while reading the source zip");
}
builder.endElement();
xmlResponse = (NodeValue) builder.getDocument().getDocumentElement();
return (xmlResponse);
} finally {
context.popDocumentContext();
}
}
Aggregations