Project

Profile

Help

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

he / src / test / nunit / SaxonNUnit / SaxonNUnit / TestXslt30Transformer.cs @ 3df04590

1
using System;
2
using System.Collections.Generic;
3
using System.Collections;
4
using System.Linq;
5
using System.IO;
6
using System.Text;
7
using Saxon.Api;
8
using NUnit.Framework;
9
using System.Xml;
10
using net.sf.saxon.tree.wrapper;
11

    
12
namespace SaxonNUnit
13
{
14
    public class TestXslt30Transformer
15
    {
16
        [Test]
17
        public void TestSimple() {
18
            // Create a Processor instance.
19
            try {
20
                Processor processor = new Processor(false);
21
                //processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
22
                processor.SetProperty(FeatureKeys.TIMING, "true");
23
                // Create a transformer for the stylesheet.
24
                Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(
25
                    new XmlTextReader(ConfigTest.DATA_DIR + "caffo/Transform2.xslt")).Load30();
26

    
27
                // Create a serializer
28
                XdmDestination serializer = new XdmDestination();
29
                TimeSpan start = DateTime.Now.TimeOfDay;
30

    
31
                // Transform the source XML to System.out.
32
                for (int i = 0; i < 10; i++) {
33
                    // Load the source document
34
                    XdmNode input = processor.NewDocumentBuilder().Build(
35
                        new XmlTextReader(ConfigTest.DATA_DIR + "caffo/Input.xml"));
36
                    // Set the root node of the source document to be the initial context node
37
                    transformer.ApplyTemplates(input, serializer);
38
                }
39

    
40
                TimeSpan end = DateTime.Now.TimeOfDay;
41
                Console.WriteLine("Av Time: " + (((end - start).Milliseconds) / 10) + "ms");
42
                Assert.True(true);
43
            } catch (javax.xml.transform.TransformerException e) {
44
                //Console.WriteLine (e.printStackTrace());
45
                Assert.Fail(e.getMessage());
46

    
47
            }
48

    
49
        }
50

    
51
        [Test]
52
        public void TestXmlPraserError() {
53
            Processor processor = new Processor();
54

    
55
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();
56

    
57
            xsltCompiler.SetErrorList(new List<XmlProcessingError>());
58
           // xsltCompiler.ErrorList = new List<StaticError>();
59
            string xslt = @"<xsl:stylesheet xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"" version=""3.0""</xsl:stylesheet>";
60

    
61
            XsltExecutable xsltExecutable;
62

    
63
            using (StringReader xsltReader = new StringReader(xslt))
64
            {
65
                try
66
                {
67
                    xsltExecutable = xsltCompiler.Compile(xsltReader);
68
                }
69
                catch (Exception)
70
                {
71
                    StringBuilder sb = new StringBuilder();
72
                    sb.AppendFormat("Stylesheet compilation failed with {0} error(s):", xsltCompiler.GetErrorList().Count);
73
                    sb.AppendLine();
74
                    int errCount = 0;
75
                    foreach (var error in xsltCompiler.GetErrorList())
76
                    {
77
                        errCount++;
78
                        string message;
79
                        try
80
                        {
81
                            message = error.InnerMessage;
82
                        }
83
                        catch (NullReferenceException)
84
                        {
85
                            message = error.Message;
86
                        }
87

    
88
                        sb.AppendFormat("Error {0} at line {1}:{2} : {3}", errCount, error.LineNumber, error.ColumnNumber, message);
89
                        sb.AppendLine();
90
                    }
91
                    Console.WriteLine(sb.ToString());
92
                }
93
            }
94

    
95

    
96

    
97
        }
98

    
99

    
100

    
101
        [Test]
102
        public void TestSimpleUNC()
103
        {
104
            // Create a Processor instance.
105
            try
106
            {
107
                Processor processor = new Processor(true);
108
                //processor.SetProperty("http://saxon.sf.net/feature/timing", "true");
109
                processor.SetProperty(FeatureKeys.TIMING, "true");
110
                // Create a transformer for the stylesheet.
111
                Xslt30Transformer transformer = processor.NewXsltCompiler().Compile(
112
                    new Uri("//crayfish/team/UNC_tests/test.xsl")).Load30();
113

    
114
                // Create a serializer
115
                StringWriter sw = new StringWriter();
116
                Serializer serializer = processor.NewSerializer(sw);
117
                TimeSpan start = DateTime.Now.TimeOfDay;
118

    
119

    
120
                // Set the root node of the source document to be the initial context node
121
                transformer.CallTemplate(new QName("main"), serializer);
122

    
123

    
124

    
125
                Console.WriteLine(sw.ToString());
126
                Assert.True(true);
127
            }
128
            catch (javax.xml.transform.TransformerException e)
129
            {
130
                //Console.WriteLine (e.printStackTrace());
131
                Assert.Fail(e.getMessage());
132

    
133
            }
134

    
135
        }
136

    
137
        [Test]
138
        public void TestLineNumber()
139
        {
140

    
141
            Processor _processor = new Processor(false);
142
            // _processor.SetProperty("http://saxon.sf.net/feature/debugByteCode", "true");
143
            // _processor.SetProperty("http://saxon.sf.net/feature/generateByteCode", "true");
144
            string sourcePath = Path.GetFullPath("C:\\work\\misc\\xmark\\xmark10.xml");
145
            string stylesheetPath = Path.GetFullPath("C:\\work\\misc\\xmark\\q12.xsl");
146
            string outputPath = Path.ChangeExtension(sourcePath, ".out.xml");
147

    
148
            DocumentBuilder builder = _processor.NewDocumentBuilder();
149
            XmlReader reader = XmlReader.Create(sourcePath);
150
            builder.BaseUri = new Uri("http://example.com");
151
            builder.IsLineNumbering = true;
152
            Type xtype = reader.GetType();
153
            if (typeof(XmlTextReader).IsAssignableFrom(xtype) || typeof(XmlValidatingReader).IsAssignableFrom(reader.GetType())) {
154
                Console.Error.WriteLine("reader is XmlReader !!!!!");
155
            }
156
            XdmNode node = builder.Build(reader);
157
            int line;// = ((net.sf.saxon.om.NodeInfo)node.Unwrap()).getLineNumber();
158
            int col;// = ((net.sf.saxon.om.NodeInfo)node.Unwrap()).getColumnNumber();
159
            //XmlNode _node = node.Unwrap()
160
            IEnumerator itr = node.EnumerateAxis(XdmAxis.Descendant);
161
            while (itr.MoveNext())
162
            {
163
                node = (XdmNode)itr.Current;
164
                line = ((net.sf.saxon.om.NodeInfo)node.Unwrap()).getLineNumber();
165
                col = ((net.sf.saxon.om.NodeInfo)node.Unwrap()).getColumnNumber();
166
                Console.Error.WriteLine("Line number : " + line + ", Position:" + col);
167
            }
168
            //XmlNode n = (XmlNode)((VirtualNode)node.Unwrap()).getUnderlyingNode();
169
            //IXmlLineInfo xInfo = (IXmlLineInfo)n;
170
            //int line = xInfo.LineNumber;
171
            //int col = xInfo.LinePosition;
172

    
173

    
174
        }
175

    
176
        [Test]
177
        public void TestPipeline1() {
178
            var p = new Processor();
179
            var c = p.NewXsltCompiler();
180
            var xsltStep1 = c.Compile(new Uri(ConfigTest.DATA_DIR + "echo_given_sourcefile.xsl"));
181
            var xsltStep2 = c.Compile(new Uri(ConfigTest.DATA_DIR + "print_elements.xsl"));
182

    
183
            var step1 = xsltStep1.Load();
184
            var step2 = xsltStep2.Load();
185

    
186
            var dest = p.NewSerializer();
187
            dest.SetOutputFile(ConfigTest.DATA_DIR + "OutputStep2.xml");
188

    
189
            step2.Destination = dest;
190

    
191
            var inputFilePath = ConfigTest.DATA_DIR + "books.xml";
192
            using (var input = System.IO.File.OpenRead(inputFilePath))
193
            {
194
                step1.SetInputStream(input, new Uri(inputFilePath));
195

    
196
                step1.Run(step2);
197
            }
198

    
199

    
200
        }
201

    
202
        [Test]
203
        public void TestSingleton() {
204
            try {
205
                Processor proc = new Processor();
206
                var compiler = proc.NewXPathCompiler();
207
                StringReader source = new StringReader("<doc><e>text</e></doc>");
208

    
209
                DocumentBuilder builder = proc.NewDocumentBuilder();
210
                builder.BaseUri = new Uri("http://www.example.com");
211
                XdmNode node = builder.Build(source);
212
                XdmValue value = compiler.Evaluate("//e[1]", node);
213
                IList<XdmItem> list = value.GetList();
214
                Assert.True(list.Count == 1, "List has one item");
215
                IEnumerator enumer = list.GetEnumerator();
216
                enumer.MoveNext();
217
                Assert.True(enumer.Current is XdmValue, "Item in List is an XdmValue");
218
            }
219
            catch (Exception ex) {
220
                Assert.Fail(ex.Message);
221

    
222
            }
223
        }
224
        /*
225
                [Test]
226
                public void TestExportFrom98()
227
                {
228
                    try
229
                    {
230
                        var p = new Processor(true);
231
                        var c = p.NewXsltCompiler();
232
                        var testXSLTP = c.Compile(new Uri(ConfigTest.NUNIT_DATA_DIR + "booksWithMain98.sef"));
233

    
234

    
235
                        var exec = testXSLTP.Load();
236
                        exec.InitialTemplate = new QName("main");
237

    
238
                        var dest = p.NewSerializer();
239
                        dest.SetOutputFile(ConfigTest.DATA_DIR + "OutputStep2.xml");
240
                        exec.Run(dest);
241
                        Assert.True(true);
242
                    }
243
                    catch (javax.xml.transform.TransformerException e)
244
                    {
245
                        Assert.Fail(e.getMessage());
246
                    }
247

    
248
                } */
249

    
250
        [Test]
251
        public void TestExport()
252
        {
253
            try
254
            {
255
                var p = new Processor(true);
256
                var c = p.NewXsltCompiler();
257
                var testXSLTP = c.Compile(new Uri(ConfigTest.NUNIT_DATA_DIR + "booksWithMain.sef"));
258

    
259
                var exec = testXSLTP.Load30();
260

    
261

    
262
                var dest = p.NewSerializer();
263
                dest.SetOutputFile(ConfigTest.DATA_DIR + "OutputStep2.xml");
264
                // exec.Run(dest);
265
                exec.CallTemplate(new QName("main"), dest);
266
                Assert.True(true);
267
            }
268
            catch (Exception e)
269
            {
270
                Assert.Fail(e.Message);
271
            }
272

    
273
        }
274

    
275

    
276
        /**
277
     * Test for the case where the context item is not the root
278
     */
279
        [Test]
280
        public void TestContextNotRoot() {
281
            try {
282
                Processor proc = new Processor(false);
283
                StringReader source = new StringReader("<doc><e>text</e></doc>");
284

    
285
                DocumentBuilder builder = proc.NewDocumentBuilder();
286
                builder.BaseUri = new Uri("http://www.example.com");
287
                XdmNode node = builder.Build(source);
288
                XsltCompiler xqcomp = proc.NewXsltCompiler();
289
                StringReader style = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
290
                    "<xsl:variable name='x' select='.'/>" +
291
                    "<xsl:template match='/'>errorA</xsl:template>" +
292
                    "<xsl:template match='e'>[<xsl:value-of select='name($x)'/>]</xsl:template>" +
293
                    "</xsl:stylesheet>");
294

    
295
                Xslt30Transformer trans = xqcomp.Compile(style).Load30();
296
                StringWriter sw = new StringWriter();
297

    
298
                Serializer serializer = proc.NewSerializer(sw);
299

    
300
                IEnumerator<XdmNode> iter = node.EnumerateAxis(XdmAxis.Descendant, new QName("e"));
301
                bool hasNext = iter.MoveNext();
302
                if (hasNext)
303
                {
304
                    XdmNode e = (XdmNode)iter.Current;
305
                    trans.GlobalContextItem = node;
306
                    trans.ApplyTemplates(e, serializer);
307

    
308
                }
309

    
310

    
311
                String result = sw.ToString();
312
                Assert.False(result.Contains("errorA"), "matched root");
313
                Assert.True(result.Contains("[]"), "matched e");
314

    
315
            } catch (javax.xml.transform.TransformerException e) {
316
                Assert.Fail(e.getMessage());
317
            }
318
        }
319

    
320

    
321
        /// <summary>
322
        /// Bug issue 4683
323
        /// </summary>
324

    
325
        [Test]
326
        public void TestChainedDescendantAxes()
327
        {
328
            try
329
            {
330
                Processor proc = new Processor(false);
331
                StringReader source = new StringReader("<?xml version='1.0' encoding='utf-8' ?><root><item/><item><foo id='foo1'/></item>" +
332
                    "<item></item><item><foo id='foo2'/></item></root>");
333
                XmlTextReader xmlReader = new XmlTextReader(source);
334
                XmlDocument doc = new XmlDocument();
335
                doc.Load(xmlReader);
336

    
337
                DocumentBuilder builder = proc.NewDocumentBuilder();
338
               // builder.BaseUri = new Uri("http://www.example.com");
339
                XdmNode node = builder.Wrap(doc);
340
                XsltCompiler xqcomp = proc.NewXsltCompiler();
341
                StringReader style = new StringReader("<xsl:transform version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
342
  " xmlns:xs='http://www.w3.org/2001/XMLSchema' exclude-result-prefixes='#all'><xsl:param name='DEBUG' static='yes' as='xs:boolean' select='true()'/>" +
343
"<xsl:output method='text' item-separator='&#10;'/><xsl:template match='/'><xsl:for-each select='//item'>" +
344
      "<xsl:assert test='not(*) eq not(descendant::foo)' use-when='$DEBUG'>No child elements but descendants</xsl:assert>" +
345
      "<xsl:value-of select='position(), not(*), descendant::foo/@id'/></xsl:for-each></xsl:template></xsl:transform>");
346

    
347
                Xslt30Transformer trans = xqcomp.Compile(style).Load30();
348
                StringWriter sw = new StringWriter();
349

    
350
                Serializer serializer = proc.NewSerializer(sw);
351

    
352
                trans.GlobalContextItem = node;
353
                trans.ApplyTemplates(node, serializer);
354

    
355

    
356
                String result = sw.ToString();
357
                Assert.AreEqual(result, "1 true\n2 false foo1\n3 true\n4 false foo2");
358

    
359
            }
360
            catch (javax.xml.transform.TransformerException e)
361
            {
362
                Assert.Fail(e.getMessage());
363
            }
364
        }
365

    
366

    
367

    
368

    
369
        [Test]
370
        public void TestResultDocHandlerFunction()
371
        {
372

    
373
            Processor processor = new Processor(true);
374

    
375
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();
376
            xsltCompiler.BaseUri = new Uri("file:///dummy/");
377
            String sr = "<?xml version='1.0' encoding='UTF-8'?>" +
378
"<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
379
 "   xmlns:xs='http://www.w3.org/2001/XMLSchema' exclude-result-prefixes='#all' version='3.0'> " +
380
"<xsl:output method='html' indent='yes' html-version='5'/>" +
381
    "<xsl:template match='/' name='xsl:initial-template'>" +
382
     "   <html><head>" +
383
               " <title>Test</title></head>" +
384
            "<body> " +
385
             "   <h1>Test</h1>" +
386
            "</body>" +
387
        "</html>" +
388
        "<xsl:result-document href='result-1.json' method='json' indent='yes'>" +
389
         "   <xsl:sequence select=\"map { 'name' : 'foo', 'values' : [ 'a', 'b', 'c' ]}\"/>" +
390
        "</xsl:result-document>" +
391
   " </xsl:template></xsl:stylesheet>";
392

    
393
            try
394
            {
395

    
396
                Processor proc = new Processor(false);
397
                proc.SetProperty(FeatureKeys.TIMING, "true");
398
                XsltTransformer transformer = proc.NewXsltCompiler().Compile(new MemoryStream(Encoding.ASCII.GetBytes(sr))).Load();
399

    
400
                transformer.InitialTemplate = new QName("http://www.w3.org/1999/XSL/Transform", "initial-template");
401
                transformer.BaseOutputUri = new Uri("file:////C://work//test");
402
                transformer.Run(proc.NewSerializer(Console.Out));
403

    
404
                Console.WriteLine();
405

    
406
                MyResultDocumentHandler resDocHandler = new MyResultDocumentHandler(proc, new Uri("file:////C://work//test"));
407
                transformer.BaseOutputUri = new Uri("file:////C://work//test");
408

    
409
                transformer.ResultDocumentHandler = resDocHandler;
410

    
411
                transformer.Run(proc.NewSerializer(Console.Out));
412

    
413
                foreach (Serializer ser in resDocHandler.Serializers)
414
                {
415
                    Console.WriteLine("{0}:\n{1}", ser.ToString());
416
                    Console.WriteLine("test");
417
                }
418
                Assert.True(true, "output");
419

    
420
            }
421
            catch (Exception ex)
422
            {
423
                //e.printStackTrace();
424
                Console.WriteLine(ex.StackTrace);
425
                Assert.Fail(ex.Message);
426
            }
427
        }
428

    
429
        internal class MyResultDocumentHandler : IResultDocumentHandler
430
        {
431
            private Processor proc;
432
            private Uri baseUri;
433

    
434
            public List<Serializer> Serializers { get; set; }
435

    
436
            public MyResultDocumentHandler(Processor proc, Uri baseUri)
437
            {
438
                this.proc = proc;
439
                Serializers = new List<Serializer>();
440
                this.baseUri = baseUri;
441
            }
442

    
443
            public XmlDestination HandleResultDocument(string href, Uri baseuri)
444
            {
445
                var ser = proc.NewSerializer();
446
                ser.BaseUri = baseUri;
447
                ser.SetOutputFile("C://work//test//" + href);
448
                Serializers.Add(ser);
449
                return ser;
450
            }
451
        }
452

    
453
        internal class MySerializer
454
        {
455
            private StringWriter resultWriter;
456

    
457
            public string Result { get; private set; }
458

    
459
            public string Href { get; }
460

    
461
            public MySerializer(Processor processor, string href)
462
            {
463
                /* SetProcessor(processor);
464

    
465
                 Href = href;
466

    
467
                 resultWriter = new StringWriter();
468

    
469
                 SetOutputWriter(resultWriter);*/
470

    
471
            }
472

    
473
            /*  public override void Close()
474
              {
475
                  Result = resultWriter.ToString();
476
                  resultWriter.Close();
477
                  resultWriter.Dispose();
478
                  base.Close();
479
              }*/
480
        }
481

    
482
        [Test]
483
        public void TestParseFragment()
484
        {
485
            try
486
            {
487
                Processor proc = new Processor(false);
488
                StringReader source = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
489
            "<root><bob>&lt;hello&gt;Burt&lt;/hello&gt;</bob></root>");
490

    
491
                DocumentBuilder builder = proc.NewDocumentBuilder();
492
                builder.BaseUri = new Uri("http://www.example.com");
493
                XdmNode node = builder.Build(source);
494
                XsltCompiler xqcomp = proc.NewXsltCompiler();
495
                StringReader style = new StringReader("<xsl:stylesheet version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:fn='http://www.w3.org/2005/xpath-functions'>" +
496
    "<xsl:output method='xml' version='1.0' encoding='UTF-8' indent='yes' /><xsl:template match='bob'><greeting>" +
497
            "<xsl:copy-of select='fn:parse-xml-fragment(\"&lt;hello&gt;Ted&lt;/hello&gt;\")'/>" +
498
        "</greeting></xsl:template></xsl:stylesheet>");
499

    
500
                Xslt30Transformer trans = xqcomp.Compile(style).Load30();
501
                StringWriter sw = new StringWriter();
502

    
503
                Serializer serializer = proc.NewSerializer(sw);
504

    
505

    
506

    
507
                String result = sw.ToString();
508
                Console.WriteLine(result);
509
                Assert.True(result.Equals(""), "Output received");
510

    
511
            }
512
            catch (javax.xml.transform.TransformerException e)
513
            {
514
                Assert.Fail(e.getMessage());
515
            }
516
        }
