示例#1
0
        private XmlReader GetXmlReader(string url)
        {
            XmlResolver   res = new XmlUrlResolver();
            Uri           uri = res.ResolveUri(null, url);
            Stream        s   = res.GetEntity(uri, null, typeof(Stream)) as Stream;
            XmlTextReader xtr = new XmlTextReader(uri.ToString(), s);

            xtr.XmlResolver = res;
            XmlValidatingReader xvr = new XmlValidatingReader(xtr);

            xvr.XmlResolver    = res;
            xvr.ValidationType = ValidationType.None;
            return(xvr);
        }
        private XmlReader GetXmlReader(string url)
        {
            XmlResolver xmlResolver = new XmlUrlResolver();
            Uri         uri         = xmlResolver.ResolveUri(null, url);
            Stream      input       = xmlResolver.GetEntity(uri, null, typeof(Stream)) as Stream;

            return(new XmlValidatingReader(new XmlTextReader(uri.ToString(), input)
            {
                XmlResolver = xmlResolver
            })
            {
                XmlResolver = xmlResolver,
                ValidationType = ValidationType.None
            });
        }
示例#3
0
    static TextReader GetReader(string filename)
    {
        XmlResolver resolver = new XmlUrlResolver();
        Stream      stream   = resolver.GetEntity(resolver.ResolveUri(null, filename), null, typeof(Stream)) as Stream;

        if (useDecentReader)
        {
            return(new XmlSignatureStreamReader(
                       new StreamReader(stream)));
        }
        else
        {
            return(new StreamReader(stream));
        }
    }
示例#4
0
        private static void LoadPart(IBaseMessage msg, XPathNavigator node, string contextFile)
        {
            // don't care about the id because we can't set it anyway
            string name = node.GetAttribute("Name", "");
            string filename = node.GetAttribute("FileName", "");
            string charset = node.GetAttribute("Charset", "");
            string contentType = node.GetAttribute("ContentType", "");
            bool isBody = XmlConvert.ToBoolean(node.GetAttribute("IsBodyPart", ""));

            XmlResolver resolver = new XmlUrlResolver();
            Uri realfile = resolver.ResolveUri(new Uri(contextFile), filename);
            IBaseMessagePart part = CreatePartFromStream(File.OpenRead(realfile.LocalPath));
            part.Charset = charset;
            part.ContentType = contentType;
            msg.AddPart(name, part, isBody);
        }
示例#5
0
        private Stream ResolveSchemaLocation(XmlSchema enclosingSchema, string location, out string fullPath)
        {
            Stream stream;

            fullPath = null;
            try {
                XmlResolver resolver = new XmlUrlResolver();
                Uri         ruri     = resolver.ResolveUri((enclosingSchema.BaseUri != null && enclosingSchema.BaseUri != String.Empty) ? resolver.ResolveUri(null, enclosingSchema.BaseUri) : null, location);
                stream   = (Stream)resolver.GetEntity(ruri, null, null);
                fullPath = ruri.ToString();
            }
            catch {
                return(null);
            }
            return(stream);
        }
        /// <summary>
        /// Loads the XML include at the given path and returns the XContainer representing it.
        /// The location is pushed onto the include stack so that any nested include directives can
        /// be resolved relative to the path of the including file.
        /// </summary>
        /// <param name="href"></param>
        /// <returns></returns>
        public XContainer PushInclude(string href)
        {
            // Get the current base uri
            Uri base_url = _include_stack.Peek();
            // Resolve the href argument against the current base uri.
            Uri url = _resolver.ResolveUri(base_url, href);

            // Record for posterity
            AddToFileset(url);

            // Try to read in the document at the resolved url
            try
            {
                // As XmlReader does not do it for us like other classes do, we must dispose of the stream
                // so that the file is no longer locked at the system level
                using (Stream stream = (Stream)_resolver.GetEntity(url, null, typeof(Stream)))
                {
                    using (
                        XmlReader reader =
                            XmlReader.Create(stream)
                        )
                    {
                        XDocument document = XDocument.Load(reader,
                                                            LoadOptions.SetLineInfo |
                                                            LoadOptions.SetBaseUri |
                                                            LoadOptions.PreserveWhitespace);
                        // Load was successful, push the current base URL onto the include stack and set the
                        // resolver's base dir.
                        _include_stack.Push(url);
                        return(document);
                    }
                }
            }
            catch (FileNotFoundException fnfe)
            {
                throw MissingIncludeException.CreateException("Failed to include file: " + fnfe.Message);
            }
            catch (DirectoryNotFoundException dnfe)
            {
                throw MissingIncludeException.CreateException("Failed to include file: " + dnfe.Message);
            }
            catch (System.Net.WebException we)
            {
                throw MissingIncludeException.CreateException("Failed to include file '{0}': {1}", url.AbsoluteUri, we.Message);
            }
        }
示例#7
0
        private void CompileProlog()
        {
            Prolog p = module.Prolog;

            // resolve external modules
            // FIXME: check if external queries are allowed by default.
            // FIXME: check recursion
            XmlUrlResolver res = new XmlUrlResolver();

            foreach (ModuleImport modimp in p.ModuleImports)
            {
                foreach (string uri in modimp.Locations)
                {
                    Stream s = res.GetEntity(res.ResolveUri(null, uri), null, typeof(Stream)) as Stream;
                    XQueryLibraryModule ext = Mono.Xml.XQuery.Parser.Parser.Parse(new StreamReader(s)) as XQueryLibraryModule;
                    if (ext == null)
                    {
                        throw new XmlQueryCompileException(String.Format("External module {0} is resolved as a main module, while it should be a library module."));
                    }
                    XQueryStaticContext sctx = new XQueryASTCompiler(ext, options, compileContext, evidence, commandImpl).Compile();
                    libModuleContexts.Add(sctx);
                }
            }

            // resolve and compile in-scope schemas
            foreach (SchemaImport xsimp in p.SchemaImports)
            {
                foreach (string uri in xsimp.Locations)
                {
                    XmlSchema schema = inScopeSchemas.Add(xsimp.Namespace, uri);
                    compileContext.InEffectSchemas.Add(schema);
                }
            }
            inScopeSchemas.Compile();

            CheckReferences();

            ResolveVariableReferences();

            // compile FunctionDeclaration into XQueryFunction
            foreach (FunctionDeclaration func in p.Functions.Values)
            {
                XQueryFunction cfunc = CompileFunction(func);
                localFunctions.Add(cfunc);
            }
        }
示例#8
0
    public static void Main()
    {
        XmlUrlResolver resolver = new XmlUrlResolver();

        Uri baseUri = new Uri("http://servername/tmp/test.xsl");

        Uri fulluri = resolver.ResolveUri(baseUri, "includefile.xsl");

        // Get a stream object containing the XSL file
        Stream s = (Stream)resolver.GetEntity(fulluri, null, typeof(Stream));

        // Read the stream object displaying the contents of the XSL file
        XmlTextReader reader = new XmlTextReader(s);

        while (reader.Read())
        {
            Console.WriteLine(reader.ReadOuterXml());
        }
    }
