Esempio n. 1
0
    /// <summary>
    /// Run the transformation
    /// </summary>
    /// <param name="testName"></param>
    /// <param name="xml"></param>
    /// <param name="xsl"></param>
    /// <param name="initialMode"></param>
    /// <param name="initialTemplate"></param>
    /// <param name="outfile"></param>
    /// <param name="paramTable"></param>
    /// <param name="initialContextPath"></param>
    /// <param name="useAssociated"></param>
    /// <param name="schemaAware"></param>
    /// <param name="validationMode"></param>
    /// <param name="recoverRecoverable"></param>
    /// <returns>Either null, indicating success, or an Exception object with information about the failure</returns>

    protected Exception runXSLT(String testName, String xml, String xsl, QName initialMode,
                                QName initialTemplate, String outfile, Hashtable paramTable, String initialContextPath,
                                bool useAssociated, bool schemaAware,
                                String validationMode, bool recoverRecoverable)
    {
        Serializer sr = new Serializer();

        sr.SetOutputFile(outfile);
        Processor f;

        if (noCacheTests.ContainsKey(testName))
        {
            //create a custom Processor to avoid schema caching
            f = new Processor(true);
        }
        else if (schemaAware)
        {
            f = schemaAwareProcessor;
            if (f == null)
            {
                return(new DynamicError("Saxon-SA not available"));
            }
        }
        else if (xml11)
        {
            f = processor;
            // Use an Xml 1.1 processor
        }
        else
        {
            f = processor;
        }


        XdmNode source = null;

        IList        errors   = new ArrayList();
        XsltCompiler compiler = f.NewXsltCompiler();

        compiler.SchemaAware = schemaAware;
        compiler.ErrorList   = errors;
        XsltExecutable  sheet = null;
        XsltTransformer inst;

        if (useAssociated)
        {
            try
            {
                source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to build source document: " + e.Message);
                return(e);
            }
            try
            {
                sheet = compiler.CompileAssociatedStylesheet(source);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to compile stylesheet: " + e.Message);
                if (errors.Count > 0)
                {
                    return((Exception)errors[0]);
                    //QName code = ((StaticError)errors[0]).ErrorCode;
                    //(code == null ? "Failed to compile stylesheet: " + e.Message : code.LocalName);
                }
                else
                {
                    return(e);
                }
            }
        }
        else
        {
            Stream stream = new FileStream(xsl, FileMode.Open, FileAccess.Read);
            compiler.BaseUri = new Uri(xsl);
            try
            {
                sheet = compiler.Compile(stream);
            }
            catch (Exception e)
            {
                if (errors.Count > 0)
                {
                    return((StaticError)errors[0]);
                }
                else
                {
                    Console.WriteLine(e.Message);
                    return(e);
                }
            }
            finally
            {
                stream.Close();
            }
        }
        if (initialContextPath != null)
        {
            if (source == null && xml != null)
            {
                try
                {
                    source = buildSource(f.NewDocumentBuilder(), xml, validationMode);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to build source document: " + e.Message);
                    return(e);
                }
            }

            XPathCompiler   xc  = f.NewXPathCompiler();
            XPathExecutable exp = xc.Compile(initialContextPath);
            XPathSelector   xpe = exp.Load();
            xpe.ContextItem = source;
            XdmNode node = (XdmNode)xpe.EvaluateSingle();
            source = node;
        }

        inst = sheet.Load();
        if (source != null)
        {
            inst.InitialContextNode = source;
        }

        if (source == null && xml != null)
        {
            Stream stream = new FileStream(xml, FileMode.Open, FileAccess.Read);
            inst.SetInputStream(stream, new Uri(xml));
        }


        if (initialMode != null)
        {
            inst.InitialMode = initialMode;
        }
        if (initialTemplate != null)
        {
            try
            {
                inst.InitialTemplate = initialTemplate;
            }
            catch (DynamicError e)
            {
                return(e);
            }
        }
        if (paramTable != null)
        {
            foreach (DictionaryEntry de in paramTable)
            {
                inst.SetParameter((QName)de.Key, new XdmAtomicValue(de.Value.ToString()));
            }
        }

        inst.BaseOutputUri  = new Uri(outfile);
        inst.RecoveryPolicy = recoverRecoverable ? RecoveryPolicy.RecoverSilently : RecoveryPolicy.DoNotRecover;

        if ("strict" == validationMode)
        {
            inst.SchemaValidationMode = SchemaValidationMode.Strict;
        }
        else
        {
            inst.SchemaValidationMode = SchemaValidationMode.None;
        }

        //inst.setURIResolver(factory.getURIResolver());
        //inst.setErrorListener(errorListener);
        //((Controller)inst).setRecoveryPolicy(recoverRecoverable ? Configuration.RECOVER_SILENTLY : Configuration.DO_NOT_RECOVER);
        // To avoid test results being dependent on the date and time (and timezone), set a fixed
        // date and time for the run
        //((Controller)inst).setCurrentDateTime(new DateTimeValue("2005-01-01T12:49:30.5+01:00"));

        try
        {
            inst.Run(sr);
        }
        catch (DynamicError e)
        {
            Console.WriteLine(e.Message);
            return(e);
        }
        return(null);    // indicating success
    }