517

    
518

    
519

    
520
        public class TestUriResolver : XmlUrlResolver
521
        {
522
            XdmNode style1;
523
            public TestUriResolver(XdmNode style)
524
            {
525
                this.style1 = style;
526
            }
527

    
528
            public override Uri ResolveUri(Uri base1, string href)
529
            {
530

    
531
                if (href.StartsWith("http:"))
532
                {
533
                    return style1.BaseUri;
534
                }
535
                else
536
                {
537
                    return null;
538
                }
539

    
540
            }
541
        }
542

    
543
        [Test]
544
        public void TestXmlResolver() {
545

    
546
            try {
547
                Processor proc = new Processor(false);
548
                StringReader source = new StringReader("<doc><e>text</e></doc>");
549

    
550
                DocumentBuilder builder = proc.NewDocumentBuilder();
551
                builder.IsLineNumbering = true;
552
                builder.BaseUri = new Uri("http://importer/");
553
                XdmNode node = builder.Build(source);
554
                XsltCompiler xqcomp = proc.NewXsltCompiler();
555
                StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
556
                        "<xsl:template match='e' as='node()'>\n" +
557
                        "<xsl:param name='x' select='0'/>\n" +
558
                        "<xsl:param name='p' as='node()*' select='()'/>\n" +
559
                        //"<e1/>" +
560
                        //"<e2/>" +
561
                        "<xsl:sequence select='$p'/>\n" +
562
                        "</xsl:template>\n" +
563
                        "</xsl:stylesheet>");
564
                builder.BaseUri = new Uri("http://imported/");
565
                XdmNode style1 = builder.Build(sr);
566

    
567
                XmlResolver resolver = new TestUriResolver(style1);
568
                xqcomp.XmlResolver = resolver;
569
                var shouldBeTrue = ReferenceEquals(xqcomp.XmlResolver, resolver);
570

    
571
                Assert.True(shouldBeTrue, "XmlResolver setter should match");
572

    
573
            }
574
            catch (Exception exc) {
575
                Assert.Fail(exc.Message);
576
            }
577
        }
578

    
579

    
580

    
581

    
582

    
583
        [Test]
584
        public void TestSqrt() {
585
            string p =
586
       @"<xsl:package name='http://www.ctk.cz/math' " +
587
       @"  xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:xs='http://www.w3.org/2001/XMLSchema' version='3.0' " +
588
       @"  xmlns:math='http://www.ctk.cz/math' " +
589
       @"  xmlns:demo='http://example.math.co.uk/demo'>" +
590
       @"  <xsl:function name='math:sqrt' as='xs:double?' visibility='final'>" +
591
       @"     <xsl:param name='num' as='xs:double?'/>" +
592
       @"     <xsl:sequence select='demo:sqrt($num)'/>" +
593
       @"  </xsl:function>" +
594
       @"</xsl:package>";
595

    
596

    
597
            String s = @"<xsl:transform version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
598
                      @" xmlns:math='http://www.ctk.cz/math' " +
599
                      @" exclude-result-prefixes='math'> " +
600
                      @" <xsl:use-package name='http://www.ctk.cz/math'/>" +
601
                      @" <xsl:template name='xsl:initial-template' > " +
602
                      @" <out " +
603
                      @" sqrt2='{math:sqrt(2.0e0)}' " +
604
                      @" sqrtEmpty='{math:sqrt(())}'> " +
605
                      @" </out> " +
606
                      @" </xsl:template></xsl:transform>";
607

    
608
            try
609
            {
610

    
611
                Processor processor = new Processor(true);
612
                processor.RegisterExtensionFunction(new Sqrt());
613
                processor.SetProperty("http://saxon.sf.net/feature/optimizationLevel", "-f");
614
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();
615
                xsltCompiler.XsltLanguageVersion = "3.0";
616
                var ms = new MemoryStream(Encoding.UTF8.GetBytes(p));
617
                XsltPackage pp = xsltCompiler.CompilePackage(ms);
618
                xsltCompiler.ImportPackage(pp);
619
                XsltExecutable exec = xsltCompiler.Compile(new StringReader(s));
620
                Xslt30Transformer transf = exec.Load30();
621
                XdmDestination dest = new XdmDestination();
622
                transf.CallTemplate(null, dest);
623
                Console.WriteLine(dest.XdmNode);
624
                Assert.True(true, "ok");
625
            }
626
            catch (Exception exc) {
627
                Assert.Fail(exc.Message);
628
            }
629
        }
630

    
631
        public class Sqrt : ExtensionFunctionDefinition
632
        {
633
            public override QName FunctionName { get { return new QName("http://example.math.co.uk/demo", "sqrt"); } }
634

    
635
            public override int MinimumNumberOfArguments
636
            {
637
                get
638
                {
639
                    return 1;
640
                }
641
            }
642

    
643
            public override int MaximumNumberOfArguments
644
            {
645
                get
646
                {
647
                    return 1;
648
                }
649
            }
650

    
651
            public override XdmSequenceType[] ArgumentTypes
652
            {
653
                get
654
                {
655
                    return new XdmSequenceType[]{
656
                new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?')
657
            };
658
                }
659
            }
660

    
661
            public override XdmSequenceType ResultType(XdmSequenceType[] ArgumentTypes)
662
            {
663
                return new XdmSequenceType(XdmAtomicType.BuiltInAtomicType(QName.XS_DOUBLE), '?');
664
            }
665

    
666
            public override bool TrustResultType
667
            {
668
                get
669
                {
670
                    return true;
671
                }
672
            }
673

    
674

    
675
            public override ExtensionFunctionCall MakeFunctionCall()
676
            {
677
                return new SqrtCall();
678
            }
679
        }
680

    
681
        internal class SqrtCall : ExtensionFunctionCall
682
        {
683
            public override IEnumerator<XdmItem> Call(IEnumerator<XdmItem>[] arguments, DynamicContext context)
684
            {
685
                Boolean exists = arguments[0].MoveNext();
686
                if (exists)
687
                {
688
                    XdmAtomicValue arg = (XdmAtomicValue)arguments[0].Current;
689
                    double val = (double)arg.Value;
690
                    double sqrt = System.Math.Sqrt(val);
691
                    XdmAtomicValue result = new XdmAtomicValue(sqrt);
692
                    return (IEnumerator<XdmItem>)result;
693
                }
694
                else
695
                {
696
                    return EmptyEnumerator<XdmItem>.INSTANCE;
697
                }
698
            }
699
        };
