Project

Profile

Help

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

he / tags / 9.6.0.7 / hen / csource / samples / Xslt30TestSuiteDriver.cs @ aa733b18

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

    
17
namespace TestRunner
18
{
19
/**
20
 * This class runs the W3C XSLT Test Suite, driven from the test catalog.
21
 */
22
public class Xslt30TestSuiteDriver : TestDriver {
23

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

    
30
        System.Console.WriteLine("Testing Saxon " + (new Processor()).ProductVersion);
31
        new Xslt30TestSuiteDriver().go(args);
32
    }
33

    
34

    
35
    
36
    public override string catalogNamespace() {
37
        return "http://www.w3.org/2012/10/xslt-test-catalog";
38
    }
39

    
40
    public void writeResultFilePreamble(Processor processor, XdmNode catalog) {
41
        resultsDoc = new Xslt30ResultsDocument(this.resultsDir, Spec.XT30);
42
        //super.writeResultFilePreamble(processor, catalog);
43
    }
44

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

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

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

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

    
114
		internal XdmValue[] getParameters(XPathCompiler xpath, XdmNode node) {
115
			List<XdmValue> params1 = new List<XdmValue>();
116

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

    
133

    
134

    
135
		internal static QName GetQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath) {
136
			string exp = "for $att in " + attributePath +
137
				" return if (contains($att, ':')) then resolve-QName($att, $att/..) else " +
138
				" if (contains($att,'{')) then QName(substring-before(substring-after($att,'{'),'}'),substring-after($att,'}')) else" +
139
				" QName('', $att)";
140
			XdmAtomicValue qname = (XdmAtomicValue) xpath.EvaluateSingle(exp, contextItem);
141

    
142
			return qname == null ? null : new QName(qname.ToString());
143
		}
144

    
145
    private bool isSlow(string testName) {
146
			return testName.StartsWith("regex-classes")||
147
				testName.Equals("normalize-unicode-008");
148
    }
149

    
150

    
151
    protected override void runTestCase(XdmNode testCase, XPathCompiler xpath)  {
152

    
153
        TestOutcome outcome = new TestOutcome(this);
154
        string testName = testCase.GetAttributeValue(new QName("name"));
155
        string testSetName = testCase.Parent.GetAttributeValue(new QName("name"));
156
        ////
157
        if (testName.Equals("type-0174"))
158
        {
159
            int num = 0;
160
            System.Console.WriteLine("Test driver" + num);
161

    
162
        }
163

    
164
        ///
165
        if (exceptionsMap.ContainsKey(testName)) {
166
            notrun++;
167
            resultsDoc.writeTestcaseElement(testName, "notRun", exceptionsMap[testName].GetAttributeValue(new QName("reason")));
168
            return;
169
        }
170

    
171
        if (exceptionsMap.ContainsKey(testName) || isSlow(testName)) {
172
            notrun++;
173
            resultsDoc.writeTestcaseElement(testName, "notRun", "requires excessive resources");
174
            return;
175
        }
176

    
177
       
178

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

    
182
        Environment env = getEnvironment(testCase, xpath);
183
        if(env == null) {
184
            resultsDoc.writeTestcaseElement(testName, "notRun", "test catalog error");
185
            return;
186
        }
187

    
188
        /*if(testName("environment-variable")) {
189
                        EnvironmentVariableResolver resolver = new EnvironmentVariableResolver() {
190
                    public Set<string> getAvailableEnvironmentVariables() {
191
                        Set<string> strings = new HashSet<string>();
192
                        strings.add("QTTEST");
193
                        strings.add("QTTEST2");
194
                        strings.add("QTTESTEMPTY");
195
                        return strings;
196
                    }
197

    
198
                    public string getEnvironmentVariable(string name) {
199
                        if (name.Equals("QTTEST")) {
200
                            return "42";
201
                        } else if (name.Equals("QTTEST2")) {
202
                            return "other";
203
                        } else if (name.Equals("QTTESTEMPTY")) {
204
                            return "";
205
                        } else {
206
                            return null;
207
                        }
208
                    }
209
                }; //TODO
210
            } */
211
         //   env.processor.SetProperty(JFeatureKeys.ENVIRONMENT_VARIABLE_RESOLVER, resolver); //TODO
212
        
213
        XdmNode testInput = (XdmNode) xpath.EvaluateSingle("test", testCase);
214
        XdmNode stylesheet = (XdmNode) xpath.EvaluateSingle("stylesheet", testInput);
215
		XdmNode pack = (XdmNode) xpath.EvaluateSingle("package", testInput);
216

    
217

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

    
226
        XsltExecutable sheet = env.xsltExecutable;
227
       //ErrorCollector collector = new ErrorCollector();
228
			string baseOutputURI = resultsDir + "/results/output.xml";
229
			ErrorCollector collector = new ErrorCollector(outcome);
230
			IList errorList = new List<StaticError> ();
231
        XmlUrlResolver res = new XmlUrlResolver();
232
		string xsltLanguageVersion = spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0";
233
        if (stylesheet != null) {
234
            XsltCompiler compiler = env.xsltCompiler;
235
				compiler.ErrorList = errorList;
236
            Uri hrefFile = res.ResolveUri(stylesheet.BaseUri, stylesheet.GetAttributeValue(new QName("file")));
237
            Stream stream = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
238
            compiler.BaseUri = hrefFile;
239
            compiler.XsltLanguageVersion = (spec.Contains("XSLT30") || spec.Contains("XSLT20+") ? "3.0" : "2.0");
240

    
241
			foreach (XdmItem param in xpath.Evaluate("param[@static='yes']", testInput)) {
242
					String name = ((XdmNode) param).GetAttributeValue(new QName("name"));
243
					String select = ((XdmNode) param).GetAttributeValue(new QName("select"));
244
					XdmValue value;
245
					try {
246
						value = xpath.Evaluate(select, null);
247
					} catch (Exception e) {
248
						Console.WriteLine("*** Error evaluating parameter " + name + ": " + e.Message);
249
						//throw e;
250
						continue;
251
					}
252
					compiler.SetParameter(new QName(name), value);
253

    
254
				}
255

    
256
            try
257
            {
258
                sheet = compiler.Compile(stream);
259
            } catch(Exception err){
260
					Console.WriteLine (err.Message);
261
					//Console.WriteLine(err.StackTrace);
262
					IEnumerator enumerator = errorList.GetEnumerator();
263
					bool checkCur = enumerator.MoveNext();
264
					/*if (checkCur && enumerator.Current != null) {
265
						outcome.SetException ((Exception)(enumerator.Current));
266
					} else {
267
						Console.WriteLine ("Error: Unknown exception thrown");
268
					}*/
269
					outcome.SetErrorsReported (errorList);
270
                
271
                //outcome.SetErrorsReported(collector.GetErrorCodes);
272
            }
273

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

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

    
285
				try {
286
					XsltPackage xpack = compiler.CompilePackage(stream);
287
					sheet = xpack.Link();
288
				} catch (Exception err) {
289
					Console.WriteLine (err.Message);
290
					IEnumerator enumerator = errorList.GetEnumerator ();
291
					enumerator.MoveNext ();
292
					outcome.SetException ((Exception)(enumerator.Current));
293
					outcome.SetErrorsReported (errorList);
294
				}
295
			}
296

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

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

    
306
			if (useXslt30Transformer) {
307
				try {
308

    
309
						bool assertsSerial = xpath.Evaluate("result//(assert-serialization|assert-serialization-error|serialization-matches)", testCase).Count > 0;
310
						bool resultAsTree = env.outputTree;
311
						bool serializationDeclared = env.outputSerialize;
312
						XdmNode needsTree = (XdmNode) xpath.EvaluateSingle("output/@tree", testInput);
313
						if (needsTree != null) {
314
							resultAsTree = needsTree.StringValue.Equals("yes");
315
						}
316
						XdmNode needsSerialization = (XdmNode) xpath.EvaluateSingle("output/@serialize", testInput);
317
						if (needsSerialization != null) {
318
							serializationDeclared = needsSerialization.StringValue.Equals("yes");
319
						}
320
						bool resultSerialized = serializationDeclared || assertsSerial;
321

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

    
328

    
329
						Xslt30Transformer transformer = sheet.Load30();
330
						transformer.InputXmlResolver = env;
331
						if (env.unparsedTextResolver != null) {
332
							transformer.GetUnderlyingController.setUnparsedTextURIResolver(env.unparsedTextResolver);
333
						}
334

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

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

    
342
						}
343

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

    
347
						}
348

    
349

    
350
						transformer.SetStylesheetParameters(globalParams);
351

    
352
						if (contextItem != null) {
353
							transformer.GlobalContextItem = contextItem;
354
						}
355

    
356
						transformer.MessageListener = collector;
357

    
358
						transformer.BaseOutputURI  = baseOutputURI;
359

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

    
362
						XdmValue result = null;
363

    
364
						TextWriter sw = new StringWriter();
365

    
366
						Serializer serializer = env.processor.NewSerializer();
367

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

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

    
374
						controller.setOutputURIResolver(serializingOutput);
375
						XmlDestination dest = null;
376
						if (resultAsTree) {
377
							// If we want non-serialized, we need to accumulate any result documents as trees too
378
							controller.setOutputURIResolver(
379
								new OutputResolver(env.processor, outcome, false));
380
							dest = new XdmDestination();
381
						}
382
						if (resultSerialized) {
383
							dest = serializer;
384
						}
385

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

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

    
402
						if (initialMode != null) {
403
							QName name = GetQNameAttribute(xpath, initialMode, "@name");
404
							try {
405
								if (name != null) {
406
									transformer.InitialMode = name;
407
								} else {
408
									controller.getInitialMode();   /// has the side effect of setting to the unnamed
409
								}
410
							} catch (Exception e) {
411
								if (e.InnerException is net.sf.saxon.trans.XPathException) {
412
									Console.WriteLine(e.Message);
413
									outcome.SetException(e);
414
									//throw new SaxonApiException(e.getCause());
415
								} else {
416
									throw e;
417
								}
418
							}
419
						}
420
						if (initialMode != null || initialTemplate != null) {
421
							XdmNode init = (XdmNode)(initialMode == null ? initialTemplate : initialMode);
422
							Dictionary<QName, XdmValue> params1 = GetNamedParameters(xpath, init, false, false);
423
							Dictionary<QName, XdmValue> tunnelledParams = GetNamedParameters(xpath, init, false, true);
424
							if (xsltLanguageVersion.Equals("2.0")) {
425
								if (!(params1.Count == 0  && tunnelledParams.Count == 0)) {
426
									Console.WriteLine("*** Initial template parameters ignored for XSLT 2.0");
427
								}
428
							} else {
429
								transformer.SetInitialTemplateParameters(params1, false);
430
								transformer.SetInitialTemplateParameters(tunnelledParams, true);
431
							}
432
						}
433

    
434

    
435
						if (initialTemplate != null) {
436
							QName name = GetQNameAttribute(xpath, initialTemplate, "@name");
437
							transformer.GlobalContextItem = contextItem;
438
							if (dest == null) {
439
								result = transformer.CallTemplate(name);
440
							} else {
441
								transformer.CallTemplate(name, dest);
442
							}
443
						} else if (initialFunction != null) {
444
							QName name = getQNameAttribute(xpath, initialFunction, "@name");
445
							XdmValue[] params2 = getParameters(xpath, initialFunction);
446
							if (dest == null) {
447
								result = transformer.CallFunction(name, params2);
448
							} else {
449
								transformer.CallFunction(name, params2, dest);
450
							}
451
						} else {
452
							if (dest == null) {
453
								if(src != null) {
454
									result = transformer.ApplyTemplates(src, srcBaseUri);
455
								} else {
456
									result = transformer.ApplyTemplates(srcNode);
457
								}
458
							} else {
459
								if(src != null) {
460
									transformer.ApplyTemplates(src, dest);
461
								} else {
462
									transformer.ApplyTemplates(srcNode, dest);
463
								}
464
							}
465
						}
466

    
467
						//outcome.SetWarningsReported(collector.getFoundWarnings());
468
						if (resultAsTree && !resultSerialized) {
469
							result = ((XdmDestination) (dest)).XdmNode;
470
						}
471
						if (resultSerialized) {
472
							outcome.SetPrincipalSerializedResult(sw.ToString());
473
						}
474
						outcome.SetPrincipalResult(result);
475

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

    
495
								saveResultsToFile(serialization, path);
496
							}
497
						}
