Search in sources :

Example 51 with MemTreeBuilder

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

the class GetScheduledJobs method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        final XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to get the list of scheduled jobs");
        logger.error("Invalid user " + SystemModule.PREFIX + ":get-scheduled-jobs", xPathException);
        throw xPathException;
    }
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("jobs", NAMESPACE_URI, PREFIX), null);
        final BrokerPool brokerPool = context.getBroker().getBrokerPool();
        logger.trace("brokerPool = {}", brokerPool.toString());
        if (brokerPool != null) {
            final org.exist.scheduler.Scheduler existScheduler = brokerPool.getScheduler();
            if (existScheduler != null) {
                final List<ScheduledJobInfo> scheduledJobsInfo = existScheduler.getScheduledJobs();
                final ScheduledJobInfo[] executingJobsInfo = existScheduler.getExecutingJobs();
                if (scheduledJobsInfo != null) {
                    for (final ScheduledJobInfo scheduledJobInfo : scheduledJobsInfo) {
                        addRow(scheduledJobInfo, builder, false);
                    }
                }
                if (executingJobsInfo != null) {
                    for (ScheduledJobInfo jobInfo : executingJobsInfo) {
                        addRow(jobInfo, builder, true);
                    }
                }
            }
        }
        builder.endElement();
        builder.endDocument();
        return ((NodeValue) builder.getDocument().getDocumentElement());
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) ScheduledJobInfo(org.exist.scheduler.ScheduledJobInfo) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) BrokerPool(org.exist.storage.BrokerPool)

Example 52 with MemTreeBuilder

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

the class GetData method parseAsXml.

private Sequence parseAsXml(InputStream is) {
    Sequence result = Sequence.EMPTY_SEQUENCE;
    XMLReader reader = null;
    context.pushDocumentContext();
    try {
        // try and construct xml document from input stream, we use eXist's in-memory DOM implementation
        // we have to use CloseShieldInputStream otherwise the parser closes the stream and we cant later reread
        final InputSource src = new InputSource(new CloseShieldInputStream(is));
        reader = context.getBroker().getBrokerPool().getParserPool().borrowXMLReader();
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
        reader.setContentHandler(receiver);
        reader.setProperty(Namespaces.SAX_LEXICAL_HANDLER, receiver);
        reader.parse(src);
        final Document doc = receiver.getDocument();
        result = (NodeValue) doc;
    } catch (final SAXException | IOException saxe) {
    // do nothing, we will default to trying to return a string below
    } finally {
        context.popDocumentContext();
        if (reader != null) {
            context.getBroker().getBrokerPool().getParserPool().returnXMLReader(reader);
        }
    }
    return result;
}
Also used : InputSource(org.xml.sax.InputSource) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) IOException(java.io.IOException) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) Document(org.w3c.dom.Document) XMLReader(org.xml.sax.XMLReader) CloseShieldInputStream(org.apache.commons.io.input.CloseShieldInputStream) SAXException(org.xml.sax.SAXException)

Example 53 with MemTreeBuilder

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

