Project

Profile

Help

How to connect?
Download (49.9 KB) Statistics
| Branch: | Tag: | Revision:

he / latest9.9 / samples / cs / TestRunner9.9 / Xslt30TestSuiteDriver.cs @ 063bf4dc

1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
using System.Text;
5
using System.Xml;
6
using System.IO;
7
using System.Text.RegularExpressions;
8
using System.Globalization;
9
using Saxon.Api;
10

    
11

    
12
using JFeatureKeys = net.sf.saxon.lib.FeatureKeys;
13
using JConfiguration = net.sf.saxon.Configuration;
14
using JVersion = net.sf.saxon.Version;
15
using JResult = javax.xml.transform.Result;
16
using System.Diagnostics;
17

    
18
namespace TestRunner
19
{
20
    //C:/work/repositories/hg/xslt30-test C:/work/repositories/hg/xslt30-test/results/saxon/ -lang:XT30 -xt30:on
21

    
22
    // file:////C:/work/repositories/hg/xslt30-test/ C:/work/repositories/hg/xslt30-test/results/saxon/ -lang:XT30 -xt30:on -s:mode -t:mode-1801
23
    /**
24
     * This class runs the W3C XSLT Test Suite, driven from the test catalog.
25
     */
26
    public class Xslt30TestSuiteDriver : TestDriver {
27

    
28
    public static void Mainxxx(string[] args) {
29
        if (args.Length == 0 || args[0].Equals("-?")) {
30
            System.Console.WriteLine("testsuiteDir catalog [-o:resultsdir] [-s:testSetName]" +
31
                    " [-t:testNamePattern] [-bytecode:on|off|debug] [-tree] [-lang] [-save]");
32
        }
33

    
34
        System.Console.WriteLine("Testing Saxon " + (new Processor()).ProductVersion);
35
        new Xslt30TestSuiteDriver().go(args);
36
    }
37

    
38

    
39
    
40
    public override string catalogNamespace() {
41
        return "http://www.w3.org/2012/10/xslt-test-catalog";
42
    }
43

    
44
    public void writeResultFilePreamble(Processor processor, XdmNode catalog) {
45
        resultsDoc = new Xslt30ResultsDocument(this.resultsDir, Spec.XT30);
46
        //super.writeResultFilePreamble(processor, catalog);
47
    }
48

    
49
    
50
    public override void processSpec(string specStr) {
51
			if (specStr.Equals("XT10")) {
52
				spec = Spec.XT10;
53
			} else if (specStr.Equals("XT20")) {
54
				spec = Spec.XT20;
55
			} else if (specStr.Equals("XT30")) {
56
				spec = Spec.XT30;
57
			} else {
58
				throw new Exception("Unknown spec " + specStr);
59
			}
60
        resultsDoc = new Xslt30ResultsDocument(this.resultsDir, Spec.XT30);
61
        // No action: always use XSLT
62
    }
63

    
64
    
65
    protected override void createGlobalEnvironments(XdmNode catalog, XPathCompiler xpc) {
66
        Environment environment = null;
67
        Environment defaultEnv = null;
68
         try
69
            {
70
                defaultEnv = localEnvironments["default"];
71
            }
72
            catch (Exception) { }
73
        foreach (XdmItem env in xpc.Evaluate("//environment", catalog)) {
74
            environment = Environment.processEnvironment(this, xpc, env, globalEnvironments, defaultEnv);
75
        }
76
        //buildDependencyMap(driverProc, environment);
77
    }
78

    
79
		/**
80
     * Return a set of named parameters as a map
81
     *
82
     * @param xpath     The XPath compiler to use
83
     * @param node      The node to search for <param> children
84
     * @param getStatic Whether to collect static or non-static sets
85
     * @param tunnel    Whether to collect tunnelled or non-tunnelled sets
86
     * @return Map of the evaluated parameters, keyed by QName
87
     * @throws SaxonApiException
88
     */
89

    
90
		internal Dictionary <QName, XdmValue> GetNamedParameters(XPathCompiler xpath, XdmNode node, bool getStatic, bool tunnel)  {
91
			Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
92
			int i = 1;
93
			string staticTest = getStatic ? "@static='yes'" : "not(@static='yes')";
94
			foreach (XdmItem parami in xpath.Evaluate("param[" + staticTest + "]", node)) {
95
				QName name = GetQNameAttribute(xpath, parami, "@name");
96
				string select = ((XdmNode) parami).GetAttributeValue(new QName("select"));
97
				string tunnelled = ((XdmNode) parami).GetAttributeValue(new QName("tunnel"));
98
				bool required = tunnel == (tunnelled != null && tunnelled.Equals("yes"));
99
				XdmValue value;
100
				if (name == null) {
101
					System.Console.WriteLine("*** No name for parameter " + i + " in initial-template");
102
					throw new Exception("*** No name for parameter " + i + " in initial-template");
103
				}
104
				try {
105
					value = xpath.Evaluate(select, null);
106
					i++;
107
				} catch (Exception e) {
108
					System.Console.WriteLine("*** Error evaluating parameter " + name + " in initial-template : " + e.Message);
109
					throw e;
110
				}
111
				if (required) {
112
					params1.Add(name, value);
113
				}
114
			}
115
			return params1;
116
		}
117

    
118
		internal XdmValue[] getParameters(XPathCompiler xpath, XdmNode node) {
119
			List<XdmValue> params1 = new List<XdmValue>();
120

    
121
			int i = 1;
122
			foreach (XdmItem param in xpath.Evaluate("param[not(@static='yes')]", node)) {
123
				string select = ((XdmNode) param).GetAttributeValue(new QName("select"));
124
				XdmValue value;
125
				try {
126
					value = xpath.Evaluate(select, null);
127
					i++;
128
				} catch (Exception e) {
129
					System.Console.WriteLine("*** Error evaluating parameter " + i + " in initial-function : " + e.Message);
130
					throw e;
131
				}
132
				params1.Add(value);
133
			}
134
			return params1.ToArray();
135
		}
136

    
137

    
138

    
139
		internal static QName GetQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath) {
140
			string exp = "for $att in " + attributePath +
141
				" return if (contains($att, ':')) then resolve-QName($att, $att/..) else " +
142
				" if (contains($att,'{')) then QName(substring-before(substring-after($att,'{'),'}'),substring-after($att,'}')) else" +
143
				" xs:string($att)";
144
            XdmAtomicValue qname = null;
145
            try
146
            {
147
               qname = (XdmAtomicValue)xpath.EvaluateSingle(exp, contextItem);
148
            }
149
            catch (Exception ex) {
150
                Trace.WriteLine("Error in GetQNameAttribute : " + ex.Message);
151
                return null;
152
            }
153
            if (qname == null) {
154
                return null;
155
            }
156
            String qnameStr = qname.GetStringValue();
157
            if (qnameStr.Equals("#unnamed")) {
158
                return new QName(NamespaceConstant.XSLT, "unnamed");
159
            } else if (qnameStr.Equals("#default"))
160
            {
161
                return new QName(NamespaceConstant.XSLT, "default");
162
            }
163
            else if (qnameStr.StartsWith("{"))
164
            {
165
                return QName.FromClarkName(qnameStr);
166
            }
167
            else if (qnameStr.StartsWith("Q{"))
168
            {
169
                return QName.FromEQName(qnameStr);
170
            }
171
            if (qnameStr.Contains(":")) {
172
                QName qqname = new QName(qnameStr, (XdmNode)contextItem);
173
                return qqname;
174
            }
175
			return qname == null ? null : new QName(qname.ToString());
176
		}
177

    
178
    private bool isSlow(string testName) {
179
			return testName.StartsWith("regex-classes")||
180
				testName.Equals("normalize-unicode-008");
181
    }
182

    
183

    
184
    protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)  {
185

    
186
        TestOutcome outcome = new TestOutcome(this);
187
        string testName = testCase.GetAttributeValue(new QName("name"));
188
        string testSetName = testCase.Parent.GetAttributeValue(new QName("name"));
189

    
190
        if (exceptionsMap.ContainsKey(testName)) {
191
            notrun++;
192
            resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
193
            return;
194
        }
195

    
196
        if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) {
197
            notrun++;
198
            resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
199
            return;
200
        }
