Search in sources :

Example 26 with Item

use of org.exist.xquery.value.Item in project exist by eXist-db.

the class ExistXqueryRegistry method extractMissingModuleHint.

private MissingModuleHint extractMissingModuleHint(final RestXqServiceCompilationException e) {
    MissingModuleHint missingModuleHint = null;
    if (e.getCause() instanceof XPathException) {
        final XPathException xpe = (XPathException) e.getCause();
        if (xpe.getErrorCode() == ErrorCodes.XQST0059) {
            final Sequence errorVals = xpe.getErrorVal();
            if (errorVals != null && errorVals.getItemCount() > 0) {
                final Item errorVal1 = errorVals.itemAt(0);
                if (errorVal1 instanceof StringValue) {
                    missingModuleHint = new MissingModuleHint();
                    missingModuleHint.moduleHint = ((StringValue) errorVal1).getStringValue();
                }
                if (errorVals.getItemCount() == 2) {
                    final Item errorVal2 = errorVals.itemAt(1);
                    if (errorVal2 instanceof StringValue) {
                        if (missingModuleHint == null) {
                            missingModuleHint = new MissingModuleHint();
                        }
                        final String dependantModuleUri = ((StringValue) errorVal2).getStringValue();
                        // path will be of xmldb:exist:///db/a/c/1.xqm form so change it to /db/a/c/1.xqm form
                        missingModuleHint.dependantModule = makeDbAbsolutePath(dependantModuleUri);
                    }
                }
            }
        }
    }
    return missingModuleHint;
}
Also used : Item(org.exist.xquery.value.Item) XPathException(org.exist.xquery.XPathException) Sequence(org.exist.xquery.value.Sequence) StringValue(org.exist.xquery.value.StringValue)

Example 27 with Item

use of org.exist.xquery.value.Item in project exist by eXist-db.

the class EXIUtils method getInputStream.

protected static InputStream getInputStream(Item item, XQueryContext context) throws XPathException, MalformedURLException, IOException {
    switch(item.getType()) {
        case Type.ANY_URI:
            LOG.debug("Streaming xs:anyURI");
            // anyURI provided
            String url = item.getStringValue();
            // Fix URL
            if (url.startsWith("/")) {
                url = "xmldb:exist://" + url;
            }
            return new URL(url).openStream();
        case Type.ELEMENT:
        case Type.DOCUMENT:
            LOG.debug("Streaming element or document node");
            /*
            if (item instanceof NodeProxy) {
                NodeProxy np = (NodeProxy) item;
                String url = "xmldb:exist://" + np.getDocument().getBaseURI();
                LOG.debug("Document detected, adding URL " + url);
                streamSource.setSystemId(url);
            }
            */
            // Node provided
            final ConsumerE<ConsumerE<Serializer, IOException>, IOException> withSerializerFn = fn -> {
                final Serializer serializer = context.getBroker().borrowSerializer();
                try {
                    fn.accept(serializer);
                } finally {
                    context.getBroker().returnSerializer(serializer);
                }
            };
            NodeValue node = (NodeValue) item;
            return new NodeInputStream(context.getBroker().getBrokerPool(), withSerializerFn, node);
        default:
            LOG.error("Wrong item type {}", Type.getTypeName(item.getType()));
            throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) Type(org.exist.xquery.value.Type) IOException(java.io.IOException) Logger(org.apache.logging.log4j.Logger) NodeValue(org.exist.xquery.value.NodeValue) Serializer(org.exist.storage.serializers.Serializer) Item(org.exist.xquery.value.Item) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) LogManager(org.apache.logging.log4j.LogManager) XPathException(org.exist.xquery.XPathException) XQueryContext(org.exist.xquery.XQueryContext) InputStream(java.io.InputStream) NodeValue(org.exist.xquery.value.NodeValue) ConsumerE(com.evolvedbinary.j8fu.function.ConsumerE) XPathException(org.exist.xquery.XPathException) IOException(java.io.IOException) URL(java.net.URL) NodeInputStream(org.exist.validation.internal.node.NodeInputStream) Serializer(org.exist.storage.serializers.Serializer)