498
					} catch (Exception err) {
499
						//if (err.getCause() is XPathException &&
500
							//!((XPathException) err.getCause()).hasBeenReported()) {
501
							//System.err.println("Unreported ERROR: " + err.getCause());
502
						//}
503
						outcome.SetException(err);
504
						if (collector.getErrorCodes ().Count > 0) {
505
							outcome.SetErrorsReported ((IList)collector.getErrorCodes());
506
						}
507
						//Console.WriteLine(err.StackTrace);
508
							/*if(err.getErrorCode() == null) {
509
                            int b = 3 + 4;  }
510
                        if(err.getErrorCode() != null)
511
							outcome.AddReportedError(err.getErrorCode().getLocalName());
512
						} else {
513
							outcome.SetErrorsReported(collector.getErrorCodes());
514
						}*/
515
					} /*catch (Exception err) {
516
						err.printStackTrace();
517
						failures++;
518
						resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.getClass() + ": " + err.getMessage());
519
						return;
520
					}*/
521
		} else {
522

    
523
            try {
524
                XsltTransformer transformer = sheet.Load();
525
                
526
                //transformer.SetURIResolver(env); //TODO
527
                if (env.unparsedTextResolver != null) {
528
                    transformer.Implementation.setUnparsedTextURIResolver(env.unparsedTextResolver);
529
                }
530
                if (initialTemplate != null) {
531
                    transformer.InitialTemplate = initialTemplateName;
532
                }
533
                if (initialMode != null) {
534
                    transformer.InitialMode = initialModeName;
535
                }
536
                foreach (XdmItem param in xpath.Evaluate("param", testInput)) {
537
                    string name = ((XdmNode)param).GetAttributeValue(new QName("name"));
538
                    string select = ((XdmNode) param).GetAttributeValue(new QName("select"));
539
                    XdmValue value = xpath.Evaluate(select, null);
540
                    transformer.SetParameter(new QName(name), value);
541
                }
542
                if (contextItem != null) {
543
                    transformer.InitialContextNode = (XdmNode)contextItem;
544
                }
545
                if (env.streamedPath != null) {
546
                    transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri);
547
                }
548
                foreach (QName varName in env.params1.Keys) {
549
                    transformer.SetParameter(varName, env.params1[varName]);
550
                }
551
                //transformer.setErrorListener(collector);
552
                transformer.BaseOutputUri = new Uri(resultsDir + "/results/output.xml");
553
                /*transformer.MessageListener = (new MessageListener() {
554
                    public void message(XdmNode content, bool terminate, SourceLocator locator) {
555
                        outcome.addXslMessage(content);
556
                    }
557
                });*/
558

    
559

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

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

    
568
            
569
                transformer.Run(serializer);
570
               
571
                outcome.SetPrincipalSerializedResult(sw.ToString());
572
                if (saveResults) {
573
                    // currently, only save the principal result file
574
                    saveResultsToFile(sw.ToString(),
575
                            resultsDir + "/results/" + testSetName + "/" + testName + ".out");
576
                }
577
                transformer.MessageListener = new TestOutcome.MessageListener(outcome);
578

    
579
                // run without serialization
580
                if (env.streamedPath != null)
581
                {
582
                    transformer.SetInputStream(new FileStream(env.streamedPath, FileMode.Open, FileAccess.Read), testCase.BaseUri); 
583
                }
584
                XdmDestination destination = new XdmDestination();
585
                 transformer.Implementation.setOutputURIResolver(
586
                    new OutputResolver(env.processor, outcome, false));
587
                transformer.Run(destination);
588
               
589
                //transformer. .transform();
590
                outcome.SetPrincipalResult(destination.XdmNode);
591
                //}
592
            } catch (Exception err) {
593
                outcome.SetException(err);
594
                //outcome.SetErrorsReported(collector.getErrorCodes());
595
               // err.printStackTrace();
596
               // failures++;
597
                //resultsDoc.writeTestcaseElement(testName, "fail", "*** crashed " + err.Message);
598
                //return;
599
            }