700

    
701

    
702

    
703
        /**
704
     * Test location information for run-time errors when stylesheet built as an XdmNode
705
     */
706
        [Test]
707
        public void TestErrorLocationFromXdm() {
708
            Processor proc = new Processor(false);
709
            try {
710
                // Norm Walsh reported getting line numbers > 2^20. Can't reproduce.
711

    
712

    
713
                StringReader source = new StringReader("<doc><e>text</e></doc>");
714

    
715
                DocumentBuilder builder = proc.NewDocumentBuilder();
716
                builder.IsLineNumbering = true;
717
                builder.BaseUri = new Uri("http://importer/");
718
                XdmNode node = builder.Build(source);
719
                XsltCompiler xqcomp = proc.NewXsltCompiler();
720

    
721
                StringReader style2Sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
722
                    "<xsl:import href='file:///" + ConfigTest.DATA_DIR + "identity.xsl'/>\n" +
723
                    "<xsl:import href='http://imported'/>\n" +
724
                    "<xsl:param name='x' select='0'/>\n" +
725
                    "<xsl:template match='/'>\n" +
726
                    "<xsl:apply-templates select='*'>\n" +
727
                    "<xsl:with-param name='p' select='()'/>\n" +
728
                    "</xsl:apply-templates>\n" +
729
                    "</xsl:template>\n" +
730
                    "</xsl:stylesheet>");
731

    
732
                XdmNode style2 = builder.Build(style2Sr);
733

    
734
                //XdmNode style2 = builder.Build(new StreamSource(sr, "http://importer/"));
735

    
736
                StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
737
                    "<xsl:template match='e' as='node()'>\n" +
738
                    "<xsl:param name='x' select='0'/>\n" +
739
                    "<xsl:param name='p' as='node()*' select='()'/>\n" +
740
                    //"<e1/>" +
741
                    //"<e2/>" +
742
                    "<xsl:sequence select='$p'/>\n" +
743
                    "</xsl:template>\n" +
744
                    "</xsl:stylesheet>");
745
                builder.BaseUri = new Uri("http://imported/");
746
                XdmNode style1 = builder.Build(sr);
747

    
748
                xqcomp.XmlResolver = new TestUriResolver(style1);
749

    
750
                Xslt30Transformer trans = xqcomp.Compile(style2.BaseUri).Load30();
751

    
752
                Serializer serializer = proc.NewSerializer();
753
                MemoryStream os = new MemoryStream();
754
                serializer.SetOutputStream(os);
755
                trans.ApplyTemplates(node, serializer);
756

    
757
                Assert.Fail("Transformation should fail");
758

    
759
            } catch (Exception e) {
760
                Assert.True(true, e.Message);
761
                //Assert.True(((net.sf.saxon.trans.XPathException) e.getCause()).getLocator().getLineNumber() == 5, "line=5");
762
            }
763
        }
764

    
765

    
766
        /**
767
         * Related to bug  issue 4253 
768
         */
769
        [Test]
770
        public void TestParseXmlFragment()
771
        {
772
            Processor processor = new Processor(true);
773

    
774
            string xslt =
775
                @"<xsl:transform version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
776
                @" <xsl:template name='xsl:initial-template' > " +
777
                @"  <xsl:variable name='doc'>to je test</xsl:variable>" +
778
                @"  <xsl:sequence select='parse-xml-fragment($doc)'/>" +
779
                @" </xsl:template>" +
780
                @"</xsl:transform>";
781

    
782
            try {
783
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();
784
                xsltCompiler.XsltLanguageVersion = "3.0";
785
                XsltExecutable exec = xsltCompiler.Compile(new StringReader(xslt));
786
                Xslt30Transformer transf = exec.Load30();
787
                Serializer ser = processor.NewSerializer();
788
                StringWriter sw = new StringWriter();
789
                ser.SetOutputWriter(sw);
790
                transf.CallTemplate(null, ser);
791
                Assert.True(sw.ToString() != null);
792
            }
793
            catch (Exception e) {
794
                Assert.Fail(e.Message);
795
            }
796

    
797
        }
798

    
799

    
800
        /**
801
     * Test created ErrorListener picks up errors in imported stylesheet
802
     */
803
        [Test]
804
        public void TestErrorInImportedStylesheet() {
805
            List<StaticError> warnings = new List<StaticError>();
806
            List<StaticError> errors = new List<StaticError>();
807
            List<StaticError> fatals = new List<StaticError>();
808

    
809
            try {
810

    
811
                Processor proc = new Processor(true);
812

    
813

    
814
                XsltCompiler xqcomp = proc.NewXsltCompiler();
815
                xqcomp.ErrorList = errors;
816
                //.setErrorListener(listener);
817

    
818
                Xslt30Transformer trans = xqcomp.Compile(new XmlTextReader(((ConfigTest.NUNIT_DATA_DIR + "main.xsl")))).Load30();
819

    
820
                Serializer serializer = proc.NewSerializer();
821
                MemoryStream os = new MemoryStream();
822
                serializer.SetOutputStream(os);
823

    
824
                trans.CallTemplate(new QName("main"), serializer);
825

    
826
                Assert.Fail("Transformation should fail");
827

    
828
            } catch (StaticError e) {
829
                Assert.True(errors.Count > 0, "errors");
830
                //e.printStackTrace();
831
            }
832
        }
833

    
834

    
835

    
836

    
837
        /**
838
     * Test for the case where the context item is not the root, when starting at a named template
839
     */
840
        [Test]
841
        public void TestContextNotRootNamedTemplate() {
842
            try {
843
                Processor proc = new Processor(false);
844
                StringReader source = new StringReader("<doc><e>text</e></doc>");
845

    
846
                DocumentBuilder builder = proc.NewDocumentBuilder();
847
                builder.BaseUri = new Uri("http://doc");
848
                XdmNode node = builder.Build(source);
849
                XsltCompiler xqcomp = proc.NewXsltCompiler();
850
                StringReader style = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
851
                    "<xsl:variable name='x' select='.'/>" +
852
                    "<xsl:template match='/'>errorA</xsl:template>" +
853
                    "<xsl:template name='main'>[<xsl:value-of select='name($x)'/>]</xsl:template>" +
854
                    "</xsl:stylesheet>");
855

    
856
                Xslt30Transformer trans = xqcomp.Compile(new XmlTextReader(ConfigTest.NUNIT_DATA_DIR + "result-document.xsl")).Load30();
857
                StringWriter os = new StringWriter();
858
                Serializer serializer = proc.NewSerializer(os);
859

    
860

    
861

    
862
                trans.GlobalContextItem = node;
863
                trans.CallTemplate(new QName("main"), serializer);
864

    
865
                String result = os.ToString();
866
                Assert.False(result.Contains("errorA"), "matched root");
867
                Assert.True(result.Contains("[]"), "matched e");
868

    
869
            } catch (javax.xml.transform.TransformerException e) {
870
                Assert.Fail(e.getMessage());
871
            }
872
        }
873

    
874
        [Test]
875
        public void TestResultDocument() {
876
            try { 
877
            Processor proc = new Processor(false);
878
            StringReader source = new StringReader("<doc><e>text</e></doc>");
879

    
880
            DocumentBuilder builder = proc.NewDocumentBuilder();
881
            builder.BaseUri = new Uri("http://doc");
882
            XdmNode node = builder.Build(source);
883
            XsltCompiler xqcomp = proc.NewXsltCompiler();
884
            StringReader style = new StringReader("<xsl:stylesheet version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
885
                "<xsl:template name='main'><xsl:result-document href='a/b/c/d.xml'>" +
886
                "<test> output </test></xsl:result-document>" +
887
                "</xsl:template>" +
888
                "</xsl:stylesheet>");
889

    
890
            Xslt30Transformer trans = xqcomp.Compile(style).Load30();
891
            StringWriter os = new StringWriter();
892
            Serializer serializer = proc.NewSerializer(os);
893

    
894

    
895

    
896
            trans.GlobalContextItem = node;
897
            trans.CallTemplate(new QName("main"));
898
            Assert.True(File.Exists("file:"+ConfigTest.DATA_DIR+"\\a\\b\\c\\d.xml"));
899

    
900
        } catch (javax.xml.transform.TransformerException e) {
901
				Assert.Fail(e.getMessage());
902
			}
903
        }
904

    
905

    
906

    
907

    
908

    
909

    
910
        [Test]
911
        public void TestUseAssociated() {
912

    
913
            try {
914
                Processor processor = new Processor(false);
915

    
916
                XsltCompiler compiler = processor.NewXsltCompiler();
917

    
918
                String d = ConfigTest.DATA_DIR + "trax/";
919

    
920
                String foo_xml = d + "xml/foo.xml";
921
                XdmNode sourceNode = processor.NewDocumentBuilder().Build(new Uri(foo_xml));
922
                XsltExecutable executable = compiler.CompileAssociatedStylesheet(sourceNode);
923

    
924

    
925
                Xslt30Transformer transformer = executable.Load30();
926

    
927
                Serializer serializer = processor.NewSerializer();
928
                serializer.SetOutputWriter(Console.Out);
929
                transformer.ApplyTemplates(new FileStream(foo_xml, FileMode.Open), serializer);
930

    
931

    
932
            }
933
            catch (Exception ex) {
934
                Assert.Fail(ex.Message);
935

    
936
            }
937

    
938
        }
939

    
940
		/**
941
     * Build a document from a non-root element of a DOMSource
942
     */
943
		[Test]
944
		public void TestNonRootDomSource() {
945
			try {
946
				Processor proc = new Processor(false);
947
				XsltCompiler comp = proc.NewXsltCompiler();
948
				StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
949
					"<xsl:template match='/'>///<xsl:apply-templates/></xsl:template>" +
950
					"<xsl:template match='*'>***<xsl:apply-templates/></xsl:template>" +
951
					"</xsl:stylesheet>");
952
				XsltExecutable exec = comp.Compile(sr);
953
				Xslt30Transformer xsl = exec.Load30();
954
				String source = "<?xml version='1.0'?>" +
955
					"<doc><a><b/></a></doc>";
956

    
957
				// Read an XML file to a DOM
958
				XmlTextReader xmlReader = new XmlTextReader(new StringReader(source));
959
				XmlDocument doc = new XmlDocument();
960
				doc.Load(xmlReader);
961

    
962

    
963
				XmlElement ele = doc.DocumentElement;
964
				DocumentBuilder builder = proc.NewDocumentBuilder();
965

    
966
				StringWriter writer = new StringWriter();
967
				Serializer serializer = proc.NewSerializer(writer);
968
				xsl.ApplyTemplates(builder.Wrap(doc).TypedValue, serializer);
969

    
970
				Assert.False(writer.ToString().Contains("///"), "started at element node");
971
			} catch (javax.xml.transform.TransformerException e) {
972
				//e.printStackTrace();
973
				Assert.Fail(e.getMessage());
974
			}
975

    
976
		}
977

    
978
		/**
979
     * Send output to an XdmDestination
980
     */
981
		[Test]
982
		public void TestXdmDestination() {
983
			try {
984
				Processor proc = new Processor(false);
985
				XsltCompiler comp = proc.NewXsltCompiler();
986
				StringReader style = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
987
					"<xsl:template name='go'><a/></xsl:template>" +
988
					"</xsl:stylesheet>");
989
				XsltExecutable exec = comp.Compile(style);
990
				Xslt30Transformer xsl = exec.Load30();
991
				XdmDestination outDest = new XdmDestination();
992
				xsl.CallTemplate(new QName("go"), outDest);
993
				XdmNode root = outDest.XdmNode;
994
				Assert.True(XdmNodeKind.ForNode(root) == XdmNodeKind.Document, "result is document node");
995
			} catch (javax.xml.transform.TransformerException e) {
996
				//Console.WriteLine(e.printStackTrace());
997
				Assert.Fail(e.getMessage());
998
			}
999

    
1000
		}
1001

    
1002
        [Test]
1003
        public void TestXdmDestinationWithItemSeparator()
1004
        {
1005
            try
1006
            {
1007
                Processor proc = new Processor(false);
1008
                XsltCompiler comp = proc.NewXsltCompiler();
1009
                StringReader sr = new StringReader(
1010
                        "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1011
                            "<xsl:template name='go'><xsl:comment>A</xsl:comment><out/><xsl:comment>Z</xsl:comment></xsl:template>" +
1012
                                "<xsl:output method='xml' item-separator='§'/>" +
1013
                                                           "</xsl:stylesheet>");
1014
                XsltExecutable exec = comp.Compile(sr);
1015
                Xslt30Transformer xsl = exec.Load30();
1016
                XdmDestination outi = new XdmDestination();
1017
                xsl.CallTemplate(new QName("go"), outi);
1018
                XdmNode root = outi.XdmNode;
1019
                Assert.AreEqual("<!--A-->§<out/>§<!--Z-->", root.ToString());
1020
                Assert.True(root.NodeKind == XmlNodeType.Document, "result is document node");
1021
            }
1022
            catch (javax.xml.transform.TransformerException e)
1023
            {
1024
                //Console.WriteLine(e.printStackTrace());
1025
                Assert.Fail(e.getMessage());
1026
            }
1027

    
1028
        }
1029

    
1030
        [Test]
1031
        public void SchematronTest()