示例#9
0
    static void Main()
    {
        // Create an XmlUrlResolver with default credentials.
        XmlUrlResolver resolver = new XmlUrlResolver();

        resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;

        // Point the resolver at the desired resource and resolve as a stream.
        Uri    baseUri = new Uri("http://serverName/");
        Uri    fulluri = resolver.ResolveUri(baseUri, "fileName.xml");
        Stream s       = (Stream)resolver.GetEntity(fulluri, null, typeof(Stream));

        // Create the reader with the resolved stream and display the data.
        XmlReader reader = XmlReader.Create(s);

        while (reader.Read())
        {
            Console.WriteLine(reader.ReadOuterXml());
        }
    }
        private Stream GetAtomResultsStream(string serverName, string relativeUri)
        {
            XNamespace a = atomNameSpace;

            //I'm using the XMLUrlResolver to pass credentials to the web service
            XmlUrlResolver resolver = new XmlUrlResolver();

            resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;

            //Build the URI to pass the the resolver
            Uri baseUri = new Uri("http://" + serverName);
            Uri fullUri = resolver.ResolveUri(baseUri, relativeUri);

            //Let's display where we're going
            lblUrl.Text = fullUri.ToString();

            //Call the resolver and receive the ATOM feed as a result
            Stream s = (Stream)resolver.GetEntity(fullUri, null, typeof(Stream));

            return(s);
        }
示例#11
0
 public JResult resolve(string href, string base1)
 {
     try {
         uri = res.ResolveUri(new Uri(base1), href);
         if (serialized)
         {
             stringWriter = new java.io.StringWriter();
             javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(stringWriter);
             result.setSystemId(uri.ToString());
             return(result);
         }
         else
         {
             destination = new XdmDestination();
             ((XdmDestination)destination).BaseUri = uri;
             return(destination.GetReceiver(proc.Implementation.makePipelineConfiguration()));
         }
     } catch (Exception e) {
         throw e;
     }
 }
        static void Main(string[] args)
        {
            //This example gets all the Tables in the specified spreadsheet and lists them
            //Note: Check that the Excel Services service application is running before you run this example

            //Get a reference to the atom namespace
            XNamespace atomNS = atomNameSpace;
            //build the relative Url to the excel workbook model
            string relativeUrl = "/_vti_bin/ExcelRest.aspx/" + docLibrary + "/" + spreadsheetFileName + "/model/Tables";
            //Use an XMLUrlResolver object to pass credentials to the REST service
            XmlUrlResolver resolver = new XmlUrlResolver();

            resolver.Credentials = CredentialCache.DefaultCredentials;
            //Build the URI to pass the the resolver
            Uri baseUri = new Uri(sharepointSite);
            Uri fullUri = resolver.ResolveUri(baseUri, relativeUrl);

            //Tell the user what the stream address is
            Console.WriteLine("Opening this stream: " + fullUri.ToString());
            //Call the resolver and receive the ATOM feed as a result
            Stream atomStream = (Stream)resolver.GetEntity(fullUri, null, typeof(Stream));
            //Load the stream into an XDocument
            XDocument atomResults = XDocument.Load(atomStream);
            //Query the XDocument for all title elements that are children of an entry element
            IEnumerable <XElement> tables =
                from t in atomResults.Descendants(atomNS + "title")
                where t.Parent.Name == atomNS + "entry"
                select t;

            Console.WriteLine("Tables in the spreadsheet " + spreadsheetFileName + ":");
            //Display each of the table
            foreach (XElement table in tables)
            {
                Console.WriteLine((string)table);
            }
            //This line prevents the console disappearing before you can read the result
            //Alternatively, remove this line a run the project without debugging (CTRL-F5)
            Console.ReadKey();
        }
示例#13
0
            public net.sf.saxon.om.SequenceIterator resolve(string href, string baseStr, net.sf.saxon.expr.XPathContext context)
            {
                try {
                    List <Uri> docs;
                    if (href == null)
                    {
                        docs = (List <Uri>)collections[new Uri("http://www.saxonica.com/defaultCollection")];
                    }
                    else
                    {
                        XmlUrlResolver res = new XmlUrlResolver();
                        Uri            abs = res.ResolveUri(new Uri(baseStr), href);
                        try
                        {
                            docs = (List <Uri>)collections[abs];
                        }
                        catch (Exception) {
                            docs = null;
                        }
                    }
                    if (docs == null)
                    {
                        return(net.sf.saxon.tree.iter.EmptyIterator.getInstance());
                    }
                    else
                    {
                        java.util.List list = new java.util.ArrayList();
                        foreach (Uri uri in docs)
                        {
                            list.add(new net.sf.saxon.value.AnyURIValue(uri.ToString()));
                        }

                        return(new net.sf.saxon.tree.iter.ListIterator(list));
                    }
                } catch (java.net.URISyntaxException e) {
                    System.Console.WriteLine("** Invalid Uri: " + e.Message);
                    return(net.sf.saxon.tree.iter.EmptyIterator.getInstance());
                }
            }
示例#14
0
 public net.sf.saxon.om.SequenceIterator resolve(string href, string baseStr, net.sf.saxon.expr.XPathContext context)  {
     try {
         List<Uri> docs;
         if (href == null) {
             docs = (List<Uri>)collections[new Uri("http://www.saxonica.com/defaultCollection")];
         } else {
             XmlUrlResolver res = new XmlUrlResolver();
             Uri abs= res.ResolveUri(new Uri(baseStr), href);
             docs = (List<Uri>)collections[abs];
         }
         if (docs == null) {
             return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
         } else {
             java.util.List list = new java.util.ArrayList();
             foreach(Uri uri in docs){
                 list.add(new net.sf.saxon.value.AnyURIValue(uri.ToString()));
             }
             
             return new net.sf.saxon.tree.iter.ListIterator(list);
         }
     } catch (java.net.URISyntaxException e) {
         Console.WriteLine("** Invalid Uri: " + e.Message);
         return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
     }
 }
示例#15
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;
        }