Esempio n. 2
0
        /////// <summary>
        /////// Schematron validates a document.
        ///////
        /////// If the validation process fails it throws a SchematronValidationFailedException If the
        /////// document has any schematron errors it throws a SchematronErrorException
        /////// </summary>
        /////// <param name="document">The document to be validated</param>
        /////// <param name="schematronStylesheet"></param>
        ////public void SchematronValidateXmlDocument(XmlDocument document, CompiledXslt compiledXsltEntry)
        ////{
        ////    if (this.errorXPath == null)
        ////    {
        ////        throw new Exception("No error XPath is set");
        ////    }
        ////    if (this.errorMessageXPath == null)
        ////    {
        ////        throw new Exception("No error message XPath is set");
        ////    }

        ////    XmlDocument result = null;
        ////    PrefixedNamespace[] prefixedNamespaces;
        ////    bool hasAnyErrors;
        ////    try
        ////    {
        ////        // this is fast and ugly...
        ////        result = xlstUtil.TransformXml(document, schematronStylesheet);
        ////        byte[] schematronResultBytes = Encoding.Default.GetBytes(result.OuterXml);
        ////        using (MemoryStream schematronResultMemoryStream = new MemoryStream(schematronResultBytes))
        ////        {
        ////            XmlTextReader schematronResultXmlTextReader = new XmlTextReader(schematronResultMemoryStream);
        ////            prefixedNamespaces = this.CreateDefaultNamespaceManager(schematronResultXmlTextReader);
        ////            hasAnyErrors = DocumentXPathResolver.HasAnyElementsByXpath(result, this.errorXPath, prefixedNamespaces);
        ////        }
        ////    }
        ////    catch (Exception ex)
        ////    {
        ////        throw new SchematronValidationFailedException(document, ex);
        ////    }

        ////    if (hasAnyErrors)
        ////    {
        ////        string firstErrorMessage = DocumentXPathResolver.GetFirstElementValueByXPath(result, this.errorMessageXPath, prefixedNamespaces);
        ////        throw new SchematronErrorException(result, firstErrorMessage);
        ////    }
        ////    else
        ////    {
        ////        // no schematron error
        ////    }
        ////}

        /// <summary>
        /// Schematron validates a document.
        ///
        /// If the validation process fails it throws a SchematronValidationFailedException If the
        /// document has any schematron errors it throws a SchematronErrorException
        /// </summary>
        /// <param name="documentAsString">The document to be validated</param>
        /// <param name="compiledXslt"></param>
        public void SchematronValidateXmlDocument(string documentAsString, CompiledXslt compiledXslt)
        {
            if (this.errorXPath == null)
            {
                throw new Exception("No error XPath is set");
            }
            if (this.errorMessageXPath == null)
            {
                throw new Exception("No error message XPath is set");
            }

            XmlDocument schematronResultXmlDocument = null;

            PrefixedNamespace[] prefixedNamespaces = null;
            bool hasAnyErrors      = false;
            bool documentValidated = false;

            //// try
            ////{
            ////    result = xlstUtil.TransformXml(documentAsString, schematronStylesheet);
            ////    hasAnyErrors = DocumentXPathResolver.HasAnyElementsByXpath(result, this.errorXPath, prefixedNamespaces);
            ////}
            ////catch (Exception ex)
            ////{
            ////    XmlDocument xmlDoc = new XmlDocument();
            ////    xmlDoc.LoadXml(documentAsString);
            ////    throw new SchematronValidationFailedException(xmlDoc, ex);
            ////}

            ////if (hasAnyErrors)
            ////{
            ////    string firstErrorMessage = DocumentXPathResolver.GetFirstElementValueByXPath(result, this.errorMessageXPath, prefixedNamespaces);
            ////    throw new SchematronErrorException(result, firstErrorMessage);
            ////}
            ////else
            ////{
            ////    // no schematron error
            ////}
            // ---------
            try
            {
                // .Net build in xslt pserser - only xslt 1.0
                if (compiledXslt != null && compiledXslt.XslCompiledTransform != null)
                {
                    schematronResultXmlDocument = xlstUtil.TransformXml(documentAsString, compiledXslt.XslCompiledTransform);
                    byte[] schematronResultBytes = Encoding.Default.GetBytes(schematronResultXmlDocument.OuterXml);
                    using (MemoryStream schematronResultMemoryStream = new MemoryStream(schematronResultBytes))
                    {
                        XmlTextReader schematronResultXmlTextReader = new XmlTextReader(schematronResultMemoryStream);
                        prefixedNamespaces = this.CreateDefaultNamespaceManager(schematronResultXmlTextReader);

                        hasAnyErrors      = DocumentXPathResolver.HasAnyElementsByXpath(schematronResultXmlDocument, this.errorXPath, prefixedNamespaces);
                        documentValidated = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.Message);
            }

            if (documentValidated == false)
            {
                // Not xslt 1.0, or complex xslt 1.0  - so try Saxon xslt
                try
                {
                    using (MemoryStream schematronResultMemoryStream = new MemoryStream())
                    {
                        using (MemoryStream xmlSchematronStylesheetMemoryStream = compiledXslt.Stream)
                        {
                            xmlSchematronStylesheetMemoryStream.Flush();//Adjust this if you want read your data
                            xmlSchematronStylesheetMemoryStream.Position = 0;

                            Processor    processor = new Processor();
                            XsltCompiler compiler  = processor.NewXsltCompiler();
                            Uri          uri       = new Uri("file://" + compiledXslt.FileInfo.Directory.FullName);
                            compiler.ErrorList = new List <object>();
                            compiler.BaseUri   = uri;
                            Serializer serializer = new Serializer();

                            try
                            {
                                XsltTransformer saxonTransformer = compiler.Compile(xmlSchematronStylesheetMemoryStream).Load();

                                // Load the XML document. Input to the build method is the document.
                                DocumentBuilder docBuilder = processor.NewDocumentBuilder();
                                if (docBuilder.BaseUri == null)
                                {
                                    docBuilder.BaseUri = uri;
                                }

                                XdmNode docXdmNode = docBuilder.Build(documentAsString.ToStream());

                                // Set the root node of the source document to be the initial
                                // context node
                                saxonTransformer.InitialContextNode = docXdmNode;

                                // Init. the result object
                                serializer.SetOutputProperty(Serializer.INDENT, "yes");
                                serializer.SetOutputProperty(Serializer.ENCODING, Encoding.UTF8.BodyName);

                                serializer.SetOutputStream(schematronResultMemoryStream);

                                // Run the transformation with result object as input param.
                                saxonTransformer.Run(serializer);
                            }
                            catch (Exception)
                            {
                                // easy debugging
                                throw;
                            }
                            finally
                            {
                                // close/dispose
                                serializer.Close();
                            }
                        }

                        // convert the schematronResultMemoryStream, into a xmlDocument
                        schematronResultMemoryStream.Position = 0;
                        schematronResultXmlDocument           = new XmlDocument();
                        schematronResultXmlDocument.Load(schematronResultMemoryStream);

                        schematronResultMemoryStream.Position = 0;
                        XmlTextReader schematronResultXmlTextReader = new XmlTextReader(schematronResultMemoryStream);
                        prefixedNamespaces = this.CreateDefaultNamespaceManager(schematronResultXmlTextReader);

                        hasAnyErrors      = DocumentXPathResolver.HasAnyElementsByXpath(schematronResultXmlDocument, this.errorXPath, prefixedNamespaces);
                        documentValidated = true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Fail(ex.Message);
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(documentAsString.ToStream());
                    throw new SchematronValidationFailedException(xmlDocument, ex);
                }
            }

            if (documentValidated == false)
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(documentAsString.ToStream());
                throw new SchematronValidationFailedException(xmlDocument, new Exception("Failed to validate the document."));
            }

            if (hasAnyErrors)
            {
                string firstErrorMessage = DocumentXPathResolver.GetFirstElementValueByXPath(schematronResultXmlDocument, this.errorMessageXPath, prefixedNamespaces);
                throw new SchematronErrorException(schematronResultXmlDocument, firstErrorMessage);
            }
            else
            {
                // no schematron error
            }
        }
Esempio n. 3
0
        public static string TransformXml(string xmlData, string xslData)
        {
            string results = "";

            try
            {
                // Saxon Transformation Start
                Processor       xsltProcessor   = new Processor();
                DocumentBuilder documentBuilder = xsltProcessor.NewDocumentBuilder();
                documentBuilder.BaseUri = new Uri("file://");
                XdmNode      xdmNode      = documentBuilder.Build(new StringReader(xmlData));
                XsltCompiler xsltCompiler = xsltProcessor.NewXsltCompiler();

                XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(xslData));

                XsltTransformer xsltTransformer = xsltExecutable.Load();
                xsltTransformer.InitialContextNode = xdmNode;

                XdmDestination xdmDest = new XdmDestination();
                xsltTransformer.Run(xdmDest);
                // Saxon Transformation End


                // Handle XML Declaration
                string version     = "1.0";
                string encoding    = "UTF-8";
                string standalone  = null;
                string declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine;

                try
                {
                    XDocument  xslt = XDocument.Parse(xslData);
                    XNamespace xsl  = "http://www.w3.org/1999/XSL/Transform";
                    XElement   elem = xslt.Root.Element(xsl + "output");

                    if (elem != null)
                    {
                        if (elem.Attribute("version") != null)
                        {
                            version = elem.Attribute("version").Value;
                        }
                        if (elem.Attribute("encoding") != null)
                        {
                            encoding = elem.Attribute("encoding").Value;
                        }
                        if (elem.Attribute("standalone") != null)
                        {
                            standalone = elem.Attribute("standalone").Value;
                        }
                        declaration = new XDeclaration(version, encoding, standalone).ToString() + Environment.NewLine;

                        // Clear Declaration
                        if (elem.Attribute("omit-xml-declaration") != null && elem.Attribute("omit-xml-declaration").Value == "yes")
                        {
                            declaration = "";
                        }
                        if (elem.Attribute("method") != null && elem.Attribute("method").Value != "xml")
                        {
                            declaration = "";
                        }
                    }
                    // Attempt to prevent duplicate declaration
                    if (xdmDest.XdmNode.OuterXml.StartsWith("<?"))
                    {
                        declaration = "";
                    }
                }
                catch
                {
                    // ignore exception
                }
                results = declaration + xdmDest.XdmNode.OuterXml;
            }
            catch (Exception e)
            {
                throw e;
            }
            return(results);
        }
