Search in sources :

Example 31 with MemTreeBuilder

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

the class ExampleFunctions method sayHello.

/**
 * Creates an XML document like <hello>name</hello>.
 *
 * @param name An optional name, if empty then "stranger" is used.
 *
 * @return An XML document
 */
private DocumentImpl sayHello(final Optional<StringValue> name) throws XPathException {
    try {
        final MemTreeBuilder builder = new MemTreeBuilder(context);
        builder.startDocument();
        builder.startElement(new QName("hello"), null);
        builder.characters(name.map(StringValue::toString).orElse("stranger"));
        builder.endElement();
        builder.endDocument();
        return builder.getDocument();
    } catch (final QName.IllegalQNameException e) {
        throw new XPathException(this, e.getMessage(), e);
    }
}
Also used : MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) StringValue(org.exist.xquery.value.StringValue)

Example 32 with MemTreeBuilder

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

the class Directory method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    if (!context.getSubject().hasDbaRole()) {
        XPathException xPathException = new XPathException(this, "Permission denied, calling user '" + context.getSubject().getName() + "' must be a DBA to call this function.");
        logger.error("Invalid user", xPathException);
        throw xPathException;
    }
    final String inputPath = args[0].getStringValue();
    final Path directoryPath = FileModuleHelper.getFile(inputPath);
    if (logger.isDebugEnabled()) {
        logger.debug("Listing matching files in directory: {}", directoryPath.toAbsolutePath().toString());
    }
    if (!Files.isDirectory(directoryPath)) {
        throw new XPathException(this, "'" + inputPath + "' does not point to a valid directory.");
    }
    // Get list of files, null if baseDir does not point to a directory
    context.pushDocumentContext();
    try (final Stream<Path> scannedFiles = Files.list(directoryPath)) {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("list", null, null), null);
        scannedFiles.forEach(entry -> {
            if (logger.isDebugEnabled()) {
                logger.debug("Found: {}", entry.toAbsolutePath().toString());
            }
            String entryType = "unknown";
            if (Files.isRegularFile(entry)) {
                entryType = "file";
            } else if (Files.isDirectory(entry)) {
                entryType = "directory";
            }
            builder.startElement(new QName(entryType, NAMESPACE_URI, PREFIX), null);
            builder.addAttribute(new QName("name", null, null), FileUtils.fileName(entry));
            try {
                if (Files.isRegularFile(entry)) {
                    final Long sizeLong = Files.size(entry);
                    String sizeString = Long.toString(sizeLong);
                    String humanSize = getHumanSize(sizeLong, sizeString);
                    builder.addAttribute(new QName("size", null, null), sizeString);
                    builder.addAttribute(new QName("human-size", null, null), humanSize);
                }
                builder.addAttribute(new QName("modified", null, null), new DateTimeValue(new Date(Files.getLastModifiedTime(entry).toMillis())).getStringValue());
                builder.addAttribute(new QName("hidden", null, null), new BooleanValue(Files.isHidden(entry)).getStringValue());
                builder.addAttribute(new QName("canRead", null, null), new BooleanValue(Files.isReadable(entry)).getStringValue());
                builder.addAttribute(new QName("canWrite", null, null), new BooleanValue(Files.isWritable(entry)).getStringValue());
            } catch (final IOException | XPathException ioe) {
                LOG.warn(ioe);
            }
            builder.endElement();
        });
        builder.endElement();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } catch (final IOException ioe) {
        throw new XPathException(this, ioe);
    } finally {
        context.popDocumentContext();
    }
}
Also used : Path(java.nio.file.Path) NodeValue(org.exist.xquery.value.NodeValue) DateTimeValue(org.exist.xquery.value.DateTimeValue) XPathException(org.exist.xquery.XPathException) QName(org.exist.dom.QName) IOException(java.io.IOException) Date(java.util.Date) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) BooleanValue(org.exist.xquery.value.BooleanValue)

Example 33 with MemTreeBuilder

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

the class DynamicPIConstructor method eval.

/* (non-Javadoc)
     * @see org.exist.xquery.Expression#eval(org.exist.xquery.value.Sequence, org.exist.xquery.value.Item)
     */