201

    
202
       
203

    
204
        XdmValue specAtt = (XdmValue)(xpath.EvaluateSingle("(/test-set/dependencies/spec/@value, ./dependencies/spec/@value)[last()]", testCase));
205
        string spec = specAtt == null ? "XSLT10+" : specAtt.ToString();
206

    
207
        Environment env = getEnvironment(testCase, xpath);
208
        if(env == null) {
209
            resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
210
            return;
211
        }
212

    
213
        /*if(testName("environment-variable")) {
214
                        EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
215
                    public Set<string> getAvailableEnvironmentVariables() {
216
                        Set<string> strings = new HashSet<string>();
217
                        strings.add("QTTEST");
218
                        strings.add("QTTEST2");
219
                        strings.add("QTTESTEMPTY");
220
                        return strings;
221
                    }
222

    
223
                    public string getEnvironmentVariable(string name) {
224
                        if (name.Equals("QTTEST")) {
225
                            return "42";
226
                        } else if (name.Equals("QTTEST2")) {
227
                            return "other";
228
                        } else if (name.Equals("QTTESTEMPTY")) {
229
                            return "";
230
                        } else {
231
                            return null;
232
                        }
233
                    }
234
                }; //TODO
235
            } */
236
         //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO
237
        
238
        XdmNode testInput = (XdmNode) xpath.EvaluateSingle("test", testCase);
239
        XdmNode stylesheet = (XdmNode) xpath.EvaluateSingle("stylesheet", testInput);
240
		XdmNode pack = (XdmNode) xpath.EvaluateSingle("package", testInput);
241

    
242

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

    
251
        XsltExecutable sheet = env.xsltExecutable;
252
       //ErrorCollector collector = new ErrorCollector();
253
			string baseOutputURI = "file:////"+ resultsDir + "/results/output.xml";
254
			ErrorCollector collector = new ErrorCollector(outcome);
255
			IList<StaticError> errorList = new List<StaticError> ();
256
        XmlUrlResolver res = new XmlUrlResolver();
257
		string xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0";