Esempio n. 4
0
        static bool[] FunctionsAvailable(QName[] names, Processor processor, XPathItemFactory itemFactory)
        {
            const string xsltNs = "http://www.w3.org/1999/XSL/Transform";

            IXPathNavigable stylesheetDoc = itemFactory.BuildNode();
            XmlWriter       builder       = stylesheetDoc.CreateNavigator().AppendChild();

            builder.WriteStartElement("stylesheet", xsltNs);
            builder.WriteAttributeString("version", "2.0");

            for (int i = 0; i < names.Length; i++)
            {
                QName item = names[i];

                builder.WriteAttributeString("xmlns", "p" + i.ToStringInvariant(), null, item.Uri);
            }

            builder.WriteStartElement("output", xsltNs);
            builder.WriteAttributeString("method", "text");
            builder.WriteEndElement();

            builder.WriteStartElement("template", xsltNs);
            builder.WriteAttributeString("name", "main");

            for (int i = 0; i < names.Length; i++)
            {
                QName item = names[i];

                if (i > 0)
                {
                    builder.WriteElementString("text", xsltNs, "|");
                }

                builder.WriteStartElement("value-of", xsltNs);
                builder.WriteAttributeString("select", "function-available('{0}:{1}')".FormatInvariant("p" + i.ToStringInvariant(), item.LocalName));
                builder.WriteEndElement();
            }

            builder.WriteEndElement(); // template
            builder.WriteEndElement(); // stylesheet

            builder.Close();

            XsltCompiler compiler = processor.NewXsltCompiler();

            compiler.BaseUri     = new Uri("foo:bar");
            compiler.XmlResolver = null;

            XsltTransformer transform = compiler.Compile(stylesheetDoc.CreateNavigator().ReadSubtree()).Load();

            transform.InitialTemplate = new QName("main");

            using (var output = new StringWriter(CultureInfo.InvariantCulture)) {
                var serializer = new Serializer();
                serializer.SetOutputWriter(output);

                transform.Run(serializer);

                return(output.ToString().Trim().Split('|').Select(s => XmlConvert.ToBoolean(s)).ToArray());
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Validates a document
        /// </summary>
        /// <param name="xmlDocument">document to validate</param>
        /// <param name="compiledXslt">stylesheet to use</param>
        public void SchematronValidateXmlDocument(XmlDocument xmlDocument, CompiledXslt compiledXslt)
        {
            if (this.errorXPath == null)
            {
                throw new Exception("No error XPath is set");
            }
            if (this.errorMessageXPath == null)
            {
                throw new Exception("No error message XPath is set");
            }

            bool documentValidated = false;

            PrefixedNamespace[] prefixedNamespaces = null;// = this.CreateDefaultNamespaceManager(xmlTextReader);
            bool        hasAnyErrors = false;
            XmlDocument schematronResultXmlDocument = null;

            // First we try windows build in transformer. It handle xslt 1.0, but not xslt 2.0. Any
            // stylesheet in xslt 2.0 will fail, and some xslt 1.0, as they is too complex for the parser.
            try
            {
                // .Net build in xslt parser - only xslt 1.0

                if (compiledXslt != null && compiledXslt.XslCompiledTransform != null)
                {
                    schematronResultXmlDocument = xlstUtil.TransformXml(xmlDocument, compiledXslt.XslCompiledTransform);
                    byte[] schematronResultBytes = Encoding.Default.GetBytes(schematronResultXmlDocument.OuterXml);
                    using (MemoryStream schematronResultMemoryStream = new MemoryStream(schematronResultBytes))
                    {
                        XmlTextReader schematronResultXmlTextReader = new XmlTextReader(schematronResultMemoryStream);
                        prefixedNamespaces = this.CreateDefaultNamespaceManager(schematronResultXmlTextReader);

                        hasAnyErrors      = DocumentXPathResolver.HasAnyElementsByXpath(schematronResultXmlDocument, this.errorXPath, prefixedNamespaces);
                        documentValidated = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.Fail(ex.Message);
            }

            if (documentValidated == false)
            {
                // Not xslt 1.0, or complex xslt 1.0  - so try Saxon xslt
                try
                {
                    using (MemoryStream schematronResultMemoryStream = new MemoryStream())
                    {
                        using (MemoryStream xmlSchematronStylesheetMemoryStream = compiledXslt.Stream)
                        {
                            xmlSchematronStylesheetMemoryStream.Flush();//Adjust this if you want read your data
                            xmlSchematronStylesheetMemoryStream.Position = 0;

                            Processor    processor  = new Processor();
                            XsltCompiler compiler   = processor.NewXsltCompiler();
                            Serializer   serializer = new Serializer();

                            try
                            {
                                XsltTransformer saxonTransformer = compiler.Compile(xmlSchematronStylesheetMemoryStream).Load();

                                // Load the XML document. Input to the build method is the document.
                                XdmNode docXdmNode = processor.NewDocumentBuilder().Build(xmlDocument);

                                // Set the root node of the source document to be the initial
                                // context node
                                saxonTransformer.InitialContextNode = docXdmNode;

                                // Init. the result object
                                serializer.SetOutputProperty(Serializer.INDENT, "yes");
                                serializer.SetOutputProperty(Serializer.ENCODING, Encoding.UTF8.BodyName);

                                serializer.SetOutputStream(schematronResultMemoryStream);

                                // Run the transformation with result object as input param.
                                saxonTransformer.Run(serializer);
                            }
                            catch (Exception)
                            {
                                // easy debugging
                                throw;
                            }
                            finally
                            {
                                // close/dispose
                                serializer.Close();
                            }
                        }

                        // convert the schematronResultMemoryStream, into a xmlDocument
                        schematronResultMemoryStream.Position = 0;
                        schematronResultXmlDocument           = new XmlDocument();
                        schematronResultXmlDocument.Load(schematronResultMemoryStream);

                        schematronResultMemoryStream.Position = 0;
                        XmlTextReader schematronResultXmlTextReader = new XmlTextReader(schematronResultMemoryStream);
                        prefixedNamespaces = this.CreateDefaultNamespaceManager(schematronResultXmlTextReader);

                        hasAnyErrors      = DocumentXPathResolver.HasAnyElementsByXpath(schematronResultXmlDocument, this.errorXPath, prefixedNamespaces);
                        documentValidated = true;
                    }
                }
                catch (Exception ex)
                {
                    Debug.Fail(ex.Message);
                    throw new SchematronValidationFailedException(xmlDocument, ex);
                }
            }

            if (documentValidated == false)
            {
                throw new SchematronValidationFailedException(xmlDocument, new Exception("Failed to validate the document."));
            }

            if (hasAnyErrors)
            {
                string firstErrorMessage = DocumentXPathResolver.GetFirstElementValueByXPath(schematronResultXmlDocument, this.errorMessageXPath, prefixedNamespaces);
                throw new SchematronErrorException(schematronResultXmlDocument, firstErrorMessage);
            }
            else
            {
                // no schematron error
            }
        }
Esempio n. 6
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());
                }
            }
        }