1032
        {
1033

    
1034
            Uri schematron = new Uri(ConfigTest.NUNIT_DATA_DIR + "cmsSchematronErrors.xsl"); //cmsSchematronErrors.xsl //cmsSchematronErrors.xsl
1035
            Uri data= new Uri(ConfigTest.NUNIT_DATA_DIR + "dummyData001.xml");
1036
            Processor processor = new Processor();
1037
            
1038
            try
1039
            {
1040

    
1041
                DocumentBuilder db = processor.NewDocumentBuilder();
1042
            db.IsLineNumbering = true;
1043

    
1044
            XdmNode input = db.Build(data);
1045

    
1046
                XsltCompiler compiler = processor.NewXsltCompiler();
1047
                compiler.XsltLanguageVersion = "3.0";
1048
            XsltTransformer transformer = compiler.Compile(schematron).Load();
1049
               
1050
            transformer.InitialContextNode = input;
1051

    
1052
            Serializer serializer = processor.NewSerializer();
1053
            serializer.SetOutputStream(new MemoryStream());
1054

    
1055
            transformer.MessageListener = new SchMessageListener();
1056

    
1057
                transformer.Run(serializer);
1058
                Assert.True(true);
1059
            }
1060
            catch (javax.xml.transform.TransformerException ex) {
1061
                Assert.Fail(ex.getMessage());
1062

    
1063
            }
1064
            Console.WriteLine("\nOutput written to ExampleSimple2.out\n");
1065

    
1066
        }
1067

    
1068
        public class SchMessageListener : IMessageListener
1069
        {
1070
            public void Message(XdmNode content, bool terminate, IXmlLocation location)
1071
            {
1072

    
1073
                int xx = content.Implementation.getLineNumber();
1074

    
1075
                Console.Out.WriteLine("MESSAGE terminate=" + (terminate ? "yes" : "no") + " at " + DateTime.Now);
1076
                Console.Out.WriteLine("From instruction at line " + location.LineNumber +
1077
                        " of " + location.BaseUri);
1078
                Console.Out.WriteLine(">>" + content.StringValue);
1079

    
1080
            }
1081
        }
1082

    
1083
        /**
1084
     * Send output to a XOM tree
1085
     */
1086
        /*
1087
		public void TestXOMDestination() {
1088
			try {
1089
				Processor proc = new Processor(false);
1090
				XsltCompiler comp = proc.NewXsltCompiler();
1091
				StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1092
					"<xsl:template name='go'><a/></xsl:template>" +
1093
					"</xsl:stylesheet>");
1094
				XsltExecutable exec = comp.Compile(new StreamSource(sr));
1095
				Xslt30Transformer xsl = exec.Load30();
1096
				XdmDestination out = new XdmDestination();
1097
				out.setTreeModel(XOMObjectModel.getInstance());
1098
				xsl.CallTemplate(new QName("go"), out);
1099
				XdmNode root = out.getXdmNode();
1100
				Assert.True(root.getUnderlyingNode() is XOMDocumentWrapper, "result is XOM document node");
1101
			} catch (javax.xml.transform.TransformerException e) {
1102
				e.printStackTrace();
1103
				Assert.Fail(e.getMessage());
1104
			}
1105

    
1106
		}*/
1107

    
1108
        /**
1109
     * Send output to a JDOM tree
1110
     */
1111
        /*
1112
		public void TestJDOMDestination() {
1113
			try {
1114
				Processor proc = new Processor(false);
1115
				XsltCompiler comp = proc.NewXsltCompiler();
1116
				StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1117
					"<xsl:template name='go'><a/></xsl:template>" +
1118
					"</xsl:stylesheet>");
1119
				XsltExecutable exec = comp.Compile(new StreamSource(sr));
1120
				Xslt30Transformer xsl = exec.Load30();
1121
				XdmDestination out = new XdmDestination();
1122
				out.setTreeModel(JDOMObjectModel.getInstance());
1123
				xsl.CallTemplate(new QName("go"), out);
1124
				XdmNode root = out.getXdmNode();
1125
				Assert.True("result is JDOM document node", root.getUnderlyingNode() instanceof JDOMDocumentWrapper);
1126
			} catch (javax.xml.transform.TransformerException e) {
1127
				e.printStackTrace();
1128
				Assert.Fail(e.getMessage());
1129
			}
1130

    
1131
		}*/
1132

    
1133
        /**
1134
     * Send output to a JDOM2 tree
1135
     */
1136
        /*
1137
		public void TestJDOM2Destination() {
1138
			try {
1139
				Processor proc = new Processor(false);
1140
				XsltCompiler comp = proc.NewXsltCompiler();
1141
				StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1142
					"<xsl:template name='go'><a/></xsl:template>" +
1143
					"</xsl:stylesheet>");
1144
				XsltExecutable exec = comp.Compile(new StreamSource(sr));
1145
				Xslt30Transformer xsl = exec.Load30();
1146
				XdmDestination out = new XdmDestination();
1147
				out.setTreeModel(JDOM2ObjectModel.getInstance());
1148
				xsl.CallTemplate(new QName("go"), out);
1149
				XdmNode root = out.getXdmNode();
1150
				Assert.True("result is JDOM2 document node", root.getUnderlyingNode() instanceof net.sf.saxon.option.jdom2.JDOM2DocumentWrapper);
1151
			} catch (javax.xml.transform.TransformerException e) {
1152
				e.printStackTrace();
1153
				Assert.Fail(e.getMessage());
1154
			}
1155

    
1156
		}*/
1157

    
1158
        public void TestExtensionWithSchemaAccess() {
1159
			// Create a Processor instance.
1160
			try {
1161
				Processor proc = new Processor(true);
1162
				proc.SetProperty("http://saxon.sf.net/feature/timing", "true");
1163
				XsltCompiler comp = proc.NewXsltCompiler();
1164
				comp.SchemaAware= true;
1165
				StringReader style = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:my='java:s9apitest.TestXslt30Transformer' exclude-result-prefixes='my'>" +
1166
					"<xsl:template match='*'><xsl:copy><xsl:copy-of select='@*'/><xsl:apply-templates/></xsl:copy></xsl:template>\n" +
1167
					"<xsl:template match='*/*/*/*[my:isOptional(.., node-name(.))]'/> \n" +
1168
					"</xsl:stylesheet>");
1169
				XsltExecutable exec = comp.Compile(style);
1170
				Xslt30Transformer transformer = exec.Load30();
1171

    
1172
				SchemaManager sm = proc.SchemaManager;
1173
				sm.Compile(new XmlTextReader(ConfigTest.DATA_DIR + "books.xsd"));
1174
				DocumentBuilder builder = proc.NewDocumentBuilder();
1175
				SchemaValidator schemaValidator =  sm.NewSchemaValidator();
1176
				schemaValidator.SetSource(builder.Build(new Uri(ConfigTest.DATA_DIR + "books.xml")));
1177
				// Create a serializer
1178
				//String outfile = @"C:/MyJava/users/caffo/Output.xml";
1179
				StringWriter sw = new StringWriter();
1180
				Serializer serializer = proc.NewSerializer(sw);
1181
				serializer.SetOutputProperty(Serializer.INDENT, "yes");
1182
				XdmDestination dest = new XdmDestination();
1183
				schemaValidator.SetDestination(dest);
1184

    
1185
					transformer.ApplyTemplates(dest.XdmNode, serializer);
1186
				Assert.True(sw.ToString().Contains("TITLE"));
1187
				Assert.False(sw.ToString().Contains("AUTHOR"));
1188
			} catch (javax.xml.transform.TransformerException e) {
1189
				//Console.WriteLine(e.printStackTrace());
1190
				Assert.Fail(e.getMessage());
1191
			}
1192

    
1193
		}
1194

    
1195

    
1196

    
1197

    
1198
		/**
1199
     * Sample extension function - explores schema information
1200
     *
1201
     * @return true if the element defined by childName is optional in the context of the governing
1202
     *         type of parent.
1203
     */
1204

    
1205
		public static bool isOptional(net.sf.saxon.om.NodeInfo parent, java.lang.Object childName)  {
1206
			//Configuration config = parent.getConfiguration();
1207
			parent.getConfiguration ();
1208
			Console.WriteLine (childName);
1209
			/*SchemaType parentType = parent.getSchemaType();
1210
			int fp = parent.getConfiguration().getNamePool().allocate("", childName.getComponent(AccessorFn.NAMESPACE).getStringValue(),
1211
				childName.getComponent(AccessorFn.LOCALNAME).getStringValue());
1212
			int cardinality = ((ComplexType) parentType).getElementParticleCardinality(fp, true);*/
1213
			return true;//Cardinality.allowsZero(cardinality);
1214
		}
1215

    
1216
		/**
1217
     * s9api transformation pipeline
1218
     */
1219
        [Test]
1220
		public void TestPipeline() {
1221
			try {
1222
				Processor proc = new Processor(false);
1223
				XsltCompiler comp = proc.NewXsltCompiler();
1224

    
1225
				String xsl = "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1226
					"<xsl:template match='/'><a><xsl:copy-of select='.'/></a></xsl:template>" +
1227
					"</xsl:stylesheet>";
1228
				String xml = "<z/>";
1229
                DocumentBuilder builder = proc.NewDocumentBuilder();
1230
                builder.BaseUri = new Uri("http://example.com");
1231
				XdmNode inNode = builder.Build(new StringReader(xml));
1232
				Xslt30Transformer stage1 = comp.Compile(new StringReader(xsl)).Load30();
1233
				Xslt30Transformer stage2 = comp.Compile(new StringReader(xsl)).Load30();
1234
				Xslt30Transformer stage3 = comp.Compile(new StringReader(xsl)).Load30();
1235
				Xslt30Transformer stage4 = comp.Compile(new StringReader(xsl)).Load30();
1236
				Xslt30Transformer stage5 = comp.Compile(new StringReader(xsl)).Load30();
1237
                XdmDestination d1 = new XdmDestination();
1238
                stage1.ApplyTemplates(inNode, d1);
1239
                XdmDestination d2 = new XdmDestination();
1240
                stage2.ApplyTemplates(d1.XdmNode, d2);
1241
                XdmDestination d3 = new XdmDestination();
1242
                stage3.ApplyTemplates(d2.XdmNode, d3);
1243
                XdmDestination d4 = new XdmDestination();
1244
                stage4.ApplyTemplates(d3.XdmNode, d4);
1245
                StringWriter sw = new StringWriter();
1246
                Serializer outi = proc.NewSerializer(sw);
1247
                stage5.ApplyTemplates(d4.XdmNode, outi);
1248
                Assert.True(sw.ToString().Contains("<a><a><a><a><a><z/></a></a></a></a></a>"), "output");
1249

    
1250
            }
1251
            catch (javax.xml.transform.TransformerException err) {
1252
				err.printStackTrace();
1253
				Assert.Fail(err.getMessage());
1254
			}
1255
		}
1256

    
1257
        [Test]
1258
        public void TestResultDocumentWithDir() {
1259

    
1260
            Processor proc = new Processor();
1261

    
1262
            XsltCompiler comp = proc.NewXsltCompiler();
1263

    
1264
            String xsl = "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +"<xsl:template name='main'>" +
1265
        "<xsl:result-document href='a/b/c/d.xml' omit-xml-declaration='yes'>" +
1266
			"<out>test</out>" +
1267
		"</xsl:result-document></xsl:template></xsl:stylesheet>";
1268
            Uri xsl2 = new Uri("C:\\work\\test\\resultDocument.xsl");
1269
            Xslt30Transformer t1 = comp.Compile(new StringReader(xsl)).Load30(); //new StringReader(xsl)
1270
            XdmDestination dest = new XdmDestination();
1271
            dest.BaseUri = new Uri("http://www.example.com");
1272
            
1273
            t1.CallTemplate(new QName("main"), dest);
1274
        }
1275

    
1276

    
1277

    
1278
        /**
1279
* s9api transformation pipeline on XsltTransformer API
1280
*/
1281
        [Test]
1282
        public void TestPipelineOnXsltTransformer()
1283
        {
1284
            try
1285
            {
1286
                Processor proc = new Processor(true);
1287
                XsltCompiler comp = proc.NewXsltCompiler();
1288

    
1289
                String xsl = "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1290
                    "<xsl:template match='/'><a><xsl:copy-of select='.'/></a></xsl:template>" +
1291
                    "</xsl:stylesheet>";
1292
                String xml = "<z/>";
1293
                DocumentBuilder builder = proc.NewDocumentBuilder();
1294
                builder.BaseUri = new Uri("http://example.com");
1295
                XdmNode doc = builder.Build(new StringReader(xml));
1296
                XsltTransformer t1 = comp.Compile(new StringReader(xsl)).Load();
1297
                XsltTransformer t2 = comp.Compile(new StringReader(xsl)).Load();
1298
                XsltTransformer t3 = comp.Compile(new StringReader(xsl)).Load();
1299

    
1300
                XdmDestination d1 = new XdmDestination();
1301
                var dest = new XdmDestination();
1302
                
1303
                t1.InitialContextNode = doc;
1304

    
1305
                t2.Destination = t3;
1306

    
1307
                t3.Destination = dest;
1308

    
1309
                t1.Run(t2);
1310

    
1311
                XdmNode node = dest.XdmNode;
1312
                StringWriter sw = new StringWriter();
1313
                Serializer serializer = proc.NewSerializer(sw);
1314
                serializer.SetOutputProperty(Serializer.SAXON_INDENT_SPACES,"0");
1315
                serializer.SerializeXdmNode(node);
1316
                Assert.True(sw.ToString().Contains("<a><a><a><z/></a></a></a>"), "output");
1317

    
1318
            }
1319
            catch (javax.xml.transform.TransformerException err)
1320
            {
1321
                err.printStackTrace();
1322
                Assert.Fail(err.getMessage());
1323
            }
1324
        }
