Search in sources :

Example 1 with DocumentBuilderReceiver

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

the class Jaxp method eval.

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    XMLEntityResolver entityResolver = null;
    GrammarPool grammarPool = null;
    final ValidationReport report = new ValidationReport();
    ContentHandler contenthandler = null;
    MemTreeBuilder instanceBuilder = null;
    InputSource instance = null;
    if (isCalledAs("jaxp-parse")) {
        instanceBuilder = context.getDocumentBuilder();
        // (namespace?)
        contenthandler = new DocumentBuilderReceiver(instanceBuilder, true);
    } else {
        contenthandler = new ValidationContentHandler();
    }
    try {
        report.start();
        // Get initialized parser
        final XMLReader xmlReader = getXMLReader();
        // Setup validation reporting
        xmlReader.setContentHandler(contenthandler);
        xmlReader.setErrorHandler(report);
        // Get inputstream for instance document
        instance = Shared.getInputSource(args[0].itemAt(0), context);
        // Handle catalog
        if (args.length == 2) {
            LOG.debug("No Catalog specified");
        } else if (args[2].isEmpty()) {
            // Use system catalog
            LOG.debug("Using system catalog.");
            final Configuration config = brokerPool.getConfiguration();
            entityResolver = (eXistXMLCatalogResolver) config.getProperty(XMLReaderObjectFactory.CATALOG_RESOLVER);
            setXmlReaderEnitityResolver(xmlReader, entityResolver);
        } else {
            // Get URL for catalog
            final String[] catalogUrls = Shared.getUrls(args[2]);
            final String singleUrl = catalogUrls[0];
            if (singleUrl.endsWith("/")) {
                // Search grammar in collection specified by URL. Just one collection is used.
                LOG.debug("Search for grammar in {}", singleUrl);
                entityResolver = new SearchResourceResolver(catalogUrls[0], brokerPool);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else if (singleUrl.endsWith(".xml")) {
                LOG.debug("Using catalogs {}", getStrings(catalogUrls));
                entityResolver = new eXistXMLCatalogResolver();
                ((eXistXMLCatalogResolver) entityResolver).setCatalogList(catalogUrls);
                setXmlReaderEnitityResolver(xmlReader, entityResolver);
            } else {
                LOG.error("Catalog URLs should end on / or .xml");
            }
        }
        // Use grammarpool
        final boolean useCache = ((BooleanValue) args[1].itemAt(0)).getValue();
        if (useCache) {
            LOG.debug("Grammar caching enabled.");
            final Configuration config = brokerPool.getConfiguration();
            grammarPool = (GrammarPool) config.getProperty(XMLReaderObjectFactory.GRAMMAR_POOL);
            xmlReader.setProperty(XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);
        }
        // Jaxp document
        LOG.debug("Start parsing document");
        xmlReader.parse(instance);
        LOG.debug("Stopped parsing document");
        // Distill namespace from document
        if (contenthandler instanceof ValidationContentHandler) {
            report.setNamespaceUri(((ValidationContentHandler) contenthandler).getNamespaceUri());
        }
    } catch (final MalformedURLException ex) {
        LOG.error(ex.getMessage());
        report.setException(ex);
    } catch (final IOException ex) {
        LOG.error(ex.getCause());
        report.setException(ex);
    } catch (final Throwable ex) {
        LOG.error(ex);
        report.setException(ex);
    } finally {
        report.stop();
        Shared.closeInputSource(instance);
    }
    // Create response
    if (isCalledAs("jaxp")) {
        final Sequence result = new ValueSequence();
        result.add(new BooleanValue(report.isValid()));
        return result;
    } else /* isCalledAs("jaxp-report or jaxp-parse ") */
    {
        if (report.getThrowable() != null) {
            throw new XPathException(report.getThrowable().getMessage(), report.getThrowable());
        }
        if (contenthandler instanceof DocumentBuilderReceiver) {
            // DocumentBuilderReceiver dbr = (DocumentBuilderReceiver) contenthandler;
            return instanceBuilder.getDocument().getNode(0);
        } else {
            context.pushDocumentContext();
            try {
                final MemTreeBuilder builder = context.getDocumentBuilder();
                return Shared.writeReport(report, builder);
            } finally {
                context.popDocumentContext();
            }
        }
    }
}
Also used : ValidationContentHandler(org.exist.validation.ValidationContentHandler) InputSource(org.xml.sax.InputSource) SearchResourceResolver(org.exist.validation.resolver.SearchResourceResolver) MalformedURLException(java.net.MalformedURLException) org.exist.validation.resolver.eXistXMLCatalogResolver(org.exist.validation.resolver.eXistXMLCatalogResolver) Configuration(org.exist.util.Configuration) XPathException(org.exist.xquery.XPathException) XMLEntityResolver(org.apache.xerces.xni.parser.XMLEntityResolver) GrammarPool(org.exist.validation.GrammarPool) IOException(java.io.IOException) ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) ContentHandler(org.xml.sax.ContentHandler) ValidationContentHandler(org.exist.validation.ValidationContentHandler) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ValidationReport(org.exist.validation.ValidationReport) BooleanValue(org.exist.xquery.value.BooleanValue) ValueSequence(org.exist.xquery.value.ValueSequence) XMLReader(org.xml.sax.XMLReader)