258
        if (stylesheet != null) {
259
                env.processor.SetProperty(FeatureKeys.ALLOW_MULTITHREADING, "false");
260
            XsltCompiler compiler = env.xsltCompiler;
261
				compiler.ErrorList = errorList;
262
            Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
263
            Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
264
            compiler.BaseUri = hrefFile;
265
            compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
266

    
267
			foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput)) {
268
					String name = ((XdmNode) param).GetAttributeValue(new QName("name"));
269
					String select = ((XdmNode) param).GetAttributeValue(new QName("select"));
270
					XdmValue value;
271
					try {
272
						value = xpath.Evaluate(select, null);
273
					} catch (Exception e) {
274
						Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
275
						//throw e;
276
						continue;
277
					}
278
					compiler.SetParameter(new QName(name), value);
279

    
280
				}
281

    
282
            try
283
            {
284
                sheet = compiler.Compile(stream);
285
            } catch(Exception err){
286
					Console.WriteLine (err.Message);
287
					//Console.WriteLine(err.StackTrace);
288
					IEnumerator enumerator = errorList.GetEnumerator();
289
					bool checkCur = enumerator.MoveNext();
290
					/*if (checkCur && enumerator.Current != null) {
291
						outcome.SetException ((Exception)(enumerator.Current));
292
					} else {
293
						Console.WriteLine ("Error: Unknown exception thrown");
294
					}*/
295
					outcome.SetErrorsReported (errorList);
296
                    outcome.SetException(err);
297

    
298
                    //outcome.SetErrorsReported(collector.GetErrorCodes);
299
                }
300

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

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

    
312
				try {
313
					XsltPackage xpack = compiler.CompilePackage(stream);
314
					sheet = xpack.Link();
315
				} catch (Exception err) {
316
					Console.WriteLine (err.Message);
317
					IEnumerator enumerator = errorList.GetEnumerator ();
318
                    if (enumerator.MoveNext())
319
                    {
320
                        outcome.SetException((Exception)(enumerator.Current));
321
                        outcome.SetErrorsReported(errorList);
322
                    }
323
				}
324
			}
325

    
326
            if (sheet != null)