Esempio n. 7
0
 static ProcessorException WrapCompileException(Exception ex, XsltCompiler compiler)
 {
     return(WrapCompileException(ex, compiler.ErrorList));
 }
Esempio n. 8
0
        private void Transform()
        {
            var          processor = new Processor();
            XsltCompiler compiler  = processor.NewXsltCompiler();

            XMLForm frmXML = null;
            XSLForm frmXSL = null;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                // Find the XSL form and XML forms
                foreach (Form frm in this.MdiChildren)
                {
                    if (frm.Tag == null)
                    {
                        if (frm.Name == "XMLForm")
                        {
                            frmXML = (XMLForm)frm;
                        }
                        else if (frm.Name == "XSLForm")
                        {
                            frmXSL = (XSLForm)frm;
                        }
                    }
                }

                if (frmXML == null)
                {
                    throw new ApplicationException("No XML form found");
                }
                if (frmXSL == null)
                {
                    throw new ApplicationException("No XSL form found");
                }
                if (frmXSL.TextEditor.Text == "")
                {
                    throw new ApplicationException("XSL form is empty");
                }
                if (frmXML.TextEditor.Text == "")
                {
                    throw new ApplicationException("XML form is empty");
                }

                TextReader xslReader = new StringReader(frmXSL.TextEditor.Text);

                // Compile stylesheet
                XsltExecutable executable = compiler.Compile(xslReader);

                // Do transformation to a destination
                RawDestination destination = new RawDestination();
                using (MemoryStream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(frmXML.TextEditor.Text ?? "")))
                {
                    Xslt30Transformer transformer = executable.Load30();
                    transformer.ApplyTemplates(xmlStream, destination);
                }

                string result;
                if (this.indentResultToolStripMenuItem.Checked)
                {
                    // Indent the XML
                    var stringBuilder = new StringBuilder();
                    var element       = XElement.Parse(destination.XdmValue.ToString());

                    var settings = new XmlWriterSettings();
                    settings.OmitXmlDeclaration  = false;
                    settings.Indent              = true;
                    settings.NewLineOnAttributes = false;
                    using (var xmlWriter = XmlWriter.Create(stringBuilder, settings))
                    {
                        element.Save(xmlWriter);
                    }
                    result = stringBuilder.ToString();
                }
                else
                {
                    result = destination.XdmValue.ToString();
                }

                // Get / create the form
                XMLForm frmResult = null;
                if (this.overwriteOutputToolStripMenuItem.Checked)
                {
                    foreach (Form frm in this.MdiChildren)
                    {
                        if (frm.Tag != null)
                        {
                            if (frm.Tag.ToString() == "Output")
                            {
                                frmResult = (XMLForm)frm;
                                break;
                            }
                        }
                    }
                }
                // If form has not been got then create it
                if (frmResult == null)
                {
                    frmResult       = new XMLForm();
                    frmResult.Owner = this;
                }
                else
                {
                    frmResult.TopMost = true;
                    frmResult.BringToFront();
                }


                frmResult.MdiParent       = this;
                frmResult.TextEditor.Text = result;
                frmResult.Tag             = "Output";
                frmResult.Show();
            }
            catch (Exception ex)
            {
                string err = ex.Message + "\n";
                err += ex.GetType().ToString() + "\n";
                foreach (StaticError staticErr in compiler.ErrorList)
                {
                    err += staticErr.Message + " (line no : " + staticErr.LineNumber + ")\n";
                }

                MessageBox.Show(err);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
Esempio n. 9
0
 public SaxonEEDriver()
 {
     processor = new Processor(true);
     compiler  = processor.NewXsltCompiler();
     // Console.WriteLine(processor.ProductTitle + " Version:"+ processor.ProductVersion);
 }
Esempio n. 10
0
        private static string TransformSAXON(string document, string xslt, string tmpDir)
        {
            try
            {
                Processor    processor    = new Processor();
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();

                if (!Directory.Exists(tmpDir))
                {
                    tmpDir = Path.GetTempPath();
                }

                string tmpXsltFile = tmpDir + "tmp.xslt";
                File.WriteAllText(tmpXsltFile, xslt, Encoding.UTF8);
                XsltExecutable xsltExecutable = xsltCompiler.Compile(new Uri(@"file://" + tmpXsltFile));

                int    si   = document.IndexOf("xmlns:xsi=\"");
                int    ei   = document.IndexOf("\"", si + "xmlns:xsi=\"".Length) + 1;
                string text = document.Remove(si, ei - si);
                si = text.IndexOf("xmlns=\"");
                ei = text.IndexOf("\"", si + "xmlns=\"".Length) + 1;
                string xmlns = text.Substring(si, ei - si);
                text = text.Remove(si, ei - si);

                string tmpDoc = tmpDir + "tmp.xml";

                File.WriteAllText(tmpDoc, text.Replace("utf-16", "utf-8"), Encoding.UTF8);


                //StringBuilder outputBuilder = new StringBuilder();
                //XmlWriterSettings outputWriterSettings = new XmlWriterSettings { Indent = true, CheckCharacters = false, NewLineOnAttributes = true};
                //XmlWriter outputWriter = XmlWriter.Create(outputBuilder, outputWriterSettings);
                //Debug.Assert(outputWriter != null);
                //XsltArgumentList xsltArgumentList = new XsltArgumentList();

                FileStream fs = null;
                try
                {
                    XsltTransformer xsltTransformer = xsltExecutable.Load();

                    fs = new FileStream(tmpDoc, FileMode.Open);
                    xsltTransformer.SetInputStream(fs, new Uri(@"file://" + tmpDoc));
                    XdmDestination destination = new XdmDestination();
                    xsltTransformer.Run(destination);

                    StringBuilder outputBuilder = new StringBuilder();
                    outputBuilder.Append(destination.XdmNode.OuterXml);
                    //outputWriter.Flush();
                    int pos1 = outputBuilder.ToString().IndexOf(">");
                    int pos2 = outputBuilder.ToString().IndexOf("/>");
                    int pos;
                    if (pos1 == -1)
                    {
                        pos = pos2;
                    }
                    else if (pos2 == -1)
                    {
                        pos = pos1;
                    }
                    else
                    {
                        pos = Math.Min(pos1, pos2);
                    }
                    outputBuilder.Insert(pos,
                                         Environment.NewLine + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + xmlns);
                    XmlDocument  d            = new XmlDocument();
                    StringReader outputReader = new StringReader(outputBuilder.ToString());
                    d.Load(outputReader);
                    outputReader.Close();
                    return(d.PrettyPrintXML());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }
            catch (Exception e)
            {
                System.Windows.MessageBox.Show(e.Message);
                return(string.Empty);
            }
        }
Esempio n. 11
0
        private static string TransformSAXON(string document, string xslt, string tmpDir, PSMSchema psmSchema = null, bool schemaAware = false)
        {
            Processor    processor    = new Processor();
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();

            //xsltCompiler.SchemaAware = true;
            xsltCompiler.Processor.SetProperty(FeatureKeys.GENERATE_BYTE_CODE, "false");

            if (!Directory.Exists(tmpDir))
            {
                tmpDir = Path.GetTempPath();
            }

            using (StringReader sr = new StringReader(xslt))
            {
                XsltExecutable xsltExecutable = xsltCompiler.Compile(sr);

                string text;

                if (!schemaAware)
                {
                    int si = document.IndexOf("xmlns:xsi=\"");
                    int ei = document.IndexOf("\"", si + "xmlns:xsi=\"".Length) + 1;
                    text = si != -1 ? document.Remove(si, ei - si) : document;
                    si   = text.IndexOf("xmlns=\"");
                    ei   = text.IndexOf("\"", si + "xmlns=\"".Length) + 1;
                    string xmlns = si != -1 ? text.Substring(si, ei - si) : string.Empty;
                    text = si != -1 ? text.Remove(si, ei - si) : text;
                }
                else
                {
                    text = document;
                }

                string tmpDoc = tmpDir + "tmp.xml";

                if (schemaAware)
                {
                    XsdSchemaGenerator xsdGen = new XsdSchemaGenerator();
                    xsdGen.Initialize(psmSchema);
                    xsdGen.GenerateXSDStructure();
                    XDocument schema    = xsdGen.GetXsd();
                    string    schemaLoc = tmpDir + "LastSchema.xsd";
                    schema.Save(schemaLoc);
                }

                File.WriteAllText(tmpDoc, text.Replace("utf-16", "utf-8"), Encoding.UTF8);


                StringBuilder outputBuilder = new StringBuilder();
                //XmlWriterSettings outputWriterSettings = new XmlWriterSettings { Indent = true, CheckCharacters = false, NewLineOnAttributes = true };
                //XmlWriter outputWriter = XmlWriter.Create(outputBuilder, outputWriterSettings);
                //Debug.Assert(outputWriter != null);
                XsltArgumentList xsltArgumentList = new XsltArgumentList();
                FileStream       fs = null;
                try
                {
                    XsltTransformer xsltTransformer = xsltExecutable.Load();
                    if (schemaAware)
                    {
                        xsltTransformer.SchemaValidationMode = SchemaValidationMode.Strict;
                    }

                    fs = new FileStream(tmpDoc, FileMode.Open);
                    xsltTransformer.SetInputStream(fs, new Uri(@"file://" + tmpDoc));
                    XdmDestination destination = new XdmDestination();
                    xsltTransformer.Run(destination);

                    outputBuilder.Append(destination.XdmNode.OuterXml);
                    //outputWriter.Flush();
                    int pos1 = outputBuilder.ToString().IndexOf(">");
                    int pos2 = outputBuilder.ToString().IndexOf("/>");
                    int pos;
                    if (pos1 == -1)
                    {
                        pos = pos2;
                    }
                    else if (pos2 == -1)
                    {
                        pos = pos1;
                    }
                    else
                    {
                        pos = Math.Min(pos1, pos2);
                    }
                    //outputBuilder.Insert(pos,
                    //                     Environment.NewLine + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + xmlns);

                    StringReader outputReader = new StringReader(outputBuilder.ToString());
                    XDocument    d            = XDocument.Load(outputReader);
                    outputReader.Close();
                    return(d.PrettyPrintXML());
                }
                finally
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
            }
        }
Esempio n. 12
0
 public void OneTimeTearDown()
 {
     _compiler  = null;
     _processor = null;
 }
Esempio n. 13
0
 public void OneTimeSetUp()
 {
     _processor = new Processor();
     _compiler  = _processor.NewXsltCompiler();
 }
Esempio n. 14
0
 public SaxonHEDriver()
 {
     processor = new Processor(false);
     compiler  = processor.NewXsltCompiler();
 }
Esempio n. 15
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());
            }
        }
