Search in sources :

Example 66 with MemTreeBuilder

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

the class DescribeFunction method eval.

@Override
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    final String fname = getArgument(0).eval(contextSequence, contextItem).getStringValue();
    final QName qname;
    try {
        qname = QName.parse(context, fname, context.getDefaultFunctionNamespace());
    } catch (final QName.IllegalQNameException e) {
        throw new XPathException(this, ErrorCodes.XPST0081, "No namespace defined for prefix " + fname);
    }
    final String uri = qname.getNamespaceURI();
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final AttributesImpl attribs = new AttributesImpl();
        attribs.addAttribute("", "name", "name", "CDATA", qname.getStringValue());
        attribs.addAttribute("", "module", "module", "CDATA", uri);
        final int nodeNr = builder.startElement("", "function", "function", attribs);
        FunctionSignature signature;
        final Module[] modules = context.getModules(uri);
        if (isNotEmpty(modules)) {
            for (final Module module : modules) {
                final Iterator<FunctionSignature> i = module.getSignaturesForFunction(qname);
                while (i.hasNext()) {
                    signature = i.next();
                    writeSignature(signature, builder);
                }
            }
        } else {
            final Iterator<FunctionSignature> i = context.getSignaturesForFunction(qname);
            while (i.hasNext()) {
                signature = i.next();
                writeSignature(signature, builder);
            }
        }
        builder.endElement();
        return ((DocumentImpl) builder.getDocument()).getNode(nodeNr);
    } finally {
        context.popDocumentContext();
    }
}
Also used : AttributesImpl(org.xml.sax.helpers.AttributesImpl) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) Module(org.exist.xquery.Module) DocumentImpl(org.exist.dom.memtree.DocumentImpl)

Example 67 with MemTreeBuilder

use of org.exist.dom.memtree.MemTreeBuilder 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)

Example 68 with MemTreeBuilder

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

the class Transform method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
     */
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final Properties attributes = new Properties();
    final Properties serializationProps = new Properties();
    final Properties stylesheetParams = new Properties();
    // Parameter 1 & 2
    final Sequence inputNode = args[0];
    final Item stylesheetItem = args[1].itemAt(0);
    // Parse 3rd parameter
    final Node options = args[2].isEmpty() ? null : ((NodeValue) args[2].itemAt(0)).getNode();
    if (options != null) {
        stylesheetParams.putAll(parseParameters(options));
    }
    // Parameter 4 when present
    if (getArgumentCount() >= 4) {
        final Sequence attrs = args[3];
        attributes.putAll(extractAttributes(attrs));
    }
    // Parameter 5 when present
    if (getArgumentCount() >= 5) {
        // extract serialization options
        final Sequence serOpts = args[4];
        serializationProps.putAll(extractSerializationProperties(serOpts));
    } else {
        context.checkOptions(serializationProps);
    }
    boolean expandXIncludes = "yes".equals(serializationProps.getProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes"));
    final XSLTErrorsListener<XPathException> errorListener = new XSLTErrorsListener<XPathException>(stopOnError, stopOnWarn) {

        @Override
        protected void raiseError(String error, Exception ex) throws XPathException {
            throw new XPathException(Transform.this, error, ex);
        }
    };
    // Setup handler and error listener
    final TransformerHandler handler = createHandler(stylesheetItem, stylesheetParams, attributes, errorListener);
    if (isCalledAs("transform")) {
        // transform:transform()
        final ValueSequence seq = new ValueSequence();
        context.pushDocumentContext();
        try {
            final MemTreeBuilder builder = context.getDocumentBuilder();
            final DocumentBuilderReceiver builderReceiver = new DocumentBuilderReceiver(builder, true);
            final SAXResult result = new SAXResult(builderReceiver);
            // preserve comments etc... from xslt output
            result.setLexicalHandler(builderReceiver);
            handler.setResult(result);
            final Receiver receiver = new ReceiverToSAX(handler);
            final Serializer serializer = context.getBroker().borrowSerializer();
            try {
                serializer.setProperties(serializationProps);
                serializer.setReceiver(receiver, true);
                if (expandXIncludes) {
                    String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH);
                    if (xiPath != null && !xiPath.startsWith(XmldbURI.XMLDB_URI_PREFIX)) {
                        final Path f = Paths.get(xiPath).normalize();
                        if (!f.isAbsolute()) {
                            xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString();
                        }
                    } else {
                        xiPath = context.getModuleLoadPath();
                    }
                    serializer.getXIncludeFilter().setModuleLoadPath(xiPath);
                }
                serializer.toSAX(inputNode, 1, inputNode.getItemCount(), false, false, 0, 0);
            } catch (final Exception e) {
                throw new XPathException(this, "Exception while transforming node: " + e.getMessage(), e);
            } finally {
                context.getBroker().returnSerializer(serializer);
            }
            errorListener.checkForErrors();
            Node next = builder.getDocument().getFirstChild();
            while (next != null) {
                seq.add((NodeValue) next);
                next = next.getNextSibling();
            }
            return seq;
        } finally {
            context.popDocumentContext();
        }
    } else {
        // transform:stream-transform()
        final Optional<ResponseWrapper> maybeResponse = Optional.ofNullable(context.getHttpContext()).map(XQueryContext.HttpContext::getResponse);
        if (!maybeResponse.isPresent()) {
            throw new XPathException(this, ErrorCodes.XPDY0002, "No response object found in the current XQuery context.");
        }
        final ResponseWrapper response = maybeResponse.get();
        if (!"org.exist.http.servlets.HttpResponseWrapper".equals(response.getClass().getName())) {
            throw new XPathException(this, ErrorCodes.XPDY0002, signatures[1] + " can only be used within the EXistServlet or XQueryServlet");
        }
        // setup the response correctly
        final String mediaType = handler.getTransformer().getOutputProperty("media-type");
        final String encoding = handler.getTransformer().getOutputProperty("encoding");
        if (mediaType != null) {
            if (encoding == null) {
                response.setContentType(mediaType);
            } else {
                response.setContentType(mediaType + "; charset=" + encoding);
            }
        }
        // do the transformation
        try {
            final OutputStream os = new BufferedOutputStream(response.getOutputStream());
            final StreamResult result = new StreamResult(os);
            handler.setResult(result);
            final Serializer serializer = context.getBroker().borrowSerializer();
            Receiver receiver = new ReceiverToSAX(handler);
            try {
                serializer.setProperties(serializationProps);
                if (expandXIncludes) {
                    XIncludeFilter xinclude = new XIncludeFilter(serializer, receiver);
                    String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH);
                    if (xiPath != null) {
                        final Path f = Paths.get(xiPath).normalize();
                        if (!f.isAbsolute()) {
                            xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString();
                        }
                    } else {
                        xiPath = context.getModuleLoadPath();
                    }
                    xinclude.setModuleLoadPath(xiPath);
                    receiver = xinclude;
                }
                serializer.setReceiver(receiver);
                serializer.toSAX(inputNode);
            } catch (final Exception e) {
                throw new XPathException(this, "Exception while transforming node: " + e.getMessage(), e);
            } finally {
                context.getBroker().returnSerializer(serializer);
            }
            errorListener.checkForErrors();
            os.close();
            // commit the response
            response.flushBuffer();
        } catch (final IOException e) {
            throw new XPathException(this, "IO exception while transforming node: " + e.getMessage(), e);
        }
        return Sequence.EMPTY_SEQUENCE;
    }
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) Node(org.w3c.dom.Node) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ResponseWrapper(org.exist.http.servlets.ResponseWrapper) Properties(java.util.Properties) XIncludeFilter(org.exist.storage.serializers.XIncludeFilter) XSLTErrorsListener(org.exist.xslt.XSLTErrorsListener) BufferedOutputStream(java.io.BufferedOutputStream) Serializer(org.exist.storage.serializers.Serializer) Path(java.nio.file.Path) StreamResult(javax.xml.transform.stream.StreamResult) ReceiverToSAX(org.exist.util.serializer.ReceiverToSAX) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Receiver(org.exist.util.serializer.Receiver) IOException(java.io.IOException) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) IOException(java.io.IOException) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SAXResult(javax.xml.transform.sax.SAXResult)

