Beispiel #1
0
        /// <summary>
        /// Compile and execute an expression supplied as a <c>String</c>, with a given context item, where
        /// the expression is expected to return a single item as its result.
        /// </summary>
        /// <param name="expression">A string containing the source text of the XPath expression</param>
        /// <param name="contextItem">The context item to be used for evaluation of the XPath expression.
        /// May be null, in which case the expression is evaluated without any context item.</param>
        /// <returns>If the XPath expression returns a singleton, then the the <c>XdmItem</c>
        /// which is the result of evaluating the XPath expression. If the expression returns an empty sequence,
        /// then null. If the expression returns a sequence containing more than one item, then the first
        /// item in the result.</returns>
        /// <exception cref="StaticError">
        /// Throws a <c>Saxon.Api.StaticError</c> if there is any static error in the XPath expression.
        /// This includes both syntax errors, semantic errors such as references to undeclared functions or
        /// variables, and statically-detected type errors.
        /// </exception>
        /// <exception cref="DynamicError">
        /// Throws a <c>Saxon.Api.DynamicError</c> if there is any dynamic error during evaluation of the XPath expression.
        /// This includes, for example, referring to the context item if no context item was supplied.
        /// </exception>

        public XdmItem EvaluateSingle(String expression, XdmItem contextItem)
        {
            try
            {
                JXdmItem value = compiler.evaluateSingle(expression, contextItem == null ? null : XdmItem.FromXdmItemItemToJXdmItem(contextItem));
                return(value == null ? null : (XdmItem)XdmValue.Wrap(value.getUnderlyingValue()));
            }
            catch (JSaxonApiException err)
            {
                if (err.getCause() is JXPathException)
                {
                    JXPathException xpathException = (JXPathException)err.getCause();
                    if (xpathException.isStaticError())
                    {
                        throw new StaticError(err);
                    }
                    else
                    {
                        throw new DynamicError(err.getMessage());
                    }
                }
                else
                {
                    throw new StaticError(err);
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Compile and execute an expression supplied as a String, with a given context item, where
        /// the expression is expected to return a single item as its result
        /// </summary>
        /// <param name="expression">A string containing the source text of the XPath expression</param>
        /// <param name="contextItem">The context item to be used for evaluation of the XPath expression.
        /// May be null, in which case the expression is evaluated without any context item.</param>
        /// <returns>If the XPath expression returns a singleton, then the the <c>XdmItem</c>
        /// which is the result of evaluating the XPath expression. If the expression returns an empty sequence,
        /// then null. If the expression returns a sequence containing more than one item, then the first
        /// item in the result.</returns>
        /// <exception cref="StaticError">
        /// Throws a <c>Saxon.Api.StaticError</c> if there is any static error in the XPath expression.
        /// This includes both syntax errors, semantic errors such as references to undeclared functions or
        /// variables, and statically-detected type errors.
        /// </exception>
        /// <exception cref="DynamicError">
        /// Throws a <c>Saxon.Api.DynamicError</c> if there is any dynamic error during evaluation of the XPath expression.
        /// This includes, for example, referring to the context item if no context item was supplied.
        /// </exception>

        public XdmItem EvaluateSingle(String expression, XdmItem contextItem)
        {
            XPathSelector xs = Compile(expression).Load();

            if (contextItem != null)
            {
                xs.ContextItem = contextItem;
            }
            return(xs.EvaluateSingle());
        }
Beispiel #3
0
        public override void write(JItem item)
        {
            XmlLocation loc = new XmlLocation();

            if (locationId != -1)
            {
                JLocationProvider provider = getPipelineConfiguration().getLocationProvider();
                loc.BaseUri    = new Uri(provider.getSystemId(locationId));
                loc.LineNumber = provider.getLineNumber(locationId);
            }
            listener.Message((XdmNode)XdmItem.Wrap(item), terminate, loc);
        }
Beispiel #4
0
        /**
         * Construct an Environment
         *
         * @param xpc          the XPathCompiler used to process the catalog file
         * @param env          the Environment element in the catalog file
         * @param environments the set of environments to which this one should be added (may be null)
         * @return the constructed Environment object
         * @throws SaxonApiException
         */

        private TestEnvironment processEnvironment(XPathCompiler xpc, XdmItem env, Dictionary<string, TestEnvironment> environments)
        {
            TestEnvironment environment = new TestEnvironment();
            string name = ((XdmNode)env).GetAttributeValue(new QName("name"));
            environment.processor = new Processor(true);
            XmlUrlResolver res = new XmlUrlResolver();
            if (generateByteCode == 1)
            {
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
            }
            else if (generateByteCode == 2)
            {
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
            }
            else
            {
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
            }
            environment.xpathCompiler = environment.processor.NewXPathCompiler();
            environment.xpathCompiler.BaseUri = (((XdmNode)env).BaseUri).ToString();
            environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
            environment.xqueryCompiler.BaseUri = (((XdmNode)env).BaseUri).ToString();
            if (unfolded)
            {
                //environment.xqueryCompiler.getUnderlyingStaticContext().setCodeInjector(new LazyLiteralInjector());
            }
            DocumentBuilder builder = environment.processor.NewDocumentBuilder();
            environment.sourceDocs = new Dictionary<string, XdmNode>();
            if (environments != null && name != null)
            {
                try
                {
                    environments.Add(name, environment);
                }catch(Exception e){}
            }
            System.Collections.IEnumerator dependency = xpc.Evaluate("dependency", env).GetEnumerator();

            while (dependency.MoveNext())
            {
                if (!DependencyIsSatisfied((XdmNode)dependency.Current, environment))
                {
                    environment.usable = false;
                }
            }

            // set the base Uri if specified
            IEnumerator base1 = xpc.Evaluate("static-base-uri", env).GetEnumerator();
            while (base1.MoveNext())
            {
                string Uri = ((XdmNode)base1.Current).GetAttributeValue(new QName("uri"));
                try
                {
                    environment.xpathCompiler.BaseUri = Uri;
                    environment.xqueryCompiler.BaseUri = Uri;
                }
                catch (Exception e)
                {
                    Console.WriteLine("**** invalid base Uri " + Uri);
                }
            }
            // set any requested collations
            base1 = xpc.Evaluate("collation", env).GetEnumerator();
            while (base1.MoveNext())
            {
                string uriStr = ((XdmNode)base1.Current).GetAttributeValue(new QName("uri"));
                string defaultAtt = ((XdmNode)base1.Current).GetAttributeValue(new QName("default"));
                Boolean defaultCol = false;
                if (defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1")))
                {
                    defaultCol = true;
                }
                if (uriStr.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind"))
                {
                    net.sf.saxon.Configuration config = xpc.Processor.Implementation;
                    net.sf.saxon.lib.StringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);

                    CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo;
                    CompareOptions options = CompareOptions.IgnoreCase;

                    environment.xpathCompiler.DeclareCollation(new Uri(uriStr), compareInfo, options, defaultCol);
                    environment.xqueryCompiler.DeclareCollation(new Uri(uriStr), compareInfo, options, defaultCol);
                }
               
            }

            // declare the requested namespaces
            IEnumerator nsElement = xpc.Evaluate("namespace", env).GetEnumerator();
            while (nsElement.MoveNext())
            {
                string prefix = ((XdmNode)nsElement.Current).GetAttributeValue(new QName("prefix"));
                string uri = ((XdmNode)nsElement.Current).GetAttributeValue(new QName("uri"));
                environment.xpathCompiler.DeclareNamespace(prefix, uri);
                environment.xqueryCompiler.DeclareNamespace(prefix, uri);
            }

            // load the requested schema documents
            SchemaManager manager = environment.processor.SchemaManager;
            System.Collections.IEnumerator schema = xpc.Evaluate("schema", env).GetEnumerator();
            while (schema.MoveNext())
            {
                string href = ((XdmNode)schema.Current).GetAttributeValue(new QName("file"));
                manager.Compile((new Uri(((XdmNode)env).BaseUri, href)));
            }

            // load the requested source documents
            //IEnumerator source = xpc.Evaluate("source", env).GetEnumerator();
            foreach (XdmItem source in xpc.Evaluate("source", env))
            {
                Uri href = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file")));
                string Uri = ((XdmNode)source).GetAttributeValue(new QName("uri"));
                string validation = ((XdmNode)source).GetAttributeValue(new QName("", "validation"));
                XdmNode doc = null;
                
                if (validation == null || validation.Equals("skip"))
                {
                    try
                    {
                        doc = builder.Build(href);
                       
                    }
                    catch (Exception e)
                    {
                        feedback.Message("Error:" + e.Message+" *** failed to build source document " + href, false);
                    }
                }
                else
                {
                    try
                    {
                        SchemaValidator validator = manager.NewSchemaValidator();
                        XdmDestination xdmDest = new XdmDestination();
                        validator.IsLax = validation.Equals("lax");
                        validator.SetDestination(xdmDest);
                        validator.SetSource(href);
                        validator.Run();
                        doc = xdmDest.XdmNode;
                        environment.xpathCompiler.SchemaAware = true;
                        environment.xqueryCompiler.SchemaAware = true;
                    }
                    catch(Exception e) {
                        feedback.Message("Error:" + e.Message+" *** failed to build source document " + href, false);
                    }

                }

                if (Uri != null)
                {
                    environment.sourceDocs.Add(Uri, doc);
                }
                string role = ((XdmNode)source).GetAttributeValue(new QName("role"));
                if (role != null)
                {
                    if (".".Equals(role))
                    {
                        environment.contextNode = doc;
                    }
                    else if (role.StartsWith("$"))
                    {
                        string varName = role.Substring(1);
                        environment.params1.Add(new QName(varName), doc);
                        environment.xpathCompiler.DeclareVariable(new QName(varName));
                        environment.paramDeclarations.Append("declare variable $" + varName + " external; ");
                    }
                }
              
            }

            // create a collection Uri resolved to handle the requested collections
            Hashtable collections = new Hashtable();
          

            foreach (XdmItem coll in xpc.Evaluate("collection", env))
            {
                string collectionUri = ((XdmNode)coll).GetAttributeValue(new QName("uri"));
                if (collectionUri == null || collectionUri.Equals(""))
                {
                    collectionUri = "http://www.saxonica.com/defaultCollection";
                }

                IList<Uri> docs = new List<Uri>();
                
                foreach (XdmItem source in xpc.Evaluate("source", coll))
                {
                   

                    Uri href = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file")));
                    //File file = new File((((XdmNode) env).GetBaseUri().resolve(href)));
                    string id = ((XdmNode)source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
                    XdmNode doc = builder.Build(href);
                    if (id != null)
                    {
                        environment.sourceDocs.Add(id, doc);
                    }
                    
                    environment.processor.RegisterCollection(href, getCollection(doc, href.AbsoluteUri));
                    environment.sourceDocs.Add(href.ToString(), doc);
                     docs.Add(doc.DocumentUri);
                }
                try {
                    collections.Add(new Uri(collectionUri), docs);
                } catch (Exception e) {
                    feedback.Message("**** Invalid collection Uri " + collectionUri, false);
                }

            }
            if (collections.Count != 0) {
                environment.processor.Implementation.setCollectionURIResolver(new CollectionResolver(collections));
               /*     new net.sf.saxon.lib.CollectionURIResolver() {
                            public SequenceIterator resolve(string href, string base, XPathContext context)  {
                                try {
                                    List<AnyUriValue> docs;
                                    if (href == null) {
                                        docs = collections.get(new Uri(""));
                                    } else {
                                        Uri abs = new Uri(base).resolve(href);
                                        docs = collections.get(abs);
                                    }
                                    if (docs == null) {
                                        return EmptyIterator.getInstance();
                                    } else {
                                        return new ListIterator(docs);
                                    }
                                } catch (UriSyntaxException e) {
                                    Console.WriteLine("** Invalid Uri: " + e.Message);
                                    return EmptyIterator.getInstance();
                                }
                            }
                        }
                )*/
            }

            // register any required decimal formats
            IEnumerator decimalFormat = xpc.Evaluate("decimal-format", env).GetEnumerator();
            while (decimalFormat.MoveNext())
            {

                   XdmNode formatElement = (XdmNode) decimalFormat.Current;
                   string formatName = formatElement.GetAttributeValue(new QName("name"));
                   QName formatQName = null;
                   if (formatName != null) {
                       if (formatName.IndexOf(':') < 0) {
                           formatQName = new QName("", "", formatName);
                       } else {
                           try {
                               formatQName =  new QName(environment.xpathCompiler.GetNamespaceURI(formatName, false), formatName.Substring(formatName.IndexOf(':')+1));
                           } catch (Exception) {
                               feedback.Message("**** Invalid QName as decimal-format name", false);
                               formatQName = new QName("", "", "error-name");
                           }
                       }
                       environment.paramDecimalDeclarations.Append("declare decimal-format " + formatName + " ");
                   } else {
                       environment.paramDecimalDeclarations.Append("declare default decimal-format ");
                   }
                   foreach (XdmItem decimalFormatAtt in xpc.Evaluate("@* except @name", formatElement)) {
                       XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
                       string property = formatAttribute.NodeName.LocalName;
                       string value = formatAttribute.StringValue;
                       environment.paramDecimalDeclarations.Append(property + "=\"" + value + "\" ");
                       environment.xpathCompiler.SetDecimalFormatProperty(formatQName, property, value);
                      
                   }
                   environment.paramDecimalDeclarations.Append(";");
            }

            // declare any variables
            IEnumerator param = xpc.Evaluate("param", env).GetEnumerator();
            while (param.MoveNext())
            {
                string varName = ((XdmNode)param.Current).GetAttributeValue(new QName("name"));
                XdmValue value = null;
                string sourceStr = ((XdmNode)param.Current).GetAttributeValue(new QName("source"));
                if (sourceStr != null)
                {
                    XdmNode sourceDoc = (XdmNode)(environment.sourceDocs[sourceStr]);
                    if (sourceDoc == null)
                    {
                        Console.WriteLine("**** Unknown source document " + sourceDoc.ToString());
                    }
                    value = sourceDoc;
                }
                else
                {
                    string select = ((XdmNode)param.Current).GetAttributeValue(new QName("select"));
                    value = xpc.Evaluate(select, null);
                }
                environment.params1.Add(new QName(varName), value);
                environment.xpathCompiler.DeclareVariable(new QName(varName));
                string declared = ((XdmNode)param.Current).GetAttributeValue(new QName("declared"));
                if (declared != null && "true".Equals(declared) || "1".Equals(declared))
                {
                    // no action
                }
                else
                {
                    environment.paramDeclarations.Append("declare variable $" + varName + " external; ");
                }
            }

            return environment;
        }
Beispiel #5
0
 public XdmItem GetXdmItem(DynamicContext context)
 {
     return(XdmItem.FromGroundedValue(resource.getItem(context.context).materialize()).ItemAt(0));
 }
Beispiel #6
0
        public object convert(object obj)
        {
            XdmItem i = (XdmItem)obj;

            return((JItem)i.Unwrap());
        }
Beispiel #7
0
 /// <summary>
 /// Determine whether this item type matches a given item.
 /// </summary>
 /// <param name="item">item the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match.</returns>
 public override bool Matches(XdmItem item)
 {
     return(item.Unwrap() is JNodeTest && kind == ((net.sf.saxon.om.NodeInfo)item.Unwrap()).getNodeKind());
 }
Beispiel #8
0
 /// <summary>
 /// Determine whether this item type matches a given item
 /// </summary>
 /// <param name="item">the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match</returns>
 public override bool Matches(XdmItem item)
 {
     return(type.matches(XdmItem.FromXdmItemItemToJXdmItem(item)));
 }
Beispiel #9
0
 /// <summary>
 /// Determine whether this item type matches a given item.
 /// </summary>
 /// <param name="item">the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match.</returns>
 public override bool Matches(XdmItem item)
 {
     return(((net.sf.saxon.om.Item)item.value) is net.sf.saxon.om.NodeInfo);
 }
Beispiel #10
0
 /// <summary>
 /// Determine whether this item type matches a given item.
 /// </summary>
 /// <param name="item">the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match.</returns>
 public override bool Matches(XdmItem item)
 {
     return(true);
 }
Beispiel #11
0
 /// <summary>
 /// Determine whether this item type matches a given item.
 /// </summary>
 /// <param name="item">the item to be tested against this item type</param>
 /// <returns>true if the item matches this item type, false if it does not match.</returns>
 virtual public bool Matches(XdmItem item)
 {
     return(type.matches((net.sf.saxon.s9api.XdmItem)XdmValue.FromGroundedValueToJXdmValue(item.value)));
 }
Beispiel #12
0
        /// <summary>
        /// Compile and execute an expression supplied as a String, with a given context item, where
        /// the expression is expected to return a single item as its result
        /// </summary>
        /// <param name="expression">A string containing the source text of the XPath expression</param>
        /// <param name="contextItem">The context item to be used for evaluation of the XPath expression.
        /// May be null, in which case the expression is evaluated without any context item.</param>
        /// <returns>If the XPath expression returns a singleton, then the the <c>XdmItem</c> 
        /// which is the result of evaluating the XPath expression. If the expression returns an empty sequence,
        /// then null. If the expression returns a sequence containing more than one item, then the first
        /// item in the result.</returns>
        /// <exception cref="StaticError">
        /// Throws a <c>Saxon.Api.StaticError</c> if there is any static error in the XPath expression.
        /// This includes both syntax errors, semantic errors such as references to undeclared functions or
        /// variables, and statically-detected type errors.
        /// </exception>
        /// <exception cref="DynamicError">
        /// Throws a <c>Saxon.Api.DynamicError</c> if there is any dynamic error during evaluation of the XPath expression.
        /// This includes, for example, referring to the context item if no context item was supplied.
        /// </exception>

        public XdmItem EvaluateSingle(String expression, XdmItem contextItem)
        {
            XPathSelector xs = Compile(expression).Load();
            if (contextItem != null)
            {
                xs.ContextItem = contextItem;
            }
            return xs.EvaluateSingle();
        }