600
        }
601
        XdmNode assertion = (XdmNode) xpath.EvaluateSingle("result/*", testCase);
602
        if (assertion == null) {
603
            failures++;
604
            resultsDoc.writeTestcaseElement(testName, "fail", "No test assertions found");
605
            return;
606
        }
607
        XPathCompiler assertionXPath = env.processor.NewXPathCompiler();
608
        //assertionXPath.setLanguageVersion("3.0");
609
        bool success = outcome.TestAssertion(assertion, outcome.GetPrincipalResultDoc(), assertionXPath, xpath, debug);
610
        if (success) {
611
            if (outcome.GetWrongErrorMessage() != null) {
612
                outcome.SetComment(outcome.GetWrongErrorMessage());
613
                wrongErrorResults++;
614
            } else {
615
                successes++;
616
            }
617
            resultsDoc.writeTestcaseElement(testName, "pass", outcome.GetComment());
618
        } else {
619
            failures++;
620
            resultsDoc.writeTestcaseElement(testName, "fail", outcome.GetComment());
621
        }
622
    }
623
}
624
		
625

    
626
	
627

    
628

    
629

    
630
   
631

    
632
   internal bool mustSerialize(XdmNode testCase, XPathCompiler xpath) {
633
        return saveResults ||
634
                ((XdmAtomicValue) xpath.EvaluateSingle(
635
                "exists(./result//(assert-serialization-error|serialization-matches|assert-serialization)[not(parent::*[self::assert-message|self::assert-result-document])])", testCase)).GetBooleanValue();
636
    }