Example 2 with DocumentBuilderReceiver

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

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

the class MessageFunctions method handlePart.

private void handlePart(Part part, MemTreeBuilder builder) throws MessagingException, IOException, XPathException, SAXException {
    Object content = part.getContent();
    if (content instanceof Multipart) {
        handleMultipart((Multipart) content, builder);
        return;
    }
    String disposition = part.getDisposition();
    String contentType = part.getContentType();
    // Check if plain
    if (contentType.contains("text/plain")) {
        builder.startElement(new QName("text", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        builder.characters(part.getContent().toString());
        builder.endElement();
    } else if (contentType.contains("text/html")) {
        builder.startElement(new QName("xhtml", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        // extract and clean up the html
        DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
        try (InputStream inputStream = part.getInputStream()) {
            DocumentImpl html = ModuleUtils.htmlToXHtml(context, new StreamSource(inputStream), null, null);
            ElementImpl rootElem = (ElementImpl) html.getDocumentElement();
            html.copyTo(rootElem, receiver);
            builder.endElement();
        }
    } else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
        builder.startElement(new QName("attachment", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("filename", null, null), part.getFileName());
        mimeParamsToAttributes(builder, part.getContentType());
        handleBinaryContent(part, builder);
        builder.endElement();
    } else if (disposition.equalsIgnoreCase(Part.INLINE)) {
        builder.startElement(new QName("inline", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        MimeBodyPart mbp = (MimeBodyPart) part;
        builder.addAttribute(new QName("filename", null, null), mbp.getFileName());
        // fix content id so that it matches the cid: format within the html
        if (mbp.getContentID() != null) {
            builder.addAttribute(new QName("content-id", null, null), "cid:" + mbp.getContentID().replaceAll("^<|>$", ""));
        }
        mimeParamsToAttributes(builder, part.getContentType());
        handleBinaryContent(part, builder);
        builder.endElement();
    } else {
        // Should never happen
        builder.startElement(new QName("other", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        mimeParamsToAttributes(builder, part.getContentType());
        builder.addAttribute(new QName("disposition", null, null), part.getDisposition());
        builder.characters(part.getContent().toString());
        builder.endElement();
    }
}
Also used : ElementImpl(org.exist.dom.memtree.ElementImpl) QName(org.exist.dom.QName) StreamSource(javax.xml.transform.stream.StreamSource) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) MimeBodyPart(jakarta.mail.internet.MimeBodyPart) DocumentImpl(org.exist.dom.memtree.DocumentImpl)

Example 4 with DocumentBuilderReceiver

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

the class Modification method deepCopy.

protected Sequence deepCopy(Sequence inSeq) throws XPathException {
    context.pushDocumentContext();
    final MemTreeBuilder builder = context.getDocumentBuilder();
    final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
    final Serializer serializer = context.getBroker().borrowSerializer();
    serializer.setReceiver(receiver);
    try {
        final Sequence out = new ValueSequence();
        for (final SequenceIterator i = inSeq.iterate(); i.hasNext(); ) {
            Item item = i.nextItem();
            if (item.getType() == Type.DOCUMENT) {
                if (((NodeValue) item).getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    final NodeHandle root = (NodeHandle) ((NodeProxy) item).getOwnerDocument().getDocumentElement();
                    item = new NodeProxy(root);
                } else {
                    item = (Item) ((Document) item).getDocumentElement();
                }
            }
            if (Type.subTypeOf(item.getType(), Type.NODE)) {
                if (((NodeValue) item).getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    final int last = builder.getDocument().getLastNode();
                    final NodeProxy p = (NodeProxy) item;
                    serializer.toReceiver(p, false, false);
                    if (p.getNodeType() == Node.ATTRIBUTE_NODE) {
                        item = builder.getDocument().getLastAttr();
                    } else {
                        item = builder.getDocument().getNode(last + 1);
                    }
                } else {
                    ((org.exist.dom.memtree.NodeImpl) item).deepCopy();
                }
            }
            out.add(item);
        }
        return out;
    } catch (final SAXException | DOMException e) {
        throw new XPathException(this, e.getMessage(), e);
    } finally {
        context.getBroker().returnSerializer(serializer);
        context.popDocumentContext();
    }
}
Also used : ValueSequence(org.exist.xquery.value.ValueSequence) Sequence(org.exist.xquery.value.Sequence) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Document(org.w3c.dom.Document) NodeProxy(org.exist.dom.persistent.NodeProxy) SAXException(org.xml.sax.SAXException) Item(org.exist.xquery.value.Item) DOMException(org.w3c.dom.DOMException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SequenceIterator(org.exist.xquery.value.SequenceIterator) NodeHandle(org.exist.dom.persistent.NodeHandle) ValueSequence(org.exist.xquery.value.ValueSequence) Serializer(org.exist.storage.serializers.Serializer)

Example 5 with DocumentBuilderReceiver

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

the class FunGMLProducers method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    Sequence result = null;
    try {
        AbstractGMLJDBCIndexWorker indexWorker = (AbstractGMLJDBCIndexWorker) context.getBroker().getIndexController().getWorkerByIndexId(AbstractGMLJDBCIndex.ID);
        if (indexWorker == null) {
            logger.error("Unable to find a spatial index worker");
            throw new XPathException(this, "Unable to find a spatial index worker");
        }
        Geometry geometry = null;
        String targetSRS = null;
        if (isCalledAs("transform")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                String sourceSRS = null;
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    sourceSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    sourceSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                targetSRS = args[1].itemAt(0).getStringValue().trim();
                geometry = indexWorker.transformGeometry(geometry, sourceSRS, targetSRS);
            }
        } else if (isCalledAs("WKTtoGML")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                String wkt = args[0].itemAt(0).getStringValue();
                WKTReader wktReader = new WKTReader();
                try {
                    geometry = wktReader.read(wkt);
                } catch (ParseException e) {
                    logger.error(e.getMessage());
                    throw new XPathException(e);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                targetSRS = args[1].itemAt(0).getStringValue().trim();
            }
        } else if (isCalledAs("buffer")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                double distance = ((DoubleValue) args[1].itemAt(0)).getDouble();
                int quadrantSegments = 8;
                int endCapStyle = BufferOp.CAP_ROUND;
                if (getArgumentCount() > 2 && Type.subTypeOf(args[2].itemAt(0).getType(), Type.INTEGER))
                    quadrantSegments = ((IntegerValue) args[2].itemAt(0)).getInt();
                if (getArgumentCount() > 3 && Type.subTypeOf(args[3].itemAt(0).getType(), Type.INTEGER))
                    endCapStyle = ((IntegerValue) args[3].itemAt(0)).getInt();
                switch(endCapStyle) {
                    case BufferOp.CAP_ROUND:
                    case BufferOp.CAP_BUTT:
                    case BufferOp.CAP_SQUARE:
                        // OK
                        break;
                    default:
                        {
                            logger.error("Invalid line end style");
                            throw new XPathException("Invalid line end style");
                        }
                }
                geometry = geometry.buffer(distance, quadrantSegments, endCapStyle);
            }
        } else if (isCalledAs("getBbox")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.getEnvelope();
            }
        } else if (isCalledAs("convexHull")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.convexHull();
            }
        } else if (isCalledAs("boundary")) {
            if (args[0].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else {
                NodeValue geometryNode = (NodeValue) args[0].itemAt(0);
                // Try to get the geometry from the index
                if (geometryNode.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    targetSRS = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode, "SRS_NAME").getStringValue();
                    geometry = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode, false);
                    hasUsedIndex = true;
                }
                // Otherwise, build it
                if (geometry == null) {
                    targetSRS = ((Element) geometryNode.getNode()).getAttribute("srsName").trim();
                    geometry = indexWorker.streamNodeToGeometry(context, geometryNode);
                }
                if (geometry == null) {
                    logger.error("Unable to get a geometry from the node");
                    throw new XPathException("Unable to get a geometry from the node");
                }
                geometry = geometry.getBoundary();
            }
        } else {
            Geometry geometry1 = null;
            Geometry geometry2 = null;
            if (args[0].isEmpty() && args[1].isEmpty())
                result = Sequence.EMPTY_SEQUENCE;
            else if (!args[0].isEmpty() && args[1].isEmpty())
                result = args[0].itemAt(0).toSequence();
            else if (args[0].isEmpty() && !args[1].isEmpty())
                result = args[1].itemAt(0).toSequence();
            else {
                NodeValue geometryNode1 = (NodeValue) args[0].itemAt(0);
                NodeValue geometryNode2 = (NodeValue) args[1].itemAt(0);
                String srsName1 = null;
                String srsName2 = null;
                // Try to get the geometries from the index
                if (geometryNode1.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    srsName1 = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode1, "SRS_NAME").getStringValue();
                    geometry1 = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode1, false);
                    hasUsedIndex = true;
                }
                if (geometryNode2.getImplementationType() == NodeValue.PERSISTENT_NODE) {
                    srsName2 = indexWorker.getGeometricPropertyForNode(context, (NodeProxy) geometryNode2, "SRS_NAME").getStringValue();
                    geometry2 = indexWorker.getGeometryForNode(context.getBroker(), (NodeProxy) geometryNode2, false);
                    hasUsedIndex = true;
                }
                // Otherwise build them
                if (geometry1 == null) {
                    srsName1 = ((Element) geometryNode1.getNode()).getAttribute("srsName").trim();
                    geometry1 = indexWorker.streamNodeToGeometry(context, geometryNode1);
                }
                if (geometry2 == null) {
                    srsName2 = ((Element) geometryNode2.getNode()).getAttribute("srsName").trim();
                    geometry2 = indexWorker.streamNodeToGeometry(context, geometryNode2);
                }
                if (geometry1 == null) {
                    logger.error("Unable to get a geometry from the first node");
                    throw new XPathException("Unable to get a geometry from the first node");
                }
                if (geometry2 == null) {
                    logger.error("Unable to get a geometry from the second node");
                    throw new XPathException("Unable to get a geometry from the second node");
                }
                if (srsName1 == null)
                    throw new XPathException("Unable to get a SRS for the first geometry");
                if (srsName2 == null)
                    throw new XPathException("Unable to get a SRS for the second geometry");
                // Transform the second geometry in the SRS of the first one if necessary
                if (!srsName1.equalsIgnoreCase(srsName2)) {
                    geometry2 = indexWorker.transformGeometry(geometry2, srsName1, srsName2);
                }
                if (isCalledAs("intersection")) {
                    geometry = geometry1.intersection(geometry2);
                } else if (isCalledAs("union")) {
                    geometry = geometry1.union(geometry2);
                } else if (isCalledAs("difference")) {
                    geometry = geometry1.difference(geometry2);
                } else if (isCalledAs("symetricDifference")) {
                    geometry = geometry1.symDifference(geometry2);
                }
                targetSRS = srsName1;
            }
        }
        if (result == null) {
            String gmlPrefix = context.getPrefixForURI(AbstractGMLJDBCIndexWorker.GML_NS);
            if (gmlPrefix == null) {
                logger.error("namespace is not defined:" + SpatialModule.PREFIX);
                throw new XPathException("'" + AbstractGMLJDBCIndexWorker.GML_NS + "' namespace is not defined");
            }
            context.pushDocumentContext();
            try {
                MemTreeBuilder builder = context.getDocumentBuilder();
                DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder);
                result = (NodeValue) indexWorker.streamGeometryToElement(geometry, targetSRS, receiver);
            } finally {
                context.popDocumentContext();
            }
        }
    } catch (SpatialIndexException e) {
        logger.error(e.getMessage());
        throw new XPathException(e);
    }
    return result;
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) Element(org.w3c.dom.Element) IntegerValue(org.exist.xquery.value.IntegerValue) Sequence(org.exist.xquery.value.Sequence) SpatialIndexException(org.exist.indexing.spatial.SpatialIndexException) WKTReader(com.vividsolutions.jts.io.WKTReader) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) NodeProxy(org.exist.dom.persistent.NodeProxy) Geometry(com.vividsolutions.jts.geom.Geometry) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DoubleValue(org.exist.xquery.value.DoubleValue) AbstractGMLJDBCIndexWorker(org.exist.indexing.spatial.AbstractGMLJDBCIndexWorker) ParseException(com.vividsolutions.jts.io.ParseException)

Aggregations

DocumentBuilderReceiver (org.exist.dom.memtree.DocumentBuilderReceiver)18 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)17 SAXException (org.xml.sax.SAXException)11 XPathException (org.exist.xquery.XPathException)6 Document (org.w3c.dom.Document)6 IOException (java.io.IOException)5 NodeValue (org.exist.xquery.value.NodeValue)5 NodeProxy (org.exist.dom.persistent.NodeProxy)4 SequenceIterator (org.exist.xquery.value.SequenceIterator)4 Properties (java.util.Properties)3 QName (org.exist.dom.QName)3 DocumentImpl (org.exist.dom.memtree.DocumentImpl)3 NodeImpl (org.exist.dom.memtree.NodeImpl)3 Serializer (org.exist.storage.serializers.Serializer)3 Item (org.exist.xquery.value.Item)3 Sequence (org.exist.xquery.value.Sequence)3 CloseShieldInputStream (org.apache.commons.io.input.CloseShieldInputStream)2 Receiver (org.exist.util.serializer.Receiver)2 FunctionReference (org.exist.xquery.value.FunctionReference)2 ValueSequence (org.exist.xquery.value.ValueSequence)2