1325

    
1326

    
1327
        /**
1328
     * s9api transformation pipeline
1329
     */
1330
        [Test]
1331
        public void TestPipeline2()
1332
        {
1333
            try
1334
            {
1335
                Processor proc = new Processor(false);
1336
                XsltCompiler comp = proc.NewXsltCompiler();
1337

    
1338
                String xsl = "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1339
                    "<xsl:template match='/'><a><xsl:copy-of select='.'/></a></xsl:template>" +
1340
                    "</xsl:stylesheet>";
1341
                String xml = "<z/>";
1342
                
1343
                Xslt30Transformer stage1 = comp.Compile(new StringReader(xsl)).Load30();
1344
                Xslt30Transformer stage2 = comp.Compile(new StringReader(xsl)).Load30();
1345
                Xslt30Transformer stage3 = comp.Compile(new StringReader(xsl)).Load30();
1346
                Xslt30Transformer stage4 = comp.Compile(new StringReader(xsl)).Load30();
1347
                Xslt30Transformer stage5 = comp.Compile(new StringReader(xsl)).Load30();
1348
                StringWriter sw = new StringWriter();
1349
                Serializer outi = proc.NewSerializer();
1350
                XdmDestination d1 = new XdmDestination();
1351
                outi.SetOutputWriter(sw);
1352
                stage1.ApplyTemplates(new MemoryStream(Encoding.ASCII.GetBytes(xml)),
1353
                                      stage2.AsDocumentDestination(
1354
                                              stage3.AsDocumentDestination(
1355
                                                      stage4.AsDocumentDestination(
1356
                                                              stage5.AsDocumentDestination(outi)))));
1357
                Console.WriteLine(sw.ToString());
1358
                Assert.True(sw.ToString().Contains("<a><a><a><a><a><z/></a></a></a></a></a>"), "output");
1359

    
1360
            }
1361
            catch (javax.xml.transform.TransformerException err)
1362
            {
1363
                err.printStackTrace();
1364
                Assert.Fail(err.getMessage());
1365
            }
1366
        }
1367

    
1368

    
1369
        /**
1370
   * s9api transformation pipeline
1371
   */
1372
        [Test]
1373
        public void TestPipelineShort()
1374
        {
1375
            try
1376
            {
1377
                Processor proc = new Processor(true);
1378
                XsltCompiler comp = proc.NewXsltCompiler();
1379

    
1380
                String xsl = "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1381
                        "<xsl:template match='/'><a><xsl:copy-of select='.'/></a></xsl:template>" +
1382
                        "</xsl:stylesheet>";
1383
                String xml = "<z/>";
1384
                Xslt30Transformer stage1 = comp.Compile(new StringReader(xsl)).Load30();
1385
                Xslt30Transformer stage2 = comp.Compile(new StringReader(xsl)).Load30();
1386
                StringWriter sw = new StringWriter();
1387
                Serializer outi = proc.NewSerializer(sw);
1388
            outi.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1389
                stage1.ApplyTemplates(new MemoryStream(Encoding.ASCII.GetBytes(xml)),
1390
                                      stage2.AsDocumentDestination(outi));
1391
                Console.WriteLine(sw);
1392
                Assert.True(sw.ToString().Contains("<a><a><z/></a></a>"), "output");
1393

    
1394
            }
1395
            catch (Exception err)
1396
            {
1397
                
1398
                Assert.Fail(err.Message);
1399
            }
1400
        }
1401
        /**
1402
     * Test location information for run-time errors when stylesheet built as an XdmNode
1403
     */
1404

    
1405
        public void TestErrorNotificationFromSaxonParse() {
1406
			List<StaticError> warnings = new List<StaticError>();
1407
			List<StaticError> errors = new List<StaticError>();
1408
			List<StaticError> fatals = new List<StaticError>();
1409

    
1410
			try {
1411
				// Norm Walsh reported saxon:parse errors not notified to the ErrorListener. Can't reproduce.
1412

    
1413
				Processor proc = new Processor(true);
1414

    
1415

    
1416
				XsltCompiler xqcomp = proc.NewXsltCompiler();
1417
				xqcomp.ErrorList = errors;
1418

    
1419
				StringReader sr = new StringReader("<xsl:stylesheet version='2.0' " +
1420
					"xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:saxon='http://saxon.sf.net/'>\n" +
1421
					"<xsl:template name='main'>\n" +
1422
					"<xsl:copy-of select=\"saxon:parse('&lt;doc>&lt;e>text&lt;/f>&lt;/doc>')\"/>\n" +
1423
					"</xsl:template>\n" +
1424
					"</xsl:stylesheet>");
1425

    
1426

    
1427
				Xslt30Transformer trans = xqcomp.Compile(sr).Load30();
1428

    
1429
				Serializer serializer = proc.NewSerializer();
1430
				MemoryStream os = new MemoryStream();
1431
				serializer.SetOutputStream(os);
1432

    
1433
				trans.CallTemplate(new QName("main"), serializer);
1434

    
1435
				Assert.Fail("Transformation should fail");
1436

    
1437
			} catch (Exception e) {
1438
				//Assert.True(warnings.isEmpty(), "warnings");
1439
				Assert.True(errors.Capacity == 0, "errors");
1440
				//Assert.True(fatals.size() == 1, "fatals");
1441
				//e.printStackTrace();
1442
			}
1443
		}
1444

    
1445
        [Test]
1446
        public void TestSchemaAware11() {
1447
			// Create a Processor instance.
1448
			try {
1449
				Processor proc = new Processor(true);
1450
				proc.SetProperty("http://saxon.sf.net/feature/timing", "true");
1451
				proc.SetProperty("http://saxon.sf.net/feature/xsd-version", "1.1");
1452
				XsltCompiler comp = proc.NewXsltCompiler();
1453
				comp.SchemaAware = true;
1454
				StringReader sr = new StringReader(
1455
					"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
1456
					"<xsl:import-schema><xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'>" +
1457
					"<xs:element name='e'><xs:complexType><xs:sequence><xs:element name='p'/></xs:sequence><xs:assert test='exists(p)'/></xs:complexType></xs:element>" +
1458
					"</xs:schema></xsl:import-schema>" +
1459
					"<xsl:variable name='v'><e><p/></e></xsl:variable>" +
1460
					"<xsl:template name='main'><xsl:copy-of select='$v' validation='strict'/></xsl:template>" +
1461
					"</xsl:stylesheet>");
1462
				XsltExecutable exec = comp.Compile(sr);
1463
				Xslt30Transformer transformer = exec.Load30();
1464

    
1465
				StringWriter sw = new StringWriter();
1466
				Serializer serializer = proc.NewSerializer(sw);
1467
				serializer.SetOutputProperty(Serializer.INDENT, "no");
1468
				transformer.CallTemplate(new QName("main"), serializer);
1469
				Assert.True(sw.ToString().Contains("<e>"));
1470
			} catch (Exception e) {
1471
			
1472
				Assert.Fail(e.Message);
1473
			}
1474

    
1475
		}
1476

    
1477
        [Test]
1478
        public void TestValidationWarnings() {
1479
			try {
1480
				Processor processor = new Processor(true);
1481
				processor.SetProperty("http://saxon.sf.net/feature/validation-warnings", "true");
1482
				processor.SchemaManager.Compile(new Uri(ConfigTest.DATA_DIR + "books.xsd"));
1483

    
1484
				Serializer serializer = processor.NewSerializer();
1485
				serializer.SetOutputFile(ConfigTest.DATA_DIR + "out/validationWarnings.xml");
1486

    
1487
				XsltCompiler compiler = processor.NewXsltCompiler();
1488
				compiler.SchemaAware = true;
1489

    
1490
				String xsl = "<xsl:stylesheet version=\"2.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" +
1491
					"\n" +
1492
					"    <xsl:output indent=\"yes\" encoding=\"UTF-8\" />\n" +
1493
					"\n" +
1494
					"    <xsl:template match=\"/\">\n" +
1495
					"        <xsl:document validation='strict'>\n" +
1496
					"            <xsl:next-match />\n" +
1497
					"        </xsl:document>\n" +
1498
					"    </xsl:template>\n" +
1499
					"\n" +
1500
					"    <xsl:template match=\"*\">\n" +
1501
					"        <xsl:element name=\"{name()}\" namespace=\"{namespace-uri()}\">\n" +
1502
					"            <invalid-element/>\n" +
1503
					"        </xsl:element>\n" +
1504
					"    </xsl:template>\n" +
1505
					"</xsl:stylesheet> ";
1506
				Xslt30Transformer transformer = compiler.Compile(new StringReader(xsl)).Load30();
1507

    
1508
				transformer.ApplyTemplates(new MemoryStream(Encoding.ASCII.GetBytes(xsl)), serializer);
1509

    
1510
				Assert.True(true);
1511
			} catch (Exception e) {
1512
				//e.printStackTrace();
1513
				Assert.Fail(e.Message);
1514
			}
1515
		}
1516

    
1517

    
1518

    
1519
        /**
1520
     * Test that the base URI of the result document is the base output URI
1521
     */
1522
        [Test]
1523
        public void TestOutputBaseUri() {
1524
			try {
1525
				Processor processor = new Processor(false);
1526

    
1527
				DocumentBuilder builder = processor.NewDocumentBuilder();
1528
                builder.BaseUri = new Uri("http://www.example.com");
1529
				//builder.DtdValidation =  false;
1530
				builder.IsLineNumbering = true;
1531

    
1532
				XdmNode document = builder.Build(new FileStream(ConfigTest.DATA_DIR + "books.xml",FileMode.Open));
1533
				XdmNode stylesheet = builder.Build(new FileStream(ConfigTest.DATA_DIR + "books.xsl", FileMode.Open));
1534

    
1535
				XsltCompiler compiler = processor.NewXsltCompiler();
1536
				compiler.SchemaAware = false;
1537
				XsltExecutable exec = compiler.Compile(stylesheet);
1538
				Xslt30Transformer transformer = exec.Load30();
1539

    
1540
				XdmDestination result = new XdmDestination();
1541
				transformer.BaseOutputURI = "file://tmp/out.xml";
1542

    
1543
				transformer.SchemaValidationMode = SchemaValidationMode.Unspecified;
1544
				transformer.GlobalContextItem = document;
1545
				transformer.ApplyTemplates(document, result);
1546

    
1547
				XdmNode xformed = result.XdmNode;
1548
				Assert.AreEqual("file://tmp/out.xml", xformed.BaseUri.ToString(), "output base uri");
1549
			} catch (Exception e) {
1550
				Console.WriteLine(e.Message);
1551
				Assert.Fail();
1552
			}
1553
		}
1554

    
1555
        /**
1556
     * test a call on XsltExecutable.getGlobalParameters
1557
     * @throws net.sf.saxon.s9api.SaxonApiException
1558
     */
1559
        [Test]
1560
        public void TestGlobalParameters() {
1561
			//Configuration configuration = Configuration.newConfiguration();
1562
			Processor processor = new Processor(true);
1563
			XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1564

    
1565
			String source = "<?xml version='1.0'?>" +
1566
				"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1567
				"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1568
				"                version='2.0'>" +
1569

    
1570
				"                <xsl:param name='surname' as='xs:string' />" +
1571
				"                <xsl:param name='age' as='xs:integer' />" +
1572

    
1573
				"                <xsl:template match='/'><xsl:element name='root' /></xsl:template>" +
1574
				"                </xsl:stylesheet>";
1575

    
1576
			XsltExecutable xsltExecutable = xsltCompiler.Compile(new MemoryStream(Encoding.ASCII.GetBytes(source)));
1577
			Dictionary<QName, XsltExecutable.ParameterDetails> params1 = xsltExecutable.GetGlobalParameters();
1578

    
1579
			Console.WriteLine();
1580
			int i = 0;
1581
			foreach (QName key in params1.Keys) {
1582
				Console.WriteLine("Parameter n." + (++i) + ": " + key);
1583
			}
1584
			Console.WriteLine();
1585
			Assert.AreEqual(2,2);
1586
		}
1587

    
1588
        /**
1589
    * Get declared types of global parameters
1590
    * @throws SaxonApiException
1591
    * @throws UnsupportedEncodingException
1592
    */
1593
        [Test]
1594
        public void TestGlobalParameterType()
