Search in sources :

Example 56 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.

the class XPathUtil method javaObjectToXPath.

public static final Sequence javaObjectToXPath(Object obj, XQueryContext context, boolean expandChars) throws XPathException {
    if (obj == null) {
        // return Sequence.EMPTY_SEQUENCE;
        return null;
    } else if (obj instanceof Sequence) {
        return (Sequence) obj;
    } else if (obj instanceof String) {
        final StringValue v = new StringValue((String) obj);
        return (expandChars ? v.expand() : v);
    } else if (obj instanceof Boolean) {
        return BooleanValue.valueOf(((Boolean) obj));
    } else if (obj instanceof Float) {
        return new FloatValue(((Float) obj));
    } else if (obj instanceof Double) {
        return new DoubleValue(((Double) obj));
    } else if (obj instanceof Short) {
        return new IntegerValue(((Short) obj), Type.SHORT);
    } else if (obj instanceof Integer) {
        return new IntegerValue(((Integer) obj), Type.INT);
    } else if (obj instanceof Long) {
        return new IntegerValue(((Long) obj), Type.LONG);
    } else if (obj instanceof byte[]) {
        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), new UnsynchronizedByteArrayInputStream((byte[]) obj));
    } else if (obj instanceof ResourceSet) {
        final Sequence seq = new AVLTreeNodeSet();
        try {
            final DBBroker broker = context.getBroker();
            for (final ResourceIterator it = ((ResourceSet) obj).getIterator(); it.hasMoreResources(); ) {
                seq.add(getNode(broker, (XMLResource) it.nextResource()));
            }
        } catch (final XMLDBException xe) {
            throw new XPathException("Failed to convert ResourceSet to node: " + xe.getMessage());
        }
        return seq;
    } else if (obj instanceof XMLResource) {
        return getNode(context.getBroker(), (XMLResource) obj);
    } else if (obj instanceof Node) {
        context.pushDocumentContext();
        final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
            streamer.setContentHandler(receiver);
            streamer.serialize((Node) obj, false);
            if (obj instanceof Document) {
                return builder.getDocument();
            } else {
                return builder.getDocument().getNode(1);
            }
        } catch (final SAXException e) {
            throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
        } finally {
            context.popDocumentContext();
            SerializerPool.getInstance().returnObject(streamer);
        }
    } else if (obj instanceof List<?>) {
        boolean createNodeSequence = true;
        for (Object next : ((List<?>) obj)) {
            if (!(next instanceof NodeProxy)) {
                createNodeSequence = false;
                break;
            }
        }
        Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
        for (Object o : ((List<?>) obj)) {
            seq.add((Item) javaObjectToXPath(o, context, expandChars));
        }
        return seq;
    } else if (obj instanceof NodeList) {
        context.pushDocumentContext();
        final DOMStreamer streamer = (DOMStreamer) SerializerPool.getInstance().borrowObject(DOMStreamer.class);
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            builder.startDocument();
            final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
            streamer.setContentHandler(receiver);
            final ValueSequence seq = new ValueSequence();
            final NodeList nl = (NodeList) obj;
            int last = builder.getDocument().getLastNode();
            for (int i = 0; i < nl.getLength(); i++) {
                final Node n = nl.item(i);
                streamer.serialize(n, false);
                final NodeImpl created = builder.getDocument().getNode(last + 1);
                seq.add(created);
                last = builder.getDocument().getLastNode();
            }
            return seq;
        } catch (final SAXException e) {
            throw new XPathException("Failed to transform node into internal model: " + e.getMessage());
        } finally {
            context.popDocumentContext();
            SerializerPool.getInstance().returnObject(streamer);
        }
    } else if (obj instanceof Object[]) {
        boolean createNodeSequence = true;
        final Object[] array = (Object[]) obj;
        for (Object arrayItem : array) {
            if (!(arrayItem instanceof NodeProxy)) {
                createNodeSequence = false;
                break;
            }
        }
        Sequence seq = createNodeSequence ? new AVLTreeNodeSet() : new ValueSequence();
        for (Object arrayItem : array) {
            seq.add((Item) javaObjectToXPath(arrayItem, context, expandChars));
        }
        return seq;
    } else {
        return new JavaObjectValue(obj);
    }
}
Also used : Node(org.w3c.dom.Node) XMLDBException(org.xmldb.api.base.XMLDBException) Document(org.w3c.dom.Document) NodeProxy(org.exist.dom.persistent.NodeProxy) SAXException(org.xml.sax.SAXException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) NodeList(org.w3c.dom.NodeList) List(java.util.List) NodeImpl(org.exist.dom.memtree.NodeImpl) NodeList(org.w3c.dom.NodeList) ResourceSet(org.xmldb.api.base.ResourceSet) AVLTreeNodeSet(org.exist.dom.persistent.AVLTreeNodeSet) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) RemoteXMLResource(org.exist.xmldb.RemoteXMLResource) XMLResource(org.xmldb.api.modules.XMLResource) LocalXMLResource(org.exist.xmldb.LocalXMLResource) DBBroker(org.exist.storage.DBBroker) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DOMStreamer(org.exist.util.serializer.DOMStreamer) ResourceIterator(org.xmldb.api.base.ResourceIterator)

