Search in sources :

Example 41 with NodeImpl

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

the class FunId method getId.

private void getId(Sequence result, Sequence seq, String id) throws XPathException {
    final Set<DocumentImpl> visitedDocs = new TreeSet<>();
    for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
        final NodeImpl v = (NodeImpl) i.nextItem();
        final DocumentImpl doc = v.getNodeType() == Node.DOCUMENT_NODE ? (DocumentImpl) v : v.getOwnerDocument();
        if (doc != null && !visitedDocs.contains(doc)) {
            final NodeImpl elem = doc.selectById(id);
            if (elem != null) {
                result.add(elem);
            }
            visitedDocs.add(doc);
        }
    }
}
Also used : NodeImpl(org.exist.dom.memtree.NodeImpl) TreeSet(java.util.TreeSet) DocumentImpl(org.exist.dom.memtree.DocumentImpl)

Example 42 with NodeImpl

use of org.exist.dom.memtree.NodeImpl 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 43 with NodeImpl

use of org.exist.dom.memtree.NodeImpl 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 44 with NodeImpl

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

the class TestCase method loadVarFromURI.

public NodeImpl loadVarFromURI(XQueryContext context, String uri) throws IOException {
    SAXAdapter adapter = new SAXAdapter(context);
    SAXParserFactory factory = ExistSAXParserFactory.getSAXParserFactory();
    factory.setNamespaceAware(true);
    XMLReader xr;
    try {
        SAXParser parser = factory.newSAXParser();
        xr = parser.getXMLReader();
        xr.setContentHandler(adapter);
        xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
    } catch (Exception e) {
        throw new IOException(e);
    }
    try (final InputStreamReader isr = new InputStreamReader(new FileInputStream(uri), "UTF-8")) {
        // URL url = new URL(uri);
        // InputStreamReader isr = new InputStreamReader(url.openStream(), "UTF-8");
        InputSource src = new InputSource(isr);
        xr.parse(src);
        adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
        return (NodeImpl) adapter.getDocument();
    } catch (SAXException e) {
        // workaround BOM
        if (e.getMessage().equals("Content is not allowed in prolog.")) {
            try {
                String xml = readFileAsString(Paths.get(uri));
                xml = xml.trim().replaceFirst("^([\\W]+)<", "<");
                InputSource src = new InputSource(new StringReader(xml));
                xr.parse(src);
                adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
                return (NodeImpl) adapter.getDocument();
            } catch (SAXException e1) {
                throw new IOException(e);
            }
        }
        throw new IOException(e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) InputStreamReader(java.io.InputStreamReader) NodeImpl(org.exist.dom.memtree.NodeImpl) IOException(java.io.IOException) XMLDBException(org.xmldb.api.base.XMLDBException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) FileInputStream(java.io.FileInputStream) SAXException(org.xml.sax.SAXException) StringReader(java.io.StringReader) SAXAdapter(org.exist.dom.memtree.SAXAdapter) SAXParser(javax.xml.parsers.SAXParser) File(java.io.File) XMLReader(org.xml.sax.XMLReader) SAXParserFactory(javax.xml.parsers.SAXParserFactory) ExistSAXParserFactory(org.exist.util.ExistSAXParserFactory)

Example 45 with NodeImpl

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

the class Jing method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // Check input parameters
    if (args.length != 2) {
        return Sequence.EMPTY_SEQUENCE;
    }
    final ValidationReport report = new ValidationReport();
    InputSource instance = null;
    InputSource grammar = null;
    try {
        report.start();
        // Get inputstream of XML instance document
        instance = Shared.getInputSource(args[0].itemAt(0), context);
        // Validate using resource specified in second parameter
        grammar = Shared.getInputSource(args[1].itemAt(0), context);
        // Special setup for compact notation
        final String grammarUrl = grammar.getSystemId();
        final SchemaReader schemaReader = ((grammarUrl != null) && (grammarUrl.endsWith(".rnc"))) ? CompactSchemaReader.getInstance() : null;
        // Setup validation properties. see Jing interface
        final PropertyMapBuilder properties = new PropertyMapBuilder();
        ValidateProperty.ERROR_HANDLER.put(properties, report);
        // Register resolver for xmldb:exist:/// embedded URLs
        final ExistResolver resolver = new ExistResolver(brokerPool);
        ValidateProperty.URI_RESOLVER.put(properties, resolver);
        ValidateProperty.ENTITY_RESOLVER.put(properties, resolver);
        // Setup driver
        final ValidationDriver driver = new ValidationDriver(properties.toPropertyMap(), schemaReader);
        // Load schema
        driver.loadSchema(grammar);
        // Validate XML instance
        driver.validate(instance);
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        Shared.closeInputSource(instance);
        Shared.closeInputSource(grammar);
        report.stop();
    }
    // Create response
    if (isCalledAs("jing")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jing-report") */
    {
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final NodeImpl result = Shared.writeReport(report, builder);
            return result;
        } finally {
            context.popDocumentContext();
        }
    }
}
Also used : InputSource(org.xml.sax.InputSource) CompactSchemaReader(com.thaiopensource.validate.rng.CompactSchemaReader) SchemaReader(com.thaiopensource.validate.SchemaReader) MalformedURLException(java.net.MalformedURLException) NodeImpl(org.exist.dom.memtree.NodeImpl) ValidationDriver(com.thaiopensource.validate.ValidationDriver) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ExistResolver(org.exist.validation.resolver.unstable.ExistResolver) ValueSequence(org.exist.xquery.value.ValueSequence) PropertyMapBuilder(com.thaiopensource.util.PropertyMapBuilder)

Aggregations

NodeImpl (org.exist.dom.memtree.NodeImpl)53 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)14 XPathException (org.exist.xquery.XPathException)9 DocumentImpl (org.exist.dom.memtree.DocumentImpl)8 Sequence (org.exist.xquery.value.Sequence)8 SAXException (org.xml.sax.SAXException)8 SAXAdapter (org.exist.dom.memtree.SAXAdapter)6 NodeProxy (org.exist.dom.persistent.NodeProxy)6 ValueSequence (org.exist.xquery.value.ValueSequence)6 IOException (java.io.IOException)5 Document (org.w3c.dom.Document)5 InputSource (org.xml.sax.InputSource)5 StringReader (java.io.StringReader)4 QName (org.exist.dom.QName)4 SequenceIterator (org.exist.xquery.value.SequenceIterator)4 XMLReader (org.xml.sax.XMLReader)4 DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)3 NodeSet (org.exist.dom.persistent.NodeSet)3 NodeId (org.exist.numbering.NodeId)3 ValidationReport (org.exist.validation.ValidationReport)3