the class DecodeExiFunction method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    try {
        BinaryValue exiBinary = ((BinaryValue) args[0].itemAt(0));
        context.pushDocumentContext();
        try {
            MemTreeBuilder builder = context.getDocumentBuilder();
            // create default factory and EXI grammar for schema
            EXIFactory exiFactory = DefaultEXIFactory.newInstance();
            if (args.length > 1) {
                if (!args[1].isEmpty()) {
                    Item xsdItem = args[1].itemAt(0);
                    try (InputStream xsdInputStream = EXIUtils.getInputStream(xsdItem, context)) {
                        GrammarFactory grammarFactory = GrammarFactory.newInstance();
                        Grammars grammar = grammarFactory.createGrammars(xsdInputStream);
                        exiFactory.setGrammars(grammar);
                    }
                }
            }
            SAXDecoder decoder = new SAXDecoder(exiFactory);
            SAXAdapter adapter = new AppendingSAXAdapter(builder);
            decoder.setContentHandler(adapter);
            try (InputStream inputStream = exiBinary.getInputStream()) {
                decoder.parse(new InputSource(inputStream));
            }
            return (NodeValue) builder.getDocument().getDocumentElement();
        } finally {
            context.popDocumentContext();
        }
    } catch (EXIException | SAXException | IOException exie) {
        throw new XPathException(this, new JavaErrorCode(exie.getCause()), exie.getMessage());
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) InputSource(org.xml.sax.InputSource) SAXDecoder(com.siemens.ct.exi.api.sax.SAXDecoder) XPathException(org.exist.xquery.XPathException) InputStream(java.io.InputStream) BinaryValue(org.exist.xquery.value.BinaryValue) GrammarFactory(com.siemens.ct.exi.GrammarFactory) EXIException(com.siemens.ct.exi.exceptions.EXIException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) JavaErrorCode(org.exist.xquery.ErrorCodes.JavaErrorCode) Item(org.exist.xquery.value.Item) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) AppendingSAXAdapter(org.exist.dom.memtree.AppendingSAXAdapter) SAXAdapter(org.exist.dom.memtree.SAXAdapter) AppendingSAXAdapter(org.exist.dom.memtree.AppendingSAXAdapter) Grammars(com.siemens.ct.exi.grammars.Grammars) DefaultEXIFactory(com.siemens.ct.exi.helpers.DefaultEXIFactory) EXIFactory(com.siemens.ct.exi.EXIFactory)

Example 54 with MemTreeBuilder

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

the class InspectModule method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final XQueryContext tempContext = new XQueryContext(context.getBroker().getBrokerPool());
    tempContext.setModuleLoadPath(context.getModuleLoadPath());
    final Module[] modules;
    if (isCalledAs(FN_INSPECT_MODULE_NAME)) {
        modules = tempContext.importModule(null, null, new AnyURIValue[] { (AnyURIValue) args[0].itemAt(0) });
    } else {
        modules = tempContext.importModule(args[0].getStringValue(), null, null);
    }
    if (modules == null || modules.length == 0) {
        return Sequence.EMPTY_SEQUENCE;
    }
    // this function only supports working with a singular module for a namespace!
    final Module module = modules[0];
    try {
        context.pushDocumentContext();
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final AttributesImpl attribs = new AttributesImpl();
        attribs.addAttribute("", "uri", "uri", "CDATA", module.getNamespaceURI());
        attribs.addAttribute("", "prefix", "prefix", "CDATA", module.getDefaultPrefix());
        if (module.isInternalModule()) {
            attribs.addAttribute("", "location", "location", "CDATA", "java:" + module.getClass().getName());
        } else if (isCalledAs("inspect-module")) {
            attribs.addAttribute("", "location", "location", "CDATA", args[0].getStringValue());
        }
        final int nodeNr = builder.startElement(MODULE_QNAME, attribs);
        if (!module.isInternalModule()) {
            XQDocHelper.parse((ExternalModule) module);
        }
        if (module.getDescription() != null) {
            builder.startElement(InspectFunctionHelper.DESCRIPTION_QNAME, null);
            builder.characters(module.getDescription());
            builder.endElement();
        }
        if (!module.isInternalModule()) {
            final ExternalModule externalModule = (ExternalModule) module;
            if (externalModule.getMetadata() != null) {
                for (final Map.Entry<String, String> entry : externalModule.getMetadata().entrySet()) {
                    builder.startElement(new QName(entry.getKey(), XMLConstants.NULL_NS_URI), null);
                    builder.characters(entry.getValue());
                    builder.endElement();
                }
            }
            // variables
            for (final VariableDeclaration var : externalModule.getVariableDeclarations()) {
                attribs.clear();
                attribs.addAttribute("", "name", "name", "CDATA", var.getName().toString());
                final SequenceType type = var.getSequenceType();
                if (type != null) {
                    attribs.addAttribute("", "type", "type", "CDATA", Type.getTypeName(type.getPrimaryType()));
                    attribs.addAttribute("", "cardinality", "cardinality", "CDATA", type.getCardinality().getHumanDescription());
                }
                builder.startElement(VARIABLE_QNAME, attribs);
                builder.endElement();
            }
        }
        // functions
        for (final FunctionSignature sig : module.listFunctions()) {
            if (!sig.isPrivate()) {
                UserDefinedFunction func = null;
                if (!module.isInternalModule()) {
                    func = ((ExternalModule) module).getFunction(sig.getName(), sig.getArgumentCount(), null);
                }
                InspectFunctionHelper.generateDocs(sig, func, builder);
            }
        }
        builder.endElement();
        return builder.getDocument().getNode(nodeNr);
    } finally {
        context.popDocumentContext();
    }
}
Also used : QName(org.exist.dom.QName) AttributesImpl(org.xml.sax.helpers.AttributesImpl) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) Module(org.exist.xquery.Module) Map(java.util.Map)