637

    
638
    private void saveResultsToFile(string content, string filePath) {
639
        try {
640
            System.IO.File.WriteAllText(filePath, content);
641
        } catch (IOException e) {
642
            println("*** Failed to save results to " + filePath);
643
            throw e;
644
        }
645
    }
646

    
647

    
648
    
649
    public override bool dependencyIsSatisfied(XdmNode dependency, Environment env) {
650
        string type = dependency.NodeName.LocalName;
651
        string value = dependency.GetAttributeValue(new QName("value"));
652
        bool inverse = "false".Equals(dependency.GetAttributeValue(new QName("satisfied")));
653
        if ("spec".Equals(type)) {
654
				bool atLeast = value.EndsWith("+");
655
				value = value.Replace("+", "");
656

    
657
				String specName = ((SpecAttr)spec.GetAttr()).svname.Replace("XT", "XSLT");
658
				int order = value.CompareTo(specName);
659
				return atLeast ? order <= 0 : order == 0;
660
        } else if ("feature".Equals(type)) {
661
//            <xs:enumeration value="backwards_compatibility" />
662
//            <xs:enumeration value="disabling_output_escaping" />
663
//            <xs:enumeration value="schema_aware" />
664
//            <xs:enumeration value="namespace_axis" />
665
//            <xs:enumeration value="streaming" />
666
//            <xs:enumeration value="XML_1.1" />
667

    
668
            if ("XML_1.1".Equals(value) && !inverse) {
669
                if (env != null) {
670
                    env.processor.XmlVersion = (decimal)1.1;
671
                    return true;
672
                } else {
673
                    return false;
674
                }
675
            } else if ("disabling_output_escaping".Equals(value)) {
676
                return !inverse;
677
            } else if ("schema_aware".Equals(value)) {
678
					if (!env.xsltCompiler.SchemaAware) {
679
                    return false; // cannot use the selected tree model for schema-aware tests
680
                }
681
                if (env != null) {
682
                    env.xsltCompiler.SchemaAware = !inverse;
683
                }
684
                return true;
685
            } else if ("namespace_axis".Equals(value)) {
686
                return !inverse;
687
            } else if ("streaming".Equals(value)) {
688
                return !inverse;
689
            } else if ("backwards_compatibility".Equals(value)) {
690
                return !inverse;
691
            }
692
            return false;
693
        } else if ("xsd-version".Equals(type)) {
694
            if ("1.1".Equals(value)) {
695
                if (env != null) {
696
                    env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.0" : "1.1"));
697
                } else {
698
                    return false;
699
                }
700
            } else if ("1.0".Equals(value)) {
701
                if (env != null) {
702
                    env.processor.SetProperty(JFeatureKeys.XSD_VERSION, (inverse ? "1.1" : "1.0"));
703
                } else {
704
                    return false;
705
                }
706
            }
707
            return true;
708
        } else if ("available_documents".Equals(type)) {
709
            return !inverse;
710
        } else if ("default_language_for_numbering".Equals(type)) {
711
            return !inverse;
712
        } else if ("languages_for_numbering".Equals(type)) {
713
            return !inverse;
714
        } else if ("supported_calendars_in_date_formatting_functions".Equals(type)) {
715
            return !inverse;
716
        } else if ("default_calendar_in_date_formatting_functions".Equals(type)) {
717
            return !inverse;
718
        } else if ("maximum_number_of_decimal_digits".Equals(type)) {
719
            return !inverse;
720
//        } else if ("collation_uri".Equals(type)) {
721
//            return !inverse;
722
//        } else if ("statically_known_collations".Equals(type)) {
723
//            if (value.Equals("http://www.w3.org/xslts/collation/caseblind") && !inverse) {
724
//                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
725
//                        new StandardCollationURIResolver() {
726
//                            public stringCollator resolve(string uri, string base, Configuration config) {
727
//                                if ("http://www.w3.org/xslts/collation/caseblind".Equals(uri)) {
728
//                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
729
//                                } else {
730
//                                    return super.resolve(uri, base, config);
731
//                                }
732
//                            }
733
//                        }
734
//                );
735
//            }
736
//            // Alternative case-blind collation URI used in QT3 tests
737
//            if (value.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") && !inverse) {
738
//                env.processor.getUnderlyingConfiguration().setCollationURIResolver(
739
//                        new StandardCollationURIResolver() {
740
//                            public stringCollator resolve(string uri, string base, Configuration config) {
741
//                                if ("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind".Equals(uri)) {
742
//                                    return super.resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
743
//                                } else {
744
//                                    return super.resolve(uri, base, config);
745
//                                }
746
//                            }
747
//                        }
748
//                );
749
//            }
750
//            return true;
751
        } else if ("default_output_encoding".Equals(type)) {
752
            return !inverse;
753
        } else if ("unparsed_text_encoding".Equals(type)) {
754
            return !inverse;
755
        } else if ("year_component_values".Equals(type)) {
756
            return !inverse;
757
        } else if ("additional_normalization_form".Equals(type)) {
758
            return !inverse;
759
        } else if ("recognize_id_as_uri_fragment".Equals(type)) {
760
            return !inverse;
761
        } else if ("on-multiple-match".Equals(type)) {
762
            if (value.Equals("error")) {
763
                env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.DoNotRecover);
764
            } else {
765
                env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.RecoverSilently);
766
            }