Example 57 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.

the class XQueryContext method getDocumentBuilder.

@Override
public MemTreeBuilder getDocumentBuilder(final boolean explicitCreation) {
    if (documentBuilder == null) {
        documentBuilder = new MemTreeBuilder(this);
        documentBuilder.startDocument(explicitCreation);
    }
    return documentBuilder;
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder)

Example 58 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.

the class TextConstructor method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.Expression#eval(org.exist.xquery.StaticContext, org.exist.dom.persistent.DocumentSet, org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (isWhitespaceOnly && context.stripWhitespace()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    if (newDocumentContext) {
        context.pushDocumentContext();
    }
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        context.proceed(this, builder);
        final int nodeNr = builder.characters(text);
        final NodeImpl node = builder.getDocument().getNode(nodeNr);
        return node;
    } finally {
        if (newDocumentContext) {
            context.popDocumentContext();
        }
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) NodeImpl(org.exist.dom.memtree.NodeImpl)

Example 59 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.

the class XQueryDeclareContextItemTest method declareContextItemExternalElement.

@Test
public void declareContextItemExternalElement() throws EXistException, PermissionDeniedException, XPathException, SAXException {
    final String query = "xquery version \"3.0\";\n" + "declare namespace env=\"http://www.w3.org/2003/05/soap-envelope\";\n" + "declare context item as element(env:Envelope) external;\n" + "<wrap>{.}</wrap>";
    final BrokerPool pool = existEmbeddedServer.getBrokerPool();
    final XQuery xquery = pool.getXQueryService();
    try (final DBBroker broker = pool.getBroker()) {
        final MemTreeBuilder builder = new MemTreeBuilder();
        builder.startDocument();
        builder.startElement(new QName("Envelope", "http://www.w3.org/2003/05/soap-envelope"), null);
        builder.endElement();
        builder.endDocument();
        final ElementImpl elem = (ElementImpl) builder.getDocument().getDocumentElement();
        final Sequence result = xquery.execute(broker, query, elem);
        assertEquals(1, result.getItemCount());
        assertEquals("<wrap><Envelope xmlns=\"http://www.w3.org/2003/05/soap-envelope\"/></wrap>", serialize(broker, (NodeValue) result.itemAt(0)));
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) DBBroker(org.exist.storage.DBBroker) ElementImpl(org.exist.dom.memtree.ElementImpl) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) Sequence(org.exist.xquery.value.Sequence) BrokerPool(org.exist.storage.BrokerPool) Test(org.junit.Test)

Example 60 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder in project exist by eXist-db.

the class IdFunctionTest method differingRealAndEffectiveUsers.

/**
 * Test of eval method, of class IdFunction.
 * when real and effective users are different
 */
@Test
public void differingRealAndEffectiveUsers() 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 mckRealUser = EasyMock.createMock(Subject.class);
    final String realUsername = "real";
    mckContext.pushDocumentContext();
    expectLastCall().once();
    expect(mckContext.getDocumentBuilder()).andReturn(new MemTreeBuilder());
    mckContext.popDocumentContext();
    expectLastCall().once();
    expect(mckContext.getRealUser()).andReturn(mckRealUser).times(2);
    expect(mckRealUser.getName()).andReturn(realUsername);
    expect(mckRealUser.getGroups()).andReturn(new String[] { "realGroup1", "realGroup2" });
    expect(mckRealUser.getId()).andReturn(1);
    final Subject mckEffectiveUser = EasyMock.createMock(Subject.class);
    final String effectiveUsername = "effective";
    expect(mckContext.getEffectiveUser()).andReturn(mckEffectiveUser).times(2);
    expect(mckEffectiveUser.getId()).andReturn(2);
    expect(mckEffectiveUser.getName()).andReturn(effectiveUsername);
    expect(mckEffectiveUser.getGroups()).andReturn(new String[] { "effectiveGroup1", "effectiveGroup2" });
    replay(mckEffectiveUser, mckRealUser, 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(realUsername, actualRealUsername);
    final String actualEffectiveUsername = xpathEngine.evaluate("/sm:id/sm:effective/sm:username", resultDoc);
    assertEquals(effectiveUsername, actualEffectiveUsername);
    verify(mckEffectiveUser, mckRealUser, 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)

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