示例#16
0
        private static void CreateCollectionUriResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder)
        {
            Dictionary <Uri, List <JItem> > collections = new Dictionary <Uri, List <JItem> >();
            XmlUrlResolver res = new XmlUrlResolver();

            foreach (XdmItem coll in xpc.Evaluate("collection", env))
            {
                String collectionURI = ((XdmNode)coll).GetAttributeValue(new QName("uri"));
                if (collectionURI == null)
                {
                    collectionURI = "";
                }
                Uri u;
                try {
                    u = new Uri(collectionURI);
                } catch (Exception e) {
                    driver.println("**** Invalid collection URI " + collectionURI);
                    break;
                }
                if (!collectionURI.Equals("") && !u.IsAbsoluteUri)
                {
                    u             = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI);
                    collectionURI = u.ToString();
                }
                List <JItem> docs = new List <JItem>();
                foreach (XdmItem source in xpc.Evaluate("source", coll))
                {
                    String href = ((XdmNode)source).GetAttributeValue(new QName("file"));
                    String frag = null;
                    int    hash = href.IndexOf('#');
                    if (hash > 0)
                    {
                        frag = href.Substring(hash + 1);
                        href = href.Substring(0, hash);
                    }
                    FileStream file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
                    // String id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
                    String uriStr = res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri;
                    builder.BaseUri = new Uri(uriStr);
                    XdmNode doc = builder.Build(file);
                    if (frag != null)
                    {
                        XdmNode selected = (XdmNode)environment.xpathCompiler.EvaluateSingle("id('" + frag + "')", doc);
                        if (selected == null)
                        {
                            driver.println("**** Fragment not found: " + frag);
                            break;
                        }
                        docs.Add(selected.Implementation);
                    }
                    else
                    {
                        docs.Add(new JAnyURIValue(doc.DocumentUri.ToString()));
                    }
                    environment.sourceDocs.Add(uriStr, doc);
                }
                try {
                    collections.Add(new Uri(collectionURI), docs);
                } catch (Exception e) {
                    driver.println("**** Invalid collection URI " + collectionURI);
                }
            }
            if (collections.Count != 0)
            {
                /*  environment.processor.Implementation.setCollectionURIResolver(
                 *        new CollectionURIResolver() {
                 *            public SequenceIterator resolve(String href, String base, XPathContext context) throws XPathException {
                 *                try {
                 *                    List<? extends Item> docs;
                 *                    if (href == null || base == null) {
                 *                        docs = collections.get(new URI(""));
                 *                    } else {
                 *                        URI abs = new URI(base).resolve(href);
                 *                        docs = collections.get(abs);
                 *                    }
                 *                    if (docs == null) {
                 *                        throw new XPathException("Collection URI not known", "FODC0002");
                 *                        //driver.println("** Collection URI " + href + " not known");
                 *                        //return EmptyIterator.getInstance();
                 *                    } else {
                 *                        return new ListIterator(docs);
                 *                    }
                 *                } catch (URISyntaxException e) {
                 *                    driver.println("** Invalid URI: " + e.getMessage());
                 *                    return EmptyIterator.getInstance();
                 *                }
                 *            }
                 *        }
                 * );*/
            }
        }
示例#17
0
        private static void LoadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder, SchemaManager manager, bool validateSources)
        {
            XmlUrlResolver res = new XmlUrlResolver();

            foreach (XdmItem source in xpc.Evaluate("source", env))
            {
                XdmNode doc = null;

                String uri  = ((XdmNode)source).GetAttributeValue(new QName("uri"));
                String mime = ((XdmNode)source).GetAttributeValue(new QName("media-type"));
                if (mime != null && "application/xml".Equals(mime))
                {
                    continue;
                }
                String validation = ((XdmNode)source).GetAttributeValue(new QName("", "validation"));
                if (validation == null)
                {
                    validation = "skip";
                }
                String streaming = ((XdmNode)source).GetAttributeValue(new QName("", "streaming"));
                if (!validateSources && validation.Equals("skip"))
                {
                    builder.SchemaValidationMode = SchemaValidationMode.None;
                }
                else
                {
                    SchemaValidator validator = manager.NewSchemaValidator();
                    if ("lax".Equals(validation))
                    {
                        validator.IsLax = true;
                        builder.SchemaValidationMode = SchemaValidationMode.Lax;
                    }
                    else
                    {
                        builder.SchemaValidationMode = SchemaValidationMode.Strict;
                    }
                    environment.xpathCompiler.SchemaAware  = true;
                    environment.xqueryCompiler.SchemaAware = true;
                    if (environment.xsltCompiler != null)
                    {
                        environment.xsltCompiler.SchemaAware = true;
                    }
                }

                String role = ((XdmNode)source).GetAttributeValue(new QName("role"));
                String href = ((XdmNode)source).GetAttributeValue(new QName("file"));
                if ("true".Equals(streaming))
                {
                    if (".".Equals(role))
                    {
                        if (href == null)
                        {
                            environment.streamedContent = xpc.Evaluate("string(content)", source).ToString();
                        }
                        else
                        {
                            environment.streamedPath = res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath;
                        }
                    }
                    else
                    {
                        try
                        {
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri);
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).ToString());
                            environment.streamedSecondaryDocs.Add(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri, validation);
                        }catch (Exception) {}
                    }
                }
                else
                {
                    Stream ss;

                    /*if (uri != null) {
                     *  uri = res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri;
                     * }*/
                    if (href != null)
                    {
                        Uri        fileLoc = res.ResolveUri(((XdmNode)env).BaseUri, href);
                        FileStream file    = null;
                        if (fileLoc.Scheme.Equals("file"))
                        {
                            file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
                            if (uri == null)
                            {
                                uri = fileLoc.AbsoluteUri;
                            }
                        }
                        try {
                            ss = (file == null ? new FileStream(fileLoc.ToString(), FileMode.Open, FileAccess.Read)
                                           : file);

                            builder.BaseUri = ((XdmNode)env).BaseUri;
                        } catch (java.io.FileNotFoundException e) {
                            driver.println("*** failed to find source document " + href + ", Exception:" + e.Message);
                            continue;
                        }
                    }
                    else
                    {
                        // content is inline in the catalog
                        if (uri == null)
                        {
                            uri = ((XdmNode)env).BaseUri.AbsolutePath;
                        }
                        string content   = xpc.Evaluate("string(content)", source).ToString();
                        byte[] byteArray = Encoding.ASCII.GetBytes(content);
                        ss = new MemoryStream(byteArray);
                        builder.BaseUri = ((XdmNode)env).BaseUri;
                    }


                    try {
                        builder.BaseUri = new Uri(res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri);
                        doc             = builder.Build(ss);
                        environment.sourceDocs.Add(uri, doc);
                    } catch (Exception e) {
                        driver.println("*** failed to build source document " + href + ", Exception:" + e.Message);
                    }

                    XdmItem selectedItem = doc;
                    String  select       = ((XdmNode)source).GetAttributeValue(new QName("select"));
                    if (select != null)
                    {
                        XPathSelector selector = environment.xpathCompiler.Compile(select).Load();
                        selector.ContextItem = selectedItem;
                        selectedItem         = selector.EvaluateSingle();
                    }


                    if (role != null)
                    {
                        if (".".Equals(role))
                        {
                            environment.contextItem = selectedItem;
                        }
                        else if (role.StartsWith("$"))
                        {
                            String varName = role.Substring(1);
                            environment.params1.Add(new QName(varName), selectedItem);
                            environment.xpathCompiler.DeclareVariable(new QName(varName));
                            environment.paramDeclarations.append("declare variable $" + varName + " external; ");
                        }
                    }
                }
                String definesStylesheet = ((XdmNode)source).GetAttributeValue(new QName("defines-stylesheet"));
                if (definesStylesheet != null)
                {
                    definesStylesheet = definesStylesheet.Trim();
                }
                if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet))
                {
                    // try using an embedded stylesheet from the source document
                    try {
                        //environment.xsltExecutable = environment.xsltCompiler.Compile(XdmNode.Wrap(JPreparedStylesheet.getAssociatedStylesheet(
                        //        environment.processor.Implementation,
                        //        ((XdmNode) environment.contextItem), null, null, null)));
                        environment.xsltExecutable = environment.xsltCompiler.CompileAssociatedStylesheet(((XdmNode)environment.contextItem));
                    } catch (Exception) {
                        driver.println("*** failed to compile stylesheet referenced in source document " + href);
                    }
                }
            }
        }