327
            {
328
                XdmItem contextItem = env.contextItem;
329
                XdmValue initialMatchSelection = null;
330
                XdmNode initialMode = (XdmNode)xpath.EvaluateSingle("initial-mode", testInput);
331
                XdmNode initialFunction = (XdmNode)xpath.EvaluateSingle("initial-function", testInput);
332
                XdmNode initialTemplate = (XdmNode)xpath.EvaluateSingle("initial-template", testInput);
333

    
334
                QName initialModeName = initialMode == null ? null : GetQNameAttribute(xpath, initialMode, "@name");
335
                QName initialTemplateName = initialTemplate == null ? null : GetQNameAttribute(xpath, initialTemplate, "@name");
336

    
337
                if (initialMode != null)
338
                {
339
                    XdmItem select = xpath.EvaluateSingle("@select", initialMode);
340
                    if (select != null)
341
                    {
342
                        initialMatchSelection = env.xpathCompiler.Evaluate(select.GetStringValue(), null);
343
                    }
344
                }
345

    
346
                if (useXslt30Transformer)
347
                {
348
                    try
349
                    {
350

    
351
                        bool assertsSerial = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0;
352
                        bool resultAsTree = env.outputTree;
353
                        bool serializationDeclared = env.outputSerialize;
354
                        XdmNode needsTree = (XdmNode)xpath.EvaluateSingle("output/@tree", testInput);
355
                        if (needsTree != null)
356
                        {
357
                            resultAsTree = needsTree.StringValue.Equals("yes");
358
                        }
359
                        XdmNode needsSerialization = (XdmNode)xpath.EvaluateSingle("output/@serialize", testInput);
360
                        if (needsSerialization != null)
361
                        {
362
                            serializationDeclared = needsSerialization.StringValue.Equals("yes");
363
                        }
364
                        bool resultSerialized = serializationDeclared || assertsSerial;
365

    
366
                        if (assertsSerial)
367
                        {
368
                            String comment = outcome.GetComment();
369
                            comment = (comment == null ? "" : comment) + "*Serialization " + (serializationDeclared ? "declared* " : "required* ");
370
                            outcome.SetComment(comment);
371
                        }
372

    
373

    
374
                        Xslt30Transformer transformer = sheet.Load30();
375
                        transformer.InputXmlResolver = env;
376
                        if (env.unparsedTextResolver != null)
377
                        {
378
                            transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver);
379
                        }
380

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

    
385
                        foreach (KeyValuePair<QName, XdmValue> entry in caseGlobalParams)
386
                        {
387
                            globalParams.Add(entry.Key, entry.Value);
388

    
389
                        }
390

    
391
                        /*foreach(KeyValuePair<QName, XdmValue> entry in caseStaticParams) {
392
							globalParams.Add(entry.Key, entry.Value);
393

    
394
						}*/
395

    
396

    
397
                        transformer.SetStylesheetParameters(globalParams);
398

    
399
                        if (contextItem != null)
400
                        {
401
                            transformer.GlobalContextItem = contextItem;
402
                        }
403

    
404
                        transformer.MessageListener = collector;
405

    
406
                        transformer.BaseOutputURI = baseOutputURI;
407

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

    
410
                        XdmValue result = null;
411

    
412
                        TextWriter sw = new StringWriter();
413

    
414
                        Serializer serializer = env.processor.NewSerializer();
415

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

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

    
422

    
423
                        XmlDestination dest = null;
424
                        if (resultAsTree && !resultSerialized)
425
                        {
426
                            // If we want non-serialized, we need to accumulate any result documents as trees too
427
                            transformer.ResultDocumentHandler = new ResultDocumentHandler(env.processor, outcome, baseOutputURI, false);
428

    
429

    
430
                            dest = new XdmDestination();
431

    
432
                        }
433
                        else
434
                        if (resultSerialized)
435
                        {
436
                            dest = serializer;
437
                        }
438

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

    
444
                        if (env.streamedPath != null)
445
                        {
446
                            src = new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read);
447
                            srcBaseUri = new Uri(env.streamedPath);
448
                        }
449
                        else if (env.streamedContent != null)
450
                        {
451
                            byte[] byteArray = Encoding.UTF8.GetBytes(env.streamedContent);
452
                            src = new MemoryStream(byteArray);//, "inlineDoc");
453
                            builder2.BaseUri = new Uri("http://uri");
454
                        }
455
                        else if (initialTemplate == null && contextItem != null)
456
                        {
457
                            srcNode = (XdmNode)(contextItem);
458
                        }
459

    
460
                        if (src != null && !"skip".Equals(env.streamedInputValidation))
461
                        {
462
                            Processor processor = (Processor)sheet.Implementation.getUnderlyingCompiledStylesheet().getConfiguration().getProcessor();
463
                            SchemaValidator validatori = processor.SchemaManager.NewSchemaValidator();
464
                            //validatori.SetDestination
465

    
466
                        }
467

    
468
                        if (initialMode != null)
469
                        {
470
                            QName name = GetQNameAttribute(xpath, initialMode, "@name");
471
                            try
472
                            {
473
                                if (name != null)
474
                                {
475
                                    transformer.InitialMode = name;
476
                                }
477
                            }
478
                            catch (Exception e)
479
                            {
480
                                if (e.InnerException is net.sf.saxon.trans.XPathException)
481
                                {
482
                                    Console.WriteLine(e.Message);
483
                                    outcome.SetException(e);
484
                                    //throw new SaxonApiException(e.getCause());
485
                                }
486
                                else
487
                                {
488
                                    throw e;
489
                                }
490
                            }
491
                        }
492
                        if (src == null && srcNode == null && initialFunction == null && initialTemplateName == null && initialModeName == null)
493
                        {
494
                            initialTemplateName = new QName("xsl", NamespaceConstant.XSLT, "initial-template");
495
                        }
496

    
497
                        if (initialMode != null || initialTemplate != null)
498
                        {
499
                            XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode);
500
                            Dictionary<QName, XdmValue> params1 = GetNamedParameters(xpath, init, false, false);
501
                            Dictionary<QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true);
502
                            if (xsltLanguageVersion.Equals("2.0"))
503
                            {
504
                                if (!(params1.Count == 0 && tunnelledParams.Count == 0))
505
                                {
506
                                    Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0");
507
                                }
508
                            }
509
                            else
510
                            {
511
                                transformer.SetInitialTemplateParameters(params1, false);
512
                                transformer.SetInitialTemplateParameters(tunnelledParams, true);
513
                            }
514
                        }
515

    
516

    
517
                        if (initialTemplateName != null)
518
                        {
519
                            transformer.GlobalContextItem = contextItem;
520
                            if (dest == null)
521
                            {
522
                                result = transformer.CallTemplate(initialTemplateName);
523
                            }
524
                            else
525
                            {
526
                                transformer.CallTemplate(initialTemplateName, dest);
527
                            }
528
                        }
529
                        else if (initialFunction != null)
530
                        {
531
                            QName name = getQNameAttribute(xpath, initialFunction, "@name");
532
                            XdmValue[] params2 = getParameters(xpath, initialFunction);
533
                            if (dest == null)
534
                            {
535
                                result = transformer.CallFunction(name, params2);
536
                            }
537
                            else
538
                            {
539
                                transformer.CallFunction(name, params2, dest);
540
                            }
541
                        }
542
                        else if (initialMatchSelection != null)
543
                        {
544
                            if (dest == null)
545
                            {
546
                                result = transformer.ApplyTemplates(initialMatchSelection);
547
                            }
548
                            else
549
                            {
550
                                transformer.ApplyTemplates(initialMatchSelection, dest);
551
                            }
552

    
553
                        }
554
                        else
555
                        {
556
                            if (dest == null)
557
                            {
558
                                if (src != null)
559
                                {
560
                                    result = transformer.ApplyTemplates(src, srcBaseUri);
561
                                }
562
                                else
563
                                {
564
                                    result = transformer.ApplyTemplates(srcNode);
565
                                }
566
                            }
567
                            else
568
                            {
569
                                if (src != null)
570
                                {
571
                                    transformer.ApplyTemplates(src, dest);
572
                                }
573
                                else
574
                                {
575
                                    transformer.ApplyTemplates(srcNode, dest);
576
                                }
577
                            }
578
                        }