1595
        {
1596
            
1597
            Processor processor = new Processor(false);
1598
            XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1599

    
1600
            String source = "<?xml version='1.0'?>" +
1601
                    "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1602
                    "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1603
                    "                version='2.0'>" +
1604

    
1605
                    "                <xsl:param name='surname' as='xs:string' />" +
1606
                    "                <xsl:param name='age' as='xs:integer?' />" +
1607
                    "                <xsl:param name='doc' as='document-node()' />" +
1608
                    "                <xsl:param name='ele' as='element(pre:a, xs:date)+' xmlns:pre='http://pre/'/>" +
1609

    
1610
                    "                <xsl:template match='/'><xsl:element name='root' /></xsl:template>" +
1611
                    "                </xsl:stylesheet>";
1612

    
1613
            XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
1614
            Dictionary < QName, XsltExecutable.ParameterDetails > paramsi = xsltExecutable.GetGlobalParameters();
1615
            XdmItemType t1 = paramsi[(new QName("surname"))].GetDeclaredItemType();
1616
            Assert.True(t1.ToString().Equals("Q{" + NamespaceConstant.SCHEMA + "}string"), "t1");
1617
            char c1 = paramsi[new QName("surname")].GetDeclaredCardinality();
1618
            Assert.True(c1==XdmSequenceType.ONE, "c1");
1619
            XdmItemType t2 = paramsi[new QName("age")].GetDeclaredItemType();
1620
            Assert.True(t2.ToString().Equals("Q{" + NamespaceConstant.SCHEMA + "}integer"), "t2");
1621
            char c2 = paramsi[new QName("age")].GetDeclaredCardinality();
1622
            Assert.True(c2 == XdmSequenceType.ZERO_OR_ONE, "c2");
1623
            XdmItemType t3 = paramsi[(new QName("doc"))].GetDeclaredItemType();
1624
            Assert.True(t3.ToString().Equals("document-node()"), "t3");
1625
            char c3 = paramsi[(new QName("doc"))].GetDeclaredCardinality();
1626
            Assert.True(c3 == XdmSequenceType.ONE, "c3");
1627
            XdmItemType t4 = paramsi[(new QName("ele"))].GetDeclaredItemType();
1628
            Assert.True(t4.ToString().Equals("element(Q{http://pre/}a, Q{" + NamespaceConstant.SCHEMA + "}date)"), "t4");
1629
            char c4 = paramsi[(new QName("ele"))].GetDeclaredCardinality();
1630
            Assert.True(c4 == XdmSequenceType.ONE_OR_MORE, "c4");
1631
        }
1632
        /**
1633
     * Test an external  call on a stylesheet function
1634
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1635
     */
1636
        [Test]
1637
		public void TestCallFunction()  {
1638
			try {
1639
				//Configuration configuration = Configuration.newConfiguration();
1640
				Processor processor = new Processor(true);
1641
			
1642
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1643

    
1644
				String source = "<?xml version='1.0'?>" +
1645
                    "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1646
                    "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1647
                    "                xmlns:f='http://localhost/'" +
1648
                    "                version='3.0'>" +
1649
                    "                <xsl:function name='f:add' visibility='public'>" +
1650
                    "                  <xsl:param name='a'/><xsl:param name='b'/>" +
1651
                    "                  <xsl:sequence select='$a + $b'/></xsl:function>" +
1652
                    "                </xsl:stylesheet>";
1653

    
1654
                xsltCompiler.BaseUri = new Uri("file:///dummy/");
1655
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new MemoryStream(Encoding.ASCII.GetBytes(source)));
1656
				Xslt30Transformer t = xsltExecutable.Load30();
1657
				XdmValue v = t.CallFunction(new QName("http://localhost/", "f:add"), new XdmValue[]{new XdmAtomicValue(2), new XdmAtomicValue(3)});
1658
				Assert.AreEqual(((XdmAtomicValue)v).GetLongValue(), 5);
1659
			} catch (Exception e) {
1660
				//e.printStackTrace();
1661
				Assert.Fail(e.Message);
1662
			}
1663
		}
1664

    
1665
        [Test]
1666
        public void TestNullInitialContext()
1667
        {
1668
            try
1669
            {
1670
                Processor proc = new Processor(false);
1671
                String sr = "<input/>";
1672
               
1673
                DocumentBuilder builder = proc.NewDocumentBuilder();
1674
                builder.BaseUri = new Uri("file:///dummy/");
1675
                XdmNode node = builder.Build(new MemoryStream(Encoding.ASCII.GetBytes(sr)));
1676
                XsltCompiler xqcomp = proc.NewXsltCompiler();
1677
                xqcomp.BaseUri = new Uri("file:///dummy/");
1678
                sr = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" +
1679
                        "  <xsl:output omit-xml-declaration=\"yes\"/>\n" +
1680
                        "  <xsl:template match=\"/\"><output1/><output2/></xsl:template>\n" +
1681
                        "</xsl:stylesheet>";
1682
                
1683
                XsltTransformer trans = xqcomp.Compile(new MemoryStream(Encoding.ASCII.GetBytes(sr))).Load();
1684
                
1685
                StringWriter sw = new StringWriter();
1686
                Serializer s = proc.NewSerializer();
1687
                s.BaseUri = new Uri("file:///dummy/");
1688
                s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1689
                s.SetOutputWriter(sw);
1690
                trans.InitialContextNode =  node;
1691
                
1692
                trans.Run(s);
1693

    
1694
                String result = sw.ToString();
1695
                Assert.True(result.Equals("<output1/><output2/>"), "output");
1696

    
1697
            }
1698
            catch (Exception e)
1699
            {
1700
                Assert.Fail(e.Message);
1701
            }
1702

    
1703
        }
1704

    
1705

    
1706
        /**
1707
     * Test an external  call on a stylesheet function with argument conversion
1708
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1709
     */
1710
     [Test]
1711
        public void TestCallFunctionArgConversion()  {
1712
			try {
1713
				//Configuration configuration = Configuration.newConfiguration();
1714
				Processor processor = new Processor(true);
1715
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1716

    
1717
                String source = "<?xml version='1.0'?>" +
1718
                        "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1719
                        "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1720
                        "                xmlns:f='http://localhost/'" +
1721
                        "                version='3.0'>" +
1722
                        "                <xsl:function name='f:add' visibility='public'>" +
1723
                        "                   <xsl:param name='a' as='xs:double'/>" +
1724
                        "                   <xsl:param name='b' as='xs:double'/>" +
1725
                        "                   <xsl:sequence select='$a + $b'/>" +
1726
                        "                </xsl:function>" +
1727
                        "                </xsl:stylesheet>";
1728

    
1729
                //MemorySource ss = new MemorySource(new ByteArrayInputStream(source.getBytes("UTF-8")), "file:///dummy/");
1730
                xsltCompiler.BaseUri = new Uri("file:///dummy/");
1731
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new MemoryStream(Encoding.ASCII.GetBytes(source)));
1732
				Xslt30Transformer t = xsltExecutable.Load30();
1733
				XdmValue v = t.CallFunction(new QName("http://localhost/", "f:add"), new XdmValue[]{new XdmAtomicValue(2), new XdmAtomicValue(3)});
1734
				Assert.AreEqual(((XdmAtomicValue)v).GetDoubleValue(), 5.0e0);
1735
				Assert.AreEqual((((XdmAtomicValue)v)).GetPrimitiveTypeName().LocalName, "double");
1736
			} catch (Exception e) {
1737
				//e.printStackTrace();
1738
				Assert.Fail(e.Message);
1739
			}
1740
		}
1741

    
1742
		/**
1743
     * Test an external  call on a stylesheet function serializing the results
1744
     * Also makes access to a stylesheet parameter which in turn accesses the global context item
1745
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1746
     */
1747
     [Test]
1748
		public void TestCallFunctionWrapResults()  {
1749
			try {
1750
				Processor processor = new Processor(true);
1751
				processor.SetProperty("http://saxon.sf.net/feature/generateByteCode", "false");
1752
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1753

    
1754
				String source = "<?xml version='1.0'?>" +
1755
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1756
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1757
					"                xmlns:f='http://localhost/'" +
1758
					"                version='2.0'>" +
1759
					"                <xsl:param name='x' as='xs:integer'/>" +
1760
					"                <xsl:param name='y' select='.+2'/>" +
1761
					"                <xsl:function name='f:add' visibility='public'>" +
1762
					"                   <xsl:param name='a' as='xs:double'/>" +
1763
					"                   <xsl:param name='b' as='xs:double'/>" +
1764
					"                   <xsl:sequence select='$a + $b + $x + $y'/>" +
1765
					"                </xsl:function>" +
1766
					"                </xsl:stylesheet>";
1767
					
1768
				xsltCompiler.BaseUri = new Uri("file:///dummy/");
1769
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new MemoryStream(Encoding.ASCII.GetBytes(source)));
1770
				Xslt30Transformer t = xsltExecutable.Load30();
1771
				t.GlobalContextItem =  new XdmAtomicValue(20);
1772
				Dictionary<QName, XdmValue> globals = new Dictionary<QName, XdmValue>();
1773
				globals.Add(new QName("x"), new XdmAtomicValue(30));
1774
				t.SetStylesheetParameters(globals);
1775
				StringWriter sw = new StringWriter();
1776
				Serializer s = processor.NewSerializer();
1777
				s.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1778
				s.SetOutputWriter(sw);
1779
				t.CallFunction(new QName("http://localhost/", "f:add"), new XdmValue[]{new XdmAtomicValue(2), new XdmAtomicValue(3)}, s);
1780
				Assert.AreEqual(sw.ToString(), "57");
1781
			} catch (Exception e) {
1782
				//e.printStackTrace();
1783
				Assert.Fail(e.Message);
1784
			}
1785
		}
1786

    
1787

    
1788
		/**
1789
     * Test an external  call on a stylesheet function with invalid argument conversion
1790
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1791
     */
1792
     [Test]
1793
		public void TestCallFunctionArgInvalid()  {
1794
			try {
1795
				//Configuration configuration = Configuration.newConfiguration();
1796
				Processor processor = new Processor(true);
1797

    
1798
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1799

    
1800
				String source = "<?xml version='1.0'?>" +
1801
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1802
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1803
					"                xmlns:f='http://localhost/'" +
1804
					"                version='2.0'>" +
1805
					"                <xsl:function name='f:add' visibility='public'>" +
1806
					"                   <xsl:param name='a' as='xs:double'/>" +
1807
					"                   <xsl:param name='b' as='xs:double'/>" +
1808
					"                   <xsl:sequence select='$a + $b'/>" +
1809
					"                </xsl:function>" +
1810
					"                </xsl:stylesheet>";
1811
					
1812
				xsltCompiler.BaseUri = new Uri("file:///dummy/");
1813
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new MemoryStream(Encoding.ASCII.GetBytes(source)));
1814
				Xslt30Transformer t = xsltExecutable.Load30();
1815
				XdmValue v = t.CallFunction(new QName("http://localhost/", "f:add"), new XdmValue[]{new XdmAtomicValue(2), new XdmAtomicValue("3")});
1816
				Assert.Fail("Failed to throw error");
1817
			}catch (DynamicError e) {
1818
				Console.WriteLine(e.Message);
1819
				// OK
1820
			}
1821
		}
1822

    
1823
		/**
1824
     * Test calling a stylesheet with an initial template with parameters
1825
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1826
     */
1827
     [Test]
1828
		public void TestCallNamedTemplateWithParams()  {
1829
			try {
1830
				//Configuration configuration = Configuration.newConfiguration();
1831
				//configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
1832
				Processor processor = new Processor(true);
1833
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1834

    
1835
				String source = "<?xml version='1.0'?>" +
1836
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1837
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1838
					"                version='2.0'>" +
1839
					"                <xsl:template name='t'>" +
1840
					"                   <xsl:param name='a' as='xs:double'/>" +
1841
					"                   <xsl:param name='b' as='xs:float'/>" +
1842
					"                   <xsl:sequence select='$a + $b'/>" +
1843
					"                </xsl:template>" +
1844
					"                </xsl:stylesheet>";
1845

    
1846

    
1847
				xsltCompiler.BaseUri = new Uri("file:///dummy/");
1848
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
1849
				Xslt30Transformer t = xsltExecutable.Load30();
1850
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
1851
				params1.Add(new QName("a"), new XdmAtomicValue(12));
1852
				params1.Add(new QName("b"), new XdmAtomicValue(5));
1853
				t.SetInitialTemplateParameters(params1, false);
1854
				StringWriter sw = new StringWriter();
1855
				Serializer se = processor.NewSerializer(sw);
1856
				se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1857
				t.CallTemplate(new QName("t"), se);
1858
				Assert.AreEqual(sw.ToString(), "17");
1859
			} catch (Exception e) {
1860
				//e.printStackTrace();
1861
				Assert.Fail(e.Message);
1862
			}
1863
		}
1864

    
1865
		/**
1866
     * Test calling a stylesheet with an initial template omitting a required parameters
1867
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1868
     */
1869
     [Test]
1870
		public void TestCallNamedTemplateWithParamsRequired()  {
1871
			try {
1872
				//Configuration configuration = Configuration.newConfiguration();
1873
				//configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
1874
				Processor processor = new Processor(true);
1875
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1876

    
1877
				String source = "<?xml version='1.0'?>" +
1878
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1879
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1880
					"                version='2.0'>" +
1881
					"                <xsl:template name='t'>" +
1882
					"                   <xsl:param name='a' as='xs:double'/>" +
1883
					"                   <xsl:param name='b' as='xs:float' required='yes'/>" +
1884
					"                   <xsl:sequence select='$a + $b'/>" +
1885
					"                </xsl:template>" +
1886
					"                </xsl:stylesheet>";
1887

    
1888

    
1889
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
1890
				Xslt30Transformer t = xsltExecutable.Load30();
1891
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
1892
				params1.Add(new QName("a"), new XdmAtomicValue(12));
1893
				t.SetInitialTemplateParameters(params1, false);
1894
				StringWriter sw = new StringWriter();
1895
				Serializer se = processor.NewSerializer(sw);
1896
				se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1897
				t.CallTemplate(new QName("t"), se);
1898
				Assert.Fail("failed to detect error");
1899
			} catch (DynamicError e) {
1900
				//Console.WriteLine(e.printStackTrace());
1901
				Assert.True(true);
1902
			}
1903
		}