Example 28 with Item

use of org.exist.xquery.value.Item in project exist by eXist-db.

the class EncodeExiFunction method eval.

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    if (args[0].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    try (final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
        EXISerializer exiSerializer;
        if (args.length > 1) {
            if (!args[1].isEmpty()) {
                Item xsdItem = args[1].itemAt(0);
                try (InputStream xsdInputStream = EXIUtils.getInputStream(xsdItem, context)) {
                    exiSerializer = new EXISerializer(baos, xsdInputStream);
                }
            } else {
                exiSerializer = new EXISerializer(baos);
            }
        } else {
            exiSerializer = new EXISerializer(baos);
        }
        Item inputNode = args[0].itemAt(0);
        exiSerializer.startDocument();
        inputNode.toSAX(context.getBroker(), exiSerializer, new Properties());
        exiSerializer.endDocument();
        return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), baos.toInputStream());
    } catch (IOException ioex) {
        // TODO - test!
        throw new XPathException(this, ErrorCodes.FODC0002, ioex.getMessage());
    } catch (EXIException | SAXException exie) {
        throw new XPathException(this, new JavaErrorCode(exie.getCause()), exie.getMessage());
    }
}
Also used : Item(org.exist.xquery.value.Item) XPathException(org.exist.xquery.XPathException) BinaryValueFromInputStream(org.exist.xquery.value.BinaryValueFromInputStream) InputStream(java.io.InputStream) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) IOException(java.io.IOException) EXIException(com.siemens.ct.exi.exceptions.EXIException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Properties(java.util.Properties) EXISerializer(org.exist.util.serializer.EXISerializer) SAXException(org.xml.sax.SAXException) JavaErrorCode(org.exist.xquery.ErrorCodes.JavaErrorCode)

Example 29 with Item

use of org.exist.xquery.value.Item in project exist by eXist-db.

the class Serializer method toSAX.

/**
 * Serialize the items in the given sequence to SAX, starting with item start. If parameter
 * wrap is set to true, output a wrapper element to enclose the serialized items. The
 * wrapper element will be in namespace {@link org.exist.Namespaces#EXIST_NS} and has the following form:
 *
 * &lt;exist:result hits="sequence length" start="value of start" count="value of count"&gt;
 *
 * @param seq The sequence to serialize
 * @param start The position in the sequence to start serialization from
 * @param count The number of items from the start position to serialize
 * @param wrap Indicates whether the output should be wrapped
 * @param typed Indicates whether the output types should be wrapped
 * @param compilationTime The time taken to compile the query which produced the sequence
 * @param executionTime The time taken to execute the query which produced the sequence
 *
 * @throws SAXException If an error occurs during serialization
 */
public void toSAX(final Sequence seq, int start, final int count, final boolean wrap, final boolean typed, final long compilationTime, final long executionTime) throws SAXException {
    try {
        setStylesheetFromProperties(null);
    } catch (final TransformerConfigurationException e) {
        throw new SAXException(e.getMessage(), e);
    }
    setXSLHandler(null, false);
    final AttrList attrs = new AttrList();
    attrs.addAttribute(ATTR_HITS_QNAME, Integer.toString(seq.getItemCount()));
    attrs.addAttribute(ATTR_START_QNAME, Integer.toString(start));
    attrs.addAttribute(ATTR_COUNT_QNAME, Integer.toString(count));
    if (outputProperties.getProperty(PROPERTY_SESSION_ID) != null) {
        attrs.addAttribute(ATTR_SESSION_ID, outputProperties.getProperty(PROPERTY_SESSION_ID));
    }
    attrs.addAttribute(ATTR_COMPILATION_TIME_QNAME, Long.toString(compilationTime));
    attrs.addAttribute(ATTR_EXECUTION_TIME_QNAME, Long.toString(compilationTime));
    if (!documentStarted) {
        receiver.startDocument();
        documentStarted = true;
    }
    if (wrap) {
        receiver.startPrefixMapping("exist", Namespaces.EXIST_NS);
        receiver.startElement(ELEM_RESULT_QNAME, attrs);
    }
    for (int i = --start; i < start + count; i++) {
        final Item item = seq.itemAt(i);
        if (item == null) {
            LOG.debug("item {} not found", i);
            continue;
        }
        itemToSAX(item, typed, wrap);
    }
    if (wrap) {
        receiver.endElement(ELEM_RESULT_QNAME);
        receiver.endPrefixMapping("exist");
    }
    receiver.endDocument();
}
Also used : Item(org.exist.xquery.value.Item) AttrList(org.exist.util.serializer.AttrList) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) SAXException(org.xml.sax.SAXException)