示例#18
0
    private static XdmNode getSourceRoot(String src)
    {
        Debug.WriteLine("getting source root node for " + src);

        Uri uri = null;
        try
        {
            XmlUrlResolver resolver = new XmlUrlResolver();
            uri = resolver.ResolveUri(null, src);   //null sets the current location as the resolution base
        }
        catch (UriFormatException e)
        {
            Console.WriteLine("error getting transformation source '" + uri + "': " + e.Message);
        }

        Debug.WriteLine("resolved uri=" + uri.AbsolutePath);

        XdmNode doc = null;
        try
        {
            doc = builder.Build(uri);
        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine("error getting transformation source: " + e.Message);
        }
        catch (XPathException e)
        {
            Console.WriteLine("error getting transformation source: " + e.Message);
        }
        return doc;
    }
示例#19
0
        protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)
        {
            TestOutcome outcome     = new TestOutcome(this);
            string      testName    = testCase.GetAttributeValue(new QName("name"));
            string      testSetName = testCase.Parent.GetAttributeValue(new QName("name"));

            ////
            if (testName.Equals("type-0174"))
            {
                int num = 0;
                System.Console.WriteLine("Test driver" + num);
            }

            ///
            if (exceptionsMap.ContainsKey(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
                return;
            }

            if (exceptionsMap.ContainsKey(testName) || isSlow(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
                return;
            }



            XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase));
            string   spec    = specAtt.ToString();

            Environment env = getEnvironment(testCase, xpath);

            if (env == null)
            {
                resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
                return;
            }

            /*if(testName("environment-variable")) {
             *              EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
             *          public Set<string> getAvailableEnvironmentVariables() {
             *              Set<string> strings = new HashSet<string>();
             *              strings.add("QTTEST");
             *              strings.add("QTTEST2");
             *              strings.add("QTTESTEMPTY");
             *              return strings;
             *          }
             *
             *          public string getEnvironmentVariable(string name) {
             *              if (name.Equals("QTTEST")) {
             *                  return "42";
             *              } else if (name.Equals("QTTEST2")) {
             *                  return "other";
             *              } else if (name.Equals("QTTESTEMPTY")) {
             *                  return "";
             *              } else {
             *                  return null;
             *              }
             *          }
             *      }; //TODO
             *  } */
            //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO

            XdmNode testInput  = (XdmNode)xpath.EvaluateSingle("test", testCase);
            XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput);
            XdmNode pack       = (XdmNode)xpath.EvaluateSingle("package", testInput);


            foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase))
            {
                if (!dependencyIsSatisfied((XdmNode)dep, env))
                {
                    notrun++;
                    resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied");
                    return;
                }
            }

            XsltExecutable sheet = env.xsltExecutable;
            //ErrorCollector collector = new ErrorCollector();
            string         baseOutputURI       = resultsDir + "/results/output.xml";
            ErrorCollector collector           = new ErrorCollector(outcome);
            IList          errorList           = new List <StaticError> ();
            XmlUrlResolver res                 = new XmlUrlResolver();
            string         xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0";

            if (stylesheet != null)
            {
                XsltCompiler compiler = env.xsltCompiler;
                compiler.ErrorList = errorList;
                Uri    hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
                Stream stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
                compiler.BaseUri             = hrefFile;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");

                foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput))
                {
                    String   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                    String   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                    XdmValue value;
                    try {
                        value = xpath.Evaluate(select, null);
                    } catch (Exception e) {
                        Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
                        //throw e;
                        continue;
                    }
                    compiler.SetParameter(new QName(name), value);
                }

                try
                {
                    sheet = compiler.Compile(stream);
                } catch (Exception err) {
                    Console.WriteLine(err.Message);
                    //Console.WriteLine(err.StackTrace);
                    IEnumerator enumerator = errorList.GetEnumerator();
                    bool        checkCur   = enumerator.MoveNext();

                    /*if (checkCur && enumerator.Current != null) {
                     *      outcome.SetException ((Exception)(enumerator.Current));
                     * } else {
                     *      Console.WriteLine ("Error: Unknown exception thrown");
                     * }*/
                    outcome.SetErrorsReported(errorList);

                    //outcome.SetErrorsReported(collector.GetErrorCodes);
                }


                //  compiler.setErrorListener(collector);
            }
            else if (pack != null)
            {
                Uri    hrefFile = res.ResolveUri(pack.BaseUri, pack.GetAttributeValue(new QName("file")));
                Stream stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);

                XsltCompiler compiler = env.xsltCompiler;
                compiler.ErrorList           = errorList;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
                //compiler.setErrorListener(collector);

                try {
                    XsltPackage xpack = compiler.CompilePackage(stream);
                    sheet = xpack.Link();
                } catch (Exception err) {
                    Console.WriteLine(err.Message);
                    IEnumerator enumerator = errorList.GetEnumerator();
                    enumerator.MoveNext();
                    outcome.SetException((Exception)(enumerator.Current));
                    outcome.SetErrorsReported(errorList);
                }
            }

            if (sheet != null)
            {
                XdmItem contextItem     = env.contextItem;
                XdmNode initialMode     = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput);
                XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput);
                XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput);

                QName initialModeName     = GetQNameAttribute(xpath, testInput, "initial-mode/@name");
                QName initialTemplateName = GetQNameAttribute(xpath, testInput, "initial-template/@name");

                if (useXslt30Transformer)
                {
                    try {
                        bool    assertsSerial         = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0;
                        bool    resultAsTree          = env.outputTree;
                        bool    serializationDeclared = env.outputSerialize;
                        XdmNode needsTree             = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput);
                        if (needsTree != null)
                        {
                            resultAsTree = needsTree.StringValue.Equals("yes");
                        }
                        XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput);
                        if (needsSerialization != null)
                        {
                            serializationDeclared = needsSerialization.StringValue.Equals("yes");
                        }
                        bool resultSerialized = serializationDeclared || assertsSerial;

                        if (assertsSerial)
                        {
                            String comment = outcome.GetComment();
                            comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* ");
                            outcome.SetComment(comment);
                        }


                        Xslt30Transformer transformer = sheet.Load30();
                        transformer.InputXmlResolver = env;
                        if (env.unparsedTextResolver != null)
                        {
                            transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver);
                        }

                        Dictionary <QName, XdmValue> caseGlobalParams = GetNamedParameters(xpath, testInput, false, false);
                        Dictionary <QName, XdmValue> caseStaticParams = GetNamedParameters(xpath, testInput, true, false);
                        Dictionary <QName, XdmValue> globalParams     = new Dictionary <QName, XdmValue>(env.params1);

                        foreach (KeyValuePair <QName, XdmValue> entry in caseGlobalParams)
                        {
                            globalParams.Add(entry.Key, entry.Value);
                        }

                        foreach (KeyValuePair <QName, XdmValue> entry in caseStaticParams)
                        {
                            globalParams.Add(entry.Key, entry.Value);
                        }


                        transformer.SetStylesheetParameters(globalParams);

                        if (contextItem != null)
                        {
                            transformer.GlobalContextItem = contextItem;
                        }

                        transformer.MessageListener = collector;

                        transformer.BaseOutputURI = baseOutputURI;

                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                        XdmValue result = null;

                        TextWriter sw = new StringWriter();

                        Serializer serializer = env.processor.NewSerializer();

                        serializer.SetOutputWriter(sw);
                        //serializer.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");

                        OutputResolver          serializingOutput = new OutputResolver(env.processor, outcome, true);
                        net.sf.saxon.Controller controller        = transformer.GetUnderlyingController;

                        controller.setOutputURIResolver(serializingOutput);
                        XmlDestination dest = null;
                        if (resultAsTree)
                        {
                            // If we want non-serialized, we need to accumulate any result documents as trees too
                            controller.setOutputURIResolver(
                                new OutputResolver(env.processor, outcome, false));
                            dest = new XdmDestination();
                        }
                        if (resultSerialized)
                        {
                            dest = serializer;
                        }

                        Stream          src        = null;
                        Uri             srcBaseUri = new Uri("http://uri");
                        XdmNode         srcNode    = null;
                        DocumentBuilder builder2   = env.processor.NewDocumentBuilder();

                        if (env.streamedPath != null)
                        {
                            src        = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read);
                            srcBaseUri = new Uri(env.streamedPath);
                        }
                        else if (env.streamedContent != null)
                        {
                            byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent);
                            src = new MemoryStream(byteArray);                            //, "inlineDoc");
                            builder2.BaseUri = new Uri("http://uri");
                        }
                        else if (initialTemplate == null && contextItem != null)
                        {
                            srcNode = (XdmNode)(contextItem);
                        }

                        if (initialMode != null)
                        {
                            QName name = GetQNameAttribute(xpath, initialMode, "@name");
                            try {
                                if (name != null)
                                {
                                    transformer.InitialMode = name;
                                }
                                else
                                {
                                    controller.getInitialMode();                                       /// has the side effect of setting to the unnamed
                                }
                            } catch (Exception e) {
                                if (e.InnerException is net.sf.saxon.trans.XPathException)
                                {
                                    Console.WriteLine(e.Message);
                                    outcome.SetException(e);
                                    //throw new SaxonApiException(e.getCause());
                                }
                                else
                                {
                                    throw e;
                                }
                            }
                        }
                        if (initialMode != null || initialTemplate != null)
                        {
                            XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode);
                            Dictionary <QName, XdmValue> params1         = GetNamedParameters(xpath, init, false, false);
                            Dictionary <QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true);
                            if (xsltLanguageVersion.Equals("2.0"))
                            {
                                if (!(params1.Count == 0 && tunnelledParams.Count == 0))
                                {
                                    Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0");
                                }
                            }
                            else
                            {
                                transformer.SetInitialTemplateParameters(params1, false);
                                transformer.SetInitialTemplateParameters(tunnelledParams, true);
                            }
                        }


                        if (initialTemplate != null)
                        {
                            QName name = GetQNameAttribute(xpath, initialTemplate, "@name");
                            transformer.GlobalContextItem = contextItem;
                            if (dest == null)
                            {
                                result = transformer.CallTemplate(name);
                            }
                            else
                            {
                                transformer.CallTemplate(name, dest);
                            }
                        }
                        else if (initialFunction != null)
                        {
                            QName      name    = getQNameAttribute(xpath, initialFunction, "@name");
                            XdmValue[] params2 = getParameters(xpath, initialFunction);
                            if (dest == null)
                            {
                                result = transformer.CallFunction(name, params2);
                            }
                            else
                            {
                                transformer.CallFunction(name, params2, dest);
                            }
                        }
                        else
                        {
                            if (dest == null)
                            {
                                if (src != null)
                                {
                                    result = transformer.ApplyTemplates(src, srcBaseUri);
                                }
                                else
                                {
                                    result = transformer.ApplyTemplates(srcNode);
                                }
                            }
                            else
                            {
                                if (src != null)
                                {
                                    transformer.ApplyTemplates(src, dest);
                                }
                                else
                                {
                                    transformer.ApplyTemplates(srcNode, dest);
                                }
                            }
                        }

                        //outcome.SetWarningsReported(collector.getFoundWarnings());
                        if (resultAsTree && !resultSerialized)
                        {
                            result = ((XdmDestination)(dest)).XdmNode;
                        }
                        if (resultSerialized)
                        {
                            outcome.SetPrincipalSerializedResult(sw.ToString());
                        }
                        outcome.SetPrincipalResult(result);

                        if (saveResults)
                        {
                            String s = sw.ToString();
                            // If a transform result is entirely xsl:result-document, then result will be null
                            if (!resultSerialized && result != null)
                            {
                                StringWriter sw2 = new StringWriter();
                                Serializer   se  = env.processor.NewSerializer(sw2);
                                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
                                env.processor.WriteXdmValue(result, se);
                                se.Close();
                                s = sw2.ToString();
                            }
                            // currently, only save the principal result file in the result directory
                            saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                            Dictionary <Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments();
                            foreach (KeyValuePair <Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments)
                            {
                                Uri    key           = entry.Key;
                                String path          = key.AbsolutePath;
                                String serialization = outcome.Serialize(env.processor, entry.Value);

                                saveResultsToFile(serialization, path);
                            }
                        }
                    } catch (Exception err) {
                        //if (err.getCause() is XPathException &&
                        //!((XPathException) err.getCause()).hasBeenReported()) {
                        //System.err.println("Unreported ERROR: " + err.getCause());
                        //}
                        outcome.SetException(err);
                        if (collector.getErrorCodes().Count > 0)
                        {
                            outcome.SetErrorsReported((IList)collector.getErrorCodes());
                        }
                        //Console.WriteLine(err.StackTrace);

                        /*if(err.getErrorCode() == null) {
                         *  int b = 3 + 4;  }
                         * if(err.getErrorCode() != null)
                         * outcome.AddReportedError(err.getErrorCode().getLocalName());
                         * } else {
                         * outcome.SetErrorsReported(collector.getErrorCodes());
                         * }*/
                    }                     /*catch (Exception err) {
                                           *    err.printStackTrace();
                                           *    failures++;
                                           *    resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
                                           *    return;
                                           * }*/
                }
                else
                {
                    try {
                        XsltTransformer transformer = sheet.Load();

                        //transformer.SetURIResolver(env); //TODO
                        if (env.unparsedTextResolver != null)
                        {
                            transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
                        }
                        if (initialTemplate != null)
                        {
                            transformer.InitialTemplate = initialTemplateName;
                        }
                        if (initialMode != null)
                        {
                            transformer.InitialMode = initialModeName;
                        }
                        foreach (XdmItem param in xpath.Evaluate("param", testInput))
                        {
                            string   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                            string   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                            XdmValue value  = xpath.Evaluate(select, null);
                            transformer.SetParameter(new QName(name), value);
                        }
                        if (contextItem != null)
                        {
                            transformer.InitialContextNode = (XdmNode)contextItem;
                        }
                        if (env.streamedPath != null)
                        {
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                        }
                        foreach (QName varName in env.params1.Keys)
                        {
                            transformer.SetParameter(varName, env.params1[varName]);
                        }
                        //transformer.setErrorListener(collector);
                        transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");

                        /*transformer.MessageListener = (new MessageListener() {
                         *  public void message(XdmNode content, bool terminate, SourceLocator locator) {
                         *      outcome.addXslMessage(content);
                         *  }
                         * });*/


                        // Run the transformation twice, once for serialized results, once for a tree.
                        // TODO: we could be smarter about this and capture both

                        // run with serialization
                        StringWriter sw         = new StringWriter();
                        Serializer   serializer = env.processor.NewSerializer(sw);
                        transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true));


                        transformer.Run(serializer);

                        outcome.SetPrincipalSerializedResult(sw.ToString());
                        if (saveResults)
                        {
                            // currently, only save the principal result file
                            saveResultsToFile(sw.ToString(),
                                              resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                        }
                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                        // run without serialization
                        if (env.streamedPath != null)
                        {
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                        }
                        XdmDestination destination = new XdmDestination();
                        transformer.Implementation.setOutputURIResolver(
                            new OutputResolver(env.processor, outcome, false));
                        transformer.Run(destination);

                        //transformer. .transform();
                        outcome.SetPrincipalResult(destination.XdmNode);
                        //}
                    } catch (Exception err) {
                        outcome.SetException(err);
                        //outcome.SetErrorsReported(collector.getErrorCodes());
                        // err.printStackTrace();
                        // failures++;
                        //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
                        //return;
                    }
                }
                XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase);
                if (assertion == null)
                {
                    failures++;
                    resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
                    return;
                }
                XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
                //assertionXPath.setLanguageVersion("3.0");
                bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);
                if (success)
                {
                    if (outcome.GetWrongErrorMessage() != null)
                    {
                        outcome.SetComment(outcome.GetWrongErrorMessage());
                        wrongErrorResults++;
                    }
                    else
                    {
                        successes++;
                    }
                    resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
                }
                else
                {
                    failures++;
                    resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
                }
            }
        }