Example 69 with MemTreeBuilder

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

the class GetRunningXQueries method getRunningXQueries.

private Sequence getRunningXQueries() throws XPathException {
    Sequence xmlResponse = null;
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("xqueries", NAMESPACE_URI, PREFIX), null);
        // Add all the running xqueries
        final XQueryWatchDog[] watchdogs = getContext().getBroker().getBrokerPool().getProcessMonitor().getRunningXQueries();
        for (XQueryWatchDog watchdog : watchdogs) {
            final XQueryContext context = watchdog.getContext();
            getRunningXQuery(builder, context, watchdog);
        }
        builder.endElement();
        xmlResponse = (NodeValue) builder.getDocument().getDocumentElement();
        return (xmlResponse);
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName) XQueryContext(org.exist.xquery.XQueryContext) Sequence(org.exist.xquery.value.Sequence) XQueryWatchDog(org.exist.xquery.XQueryWatchDog)

Example 70 with MemTreeBuilder

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

the class Restore method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    final String dirOrFile = args[0].getStringValue();
    String adminPass = null;
    if (args[1].hasOne()) {
        adminPass = args[1].getStringValue();
    }
    String adminPassAfter = null;
    if (args[2].hasOne()) {
        adminPassAfter = args[2].getStringValue();
    }
    final boolean overwriteApps = args.length == 4 && args[3].effectiveBooleanValue();
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(RESTORE_ELEMENT, null);
        final BrokerPool pool = context.getBroker().getBrokerPool();
        try {
            final Subject admin = pool.getSecurityManager().authenticate(SecurityManager.DBA_USER, adminPass);
            try (final DBBroker broker = pool.get(Optional.of(admin));
                final Txn transaction = broker.continueOrBeginTransaction()) {
                final RestoreListener listener = new XMLRestoreListener(builder);
                final org.exist.backup.Restore restore = new org.exist.backup.Restore();
                restore.restore(broker, transaction, adminPassAfter, Paths.get(dirOrFile), listener, overwriteApps);
                transaction.commit();
            }
        } catch (final Exception e) {
            throw new XPathException(this, "restore failed with exception: " + e.getMessage(), e);
        }
        builder.endElement();
        builder.endDocument();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) XPathException(org.exist.xquery.XPathException) Txn(org.exist.storage.txn.Txn) Subject(org.exist.security.Subject) XPathException(org.exist.xquery.XPathException) DBBroker(org.exist.storage.DBBroker) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) RestoreListener(org.exist.backup.restore.listener.RestoreListener) AbstractRestoreListener(org.exist.backup.restore.listener.AbstractRestoreListener) BrokerPool(org.exist.storage.BrokerPool)

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