Package net.sf.saxon.s9api

Examples of net.sf.saxon.s9api.XdmNode


                Input input = step.getInput(port);
                loopdone = loopdone && (input.getPosition() <= position);
                if (input.getPosition() == position) {
                    for (ReadablePipe source : inputs.get(port)) {
                        while (source.moreDocuments()) {
                            XdmNode node = source.read();
                            XdmNode docelem = S9apiUtils.getDocumentElement(node);

                            if (XProcConstants.c_param_set.equals(docelem.getNodeName())) {
                                // Check the attributes...
                                for (XdmNode attr : new AxisNodes(docelem, Axis.ATTRIBUTE)) {
                                    QName aname = attr.getNodeName();
                                    if ("".equals(aname.getNamespaceURI())
                                        || XProcConstants.NS_XPROC.equals(aname.getNamespaceURI())) {
                                        throw XProcException.dynamicError(14, step.getNode(), "Attribute not allowed");
                                    }
                                }

                                for (XdmNode child : new AxisNodes(runtime, docelem, Axis.CHILD, AxisNodes.SIGNIFICANT)) {
                                    if (child.getNodeKind() == XdmNodeKind.ELEMENT) {
                                        if (!child.getNodeName().equals(XProcConstants.c_param)) {
                                            throw XProcException.dynamicError(18, step.getNode(), "Element not allowed: " + child.getNodeName());
                                        }
                                        parseParameterNode(xstep,child);
                                    }
                                }
                            } else if (XProcConstants.c_param.equals(docelem.getNodeName())) {
                                parseParameterNode(xstep,docelem);
                            } else {
                                throw new XProcException(step.getNode(), docelem.getNodeName() + " found where c:param or c:param-set expected");
                            }
                        }
                    }
                }
            }