示例#20
0
		private XmlReader GetXmlReader (string url)
		{
			XmlResolver res = new XmlUrlResolver ();
			Uri uri = res.ResolveUri (null, url);
			Stream s = res.GetEntity (uri, null, typeof (Stream)) as Stream;
			XmlTextReader xtr = new XmlTextReader (uri.ToString (), s);
			xtr.XmlResolver = res;
			XmlValidatingReader xvr = new XmlValidatingReader (xtr);
			xvr.XmlResolver = res;
			xvr.ValidationType = ValidationType.None;
			return xvr;
		}
示例#21
0
        private bool TestAssertion2(XdmNode assertion, SingleResultDoc result, XPathCompiler assertXpc, XPathCompiler catalogXpc, bool debug)
        {
            string tag = assertion.NodeName.LocalName;

            if (tag.Equals("assert-eq"))
            {
                return(assertEq(assertion, result, assertXpc));
            }
            else if (tag.Equals("assert-deep-eq"))
            {
                return(assertDeepEq(assertion, result, assertXpc));
            }
            else if (tag.Equals("assert-permutation"))
            {
                return(assertPermutation(assertion, result, assertXpc));
            }
            else if (tag.Equals("assert-xml"))
            {
                return(assertXml(assertion, result, assertXpc, catalogXpc, debug));
            }
            else if (tag.Equals("serialization-matches"))
            {
                return(AssertSerializationMatches(assertion, result, catalogXpc));
            }
            else if (tag.Equals("assert-serialization-error"))
            {
                return(AssertSerializationError(assertion, result, assertXpc));
            }
            else if (tag.Equals("assert-empty"))
            {
                return(assertEmpty(result.value));
            }
            else if (tag.Equals("assert-count"))
            {
                return(assertCount(assertion, result));
            }
            else if (tag.Equals("assert"))
            {
                return(AssertXPath(assertion, result, assertXpc, debug));
            }
            else if (tag.Equals("assert-string-value"))
            {
                return(AssertstringValue(assertion, result, debug));
            }
            else if (tag.Equals("assert-serialization"))
            {
                return(AssertSerialization(assertion, result, catalogXpc, debug));
            }
            else if (tag.Equals("assert-type"))
            {
                return(AssertType(assertion, result, assertXpc));
            }
            else if (tag.Equals("assert-true"))
            {
                return(AssertTrue(result));
            }
            else if (tag.Equals("assert-false"))
            {
                return(AssertFalse(result));
            }
            else if (tag.Equals("assert-warning"))
            {
                return(AssertWarning());
            }
            else if (tag.Equals("assert-message"))
            {
                XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
                foreach (XdmNode message in xslMessages)
                {
                    if (TestAssertion2(subAssertion, new SingleResultDoc(message, ""), assertXpc, catalogXpc, debug))
                    {
                        return(true);
                    }
                }
                return(false);
            }
            else if (tag.Equals("assert-result-document"))
            {
                XdmNode        subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
                XmlUrlResolver res          = new XmlUrlResolver();
                Uri            uri          = new Uri(driver.getResultsDir() + "/results/output.xml");
                uri = res.ResolveUri(uri, assertion.GetAttributeValue(new QName("uri")));
                SingleResultDoc doc = GetSecondaryResult(uri);
                if (doc == null)
                {
                    System.Console.WriteLine("**** No output document found for " + uri);
                    return(false);
                }
                bool ok = TestAssertion2(subAssertion, doc, assertXpc, catalogXpc, debug);
                if (!ok)
                {
                    System.Console.WriteLine("**** Assertion failed for result-document " + uri);
                }
                return(ok);
            }
            else if (tag.Equals("error"))
            {
                bool b = false;
                try {
                    b = IsException() && compareExpectedError(assertion);
                } catch (Exception) {
                    if (GetException() is StaticError)
                    {
                        string expectedError = assertion.GetAttributeValue(new QName("code"));
                        QName  expectedErrorQ;
                        if (expectedError.Equals("*"))
                        {
                            expectedErrorQ = null;
                        }
                        else if (expectedError.StartsWith("Q{"))
                        {
                            expectedErrorQ = QName.FromEQName(expectedError);
                        }
                        else
                        {
                            expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
                        }

                        JFastStringBuffer fsb = new JFastStringBuffer(100);
                        fsb.append("Expected ");
                        fsb.append(expectedErrorQ.LocalName);
                        fsb.append("; got ");
                        fsb.append("err:XXX");
                        fsb.setLength(fsb.length() - 1);
                        wrongError = fsb.ToString();
                        return(true);
                    }
                    if (GetException() is DynamicError)
                    {
                        string expectedError = assertion.GetAttributeValue(new QName("code"));
                        QName  expectedErrorQ;
                        if (expectedError.Equals("*"))
                        {
                            expectedErrorQ = null;
                        }
                        else if (expectedError.StartsWith("Q{"))
                        {
                            expectedErrorQ = QName.FromEQName(expectedError);
                        }
                        else
                        {
                            expectedErrorQ = new QName("err", JNamespaceConstant.ERR, expectedError);
                        }

                        JFastStringBuffer fsb = new JFastStringBuffer(100);
                        fsb.append("Expected ");
                        fsb.append(expectedErrorQ.LocalName);
                        fsb.append("; got ");
                        fsb.append("err:XXX");
                        fsb.setLength(fsb.length() - 1);
                        wrongError = fsb.ToString();
                        return(true);
                    }
                }
                return(b);
            }
            else if (tag.Equals("all-of"))
            {
                foreach (XdmItem child in catalogXpc.Evaluate("*", assertion))
                {
                    if (!TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug))
                    {
                        return(false);
                    }
                }
                return(true);
            }
            else if (tag.Equals("any-of"))
            {
                bool partialSuccess = false;
                foreach (XdmItem child in catalogXpc.Evaluate("*", assertion))
                {
                    if (TestAssertion((XdmNode)child, result, assertXpc, catalogXpc, debug))
                    {
                        if (wrongError != null)
                        {
                            partialSuccess = true;
                            continue;
                        }
                        return(true);
                    }
                }
                return(partialSuccess);
            }
            else if (tag.Equals("not"))
            {
                XdmNode subAssertion = (XdmNode)catalogXpc.EvaluateSingle("*", assertion);
                return(!TestAssertion(subAssertion, result, assertXpc, catalogXpc, debug));
            }
            throw new Exception("Unknown assertion element " + tag);
        }