579

    
580
                        //outcome.SetWarningsReported(collector.getFoundWarnings());
581
                        if (resultAsTree && !resultSerialized)
582
                        {
583
                            result = ((XdmDestination)(dest)).XdmNode;
584
                        }
585
                        if (resultSerialized)
586
                        {
587
                            outcome.SetPrincipalSerializedResult(sw.ToString());
588
                        }
589
                        outcome.SetPrincipalResult(result);
590

    
591
                        if (saveResults)
592
                        {
593
                            String s = sw.ToString();
594
                            // If a transform result is entirely xsl:result-document, then result will be null
595
                            if (!resultSerialized && result != null)
596
                            {
597
                                StringWriter sw2 = new StringWriter();
598
                                Serializer se = env.processor.NewSerializer(sw2);
599
                                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
600
                                env.processor.WriteXdmValue(result, se);
601
                                se.Close();
602
                                s = sw2.ToString();
603
                            }
604
                            // currently, only save the principal result file in the result directory
605
                            saveResultsToFile(s, resultsDir + "/results/" + testSetName + "/" + testName + ".out");
606
                            Dictionary<Uri, TestOutcome.SingleResultDoc> xslResultDocuments = outcome.GetSecondaryResultDocuments();
607
                            foreach (KeyValuePair<Uri, TestOutcome.SingleResultDoc> entry in xslResultDocuments)
608
                            {
609
                                Uri key = entry.Key;
610
                                String path = key.AbsolutePath;
611
                                String serialization = outcome.Serialize(env.processor, entry.Value);
612

    
613
                                saveResultsToFile(serialization, path);
614
                            }
615
                        }
616
                    }
617
                    catch (Exception err)
618
                    {
619
                        //if (err.getCause() is XPathException &&
620
                        //!((XPathException) err.getCause()).hasBeenReported()) {
621
                        //System.err.println("Unreported ERROR: " + err.getCause());
622
                        //}
623
                        outcome.SetException(err);
624
                        if (collector.getErrorCodes().Count > 0)
625
                        {
626
                            outcome.SetErrorQNameReported(collector.getErrorCodes());
627
                        }
628
                        //Console.WriteLine(err.StackTrace);
629
                        /*if(err.getErrorCode() == null) {
630
                        int b = 3 + 4;  }
631
                    if(err.getErrorCode() != null)
632
                        outcome.AddReportedError(err.getErrorCode().getLocalName());
633
                    } else {
634
                        outcome.SetErrorsReported(collector.getErrorCodes());
635
                    }*/
636
                    } /*catch (Exception err) {
637
						err.printStackTrace();
638
						failures++;
639
						resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
640
						return;
641
					}*/
642
                }
643
                else
644
                {
645

    
646
                    try
647
                    {
648
                        XsltTransformer transformer = sheet.Load();
649

    
650

    
651
                        //transformer.SetURIResolver(env); //TODO
652
                        if (env.unparsedTextResolver != null)
653
                        {
654
                            transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
655
                        }
656
                        if (initialTemplate != null)
657
                        {
658
                            transformer.InitialTemplate = initialTemplateName;
659
                        }
660
                        if (initialMode != null)
661
                        {
662
                            transformer.InitialMode = initialModeName;
663
                        }
664
                        foreach (XdmItem param in xpath.Evaluate("param", testInput))
665
                        {
666
                            string name = ((XdmNode)param).GetAttributeValue(new QName("name"));
667
                            string select = ((XdmNode)param).GetAttributeValue(new QName("select"));
668
                            XdmValue value = xpath.Evaluate(select, null);
669
                            transformer.SetParameter(new QName(name), value);
670
                        }
671
                        if (contextItem != null)
672
                        {
673
                            transformer.InitialContextNode = (XdmNode)contextItem;
674
                        }
675
                        if (env.streamedPath != null)
676
                        {
677
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
678
                        }
679
                        foreach (QName varName in env.params1.Keys)
680
                        {
681
                            transformer.SetParameter(varName, env.params1[varName]);
682
                        }
683
                        //transformer.setErrorListener(collector);
684
                        transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");
685
                        /*transformer.MessageListener = (new MessageListener() {
686
                            public void message(XdmNode content, bool terminate, SourceLocator locator) {
687
                                outcome.addXslMessage(content);
688
                            }
689
                        });*/
690

    
691

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

    
695
                        // run with serialization
696
                        StringWriter sw = new StringWriter();
697
                        Serializer serializer = env.processor.NewSerializer(sw);
698
                        transformer.ResultDocumentHandler = new ResultDocumentHandler(driverProc, outcome, testCase.BaseUri.AbsolutePath, true);
699

    
700

    
701
                        transformer.Run(serializer);
702

    
703
                        outcome.SetPrincipalSerializedResult(sw.ToString());
704
                        if (saveResults)
705
                        {
706
                            // currently, only save the principal result file
707
                            saveResultsToFile(sw.ToString(),
708
                                    resultsDir + "/results/" + testSetName + "/" + testName + ".out");
709
                        }
710
                        transformer.MessageListener = new TestOutcome.MessageListener(outcome);
711

    
712
                        // run without serialization
713
                        if (env.streamedPath != null)
714
                        {
715
                            transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
716
                        }
717
                        XdmDestination destination = new XdmDestination();
718
                        transformer.ResultDocumentHandler = new ResultDocumentHandler(env.processor, outcome, testCase.BaseUri.AbsolutePath, false);
719
                        transformer.Run(destination);
720

    
721
                        //transformer. .transform();
722
                        outcome.SetPrincipalResult(destination.XdmNode);
723
                        //}
724
                    }
725
                    catch (Exception err)
726
                    {
727
                        outcome.SetException(err);
728
                        //outcome.SetErrorsReported(collector.getErrorCodes());
729
                        // err.printStackTrace();
730
                        // failures++;
731
                        //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
732
                        //return;
733
                    }
734
                }