Esempio n. 16
0
        public bool validate(EA.Repository Repository, string maxFile, string schFile, string svrlFile)
        {
            string iso_sch_xsl_file = Main.getAppDataFullPath(@"Schematron\iso_svrl_for_xslt2.xsl");
            string sch_xsl_file     = Path.Combine(Filters.CurrentOutputPath, "max-tmp.sch.xsl");

            // Create a Processor instance.
            Processor    processor = new Processor();
            XsltCompiler compiler  = processor.NewXsltCompiler();

            compiler.ErrorList = new List <StaticError>();
            DocumentBuilder builder = processor.NewDocumentBuilder();

            // First transform the Schematron to XSLT
            try
            {
                // Create a transformer for the stylesheet.
                XsltTransformer transformer = compiler.Compile(new Uri(iso_sch_xsl_file)).Load();

                // Load the source document
                XdmNode input = builder.Build(new Uri(schFile));

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer, with output to the standard output stream
                Serializer serializer = new Serializer();
                //StringWriter output = new StringWriter();
                //serializer.SetOutputWriter(output);
                serializer.SetOutputFile(sch_xsl_file);

                // Transform the source XML and serialize the result document
                transformer.Run(serializer);
            }
            catch (Exception ex)
            {
                if (Repository == null)
                {
                    Console.WriteLine(ex);
                    StringBuilder sb = new StringBuilder();
                    foreach (var error in compiler.ErrorList)
                    {
                        sb.AppendLine(error.ToString());
                    }
                    Console.WriteLine(sb);
                }
                else
                {
                    Main.LogMessage(Repository, ex.Message, 0);
                    foreach (var error in compiler.ErrorList)
                    {
                        Main.LogMessage(Repository, error.ToString(), 0);
                    }
                }
                return(true);
            }

            // Now run the Schematron XSLT on the XML
            try
            {
                // Create a transformer for the stylesheet.
                XsltTransformer transformer = compiler.Compile(new Uri(sch_xsl_file)).Load();

                // Load the source document
                XdmNode input = builder.Build(new Uri(maxFile));

                // Set the root node of the source document to be the initial context node
                transformer.InitialContextNode = input;

                // Create a serializer, with output to the standard output stream
                Serializer serializer = new Serializer();
                serializer.SetOutputFile(svrlFile);

                // Transform the source XML and serialize the result document
                transformer.Run(serializer);

                // Show messages in Output Tab
                XmlReader xReader = XmlReader.Create(svrlFile);
                using (xReader)
                {
                    XElement            svrl  = XElement.Load(xReader);
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(xReader.NameTable);
                    nsmgr.AddNamespace("svrl", "http://purl.oclc.org/dsdl/svrl");

                    appendSvrlMessagesToOutputTab(Repository, svrl.XPathSelectElements("//svrl:successful-report", nsmgr), nsmgr);
                    appendSvrlMessagesToOutputTab(Repository, svrl.XPathSelectElements("//svrl:failed-assert", nsmgr), nsmgr);
                }
                return(false);
            }
            catch (Exception ex)
            {
                if (Repository == null)
                {
                    Console.WriteLine(ex);
                    StringBuilder sb = new StringBuilder();
                    foreach (var error in compiler.ErrorList)
                    {
                        sb.AppendLine(error.ToString());
                    }
                    Console.WriteLine(sb);
                }
                else
                {
                    Main.LogMessage(Repository, ex.Message, 0);
                    foreach (var error in compiler.ErrorList)
                    {
                        Main.LogMessage(Repository, error.ToString(), 0);
                    }
                }
                return(true);
            }
        }