示例#22
0
 private bool LoadSchema(string uri) {
     uri = _NameTable.Add(uri);
     if (_SchemaInfo.HasSchema(uri)) {
         return false;
     }
     SchemaInfo schemaInfo = null;
     XmlResolver resolver = new XmlUrlResolver();
     Uri _baseUri = resolver.ResolveUri(null,_reader.BaseURI);
     XmlReader reader = null;
     try {
         
         Uri ruri = resolver.ResolveUri(_baseUri, uri.Substring(x_schema.Length));
         Stream stm = (Stream)resolver.GetEntity(ruri,null,null);
         reader = new XmlTextReader(ruri.ToString(), stm, _NameTable);
         schemaInfo = new SchemaInfo(_SchemaNames);
         new Parser(null, _NameTable, _SchemaNames, validationEventHandler).Parse(reader, uri, schemaInfo);
     }
     catch(XmlException e) {
         SendValidationEvent(Res.Sch_CannotLoadSchema, new string[] {uri, e.Message}, XmlSeverityType.Warning);
         schemaInfo = null;
     }
     finally {
         if (reader != null) {
             reader.Close();
         }
     }
     if (schemaInfo != null && schemaInfo.ErrorCount == 0) {
         _SchemaInfo.Add(uri, schemaInfo, validationEventHandler);
         return true;
     }
     return false;
 }