767
            return true;
768
        } else if ("ignore-doc-failure".Equals(type)) {
769
            if (value.Equals("false")) {
770
                env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.DoNotRecover);
771
            } else {
772
                env.xsltCompiler.GetUnderlyingCompilerInfo().setRecoveryPolicy((int)RecoveryPolicy.RecoverSilently);
773
            }
774
            return true;
775
        } else if ("combinations_for_numbering".Equals(type)) {
776
            return !inverse;
777
        } else {
778
            println("**** dependency not recognized: " + type);
779
            return false;
780
        }
781
    }
782

    
783
    /*private static string getCanonicalPath(File file) {
784
        try {
785
            return file.getCanonicalPath();
786
        } catch (IOException err) {
787
            return file.getAbsolutePath();
788
        }
789
    }*/
790

    
791
    private static QName getQNameAttribute(XPathCompiler xpath, XdmItem contextItem, string attributePath)  {
792
        string exp = "for $att in " + attributePath +
793
                " return if (contains($att, ':')) then resolve-QName($att, $att/..) else QName('', $att)";
794
        XdmAtomicValue qname = (XdmAtomicValue) xpath.EvaluateSingle(exp, contextItem);
795
        return (qname == null ? null : (QName) qname.Value);
796
    }
797

    
798
    private class OutputResolver : net.sf.saxon.lib.OutputURIResolver{
799

    
800
        private Processor proc;
801
        private TestOutcome outcome;
802
        private XdmDestination destination;
803
        private java.io.StringWriter stringWriter;
804
        bool serialized;
805
        Uri uri;
806

    
807
        public OutputResolver(Processor proc, TestOutcome outcome, bool serialized) {
808
            this.proc = proc;
809
            this.outcome = outcome;
810
            this.serialized = serialized;
811
        }
812

    
813
        public net.sf.saxon.lib.OutputURIResolver newInstance()
814
        {
815
            return new OutputResolver(proc, outcome, serialized);
816
        }
817
         XmlUrlResolver res = new XmlUrlResolver();
818
         public JResult resolve(string href, string base1)
819
         {
820
            try {
821
                uri = res.ResolveUri(new Uri(base1), href);
822
                if (serialized) {
823
                  
824
                    stringWriter = new java.io.StringWriter();
825
                    javax.xml.transform.stream.StreamResult result =  new javax.xml.transform.stream.StreamResult(stringWriter);
826
                    result.setSystemId(uri.ToString());
827
                    return result; 
828
                } else {
829
                    destination = new XdmDestination();
830
                    ((XdmDestination)destination).BaseUri = uri;
831
						return destination.GetReceiver(proc.Implementation.makePipelineConfiguration());
832
                }
833
            } catch (Exception e) {
834
                throw e;
835
            }
836
        }
837

    
838
        public void close(JResult result) {
839
            if (serialized) {
840
                outcome.SetSecondaryResult(uri, null, stringWriter.ToString());
841
            } else {
842
                XdmDestination xdm = (XdmDestination)destination;
843
                outcome.SetSecondaryResult(xdm.BaseUri, xdm.XdmNode, null);
844
            }
845
        }
846

    
847
    }
848

    
849

    
850

    
851
}
852
		
853

    
854

    
855

    
856
}
(23-23/24)