Search in sources :

Example 6 with MemTreeBuilder

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();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) FunctionReference(org.exist.xquery.value.FunctionReference) FunctionSignature(org.exist.xquery.FunctionSignature)

Example 7 with MemTreeBuilder

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;
    }
}
Also used : XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) URI(java.net.URI) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) Module(org.exist.xquery.Module) ExternalModule(org.exist.xquery.ExternalModule) StringValue(org.exist.xquery.value.StringValue) Map(java.util.Map)

Example 8 with MemTreeBuilder

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();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) INodeHandle(org.exist.dom.INodeHandle) QName(org.exist.dom.QName) InMemoryNodeSet(org.exist.dom.memtree.InMemoryNodeSet) Properties(java.util.Properties) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Attr(org.w3c.dom.Attr) SAXException(org.xml.sax.SAXException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SequenceIterator(org.exist.xquery.value.SequenceIterator)

Example 9 with MemTreeBuilder

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);
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XpathEngine(org.custommonkey.xmlunit.XpathEngine) HashMap(java.util.HashMap) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) SimpleNamespaceContext(org.custommonkey.xmlunit.SimpleNamespaceContext) DocumentImpl(org.exist.dom.memtree.DocumentImpl) Subject(org.exist.security.Subject) Test(org.junit.Test)

Example 10 with MemTreeBuilder

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();
    }
}
Also used : ZipInputStream(java.util.zip.ZipInputStream) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) ZipEntry(java.util.zip.ZipEntry) PermissionDeniedException(org.exist.security.PermissionDeniedException) IOException(java.io.IOException)

Aggregations

MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)81 QName (org.exist.dom.QName)28 XPathException (org.exist.xquery.XPathException)23 Sequence (org.exist.xquery.value.Sequence)19 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)17 SAXException (org.xml.sax.SAXException)16 NodeValue (org.exist.xquery.value.NodeValue)15 IOException (java.io.IOException)14 NodeImpl (org.exist.dom.memtree.NodeImpl)14 Item (org.exist.xquery.value.Item)8 SequenceIterator (org.exist.xquery.value.SequenceIterator)8 Test (org.junit.Test)8 XQueryContext (org.exist.xquery.XQueryContext)7 ValueSequence (org.exist.xquery.value.ValueSequence)7 AttributesImpl (org.xml.sax.helpers.AttributesImpl)7 DocumentImpl (org.exist.dom.memtree.DocumentImpl)6 BrokerPool (org.exist.storage.BrokerPool)6 InputSource (org.xml.sax.InputSource)6 MalformedURLException (java.net.MalformedURLException)5 Path (java.nio.file.Path)5