示例#23
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
         */

        public static Environment processEnvironment(TestRunner.TestDriver driver,
                                                     XPathCompiler xpc, XdmItem env, Dictionary <string, Environment> environments, Environment defaultEnvironment)
        {
            Environment environment = new Environment();
            String      name        = ((XdmNode)env).GetAttributeValue(new QName("name"));

            if (name != null)
            {
                System.Console.WriteLine("Loading environment " + name);
            }
            environment.processor = new Processor(true);
            if (defaultEnvironment != null)
            {
                environment.processor.SetProperty(JFeatureKeys.XSD_VERSION,
                                                  defaultEnvironment.processor.Implementation.getConfigurationProperty(JFeatureKeys.XSD_VERSION).ToString());
            }
            // AutoActivate.activate(environment.processor);
            if (driver.GenerateByteCode == 1)
            {
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
            }
            else if (driver.GenerateByteCode == 2)
            {
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
                //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
            }
            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.AbsolutePath;
            if (driver.Spec.ToString().Contains("XT"))
            {
                environment.xsltCompiler = environment.processor.NewXsltCompiler();
                environment.xsltCompiler.XsltLanguageVersion = ((SpecAttr)(driver.Spec.GetAttr())).version;
            }
            if (driver.Unfolded)
            {
                // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
            }
            DocumentBuilder builder = environment.processor.NewDocumentBuilder();

            builder.TreeModel      = driver.TreeModel;
            environment.sourceDocs = new Dictionary <string, XdmNode>();
            if (environments != null && name != null)
            {
                try
                {
                    environments.Add(name, environment);
                }
                catch (Exception) { }
            }
            foreach (XdmItem dependency in xpc.Evaluate("dependency", env))
            {
                if (!driver.dependencyIsSatisfied((XdmNode)dependency, environment))
                {
                    environment.usable = false;
                }
            }

            // set the base URI if specified

            SetBaseUri(driver, xpc, env, environment);

            // set any requested collations

            RegisterCollations(xpc, env, environment);

            // declare the requested namespaces

            DeclareNamespaces(xpc, env, environment);

            // load the requested schema documents

            SchemaManager manager         = environment.processor.SchemaManager;
            bool          validateSources = LoadSchemaDocuments(xpc, env, manager);

            // load the requested source documents

            LoadSourceDocuments(driver, xpc, env, environment, builder, manager, validateSources);

            // create a collection URI resolver to handle the requested collections

            CreateCollectionUriResolver(driver, xpc, env, environment, builder);

            // create an unparsed text resolver to handle any unparsed text resources

            CreateUnparsedTextResolver(driver, xpc, env, environment);

            // register any required decimal formats

            // registerDecimalFormats(driver, xpc, env, environment);

            // declare any variables

            DeclareExternalVariables(driver, xpc, env, environment);

            // declare any output controls
            DeclareOutputControls(driver, xpc, env, environment);

            // handle requested context item
            foreach (XdmItem param in xpc.Evaluate("context-item", env))
            {
                String   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                XdmValue value  = xpc.Evaluate(select, null);
                environment.contextItem = (XdmItem)value;
            }

            XmlUrlResolver res = new XmlUrlResolver();
            // compile any stylesheet defined as part of the environment (only one allowed)
            DocumentBuilder builder1 = environment.processor.NewDocumentBuilder();

            foreach (XdmItem stylesheet in xpc.Evaluate("stylesheet[not(@role='secondary')]", env))
            {
                string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
                try
                {
                    XdmNode styleSource = builder1.Build(res.ResolveUri(((XdmNode)env).BaseUri, fileName));
                    environment.xsltExecutable = environment.xsltCompiler.Compile(styleSource);
                }
                catch (Exception e)
                {
                    driver.println("**** failure while compiling environment-defined stylesheet " + fileName);
                }
            }


            // compile any stylesheet packages defined as part of the environment
            // Support this only in EE - an unusable environment in PE/HE
            foreach (XdmItem stylesheet in xpc.Evaluate("package[@role='secondary']", env))
            {
                if (!"EE".Equals(environment.processor.Edition))
                {
                    environment.usable = false;
                    break;
                }
                string     fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
                Uri        uri      = res.ResolveUri(((XdmNode)env).BaseUri, fileName);
                FileStream file     = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
                try
                {
                    XsltPackage pkg = environment.xsltCompiler.CompilePackage(file);
                    environment.xsltCompiler.ImportPackage(pkg);
                }
                catch (Exception e)
                {
                    //e.printStackTrace();
                    driver.println("**** failure while compiling environment-defined stylesheet package " + fileName);
                    driver.println("****Failure " + e.Message + " in compiling environment " + name);
                    environment.usable = false;
                }
            }

            return(environment);
        }