Example 30 with Item

use of org.exist.xquery.value.Item in project exist by eXist-db.

the class ArrowOperator method eval.

@Override
public Sequence eval(Sequence contextSequence, final Item contextItem) throws XPathException {
    if (contextItem != null) {
        contextSequence = contextItem.toSequence();
    }
    contextSequence = leftExpr.eval(contextSequence);
    final FunctionReference fref;
    if (fcall != null) {
        fref = new FunctionReference(fcall);
    } else {
        final Sequence funcSeq = funcSpec.eval(contextSequence, contextItem);
        if (funcSeq.getCardinality() != Cardinality.EXACTLY_ONE) {
            throw new XPathException(this, ErrorCodes.XPTY0004, "Expected exactly one item for the function to be called, got " + funcSeq.getItemCount() + ". Expression: " + ExpressionDumper.dump(funcSpec));
        }
        final Item item0 = funcSeq.itemAt(0);
        if (!Type.subTypeOf(item0.getType(), Type.FUNCTION_REFERENCE)) {
            throw new XPathException(this, ErrorCodes.XPTY0004, "Type error: expected function, got " + Type.getTypeName(item0.getType()));
        }
        fref = (FunctionReference) item0;
    }
    try {
        final List<Expression> fparams = new ArrayList<>(parameters.size() + 1);
        fparams.add(new ContextParam(context, contextSequence));
        fparams.addAll(parameters);
        fref.setArguments(fparams);
        // need to create a new AnalyzeContextInfo to avoid memory leak
        // cachedContextInfo will stay in memory
        fref.analyze(new AnalyzeContextInfo(cachedContextInfo));
        // Evaluate the function
        return fref.eval(null);
    } finally {
        fref.close();
    }
}
Also used : Item(org.exist.xquery.value.Item) ArrayList(java.util.ArrayList) FunctionReference(org.exist.xquery.value.FunctionReference) Sequence(org.exist.xquery.value.Sequence)

Aggregations

Item (org.exist.xquery.value.Item)88 Sequence (org.exist.xquery.value.Sequence)69 SequenceIterator (org.exist.xquery.value.SequenceIterator)36 XPathException (org.exist.xquery.XPathException)26 DBBroker (org.exist.storage.DBBroker)18 NodeValue (org.exist.xquery.value.NodeValue)17 XQuery (org.exist.xquery.XQuery)16 ValueSequence (org.exist.xquery.value.ValueSequence)16 BrokerPool (org.exist.storage.BrokerPool)14 NumericValue (org.exist.xquery.value.NumericValue)12 SAXException (org.xml.sax.SAXException)11 Properties (java.util.Properties)10 StringValue (org.exist.xquery.value.StringValue)10 Node (org.w3c.dom.Node)10 MemTreeBuilder (org.exist.dom.memtree.MemTreeBuilder)9 AtomicValue (org.exist.xquery.value.AtomicValue)9 Txn (org.exist.storage.txn.Txn)8 IOException (java.io.IOException)7 StringWriter (java.io.StringWriter)7 EXistException (org.exist.EXistException)7