1904

    
1905
		/**
1906
     * Test calling a stylesheet with an initial template with tunnel parameters
1907
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1908
     */
1909
     [Test]
1910
		public void TestCallNamedTemplateWithTunnelParams()  {
1911
			try {
1912
				//Configuration configuration = Configuration.newConfiguration();
1913
				//configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
1914
				Processor processor = new Processor(true);
1915
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1916

    
1917
				String source = "<?xml version='1.0'?>" +
1918
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1919
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1920
					"                version='2.0'>" +
1921
					"                <xsl:template name='t'>" +
1922
					"                   <xsl:call-template name='u'/>" +
1923
					"                </xsl:template>" +
1924
					"                <xsl:template name='u'>" +
1925
					"                   <xsl:param name='a' as='xs:double' tunnel='yes'/>" +
1926
					"                   <xsl:param name='b' as='xs:float' tunnel='yes'/>" +
1927
					"                   <xsl:sequence select='$a + $b'/>" +
1928
					"                </xsl:template>" +
1929
					"                </xsl:stylesheet>";
1930

    
1931

    
1932
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
1933
				Xslt30Transformer t = xsltExecutable.Load30();
1934
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
1935
				params1.Add(new QName("a"), new XdmAtomicValue(12));
1936
				params1.Add(new QName("b"), new XdmAtomicValue(5));
1937
				t.SetInitialTemplateParameters(params1, true);
1938
				StringWriter sw = new StringWriter();
1939
				Serializer se = processor.NewSerializer(sw);
1940
				se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
1941
				t.CallTemplate(new QName("t"), se);
1942
				Assert.AreEqual(sw.ToString(), "17");
1943
			} catch (java.io.UnsupportedEncodingException e) {
1944
				//Console.WriteLine(e.printStackTrace());
1945
				Assert.Fail();
1946
			}
1947
		}
1948

    
1949

    
1950
		/**
1951
     * Test calling a stylesheet named template getting raw results back
1952
     *
1953
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1954
     */
1955
     [Test]
1956
		public void TestCallNamedTemplateWithParamsRaw() {
1957
			
1958
			try{
1959
				//configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
1960
				Processor processor = new Processor(true);
1961
                processor.SetProperty(FeatureKeys.GENERATE_BYTE_CODE, "false");
1962
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
1963

    
1964
				String source = "<?xml version='1.0'?>" +
1965
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
1966
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
1967
					"                version='3.0'>" +
1968
					"                <xsl:template name='t'>" +
1969
					"                   <xsl:param name='a' as='xs:double'/>" +
1970
					"                   <xsl:param name='b' as='xs:float'/>" +
1971
					"                   <xsl:sequence select='$a+1, $b+1'/>" +
1972
					"                </xsl:template>" +
1973
					"                </xsl:stylesheet>";
1974

    
1975
	
1976
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
1977
				Xslt30Transformer t = xsltExecutable.Load30();
1978
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
1979
				params1.Add(new QName("a"), new XdmAtomicValue(12));
1980
				params1.Add(new QName("b"), new XdmAtomicValue(5));
1981
				t.SetInitialTemplateParameters(params1, false);
1982
				XdmValue val = t.CallTemplate(new QName("t"));
1983
				Assert.AreEqual(2, val.Count);
1984
				Assert.AreEqual(13, ((XdmAtomicValue) val.ItemAt(0)).GetLongValue());
1985
				Assert.AreEqual(6, ((XdmAtomicValue) val.ItemAt(1)).GetLongValue());
1986
			} catch (java.io.UnsupportedEncodingException e) {
1987
				//Console.WriteLine(e.printStackTrace());
1988
				Assert.Fail();
1989
			}
1990
		}
1991

    
1992

    
1993
        /**
1994
     * Test calling a stylesheet named template getting raw results back as a Destination
1995
     *
1996
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
1997
     */
1998

    
1999
        [Test]
2000
        public void TestCallNamedTemplateWithParamsRawDestination()
2001
        {
2002
        try {
2003
                //Configuration configuration = Configuration.newConfiguration();
2004
                //configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
2005
                Processor processor = new Processor();
2006
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();
2007

    
2008
                String source = "<?xml version='1.0'?>" +
2009
                        "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
2010
                        "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
2011
                        "                version='3.0'>" +
2012
                        "                <xsl:template name='t'>" +
2013
                        "                   <xsl:param name='a' as='xs:double'/>" +
2014
                        "                   <xsl:param name='b' as='xs:float'/>" +
2015
                        "                   <xsl:sequence select='$a+1, $b+1'/>" +
2016
                        "                </xsl:template>" +
2017
                        "                </xsl:stylesheet>";
2018

    
2019
                //StreamSource ss = new StreamSource(new ByteArrayInputStream(source.getBytes("UTF-8")), "file:///dummy/");
2020
                XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
2021
                Xslt30Transformer t = xsltExecutable.Load30();
2022
                Dictionary < QName, XdmValue > paramsi = new Dictionary<QName, XdmValue>();
2023
                paramsi.Add(new QName("a"), new XdmAtomicValue(12));
2024
            paramsi.Add(new QName("b"), new XdmAtomicValue(5));
2025
                t.SetInitialTemplateParameters(paramsi, false);
2026
                RawDestination outi = new RawDestination();
2027
                t.CallTemplate(new QName("t"), outi);
2028
                XdmValue val = outi.XdmValue;
2029
                Assert.AreEqual(2, val.Count);
2030
                Assert.AreEqual(13, ((XdmAtomicValue)val.ItemAt(0)).GetLongValue());
2031
                Assert.AreEqual(6, ((XdmAtomicValue)val.ItemAt(1)).GetLongValue());
2032
            } catch (Exception e) {
2033
            
2034
            Assert.Fail(e.Message);
2035
    }
2036
}
2037

    
2038

    
2039
/**
2040
* Test calling a stylesheet with an initial template rule with parameters
2041
* @throws net.sf.saxon.s9api.SaxonApiException if the call fails
2042
*/
2043
        [Test]
2044
        public void TestCallTemplateRuleWithParams()  {
2045
			try {
2046

    
2047
				//configuration.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, false);
2048
				Processor processor = new Processor(true);
2049
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
2050

    
2051
				String source = "<?xml version='1.0'?>" +
2052
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
2053
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
2054
					"                version='2.0'>" +
2055
					"                <xsl:template match='*'>" +
2056
					"                   <xsl:param name='a' as='xs:double'/>" +
2057
					"                   <xsl:param name='b' as='xs:float'/>" +
2058
					"                   <xsl:sequence select='name(.), $a + $b'/>" +
2059
					"                </xsl:template>" +
2060
					"                </xsl:stylesheet>";
2061

    
2062
				xsltCompiler.BaseUri = new Uri("file:///dummy/");
2063

    
2064
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
2065
				Xslt30Transformer t = xsltExecutable.Load30();
2066
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
2067
				params1.Add(new QName("a"), new XdmAtomicValue(12));
2068
				params1.Add(new QName("b"), new XdmAtomicValue(5));
2069
				t.SetInitialTemplateParameters(params1, false);
2070
				StringWriter sw = new StringWriter();
2071
				Serializer se = processor.NewSerializer(sw);
2072
				se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
2073
				t.ApplyTemplates(new MemoryStream(Encoding.ASCII.GetBytes("<e/>")), se); //TODO remove uri argument
2074
				Assert.AreEqual(sw.ToString(), "e 17");
2075
			} catch (java.io.UnsupportedEncodingException ex) {
2076
				//Console.WriteLine(e.printStackTrace());
2077
				Assert.Fail();
2078
			}
2079
		}
2080

    
2081

    
2082
        /**
2083
     * Test calling a stylesheet with an initial template rule getting the raw result
2084
     *
2085
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
2086
     */
2087
        [Test]
2088
        public void TestApplyTemplatesRaw() {
2089
							
2090
				Processor processor = new Processor(true);
2091
				XsltCompiler xsltCompiler = processor.NewXsltCompiler();
2092

    
2093
				String source = "<?xml version='1.0'?>" +
2094
					"                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
2095
					"                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
2096
					"                version='3.0'>" +
2097
					"                <xsl:template match='*'>" +
2098
					"                   <xsl:param name='a' as='xs:double'/>" +
2099
					"                   <xsl:param name='b' as='xs:float'/>" +
2100
					"                   <xsl:sequence select='., $a + $b'/>" +
2101
					"                </xsl:template>" +
2102
					"                </xsl:stylesheet>";
2103

    
2104

    
2105
				XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
2106
				Xslt30Transformer t = xsltExecutable.Load30();
2107
				Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
2108

    
2109
				params1.Add(new QName("a"), new XdmAtomicValue(12));
2110
				params1.Add(new QName("b"), new XdmAtomicValue(5));
2111
				t.SetInitialTemplateParameters(params1, false);
2112
				StringWriter sw = new StringWriter();
2113
				Serializer se = processor.NewSerializer(sw);
2114
				se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
2115
				XdmValue result = t.ApplyTemplates(new MemoryStream(Encoding.UTF8.GetBytes("<e/>")), new Uri("http://dummpy.com"));
2116
				Assert.AreEqual(2, result.Count);
2117
				XdmItem first = result.ItemAt(0);
2118
				Assert.True(first is XdmNode, "t1");
2119
				Assert.AreEqual(((XdmNode) first).NodeName.LocalName, "e");
2120
				XdmItem second = result.ItemAt(1);
2121
				Assert.True(second is XdmAtomicValue, "t2");
2122
				Assert.AreEqual(((XdmAtomicValue) second).GetDoubleValue(), 17e0);
2123
			
2124
		}
2125

    
2126
        class MyTraceListener //: net.sf.saxon.lib.TraceListener
2127
        {
2128
            public void close()
2129
            {
2130
            }
2131

    
2132
            public void endCurrentItem(net.sf.saxon.om.Item i)
2133
            {
2134
            }
2135

    
2136
            public void enter(net.sf.saxon.trace.InstructionInfo ii, net.sf.saxon.expr.XPathContext xpc)
2137
            {
2138
            }
2139

    
2140
            public void leave(net.sf.saxon.trace.InstructionInfo ii)
2141
            {
2142
            }
2143

    
2144
            public void open(net.sf.saxon.Controller c)
2145
            {
2146
            }
2147

    
2148
            public void setOutputDestination(net.sf.saxon.lib.Logger l)
2149
            {
2150
            }
2151

    
2152
            public void startCurrentItem(net.sf.saxon.om.Item i)
2153
            {
2154
                Console.WriteLine("test currentItem");
2155
            }
2156
        }
2157

    
2158
        /**
2159
     * Test calling a stylesheet with an initial template rule getting the raw result
2160
     *
2161
     * @throws net.sf.saxon.s9api.SaxonApiException if the call fails
2162
     */
2163
        [Test]
2164
        public void TestApplyTemplatesToXdm() 
2165
        {
2166
        try {
2167
               // Configuration configuration = Configuration.newConfiguration();
2168
                Processor processor = new Processor();
2169
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();
2170

    
2171
                String source = "<?xml version='1.0'?>" +
2172
                        "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
2173
                        "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
2174
                        "                version='3.0'>" +
2175
                        "                <xsl:template match='*'>" +
2176
                        "                   <xsl:param name='a' as='xs:double'/>" +
2177
                        "                   <xsl:param name='b' as='xs:float'/>" +
2178
                        "                   <xsl:sequence select='., $a + $b'/>" +
2179
                        "                </xsl:template>" +
2180
                        "                </xsl:stylesheet>";
2181

    
2182
               
2183
                XsltExecutable xsltExecutable = xsltCompiler.Compile(new StringReader(source));
2184
                Xslt30Transformer t = xsltExecutable.Load30();
2185
                Dictionary < QName, XdmValue > paramsi = new Dictionary<QName, XdmValue>();
2186
            paramsi.Add(new QName("a"), new XdmAtomicValue(12));
2187
            paramsi.Add(new QName("b"), new XdmAtomicValue(5));
2188
                t.SetInitialTemplateParameters(paramsi, false);
2189
                StringWriter sw = new StringWriter();
2190
                Serializer se = processor.NewSerializer(sw);
2191
                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
2192
               
2193
                XdmValue result = t.ApplyTemplates(new MemoryStream(Encoding.ASCII.GetBytes("<e/>")), new Uri("file:///dummy/"));
2194
                Assert.AreEqual(2, result.Count);
2195
                XdmItem first = result.ItemAt(0);
2196
                Assert.True(first is XdmNode, "t1");
2197
                Assert.True(((XdmNode)first).NodeName.LocalName.Equals("e"));
2198
                XdmItem second = result.ItemAt(1);
2199
                Assert.True(second is XdmAtomicValue, "t2");
2200
                Assert.True(((XdmAtomicValue)second).GetDoubleValue()== 17e0, "v2");
2201
            } catch (Exception e) {
2202
                Assert.Fail(e.Message);
2203
    }
2204
}
2205

    
2206

    
2207

    
2208
/**
2209
* Test calling a stylesheet with an initial template rule getting the serialized
2210
* result with item separators
2211
*
2212
* @throws net.sf.saxon.s9api.SaxonApiException if the call fails
2213
*/
2214
    [Test]