735
            }
736
        XdmNode assertion = (XdmNode) xpath.EvaluateSingle("result/*", testCase);
737
        if (assertion == null) {
738
            failures++;
739
            resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
740
            return;
741
        }
742
        XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
743
        //assertionXPath.setLanguageVersion("3.0");
744
        bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);
745
        if (success) {
746
            if (outcome.GetWrongErrorMessage() != null) {
747
                outcome.SetComment(outcome.GetWrongErrorMessage());
748
                wrongErrorResults++;
749
            } else {
750
                successes++;
751
            }
752
            resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
753
        } else {
754
            failures++;
755
            resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
756
        }
757
    
758
}
759

    
760

    
761

    
762

    
763
        public class ResultDocumentHandler : IResultDocumentHandler
764
        {
765

    
766
            private Processor proc;
767
            private TestOutcome outcome;
768
            private Uri baseOutputUri;
769
            bool serialized;
770
            public ResultDocumentHandler(Processor processor, TestOutcome outcome, String baseOutputURI, bool serialized) {
771
                this.proc = processor;
772
                this.outcome = outcome;
773
                try {
774
                    this.baseOutputUri = new Uri(baseOutputURI);
775
                }
776
                catch (Exception e) { }
777
                this.serialized = serialized;
778

    
779
            }
780
            public XmlDestination HandleResultDocument(string href, Uri baseUri)
781
            {
782
               // if (serialized)
783
              //  {
784

    
785
                    StringWriter writer = new StringWriter();
786
                    Serializer dest = proc.NewSerializer();
787
                   
788
                    XmlUrlResolver res = new XmlUrlResolver();
789
                    Uri uri = res.ResolveUri(baseUri, href);
790
                    dest.BaseUri = uri;
791
                dest.SetOutputFile(uri.AbsolutePath);
792

    
793
                if (uri.Equals(baseOutputUri))
794
                    {
795

    
796
                        outcome.SetPrincipalSerializedResult(writer.ToString());
797
                    }
798
                    else
799
                    {
800
                        outcome.SetSecondaryResult(uri, null, writer.ToString());
801
                    }
802
                    return dest;
803
                /*   }
804
                   else {
805

    
806
                       XdmDestination dest = new XdmDestination();
807
                       XmlUrlResolver res = new XmlUrlResolver();
808
                       Uri uri = res.ResolveUri(baseUri, href);
809
                       dest.BaseUri = uri;
810
                       if (uri.Equals(baseOutputUri))
811
                       {
812

    
813
                           outcome.SetPrincipalResult(dest.XdmNode);
814
                       }
815
                       else
816
                       {
817
                           outcome.SetSecondaryResult(uri, dest.XdmNode ,null);
818
                       }
819
                       return dest;
820

    
821
                   }*/
822
            }
823
        }
824

    
825

    
826

    
827

    
828
        internal bool mustSerialize(XdmNode testCase, XPathCompiler xpath) {
829
        return saveResults ||
830
                ((XdmAtomicValue) xpath.EvaluateSingle(
831
                "exists(./result//(assert-serialization-error|serialization-matches|assert-serialization)[not(parent::*[self::assert-message|self::assert-result-document])])", testCase)).GetBooleanValue();
832
    }
833

    
834
    private void saveResultsToFile(string content, string filePath) {
835
        try {
836
            System.IO.File.WriteAllText(filePath, content);
837
        } catch (IOException e) {
838
            println("*** Failed to save results to " + filePath);
839
            throw e;
840
        }
841
    }
842

    
843

    
844
    