Example 55 with MemTreeBuilder

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

the class FunSerialize method normalize.

/**
 * Sequence normalization as described in
 * http://www.w3.org/TR/xslt-xquery-serialization-30/#serdm
 *
 * @param input non-normalized sequence
 * @param context current context
 * @param callingExpr the expression from which the function is called.
 *                    needed for error reporting
 * @return normalized sequence
 * @throws XPathException in case of dynamic error
 */
public static Sequence normalize(final Expression callingExpr, final XQueryContext context, final Sequence input) throws XPathException {
    if (input.isEmpty()) // "If the sequence that is input to serialization is empty, create a sequence S1 that consists of a zero-length string."
    {
        return StringValue.EMPTY_STRING;
    }
    final ValueSequence temp = new ValueSequence(input.getItemCount());
    for (final SequenceIterator i = input.iterate(); i.hasNext(); ) {
        final Item next = i.nextItem();
        if (Type.subTypeOf(next.getType(), Type.NODE)) {
            if (next.getType() == Type.ATTRIBUTE || next.getType() == Type.NAMESPACE || next.getType() == Type.FUNCTION_REFERENCE) {
                throw new XPathException(callingExpr, FnModule.SENR0001, "It is an error if an item in the sequence to serialize is an attribute node or a namespace node.");
            }
            temp.add(next);
        } else {
            // atomic value
            Item last = null;
            if (!temp.isEmpty()) {
                last = temp.itemAt(temp.getItemCount() - 1);
            }
            if (last != null && last.getType() == Type.STRING) // "For each subsequence of adjacent strings in S2, copy a single string to the new sequence
            // equal to the values of the strings in the subsequence concatenated in order, each separated
            // by a single space."
            {
                ((StringValue) last).append(" " + next.getStringValue());
            } else // "For each item in S1, if the item is atomic, obtain the lexical representation of the item by
            // casting it to an xs:string and copy the string representation to the new sequence;"
            {
                temp.add(new StringValue(next.getStringValue()));
            }
        }
    }
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(builder, true);
        for (final SequenceIterator i = temp.iterate(); i.hasNext(); ) {
            final Item next = i.nextItem();
            if (Type.subTypeOf(next.getType(), Type.NODE)) {
                next.copyTo(context.getBroker(), receiver);
            } else {
                receiver.characters(next.getStringValue());
            }
        }
        return (DocumentImpl) receiver.getDocument();
    } catch (final SAXException e) {
        throw new XPathException(callingExpr, FnModule.SENR0001, e.getMessage());
    } finally {
        context.popDocumentContext();
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) DocumentBuilderReceiver(org.exist.dom.memtree.DocumentBuilderReceiver) DocumentImpl(org.exist.dom.memtree.DocumentImpl) SAXException(org.xml.sax.SAXException)

Aggregations

MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)82 QName (org.exist.dom.QName)29 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