2215
    public void TestApplyTemplatesToSerializer() {
2216
        try {
2217
                //Configuration configuration = Configuration.newConfiguration();
2218
                Processor processor = new Processor();
2219
                XsltCompiler xsltCompiler = processor.NewXsltCompiler();
2220

    
2221
                String source = "<?xml version='1.0'?>" +
2222
                        "                <xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'" +
2223
                        "                xmlns:xs='http://www.w3.org/2001/XMLSchema'" +
2224
                        "                version='3.0'>" +
2225
                        "                <xsl:output method='text' item-separator='~~'/>" +
2226
                        "                <xsl:template match='.'>" +
2227
                        "                   <xsl:param name='a' as='xs:double'/>" +
2228
                        "                   <xsl:param name='b' as='xs:float'/>" +
2229
                        "                   <xsl:sequence select='., $a + $b'/>" +
2230
                        "                </xsl:template>" +
2231
                        "                </xsl:stylesheet>";
2232

    
2233
                Stream ss = new MemoryStream(Encoding.UTF8.GetBytes(source));
2234
                XsltExecutable xsltExecutable = xsltCompiler.Compile(ss);
2235
                Xslt30Transformer t = xsltExecutable.Load30();
2236
                Dictionary < QName, XdmValue > paramsi = new Dictionary<QName, XdmValue>();
2237
            paramsi.Add(new QName("a"), new XdmAtomicValue(12));
2238
            paramsi.Add(new QName("b"), new XdmAtomicValue(5));
2239
                t.SetInitialTemplateParameters(paramsi, false);
2240
                StringWriter sw = new StringWriter();
2241
                Serializer se = processor.NewSerializer(sw);
2242
                se.SetOutputProperty(Serializer.OMIT_XML_DECLARATION, "yes");
2243
                t.ApplyTemplates(new XdmAtomicValue(16), se);
2244
                Assert.True("16~~17".Equals(sw.ToString()));
2245
            } catch (Exception e) {
2246
                Assert.Fail(e.Message);
2247
    }
2248
}
2249

    
2250

    
2251

    
2252

    
2253
[Test]
2254
        public void TestTraceListener() {
2255
            try
2256
            {
2257
                // Create a Processor instance.
2258
                Processor processor = new Processor();
2259

    
2260
                ////////////////////////////// ADDING THIS CAUSES AN ISSUE IN THE CONTEXT ///////////////////////////
2261
                // processor.Implementation.setTraceListener(new MyTraceListener());
2262
                // Load the source document
2263
                XdmNode input = processor.NewDocumentBuilder().Build(new Uri(new Uri(ConfigTest.DATA_DIR), "books.xml"));
2264

    
2265
                // Create a transformer for the stylesheet.
2266
                XsltTransformer transformer = processor.NewXsltCompiler().Compile(new Uri(new Uri(ConfigTest.DATA_DIR), "books.xsl")).Load();
2267

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

    
2271
                // Create a serializer, with output to the standard output stream
2272
                Serializer serializer = processor.NewSerializer();
2273
                serializer.SetOutputWriter(Console.Out);
2274

    
2275
                // Transform the source XML and serialize the result document
2276
                transformer.Run(serializer);
2277
                Assert.True(true);
2278
            }
2279
            catch (Exception ex) {
2280
                Assert.Fail(ex.Message);
2281
            }
2282

    
2283
        }
2284

    
2285

    
2286
        /**
2287
     * Send output to an XdmDestination
2288
     */
2289
     [Test]
2290
        public void TestItemSeparatorToSerializer()
2291
        {
2292
            try
2293
            {
2294
                Processor proc = new Processor(false);
2295
                XsltCompiler comp = proc.NewXsltCompiler();
2296
                StringReader sr = new StringReader(
2297
                        "<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" +
2298
                           "  <xsl:template name='go'>"
2299
                                + "<xsl:comment>start</xsl:comment><a><b/><c/></a><xsl:comment>end</xsl:comment>"
2300
                                + "</xsl:template>" +
2301
                                "</xsl:stylesheet>");
2302
                XsltExecutable exec = comp.Compile(sr);
2303
                Xslt30Transformer xsl = exec.Load30();
2304
                StringWriter sw = new StringWriter();
2305
                Serializer outi = proc.NewSerializer(sw);
2306
            outi.SetOutputProperty(Serializer.METHOD, "xml");
2307
            outi.SetOutputProperty(Serializer.INDENT, "no");
2308
            outi.SetOutputProperty(Serializer.ITEM_SEPARATOR, "+++");
2309
            xsl.CallTemplate(new QName("go"), outi);
2310
            Console.WriteLine(sw.ToString());
2311
            Assert.True(sw.ToString().Contains("<!--start-->+++"));
2312
            Assert.True(sw.ToString().Contains("+++<!--end-->"));
2313
                Assert.True(sw.ToString().Contains("<a><b/><c/></a>"));
2314
            }
2315
            catch (Exception e)
2316
            {
2317
               
2318
                Assert.Fail(e.Message);
2319
            }
2320

    
2321
        }
2322

    
2323

    
2324
        [Test]
2325
        public void TestTransformReturningFunction()
2326
        {
2327
            try
2328
            {
2329
                Processor proc = new Processor(true);
2330
                XsltCompiler comp = proc.NewXsltCompiler();
2331
                comp.SchemaAware = true;
2332
                StringReader sr = new StringReader(
2333
                        "<xsl:stylesheet version='3.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:f='f' xmlns:xs='http://www.w3.org/2001/XMLSchema'>" +
2334
                                "<xsl:template name='main'><xsl:sequence select='f:f#1'/></xsl:template> \n" +
2335
                                "<xsl:function name='f:f' as='xs:integer'><xsl:param name='p'/><xsl:sequence select='$p+42'/></xsl:function> \n" +
2336
                                "</xsl:stylesheet>");
2337
                XsltExecutable exec = comp.Compile(sr);
2338
                Xslt30Transformer transformer = exec.Load30();
2339
                XdmValue value = transformer.CallTemplate(new QName("main"));
2340
                XdmValue[] values = new XdmValue[1];
2341
                values[0] = new XdmAtomicValue(17);
2342
                XdmValue result = ((XdmFunctionItem)value).Invoke(values, proc);
2343
                Assert.True(result is XdmAtomicValue);
2344
                Assert.AreEqual(59, ((XdmAtomicValue)result).GetLongValue());
2345
            }
2346
            catch (Exception e)
2347
            {
2348
                
2349
                Assert.Fail(e.Message);
2350
            }
2351

    
2352
        }
2353

    
2354

    
2355
        [Test]
2356
		public void TestStripTypeAnnotations() {
2357
			try {
2358
				Processor proc = new Processor(true);
2359
				XsltCompiler comp = proc.NewXsltCompiler();
2360
				StringReader sr = new StringReader("<xslt:transform xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" +
2361
					"                xmlns:my=\"http://ns.example.com/strip-type\"\n" +
2362
					"                xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\"\n" +
2363
					"                exclude-result-prefixes=\"xs my\"\n" +
2364
					"                input-type-annotations=\"strip\"\n" +
2365
					"                version=\"2.0\">\n" +
2366
					"<!-- Purpose: Show that when @input-type-annotations=\"strip\", is-nilled property of element  nodes is set to false.-->\n" +
2367
					"\n" +
2368
					"   <xslt:template match=\"/my:userNode\">\n" +
2369
					"      <out>\n" +
2370
					"         <xslt:value-of select=\"nilled(.)\"/>\n" +
2371
					"      </out>\n" +
2372
					"   </xslt:template>\n" +
2373
					"</xslt:transform>");
2374

    
2375
				SchemaManager manager = proc.SchemaManager;
2376
				comp.SchemaAware =true;
2377

    
2378
				manager.Compile(new FileStream(ConfigTest.DATA_DIR + "varietyOfTypes.xsd", FileMode.Open), new Uri(ConfigTest.DATA_DIR + "varietyOfTypes.xsd"));
2379

    
2380
				XsltExecutable exec = comp.Compile(sr);
2381
				Xslt30Transformer xsl = exec.Load30();
2382
				String inn = "<?xml version='1.0'?> \n" +
2383
					"<my:userNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
2384
					"\t\t  xsi:schemaLocation=\"http://ns.example.com/strip-type varietyOfTypes.xsd\"\n" +
2385
					"\t\t  xmlns:my=\"http://ns.example.com/strip-type\"\n" +
2386
					"\t \t  specialPart=\"123-AB\" listParts=\"000-SS 000-RR\" xsi:nil=\"true\"/>";
2387

    
2388
				SchemaValidator validator = manager.NewSchemaValidator();
2389
				validator.IsLax = false;
2390
				DocumentBuilder builder = proc.NewDocumentBuilder();
2391
				builder.SchemaValidator = validator;
2392
				Stream sDoc = new MemoryStream(Encoding.UTF8.GetBytes(inn));
2393
                builder.BaseUri = new Uri("file:///dummy/");
2394
				XdmNode doc = builder.Build(sDoc);
2395

    
2396
				StringWriter writer = new StringWriter();
2397
				Serializer outi = proc.NewSerializer(writer);
2398
				xsl.ApplyTemplates(doc, outi);
2399
				Assert.True(writer.ToString().Contains("false"), "strip-type-annotations not working");
2400
			} catch (Exception e) {
2401
				
2402
				Assert.Fail(e.Message);
2403
			}
2404

    
2405
		}
2406

    
2407

    
2408

    
2409
        [Test]
2410
        public void TestTextWriterDestination() {
2411
            Processor proc = new Processor(true);
2412
            XsltCompiler comp = proc.NewXsltCompiler();
2413
            StringReader sr = new StringReader("<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>\n" +
2414
           "  <xsl:template match='/'>\n" +
2415
           "    <xsl:variable name='node'>\n" +
2416
           "      <xsl:sequence select='.'/>\n" +
2417
           "    </xsl:variable>\n" +
2418
           "    <xsl:sequence select='$node/node()'/>\n" +
2419
           "  </xsl:template>\n" +
2420
           "</xsl:stylesheet>");
2421
            XsltExecutable exec = comp.Compile(sr);
2422
            Xslt30Transformer xsl = exec.Load30();
2423
            StringReader input = new StringReader("<input/>");
2424
            DocumentBuilder builder = proc.NewDocumentBuilder();
2425
            builder.BaseUri = new Uri("http://example.com");
2426
            XdmNode doc = builder.Build(input);
2427
            TextWriterDestination dest = new TextWriterDestination(XmlWriter.Create("C:\\work\\output.xml"));
2428
            xsl.ApplyTemplates(doc,dest);
2429
          
2430

    
2431

    
2432
        }
2433

    
2434

    
2435
        /**
2436
    * Test Strip-space with ApplyTemplates
2437
    */
2438
    [Test]
2439
        public void TestStripSpace()
2440
        {
2441
            try
2442
            {
2443
                Processor proc = new Processor(true);
2444
                XsltCompiler comp = proc.NewXsltCompiler();
2445
                StringReader sr = new StringReader("<xslt:transform xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n" +
2446
                                                           "                xmlns:my=\"http://ns.example.com/strip-type\"\n" +
2447
                                                           "                xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\"\n" +
2448
                                                           "                exclude-result-prefixes=\"xs my\"\n" +
2449
                                                           "                version=\"3.0\">\n" +
2450
                                                           "   <xslt:strip-space elements='foo my:foo'/>\n" +
2451
                                                           "   <xslt:mode on-no-match='deep-copy'/>\n" +
2452
                                                           "</xslt:transform>");
2453

    
2454
                XsltExecutable exec = comp.Compile(sr);
2455
                Xslt30Transformer xsl = exec.Load30();
2456
                String inn = "<?xml version='1.0'?> \n" +
2457
                        "<my:userNode xmlns:my='http://ns.example.com/strip-type'><foo> </foo><bar> </bar><my:foo> </my:foo><my:bar> </my:bar></my:userNode>";
2458

    
2459
                DocumentBuilder builder = proc.NewDocumentBuilder();
2460
                builder.BaseUri = new Uri("http://www.example.com");
2461
               MemoryStream sDoc = new MemoryStream(Encoding.UTF8.GetBytes(inn));
2462
                XdmNode doc = builder.Build(sDoc);
2463

    
2464
                StringWriter writer = new StringWriter();
2465
                Serializer outi = proc.NewSerializer(writer);
2466
                xsl.ApplyTemplates(doc, outi);
2467
                Assert.True(writer.ToString().Contains("<foo/>"), "strip-space not working");
2468
                Assert.True(writer.ToString().Contains("<my:foo/>"), "strip-space not working");
2469
                Assert.False( writer.ToString().Contains("<bar/>"), "strip-space not working");
2470
                Assert.False(writer.ToString().Contains("<my:bar/>"), "strip-space not working");
2471
            }
2472
            catch (Exception e)
2473
            {
2474
                
2475
                Assert.Fail(e.Message);
2476
            }
2477

    
2478
        }
2479

    
2480

    
2481
    }
2482
}
2483

    
2484

    
(18-18/19)