845
    public override bool dependencyIsSatisfied(XdmNode dependency, Environment env) {
846
        string type = dependency.NodeName.LocalName;
847
        string value = dependency.GetAttributeValue(new QName("value"));
848
            if (value == null) {
849
                value = "*";
850
            }
851
        bool inverse = "false".Equals(dependency.GetAttributeValue(new QName("satisfied")));
852
            if ("spec".Equals(type))
853
            {
854
                bool atLeast = value.EndsWith("+");
855
                value = value.Replace("+", "");
856

    
857
                String specName = ((SpecAttr)spec.GetAttr()).svname.Replace("XT", "XSLT");
858
                int order = value.CompareTo(specName);
859
                return atLeast ? order <= 0 : order == 0;
860
            }
861
            else if ("feature".Equals(type))
862
            {
863
                //            <xs:enumeration value="backwards_compatibility" />
864
                //            <xs:enumeration value="disabling_output_escaping" />
865
                //            <xs:enumeration value="schema_aware" />
866
                //            <xs:enumeration value="namespace_axis" />
867
                //            <xs:enumeration value="streaming" />
868
                //            <xs:enumeration value="XML_1.1" />
869

    
870
                if ("XML_1.1".Equals(value) && !inverse)
871
                {
872
                    if (env != null)
873
                    {
874
                        env.processor.XmlVersion = (decimal)1.1;
875
                        return true;
876
                    }
877
                    else
878
                    {
879
                        return false;
880
                    }
881
                }
882
                else if ("disabling_output_escaping".Equals(value))
883
                {
884
                    return !inverse;
885
                }
886
                else if ("schema_aware".Equals(value))
887
                {
888
                    if (!env.xsltCompiler.SchemaAware)
889
                    {
890
                        return false; // cannot use the selected tree model for schema-aware tests
891
                    }
892
                    if (env != null)
893
                    {
894
                        env.xsltCompiler.SchemaAware = !inverse;
895
                    }
896
                    return true;
897
                }
898
                else if ("namespace_axis".Equals(value))
899
                {
900
                    return !inverse;
901
                }
902
                else if ("streaming".Equals(value))
903
                {
904
                    return !inverse;
905
                }
906
                else if ("backwards_compatibility".Equals(value))
907
                {
908
                    return !inverse;
909
                }
910
                return false;
911
            }
912
            else if ("xsd-version".Equals(type))
913
            {
914
                if ("1.1".Equals(value))
915
                {
916
                    if (env != null)
917
                    {
918
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.0" : "1.1"));
919
                    }
920
                    else
921
                    {
922
                        return false;
923
                    }
924
                }
925
                else if ("1.0".Equals(value))
926
                {
927
                    if (env != null)
928
                    {
929
                        env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.1" : "1.0"));
930
                    }
931
                    else
932
                    {
933
                        return false;
934
                    }
935
                }
936
                return true;
937
            }
938
            else if ("available_documents".Equals(type))
939
            {
940
                return !inverse;
941
            }
942
            else if ("default_language_for_numbering".Equals(type))
943
            {
944
                return !inverse;
945
            }
946
            else if ("languages_for_numbering".Equals(type))
947
            {
948
                return !inverse;
949
            }
950
            else if ("supported_calendars_in_date_formatting_functions".Equals(type))
951
            {
952
                return !inverse;
953
            }
954
            else if ("default_calendar_in_date_formatting_functions".Equals(type))
955
            {
956
                return !inverse;
957
            }
958
            else if ("maximum_number_of_decimal_digits".Equals(type))
959
            {
960
                return !inverse;
961
                //        } else if ("collation_uri".Equals(type)) {
962
                //            return !inverse;
963
                //        } else if ("statically_known_collations".Equals(type)) {
964
                //            if (value.Equals("http://www.w3.org/xslts/collation/caseblind") && !inverse) {
965
                //                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
966
                //                        new StandardCollationURIResolver() {
967
                //                            public stringCollator resolve(string uri, string base, Configuration config) {
968
                //                                if ("http://www.w3.org/xslts/collation/caseblind".Equals(uri)) {
969
                //                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
970
                //                                } else {
971
                //                                    return super.resolve(uri, base, config);
972
                //                                }
973
                //                            }
974
                //                        }
975
                //                );
976
                //            }
977
                //            // Alternative case-blind collation URI used in QT3 tests
978
                //            if (value.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") && !inverse) {
979
                //                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
980
                //                        new StandardCollationURIResolver() {
981
                //                            public stringCollator resolve(string uri, string base, Configuration config) {
982
                //                                if ("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind".Equals(uri)) {
983
                //                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
984
                //                                } else {
985
                //                                    return super.resolve(uri, base, config);
986
                //                                }
987
                //                            }
988
                //                        }
989
                //                );
990
                //            }
991
                //            return true;
992
            }
993
            else if ("default_output_encoding".Equals(type))
994
            {
995
                return !inverse;
996
            }
997
            else if ("unparsed_text_encoding".Equals(type))
998
            {
999
                return !inverse;
1000
            }
1001
            else if ("additional_normalization_form".Equals(type))
1002
            {
1003
                return !inverse;
1004
            }
1005
            else if ("recognize_id_as_uri_fragment".Equals(type))
1006
            {
1007
                return !inverse;
1008
            }
1009
            else if ("on-multiple-match".Equals(type))
1010
            {
1011
                if (value.Equals("error"))
1012
                {
1013
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.DoNotRecover);
1014
                }
1015
                else
1016
                {
1017
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.RecoverSilently);
1018
                }
1019
                return true;
1020
            }
1021
            else if ("ignore-doc-failure".Equals(type))
1022
            {
1023
                if (value.Equals("false"))
1024
                {
1025
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.DoNotRecover);
1026
                }
1027
                else
1028
                {
1029
                    env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.RecoverSilently);
1030
                }
1031
                return true;
1032
            }