示例#24
0
        protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)
        {
            TestOutcome outcome     = new TestOutcome(this);
            string      testName    = testCase.GetAttributeValue(new QName("name"));
            string      testSetName = testCase.Parent.GetAttributeValue(new QName("name"));

            ////
            if (testName.Equals("type-0174"))
            {
                int num = 0;
                System.Console.WriteLine("Test driver" + num);
            }

            ///
            if (exceptionsMap.ContainsKey(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
                return;
            }

            if (exceptionsMap.ContainsKey(testName) || isSlow(testName))
            {
                notrun++;
                resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
                return;
            }



            XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase));
            string   spec    = specAtt.ToString();

            Environment env = getEnvironment(testCase, xpath);

            if (env == null)
            {
                resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
                return;
            }

            /*if(testName("environment-variable")) {
             *              EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
             *          public Set<string> getAvailableEnvironmentVariables() {
             *              Set<string> strings = new HashSet<string>();
             *              strings.add("QTTEST");
             *              strings.add("QTTEST2");
             *              strings.add("QTTESTEMPTY");
             *              return strings;
             *          }
             *
             *          public string getEnvironmentVariable(string name) {
             *              if (name.Equals("QTTEST")) {
             *                  return "42";
             *              } else if (name.Equals("QTTEST2")) {
             *                  return "other";
             *              } else if (name.Equals("QTTESTEMPTY")) {
             *                  return "";
             *              } else {
             *                  return null;
             *              }
             *          }
             *      }; //TODO
             *  } */
            //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO

            XdmNode testInput  = (XdmNode)xpath.EvaluateSingle("test", testCase);
            XdmNode stylesheet = (XdmNode)xpath.EvaluateSingle("stylesheet", testInput);


            foreach (XdmItem dep in xpath.Evaluate("(/test-set/dependencies/*, ./dependencies/*)", testCase))
            {
                if (!dependencyIsSatisfied((XdmNode)dep, env))
                {
                    notrun++;
                    resultsDoc.writeTestcaseElement(testName, "notRun", "dependency not satisfied");
                    return;
                }
            }

            XsltExecutable sheet = env.xsltExecutable;
            //ErrorCollector collector = new ErrorCollector();
            XmlUrlResolver res = new XmlUrlResolver();

            if (stylesheet != null)
            {
                XsltCompiler compiler = env.xsltCompiler;
                Uri          hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
                Stream       stream   = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
                compiler.BaseUri             = hrefFile;
                compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
                try
                {
                    sheet = compiler.Compile(stream);
                } catch (Exception err) {
                    outcome.SetException(err);

                    //outcome.SetErrorsReported(collector.GetErrorCodes);
                }


                //  compiler.setErrorListener(collector);
            }

            if (sheet != null)
            {
                XdmItem contextItem     = env.contextItem;
                QName   initialMode     = getQNameAttribute(xpath, testInput, "initial-mode/@name");
                QName   initialTemplate = getQNameAttribute(xpath, testInput, "initial-template/@name");

                try {
                    XsltTransformer transformer = sheet.Load();

                    //transformer.SetURIResolver(env); //TODO
                    if (env.unparsedTextResolver != null)
                    {
                        transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
                    }
                    if (initialTemplate != null)
                    {
                        transformer.InitialTemplate = initialTemplate;
                    }
                    if (initialMode != null)
                    {
                        transformer.InitialMode = initialMode;
                    }
                    foreach (XdmItem param in xpath.Evaluate("param", testInput))
                    {
                        string   name   = ((XdmNode)param).GetAttributeValue(new QName("name"));
                        string   select = ((XdmNode)param).GetAttributeValue(new QName("select"));
                        XdmValue value  = xpath.Evaluate(select, null);
                        transformer.SetParameter(new QName(name), value);
                    }
                    if (contextItem != null)
                    {
                        transformer.InitialContextNode = (XdmNode)contextItem;
                    }
                    if (env.streamedPath != null)
                    {
                        transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                    }
                    foreach (QName varName in env.params1.Keys)
                    {
                        transformer.SetParameter(varName, env.params1[varName]);
                    }
                    //transformer.setErrorListener(collector);
                    transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");

                    /*transformer.MessageListener = (new MessageListener() {
                     *  public void message(XdmNode content, bool terminate, SourceLocator locator) {
                     *      outcome.addXslMessage(content);
                     *  }
                     * });*/


                    // Run the transformation twice, once for serialized results, once for a tree.
                    // TODO: we could be smarter about this and capture both

                    // run with serialization
                    StringWriter sw         = new StringWriter();
                    Serializer   serializer = env.processor.NewSerializer(sw);
                    transformer.Implementation.setOutputURIResolver(new OutputResolver(driverProc, outcome, true));


                    transformer.Run(serializer);

                    outcome.SetPrincipalSerializedResult(sw.ToString());
                    if (saveResults)
                    {
                        // currently, only save the principal result file
                        saveResultsToFile(sw.ToString(),
                                          resultsDir + "/results/" + testSetName + "/" + testName + ".out");
                    }
                    transformer.MessageListener = new TestOutcome.MessageListener(outcome);

                    // run without serialization
                    if (env.streamedPath != null)
                    {
                        transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
                    }
                    XdmDestination destination = new XdmDestination();
                    transformer.Implementation.setOutputURIResolver(
                        new OutputResolver(env.processor, outcome, false));
                    transformer.Run(destination);

                    //transformer. .transform();
                    outcome.SetPrincipalResult(destination.XdmNode);
                    //}
                } catch (Exception err) {
                    outcome.SetException(err);
                    //outcome.SetErrorsReported(collector.getErrorCodes());
                    // err.printStackTrace();
                    // failures++;
                    //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
                    //return;
                }
            }
            XdmNode assertion = (XdmNode)xpath.EvaluateSingle("result/*", testCase);

            if (assertion == null)
            {
                failures++;
                resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
                return;
            }
            XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
            //assertionXPath.setLanguageVersion("3.0");
            bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);

            if (success)
            {
                if (outcome.GetWrongErrorMessage() != null)
                {
                    outcome.SetComment(outcome.GetWrongErrorMessage());
                    wrongErrorResults++;
                }
                else
                {
                    successes++;
                }
                resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
            }
            else
            {
                failures++;
                resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
            }
        }
示例#25
0
文件: xmldsig.cs 项目: nlhepler/mono
	static TextReader GetReader (string filename)
	{
		XmlResolver resolver = new XmlUrlResolver ();
		Stream stream = resolver.GetEntity (resolver.ResolveUri (null, filename), null, typeof (Stream)) as Stream;
		if (useDecentReader)
			return new XmlSignatureStreamReader (
				new StreamReader (stream));
		else
			return new StreamReader (stream);
	}