View Full Code Here


                    pipe.canWriteSequence(true);
                    pipe.canReadSequence(input.getSequence());
                    for (ReadablePipe reader : inputs.get(port)) {
                        if (reader.moreDocuments()) {
                            while (reader.moreDocuments()) {
                                XdmNode doc = reader.read();
                                pipe.write(doc);
                                totalDocs++;
                            }
                        } else if (reader instanceof ReadableDocument) {
                            // HACK: We haven't necessarily read the document yet
                            totalDocs++;
                        }
                    }
                    xstep.setInput(port, pipe);
                } else if (readerCount == 1) {
                    ReadablePipe pipe = inputs.get(port).firstElement();
                    pipe.setReader(step);
                    if (pipe.moreDocuments()) {
                        totalDocs += pipe.documentCount();
                    } else if (pipe instanceof ReadableDocument) {
                        totalDocs++;
                    }
                    xstep.setInput(port, pipe);
                }
            }

            if (totalDocs != 1 && !input.getSequence()) {
                throw XProcException.dynamicError(6, step.getNode(), totalDocs + " documents appear on the '" + port + "' port.");
            }
        }

        for (String port : outputs.keySet()) {
            xstep.setOutput(port, outputs.get(port));
        }

        // N.B. At this time, there are no compound steps that accept parameters or options,
        // so the order in which we calculate them doesn't matter. That will change if/when
        // there are such compound steps.

        // Calculate all the options
        DeclareStep decl = step.getDeclaration();
        inScopeOptions = parent.getInScopeOptions();
        for (QName name : step.getOptions()) {
            Option option = step.getOption(name);
            RuntimeValue value = computeValue(option);

            Option optionDecl = decl.getOption(name);
            String typeName = optionDecl.getType();
            XdmNode declNode = optionDecl.getNode();
            if (typeName != null && declNode != null) {
                if (typeName.contains("|")) {
                    TypeUtils.checkLiteral(value.getString(), typeName);
                } else {
                    QName type = new QName(typeName, declNode);
                    TypeUtils.checkType(runtime, value.getString(),type,option.getNode());
                }
            }

            xstep.setOption(name, value);
            inScopeOptions.put(name, value);
        }

        xstep.reset();
        computeParameters(xstep);

        // HACK HACK HACK!
        if (XProcConstants.p_in_scope_names.equals(step.getType())) {
            for (QName name : inScopeOptions.keySet()) {
                xstep.setParameter(name, inScopeOptions.get(name));
            }
        }
       
        // Make sure we do this *after* calculating any option/parameter values...
        XProcData data = runtime.getXProcData();
        data.openFrame(this);

        runtime.start(this);
        try {
            xstep.run();

            // FIXME: Is it sufficient to only do this for atomic steps?
            String cache = getInheritedExtensionAttribute(XProcConstants.cx_cache);
            if ("true".equals(cache)) {
                for (String port : outputs.keySet()) {
                    WritablePipe wpipe = outputs.get(port);
                    // FIXME: Hack. There should be a better way...
                    if (wpipe instanceof Pipe) {
                        ReadablePipe rpipe = new Pipe(runtime, ((Pipe) wpipe).documents());
                        rpipe.canReadSequence(true);
                        rpipe.setReader(step);
                        while (rpipe.moreDocuments()) {
                            XdmNode doc = rpipe.read();
                            runtime.cache(doc, step.getNode().getBaseURI());
                        }
                    }
                }
            } else if (!"false".equals(cache) && cache != null) {
View Full Code Here

                    Vector<XdmValue> nodes = new Vector<XdmValue> ();
                    URI baseURI = null;

                    XdmSequenceIterator iter = child.axisIterator(Axis.CHILD);
                    while (iter.hasNext()) {
                        XdmNode gchild = (XdmNode) iter.next();

                        if (baseURI == null && gchild.getNodeKind() == XdmNodeKind.ELEMENT) {
                            baseURI = gchild.getBaseURI();
                        }

                        nodes.add(gchild);
                    }

                    XdmDestination dest = new XdmDestination();

                    try {
                        if (baseURI == null) {
                            baseURI = new URI("http://example.com/"); // FIXME: do I need this?
                        }
                        S9apiUtils.writeXdmValue(runtime.getProcessor(), nodes, dest, baseURI);
                        XdmNode doc = dest.getXdmNode();
                        stringValue += doc.getStringValue();
                        items.add(doc);
                    } catch (URISyntaxException use) {
                        throw new XProcException(use);
                    } catch (SaxonApiException sae) {
                        throw new XProcException(sae);
View Full Code Here

    }

    protected RuntimeValue computeValue(ComputableValue var) {
        Hashtable<String,String> nsBindings = new Hashtable<String,String> ();
        Hashtable<QName,RuntimeValue> globals = inScopeOptions;
        XdmNode doc = null;

        try {
            if (var.getBinding().size() > 0) {
                Binding binding = var.getBinding().firstElement();

                ReadablePipe pipe = null;
                if (binding.getBindingType() == Binding.ERROR_BINDING) {
                    pipe = ((XCatch) this).errorPipe;
                } else {
                    pipe = getPipeFromBinding(binding);
                }
                doc = pipe.read();
                if (pipe.moreDocuments()) {
                    throw XProcException.dynamicError(step, 8, "More than one document in context for parameter '" + var.getName() + "'");
                }
            }
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }

        for (NamespaceBinding nsbinding : var.getNamespaceBindings()) {
            Hashtable<String,String> localBindings = new Hashtable<String,String> ();

            // Compute the namespaces associated with this binding
            if (nsbinding.getBinding() != null) {
                QName binding = new QName(nsbinding.getBinding(), nsbinding.getNode());
                RuntimeValue nsv = globals.get(binding);
                if (nsv == null) {
                    throw new XProcException(var.getNode(), "No in-scope option or variable named: " + binding);
                }

                localBindings = nsv.getNamespaceBindings();
            } else if (nsbinding.getXPath() != null) {
                try {
                    XPathCompiler xcomp = runtime.getProcessor().newXPathCompiler();
                    xcomp.setBaseURI(step.getNode().getBaseURI());

                    for (QName varname : globals.keySet()) {
                        xcomp.declareVariable(varname);
                    }

                    // Make sure the namespace bindings for evaluating the XPath expr are correct
                    // FIXME: Surely there's a better way to do this?
                    Hashtable<String,String> lclnsBindings = new Hashtable<String, String>();
                    NodeInfo inode = nsbinding.getNode().getUnderlyingNode();
                    NamePool pool = inode.getNamePool();
                    InscopeNamespaceResolver inscopeNS = new InscopeNamespaceResolver(inode);
                    Iterator<?> pfxiter = inscopeNS.iteratePrefixes();
                    while (pfxiter.hasNext()) {
                        String nspfx = (String)pfxiter.next();
                        String nsuri = inscopeNS.getURIForPrefix(nspfx, "".equals(nspfx));
                        lclnsBindings.put(nspfx, nsuri);
                    }

                    for (String prefix : lclnsBindings.keySet()) {
                        xcomp.declareNamespace(prefix, lclnsBindings.get(prefix));
                    }

                    XPathExecutable xexec = xcomp.compile(nsbinding.getXPath());
                    XPathSelector selector = xexec.load();

                    for (QName varname : globals.keySet()) {
                        XdmAtomicValue avalue = new XdmAtomicValue(globals.get(varname).getString());
                        selector.setVariable(varname,avalue);
                    }

                    if (doc != null) {
                        selector.setContextItem(doc);
                    }

                    XdmNode element = null;
                    Iterator<XdmItem> values = selector.iterator();
                    while (values.hasNext()) {
                        XdmItem item = values.next();
                        if (element != null || item.isAtomicValue()) {
                            throw XProcException.dynamicError(9);
                        }
                        element = (XdmNode) item;
                        if (element.getNodeKind() != XdmNodeKind.ELEMENT) {
                            throw XProcException.dynamicError(9);
                        }
                    }

                    if (element == null) {
                        throw XProcException.dynamicError(9);
                    }

                    XdmSequenceIterator nsIter = element.axisIterator(Axis.NAMESPACE);
                    while (nsIter.hasNext()) {
                        XdmNode ns = (XdmNode) nsIter.next();
                        QName prefix = ns.getNodeName();
                        localBindings.put(prefix == null ? "" : prefix.getLocalName(),ns.getStringValue());
                    }
                } catch (SaxonApiException sae) {
                    throw new XProcException(sae);
                }
            } else if (nsbinding.getNamespaceBindings() != null) {
                Hashtable<String,String> bindings = nsbinding.getNamespaceBindings();
                for (String prefix : bindings.keySet()) {
                    if ("".equals(prefix) || prefix == null) {
                        // nop; the default namespace never plays a role in XPath expression evaluation
                    } else {
                        localBindings.put(prefix,bindings.get(prefix));
                    }
                }
            }

            // Remove the excluded ones
            HashSet<String> prefixes = new HashSet<String> ();
            for (String uri : nsbinding.getExcludedNamespaces()) {
                for (String prefix : localBindings.keySet()) {
                    if (uri.equals(localBindings.get(prefix))) {
                        prefixes.add(prefix);
                    }
                }
            }
            for (String prefix : prefixes) {
                localBindings.remove(prefix);
            }

            // Add them to the bindings for this value, making sure there are no errors...
            for (String pfx : localBindings.keySet()) {
                if (nsBindings.containsKey(pfx) && !nsBindings.get(pfx).equals(localBindings.get(pfx))) {
                    throw XProcException.dynamicError(13);
                }
                nsBindings.put(pfx,localBindings.get(pfx));
            }
        }

        String select = var.getSelect();
        Vector<XdmItem> results = evaluateXPath(doc, nsBindings, select, globals);
        String value = "";

        try {
            for (XdmItem item : results) {
                if (item.isAtomicValue()) {
                    value += item.getStringValue();
                } else {
                    XdmNode node = (XdmNode) item;
                    if (node.getNodeKind() == XdmNodeKind.ATTRIBUTE
                            || node.getNodeKind() == XdmNodeKind.NAMESPACE) {
                        value += node.getStringValue();
                    } else {
                        XdmDestination dest = new XdmDestination();
                        S9apiUtils.writeXdmValue(runtime,item,dest,null);
                        value += dest.getXdmNode().getStringValue();
                    }
                }
            }
        } catch (SaxonApiUncheckedException saue) {
            Throwable sae = saue.getCause();
            if (sae instanceof XPathException) {
                XPathException xe = (XPathException) sae;
                if ("http://www.w3.org/2005/xqt-errors".equals(xe.getErrorCodeNamespace()) && "XPDY0002".equals(xe.getErrorCodeLocalPart())) {
                    throw XProcException.dynamicError(26, step.getNode(), "The expression for $" + var.getName() + " refers to the context item.");
                } else {
                    throw saue;
                }
            } else {
                throw saue;
            }
        } catch (SaxonApiException sae) {
            throw new XProcException(sae);
        }

        // Now test to see if the option is a reasonable value
        if (var.getType() != null) {
            String type = var.getType();
            if (type.contains("|")) {
                TypeUtils.checkLiteral(value, type);
            } else if (type.contains(":")) {
                TypeUtils.checkType(runtime, value, var.getTypeAsQName(), var.getNode());
            }
        }

        // Section 5.7.5 Namespaces on variables, options, and parameters
        //
        // If the select attribute was used to specify the value and it consisted of a single VariableReference
        // (per [XPath 1.0] or [XPath 2.0], as appropriate), then the namespace bindings from the referenced
        // option or variable are used.
        Pattern varrefpat = Pattern.compile("^\\s*\\$([^\\s=]+)\\s*$");
        Matcher varref = varrefpat.matcher(select);
        if (varref.matches()) {
            String varrefstr = varref.group(1);
            QName varname = null;
            if (varrefstr.contains(":")) {
                String vpfx = varrefstr.substring(0, varrefstr.indexOf(":"));
                String vlocal = varrefstr.substring(varrefstr.indexOf(":")+1);
                String vns = nsBindings.get(vpfx);
                varname = new QName(vpfx, vns, vlocal);
            } else {
                varname = new QName("", varrefstr);
            }
            RuntimeValue val = globals.get(varname);
            nsBindings = val.getNamespaceBindings();
        }

        // Section 5.7.5 Namespaces on variables, options, and parameters
        //
        // If the select attribute was used to specify the value and it evaluated to a node-set, then the in-scope
        // namespaces from the first node in the selected node-set (or, if it's not an element, its parent) are used.
        if (results.size() > 0 && results.get(0) instanceof XdmNode) {
            XdmNode node = (XdmNode) results.get(0);
            nsBindings.clear();

            XdmSequenceIterator nsIter = node.axisIterator(Axis.NAMESPACE);
            while (nsIter.hasNext()) {
                XdmNode ns = (XdmNode) nsIter.next();
                nsBindings.put((ns.getNodeName()==null ? "" : ns.getNodeName().getLocalName()),ns.getStringValue());
            }
        }

        if (runtime.getAllowGeneralExpressions()) {
            return new RuntimeValue(value,results,var.getNode(),nsBindings);
View Full Code Here

            count += 1;
            if (count >= limit) {
                tree.addEndElement();
                tree.endDocument();

                XdmNode out = tree.getResult();
                result.write(out);

                tree = new TreeWriter(runtime);
                tree.startDocument(step.getNode().getBaseURI());
                tree.addStartElement(sem_triples);
                tree.startContent();

                tree.addStartElement(cx_database_uri);
                tree.startContent();
                tree.addText(nextDatabaseUri());
                tree.addEndElement();

                if (graphName != null) {
                    tree.addStartElement(cx_graph_name);
                    tree.startContent();
                    tree.addText(graphName);
                    tree.addEndElement();
                }

                count = 0;
            }
        }

        if (count > 0) {
            tree.addEndElement();
            tree.endDocument();

            XdmNode out = tree.getResult();
            result.write(out);
        }
    }
View Full Code Here

    protected void loadRdf(Dataset dataset, XdmNode doc) {
        Model model = dataset.getDefaultModel();
        String graphName = null;

        XdmNode root = S9apiUtils.getDocumentElement(doc);
        if (root.getNodeName().equals(sem_triples)) {
            for (XdmNode node : new AxisNodes(root, Axis.CHILD, AxisNodes.SIGNIFICANT)) {
                if (node.getNodeName().equals(cx_graph_name)) {
                    graphName = node.getStringValue();
                    model = dataset.getNamedModel(graphName);
                    // ModelFactory.createDefaultModel();
                } else if (node.getNodeName().equals(sem_triple)) {
                    XdmNode subj = null;
                    XdmNode pred = null;
                    XdmNode obj = null;

                    for (XdmNode child : new AxisNodes(node, Axis.CHILD)) {
                        if (child.getNodeName().equals(sem_subject)) {
                            subj = child;
                        } else if (child.getNodeName().equals(sem_predicate)) {
                            pred = child;
                        } else if (child.getNodeName().equals(sem_object)) {
                            obj = child;
                        }
                    }

                    Resource rsrc = getResource(model, subj.getStringValue());
                    Property prop = model.createProperty(pred.getStringValue());

                    String objstr = obj.getStringValue();
                    String lang = obj.getAttributeValue(XProcConstants.xml_lang);
                    String datatype = obj.getAttributeValue(_datatype);

                    if (lang != null) {
                        Literal literal = model.createLiteral(objstr, lang);
                        rsrc.addProperty(prop, literal);
                    } else if (datatype != null) {
View Full Code Here

        // We're going to have to loop through the attributes several times, so let's grab 'em
        Hashtable<QName, String> attrs = new Hashtable<QName, String> ();

        XdmSequenceIterator iter = node.axisIterator(Axis.ATTRIBUTE);
        while (iter.hasNext()) {
            XdmNode child = (XdmNode) iter.next();
            String value =  child.getStringValue();

            if (!child.getNodeName().equals(attrName)) {
                attrs.put(child.getNodeName(), value);
            }
        }

        QName instanceAttrName = attrName;
View Full Code Here

    public XdmNode read() throws SaxonApiException {
        if (!readDoc) {
            readDoc();
        }

        XdmNode doc = documents.get(pos++);

        if (reader != null) {
            logger.trace(MessageFormatter.nodeMessage(reader.getNode(),
                    reader.getName() + " select read '" + (doc == null ? "null" : doc.getBaseURI()) + "' from " + this));
        }

        return doc;
    }
View Full Code Here

            }
        }
    }

    private XdmNode parse(String uri, String base) {
        XdmNode doc = runtime.parse(uri, base);

        if (uri.contains("#")) {
            int pos = uri.indexOf("#");
            String ptr = uri.substring(pos+1);
View Full Code Here

    }

    public void run() throws SaxonApiException {
        super.run();

        XdmNode doc = source.read();
        if (doc == null) {
            logger.trace("Error step read empty");
        } else {
            logger.trace("Error step read " + doc.getDocumentURI());
        }

        RuntimeValue codeNameValue = getOption(_code);
        String codeNameStr = codeNameValue.getString();
        String cpfx = getOption(_code_prefix, (String) null);
        String cns = getOption(_code_namespace, (String) null);

        if (cpfx == null && cns != null) {
            cpfx = "ERR";
        }

        if (cpfx != null && cns == null) {
            throw XProcException.dynamicError(34, "You can't specify a prefix without a namespace");
        }

        if (cns != null && codeNameStr.contains(":")) {
            throw XProcException.dynamicError(34, "You can't specify a namespace if the code name contains a colon");
        }

        QName errorCode = null;
        if (codeNameStr.contains(":")) {
            errorCode = new QName(codeNameStr, codeNameValue.getNode());
        } else {
            errorCode = new QName(cpfx == null ? "" : cpfx, cns, codeNameStr);
        }

        cpfx = errorCode.getPrefix();
        cns = errorCode.getNamespaceURI();

        TreeWriter treeWriter = new TreeWriter(runtime);
        treeWriter.startDocument(step.getNode().getBaseURI());
        treeWriter.addStartElement(c_error);
        treeWriter.addNamespace(cpfx, cns);

        treeWriter.addAttribute(_name, step.getName());
        treeWriter.addAttribute(_type, "p:error");
        treeWriter.addAttribute(_code, errorCode.toString());
        treeWriter.startContent();
        if (doc != null) {
            treeWriter.addSubtree(doc);
        }
        treeWriter.addEndElement();
        treeWriter.endDocument();

        step.reportError(treeWriter.getResult());

        if (doc == null) {
            throw new XProcException(errorCode);
        } else {
            throw new XProcException(errorCode, doc, doc.getStringValue());
        }
    }
View Full Code Here

TOP

Related Classes of net.sf.saxon.s9api.XdmNode

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.