1033
            else if ("combinations_for_numbering".Equals(type))
1034
            {
1035
                if (value.Equals("COPTIC EPACT DIGIT ONE") || value.Equals("SINHALA ARCHAIC DIGIT ONE") || value.Equals("MENDE KIKAKUI DIGIT ONE")) {
1036
                    return false;
1037
                }
1038
                return !inverse;
1039
            }
1040
            else if ("higher_order_functions".Equals(type))
1041
            {
1042
                return !inverse;
1043

    
1044
            }
1045
            else if ("ignore_doc_failure".Equals(type))
1046
            {
1047
                //TODO
1048
                return false;
1049

    
1050
            }
1051
            else if ("simple-uca-fallback".Equals(type))
1052
            {
1053
                return !inverse;
1054

    
1055
            }
1056
            else if ("advanced-uca-fallback".Equals(type))
1057
            {
1058
                return !inverse;
1059

    
1060
            }
1061
            else if ("streaming-fallback".Equals(type))
1062
            {
1063
                bool required = !inverse;
1064
                bool old = env.processor.GetProperty(FeatureKeys.STREAMING_FALLBACK) == "true" || env.processor.GetProperty(FeatureKeys.STREAMING_FALLBACK) == "on";
1065
                if (old != required)
1066
                {
1067
                    env.processor.SetProperty<bool>(Feature<bool>.STREAMING_FALLBACK, required);
1068
                }
1069

    
1070
                return true;
1071
            }
1072
            else if ("sweep_and_posture".Equals(type))
1073
            {
1074
                return !inverse;
1075
            }
1076
            else if ("unicode_version".Equals(type))
1077
            {
1078
                return value.Equals("6.0");
1079
            }
1080
            else if ("enable_assertions".Equals(type))
1081
            {
1082
                return false;
1083
            }
1084
            else if ("year_component_values".Equals(type))
1085
            {
1086
                if ("support year zero".Equals(value)) {
1087
                    if (env != null)
1088
                    {
1089
                        env.processor.SetProperty<String>(Feature<String>.XSD_VERSION, inverse ? "1.0" : "1.1");
1090
                    }
1091
                    else {
1092
                        return false;
1093
                    }
1094

    
1095
                }
1096
                return !inverse;
1097

    
1098
            }
1099
            else
1100
            {
1101
                println("**** dependency not recognized: " + type);
1102
                return false;
1103
            }
1104
    }
1105

    
1106
    /*private static string getCanonicalPath(File file) {
1107
        try {
1108
            return file.getCanonicalPath();
1109
        } catch (IOException err) {
1110
            return file.getAbsolutePath();
1111
        }
1112
    }*/
1113

    
1114
    private static QName getQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath)  {
1115
        string exp = "for $att in " + attributePath +
1116
                " return if (contains($att, ':')) then resolve-QName($att, $att/..) else QName('', $att)";
1117
        XdmAtomicValue qname = (XdmAtomicValue) xpath.EvaluateSingle(exp, contextItem);
1118
        return (qname == null ? null : (QName) qname.Value);
1119
    }
1120

    
1121
    private class OutputResolver : net.sf.saxon.lib.OutputURIResolver{
1122

    
1123
        private Processor proc;
1124
        private TestOutcome outcome;
1125
        private XdmDestination destination;
1126
        private java.io.StringWriter stringWriter;
1127
        bool serialized;
1128
        Uri uri;
1129

    
1130
        public OutputResolver(Processor proc, TestOutcome outcome, bool serialized) {
1131
            this.proc = proc;
1132
            this.outcome = outcome;
1133
            this.serialized = serialized;
1134
        }
1135

    
1136
        public net.sf.saxon.lib.OutputURIResolver newInstance()
1137
        {
1138
            return new OutputResolver(proc, outcome, serialized);
1139
        }
1140
         XmlUrlResolver res = new XmlUrlResolver();
1141
         public JResult resolve(string href, string base1)
1142
         {
1143
            try {
1144
                uri = res.ResolveUri(new Uri(base1), href);
1145
                if (serialized) {
1146
                  
1147
                    stringWriter = new java.io.StringWriter();
1148
                    javax.xml.transform.stream.StreamResult result =  new javax.xml.transform.stream.StreamResult(stringWriter);
1149
                    result.setSystemId(uri.ToString());
1150
                    return result; 
1151
                } else {
1152
                    destination = new XdmDestination();
1153
                    ((XdmDestination)destination).BaseUri = uri;
1154
                        return null;//  destination..GetReceiver(proc.Implementation.makePipelineConfiguration());
1155
                }
1156
            } catch (Exception e) {
1157
                throw e;
1158
            }
1159
        }
1160

    
1161
        public void close(JResult result) {
1162
            if (serialized) {
1163
                outcome.SetSecondaryResult(uri, null, stringWriter.ToString());
1164
            } else {
1165
                XdmDestination xdm = (XdmDestination)destination;
1166
                outcome.SetSecondaryResult(xdm.BaseUri, xdm.XdmNode, null);
1167
            }
1168
        }
1169

    
1170
    }
1171

    
1172

    
1173

    
1174
}
1175
		
1176

    
1177

    
1178

    
1179
}
(18-18/19)