public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathException {
    if (context.getProfiler().isEnabled()) {
        context.getProfiler().start(this);
        context.getProfiler().message(this, Profiler.DEPENDENCIES, "DEPENDENCIES", Dependency.getDependenciesName(this.getDependencies()));
        if (contextSequence != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT SEQUENCE", contextSequence);
        }
        if (contextItem != null) {
            context.getProfiler().message(this, Profiler.START_SEQUENCES, "CONTEXT ITEM", contextItem.toSequence());
        }
    }
    if (newDocumentContext) {
        context.pushDocumentContext();
    }
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        context.proceed(this, builder);
        final Sequence nameSeq = name.eval(contextSequence, contextItem);
        // TODO : get rid of getLength()
        if (!nameSeq.hasOne()) {
            throw new XPathException(this, ErrorCodes.XPTY0004, "The name expression should evaluate to a single value");
        }
        final Item nameItem = nameSeq.itemAt(0);
        if (!(nameItem.getType() == Type.STRING || nameItem.getType() == Type.NCNAME || nameItem.getType() == Type.UNTYPED_ATOMIC)) {
            throw new XPathException(this, ErrorCodes.XPTY0004, "The name expression should evaluate to a " + Type.getTypeName(Type.STRING) + " or a " + Type.getTypeName(Type.NCNAME) + " or a " + Type.getTypeName(Type.UNTYPED_ATOMIC) + ". Got: " + Type.getTypeName(nameItem.getType()));
        }
        if (!XMLNames.isNCName(nameSeq.getStringValue())) {
            throw new XPathException(this, ErrorCodes.XQDY0041, nameSeq.getStringValue() + "' is not a valid processing instruction name", nameSeq);
        }
        if (nameSeq.getStringValue().equalsIgnoreCase("XML")) {
            throw new XPathException(this, ErrorCodes.XQDY0064, nameSeq.getStringValue() + "' is not a valid processing instruction name", nameSeq);
        }
        String contentString;
        final Sequence contentSeq = content.eval(contextSequence, contextItem);
        if (contentSeq.isEmpty()) {
            contentString = "";
        } else {
            final StringBuilder buf = new StringBuilder();
            for (final SequenceIterator i = Atomize.atomize(contentSeq).iterate(); i.hasNext(); ) {
                context.proceed(this, builder);
                final Item next = i.nextItem();
                if (buf.length() > 0) {
                    buf.append(' ');
                }
                buf.append(next.getStringValue());
            }
            while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) buf.deleteCharAt(0);
            contentString = buf.toString();
        }
        if (contentString.contains("?>")) {
            throw new XPathException(this, ErrorCodes.XQDY0026, contentString + "' is not a valid processing intruction content", contentSeq);
        }
        final int nodeNo = builder.processingInstruction(nameSeq.getStringValue(), contentString);
        final Sequence result = ((DocumentImpl) builder.getDocument()).getNode(nodeNo);
        if (context.getProfiler().isEnabled()) {
            context.getProfiler().end(this, "", result);
        }
        return result;
    } finally {
        if (newDocumentContext) {
            context.popDocumentContext();
        }
    }
}
Also used : Item(org.exist.xquery.value.Item) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) SequenceIterator(org.exist.xquery.value.SequenceIterator) Sequence(org.exist.xquery.value.Sequence) DocumentImpl(org.exist.dom.memtree.DocumentImpl)

Example 34 with MemTreeBuilder

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

the class CommentConstructor 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 (newDocumentContext) {
        context.pushDocumentContext();
    }
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        final int nodeNr = builder.comment(data);
        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 35 with MemTreeBuilder

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

the class FunAnalyzeString method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    context.pushDocumentContext();
    try {
        final MemTreeBuilder builder = context.getDocumentBuilder();
        builder.startDocument();
        builder.startElement(new QName("analyze-string-result", Function.BUILTIN_FUNCTION_NS), null);
        String input = "";
        if (!args[0].isEmpty()) {
            input = args[0].itemAt(0).getStringValue();
        }
        if (input != null && !input.isEmpty()) {
            final String pattern = args[1].itemAt(0).getStringValue();
            String flags = "";
            if (args.length == 3) {
                flags = args[2].itemAt(0).getStringValue();
            }
            analyzeString(builder, input, pattern, flags);
        }
        builder.endElement();
        builder.endDocument();
        return (NodeValue) builder.getDocument().getDocumentElement();
    } finally {
        context.popDocumentContext();
    }
}
Also used : NodeValue(org.exist.xquery.value.NodeValue) MemTreeBuilder(org.exist.dom.memtree.MemTreeBuilder) QName(org.exist.dom.QName)

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