Project

Profile

Help

Revision be17ef52

Added by Debbie Lockett 8 months ago

Get saxon10 samples up to date (copied from saxon.he/latest10/samples)

View differences:

src/samples/config/config-HE.xml
18 18
          preferJaxpParser="true"
19 19
          sourceResolver=""
20 20
          uriResolver="net.sf.saxon.lib.StandardURIResolver"
21
          collectionUriResolver="net.sf.saxon.lib.StandardCollectionURIResolver"
22 21
          defaultCollection="file:///e:/temp"
23 22
          recognizeUriQueryParameters="true"
24 23
          useTypedValueCache="false"
......
72 71
          preserveBoundarySpace="false"
73 72
          requiredContextItemType="document-node()"
74 73
          emptyLeast="true"/>
75
</configuration>
74
</configuration>
src/samples/config/config-raw.xsd
36 36
            information into the execution.</xs:documentation>
37 37
        </xs:annotation>
38 38
      </xs:attribute>
39
      <xs:attribute name="targetEdition" type="xs:string">
40
        <xs:annotation>
41
          <xs:documentation>The target edition if export SEF files are to be used, for example
42
            targetEdition="JS". Specifically, this affects the recognition of extension namespaces
43
            (such as the IXSL namespace) when packages in the packageLibrary are compiled.</xs:documentation>
44
        </xs:annotation>
45
      </xs:attribute>
39 46
    </xs:complexType>
40 47
  </xs:element>
41 48
  
......
44 51
      <xs:documentation> Defines properties of the global configuration. </xs:documentation>
45 52
    </xs:annotation>
46 53
    <xs:complexType>
54
      <xs:attribute name="allowedProtocols" use="optional" type="xs:string"/>  
47 55
      <xs:attribute name="allowExternalFunctions" use="optional" type="xs:boolean"/>
48 56
      <xs:attribute name="allowMultiThreading" use="optional" type="xs:boolean"/>
49 57
      <xs:attribute name="allowOldJavaUriFormat" use="optional" type="xs:boolean"/>
......
55 63
      <xs:attribute name="allowSyntaxExtensions" use="optional" type="xs:boolean"/>    
56 64
      <xs:attribute name="collationUriResolver" use="optional" type="c:javaClassNameType"/>
57 65
      <xs:attribute name="collectionFinder" use="optional" type="c:javaClassNameType"/>
58
      <xs:attribute name="collectionUriResolver" use="optional" type="c:javaClassNameType"/>
59 66
      <xs:attribute name="compileWithTracing" use="optional" type="xs:boolean"/>
60 67
      <xs:attribute name="debugByteCode" use="optional" type="xs:boolean"/>
61 68
      <xs:attribute name="debugByteCodeDirectory" use="optional" type="c:fileNameType"/>
......
83 90
      <xs:attribute name="preferJaxpParser" use="optional" type="xs:boolean"/>
84 91
      <xs:attribute name="recognizeUriQueryParameters" use="optional" type="xs:boolean"/>
85 92
      <xs:attribute name="regexBacktrackingLimit" use="optional" type="xs:integer"/>
93
      <xs:attribute name="retainNodeForDiagnostics" use="optional" type="xs:boolean"/>
86 94
      <xs:attribute name="schemaValidation" use="optional" type="c:schemaValidationType"/>
87 95
      <xs:attribute name="serializerFactory" use="optional" type="c:javaClassNameType"/>
88 96
      <xs:attribute name="sourceResolver" use="optional" type="c:javaClassNameType"/>
......
237 245
      </xs:documentation>
238 246
    </xs:annotation>
239 247
    <xs:complexType>
248
      <xs:attribute name="allowUnresolvedSchemaComponents" use="optional" type="xs:boolean"/>
240 249
      <xs:attribute name="assertionsCanSeeComments" use="optional" type="xs:boolean"/>
241 250
      <xs:attribute name="implicitSchemaImports" use="optional" type="xs:boolean"/>
242 251
      <xs:attribute name="multipleSchemaImports" use="optional" type="xs:boolean"/>
src/samples/cs/SampleExtensions.cs
11 11
    /// <summary>
12 12
    /// This class contains some example methods that can be invoked from XSLT as
13 13
    /// extension functions or from XQuery as external functions. For examples of calls
14
    /// on these functions, from both XSLT and XQuery, see the ExamplesPE.cs and 
15
    /// ExamplesEE.cs programs.
14
	/// on these functions, from both XSLT and XQuery, see the ExamplesPE.cs and 
15
	/// ExamplesEE.cs programs.
16 16
    /// </summary>
17 17

  
18 18
    public class SampleExtensions
......
47 47

  
48 48
        public static string hostLanguage(net.sf.saxon.expr.XPathContext context)
49 49
        {
50
            int lang = context.getController().getExecutable().getHostLanguage();
51
            if (lang == net.sf.saxon.Configuration.XQUERY)
50
            var lang = context.getController().getExecutable().getHostLanguage();
51
            if (lang == net.sf.saxon.s9api.HostLanguage.XQUERY)
52 52
            {
53 53
                return "XQuery";
54 54
            }
55
            else if (lang == net.sf.saxon.Configuration.XSLT)
55
            else if (lang == net.sf.saxon.s9api.HostLanguage.XSLT)
56 56
            {
57 57
                return "XSLT";
58 58
            }
59
            else if (lang == net.sf.saxon.Configuration.XPATH)
59
            else if (lang == net.sf.saxon.s9api.HostLanguage.XPATH)
60 60
            {
61 61
                return "XPath";
62 62
            }
src/samples/cs/TestRunner10.0/Environment.cs
1
using System;
2
using System.Collections;
3
using System.Collections.Generic;
4
using System.Text;
5
using Saxon.Api;
6
using System.Xml;
7
using System.IO;
8
using System.Text.RegularExpressions;
9
using System.Globalization;
10
using JavaExtenionFunctionCall = com.saxonica.expr.JavaExtensionFunctionCall;
11
using JConfiguration = net.sf.saxon.Configuration;
12
using JPreparedStylesheet = net.sf.saxon.PreparedStylesheet;
13
using JClause = net.sf.saxon.expr.flwor.Clause;
14
using JCodeInjector = net.sf.saxon.expr.parser.CodeInjector;
15
using JSimpleCollection = net.sf.saxon.expr.sort.SimpleCollation;
16
using JDecimalFormatManager = net.sf.saxon.trans.DecimalFormatManager;
17
using JDecimalSymbols = net.sf.saxon.trans.DecimalSymbols;
18
using JXpathException = net.sf.saxon.trans.XPathException;
19
using JFastStringBuffer = net.sf.saxon.tree.util.FastStringBuffer;
20
using JUnparsedTextURIResolver = net.sf.saxon.lib.UnparsedTextURIResolver;
21
using JFeatureKeys = net.sf.saxon.lib.FeatureKeys;
22
using JStringCollator = net.sf.saxon.lib.StringCollator;
23
using JAnyURIValue = net.sf.saxon.value.AnyURIValue;
24
using JItem = net.sf.saxon.om.Item;
25
using JNamespaceConstant = net.sf.saxon.lib.NamespaceConstant;
26
using JCharSequence = java.lang.CharSequence;
27
using JExpression = net.sf.saxon.expr.Expression;
28
using JStructuredQName = net.sf.saxon.om.StructuredQName;
29
using java.io;
30
using java.net;
31
using net.sf.saxon;
32
using net.sf.saxon.expr;
33
using net.sf.saxon.lib;
34
using java.util;
35
using net.sf.saxon.om;
36
using net.sf.saxon.resource;
37

  
38
namespace TestRunner
39
{
40

  
41
    /**
42
     * This class represents a collection of resources (source documents, schemas, collections etc) used for a number
43
     * of test cases.
44
     */
45

  
46
    public class
47
            Environment : XmlUrlResolver
48
    {
49

  
50
        private class MyEnvironment
51
        {
52

  
53
        }
54

  
55
        public Processor processor;
56
        public Dictionary<string, XdmNode> sourceDocs = new Dictionary<string, XdmNode>();
57
        public Dictionary<string, string> streamedSecondaryDocs = new Dictionary<string, string>();
58
        public string streamedPath;
59
        public string streamedContent;
60
        public XPathCompiler xpathCompiler;
61
        public XQueryCompiler xqueryCompiler;
62
        public XsltCompiler xsltCompiler;
63
        public XsltExecutable xsltExecutable;
64
        public XdmItem contextItem;
65
        public Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
66
        public bool xml11 = false;
67
        public bool usable = true;
68
        public JFastStringBuffer paramDeclarations = new JFastStringBuffer(256);
69
        public JFastStringBuffer paramDecimalDeclarations = new JFastStringBuffer(256);
70
        public JUnparsedTextURIResolver unparsedTextResolver;
71
        public IList<ResetAction> resetActions = new List<ResetAction>();
72
        public bool outputTree = true;
73
        public bool outputSerialize = false;
74
        public String streamedInputValidation = "skip";
75
        internal bool failedToBuild = false;
76

  
77

  
78
        /**
79
         * Construct a local default environment for a test set
80
         */
81

  
82
        public static Environment createLocalEnvironment(Uri baseURI, int generateByteCode, bool unfolded, Spec spec)
83
        {
84
            Environment environment = new Environment();
85
            environment.processor = new Processor(true);
86
          
87
            environment.processor.Implementation.setLogger(new TestDriver.MyLogger());
88
            //AutoActivate.activate(environment.processor);
89
            if (generateByteCode == 1)
90
            {
91
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
92
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
93
            }
94
            else if (generateByteCode == 2)
95
            {
96
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
97
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
98
                //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
99
            }
100
            else
101
            {
102
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
103
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
104
            }
105
            //environment.processor.SetProperty(JFeatureKeys.TRACE_EXTERNAL_FUNCTIONS, "true");
106
            environment.xpathCompiler = environment.processor.NewXPathCompiler();
107
            environment.xpathCompiler.BaseUri = baseURI.ToString(); //TODO: Check that this is OK
108
            environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
109
            environment.xqueryCompiler.BaseUri = "file:////"+baseURI.AbsolutePath;
110
            environment.xsltCompiler = environment.processor.NewXsltCompiler();
111
            environment.xsltCompiler.BaseUri = new Uri(baseURI.ToString());
112
            if (spec.Equals(Spec.XT30))
113
            {
114
                environment.xsltCompiler.XsltLanguageVersion = "3.0";
115
            }
116
            else
117
            {
118
                environment.xsltCompiler.XsltLanguageVersion = "2.0";
119
            }
120
            if (unfolded)
121
            {
122
                // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
123
            }
124
            environment.processor.Implementation.setDefaultCollection(null);
125
            return environment;
126
        }
127

  
128
        private static void DeclareOutputControls(TestRunner.TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
129
        {
130
            String needsTree = xpc.Evaluate("string((output/@tree,'yes')[1])", env).ToString();
131
            environment.outputTree = "yes".Equals(needsTree);
132
            String needsSerialization = xpc.Evaluate("string((output/@serialize,'no')[1])", env).ToString();
133
            environment.outputSerialize = "yes".Equals(needsSerialization);
134
        }
135

  
136
        /**
137
         * Construct an Environment
138
         *
139
         * @param xpc          the XPathCompiler used to process the catalog file
140
         * @param env          the Environment element in the catalog file
141
         * @param environments the set of environments to which this one should be added (may be null)
142
         * @return the constructed Environment object
143
         * @throws SaxonApiException
144
         */
145

  
146
        public static Environment processEnvironment(TestRunner.TestDriver driver,
147
                XPathCompiler xpc, XdmNode env, Dictionary<string, Environment> environments, Environment defaultEnvironment)
148
        {
149
            Environment environment = new Environment();
150
            String name = env.GetAttributeValue(new QName("name"));
151
            if (name != null)
152
            {
153
                System.Console.WriteLine("Loading environment " + name);
154
            }
155
            environment.processor = new Processor(true);
156
            if (defaultEnvironment != null)
157
            {
158
                environment.processor.SetProperty(JFeatureKeys.XSD_VERSION,
159
                        defaultEnvironment.processor.Implementation.getConfigurationProperty(JFeatureKeys.XSD_VERSION).ToString());
160
            }
161
            // AutoActivate.activate(environment.processor);
162
            if (driver.GenerateByteCode == 1)
163
            {
164
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
165
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
166
            }
167
            else if (driver.GenerateByteCode == 2)
168
            {
169
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
170
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
171
                //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
172
            }
173
            else
174
            {
175
                environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
176
                environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
177
            }
178
            environment.xpathCompiler = environment.processor.NewXPathCompiler();
179
            environment.xpathCompiler.BaseUri = ((XdmNode)env).BaseUri.ToString();
180
            environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
181
            environment.xqueryCompiler.BaseUri = "file:////"+((XdmNode)env).BaseUri.AbsolutePath;
182
            if (driver.Spec.ToString().Contains("XT"))
183
            {
184
                environment.xsltCompiler = environment.processor.NewXsltCompiler();
185
                environment.xsltCompiler.XsltLanguageVersion = ((SpecAttr)(driver.Spec.GetAttr())).version;
186
            }
187
            if (driver.Unfolded)
188
            {
189
                // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
190
            }
191
            DocumentBuilder builder = environment.processor.NewDocumentBuilder();
192
            builder.TreeModel = driver.TreeModel;
193
            environment.sourceDocs = new Dictionary<string, XdmNode>();
194
            if (environments != null && name != null)
195
            {
196
                try
197
                {
198
                    environments.Add(name, environment);
199
                }
200
                catch (Exception) { }
201
            }
202
            foreach (XdmItem dependency in xpc.Evaluate("dependency", env))
203
            {
204
                if (!driver.EnsureDependencySatisfied((XdmNode)dependency, environment))
205
                {
206
                    environment.usable = false;
207
                }
208
            }
209

  
210
            // set the base URI if specified
211

  
212
            SetBaseUri(driver, xpc, env, environment);
213

  
214
            // set any requested collations
215

  
216
            RegisterCollations(xpc, (XdmNode)env, environment);
217

  
218
            // declare the requested namespaces
219

  
220
            DeclareNamespaces(xpc, env, environment);
221

  
222
            // load the requested schema documents
223

  
224
            SchemaManager manager = environment.processor.SchemaManager;
225
            bool validateSources = LoadSchemaDocuments(driver, xpc, env, environment, manager);
226

  
227
            // load the requested source documents
228

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

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

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

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

  
237
            CreateUnparsedTextResolver(driver, xpc, env, environment);
238

  
239
            // register any required decimal formats
240

  
241
             RegisterDecimalFormats(driver, xpc, env, environment);
242

  
243
            // declare any variables
244

  
245
            DeclareExternalVariables(driver, xpc, env, environment);
246

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

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

  
258
            XmlUrlResolver res = new XmlUrlResolver();
259
            // compile any stylesheet defined as part of the environment (only one allowed)
260
            DocumentBuilder builder1 = environment.processor.NewDocumentBuilder();
261
            foreach (XdmItem stylesheet in xpc.Evaluate("stylesheet[not(@role='secondary')]", env))
262
            {
263
                string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
264
                try
265
                {
266
                    XdmNode styleSource = builder1.Build(res.ResolveUri(((XdmNode)env).BaseUri, fileName));
267
                    environment.xsltExecutable = environment.xsltCompiler.Compile(styleSource);
268
                }
269
                catch (Exception e)
270
                {
271
                    environment.failedToBuild = true;
272
                    environment.usable = false;
273
                    driver.println("**** failure while compiling environment-defined stylesheet " + fileName);
274
                }
275
            }
276

  
277

  
278
            // compile any stylesheet packages defined as part of the environment
279
            // Support this only in EE - an unusable environment in PE/HE
280
            foreach (XdmItem stylesheet in xpc.Evaluate("package[@role='secondary']", env))
281
            {
282
                if (!"EE".Equals(environment.processor.Edition))
283
                {
284
                    environment.usable = false;
285
                    break;
286
                }
287
                string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
288
                Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, fileName);
289
                FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
290
                try
291
                {
292
                    XsltPackage pkg = environment.xsltCompiler.CompilePackage(file);
293
                    environment.xsltCompiler.ImportPackage(pkg);
294
                }
295
                catch (Exception e)
296
                {
297
                    //e.printStackTrace();
298
                    driver.println("**** failure while compiling environment-defined stylesheet package " + fileName);
299
                    driver.println("****Failure " + e.Message + " in compiling environment " + name);
300
                    environment.usable = false;
301
                    environment.failedToBuild = true;
302
                }
303
            }
304

  
305
            return environment;
306
        }
307

  
308

  
309
        private static void SetBaseUri(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
310
        {
311
            foreach (XdmItem basei in xpc.Evaluate("static-base-uri", env))
312
            {
313
                string uri = ((XdmNode)basei).GetAttributeValue(new QName("uri"));
314
                if (uri == null || "#UNDEFINED".Equals(uri))
315
                {
316
                    driver.println("**** Error: The BaseURI null and #UNDEFINED is not supported");
317
                }
318
                else
319
                {
320
                    try
321
                    {
322
                        environment.xpathCompiler.BaseUri = uri;
323
                        environment.xqueryCompiler.BaseUri = uri;
324
                    }
325
                    catch (Exception e)
326
                    {
327
                        driver.println("**** invalid base URI " + uri);
328
                    }
329
                }
330
            }
331
        }
332

  
333
        private static void RegisterCollations(XPathCompiler xpc, XdmNode env, Environment environment)
334
        {
335
            //CompareInfo info = CultureInfo.CurrentCulture.CompareInfo;
336
            //CompareOptions options = CompareOptions.IgnoreCase;
337
            foreach (XdmNode basei in env.Children("collation"))
338
            {
339
                string uri = basei.GetAttributeValue("uri");
340
                if (uri.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") ||
341
                        uri.Equals("http://www.w3.org/xslts/collation/caseblind"))
342
                {
343
                    try
344
                    {
345

  
346
                        JConfiguration config = xpc.Processor.Implementation;
347
                        JStringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", config);
348
                        
349
                        environment.processor.DeclareCollation(new Uri(uri), CultureInfo.CurrentCulture.CompareInfo, CompareOptions.IgnoreCase);
350
                    }
351
                    catch (Exception e)
352
                    {
353
                        throw new Exception(e.Message);
354
                    }
355
                }
356
                string defaultAtt = basei.GetAttributeValue("default");
357
                if (defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1")))
358
                {
359
                    environment.xpathCompiler.DeclareDefaultCollation(uri);
360
                    //environment.xqueryCompiler.DeclareCollation(uri, true);
361
                    environment.xsltCompiler.DefaultCollationName = uri;
362
                }
363
            }
364
        }
365
            
366
        private static void DeclareNamespaces(XPathCompiler xpc, XdmItem env, Environment environment)
367
        {
368
            foreach (XdmItem nsElement in xpc.Evaluate("namespace", env))
369
            {
370
                String prefix = ((XdmNode)nsElement).GetAttributeValue(new QName("prefix"));
371
                String uri = ((XdmNode)nsElement).GetAttributeValue(new QName("uri"));
372
                environment.xpathCompiler.DeclareNamespace(prefix, uri);
373
                environment.xqueryCompiler.DeclareNamespace(prefix, uri);
374
                if (uri.Equals("http://expath.org/ns/file"))
375
                {
376
                    // For EXPath file tests, set the EXPath base directory to the catalog directory
377
                    string basei = ((XdmNode)nsElement).BaseUri.ToString();
378
                    if (basei.StartsWith("file:///"))
379
                    {
380
                        basei = basei.Substring(7);
381
                    }
382
                    else if (basei.StartsWith("file:/"))
383
                    {
384
                        basei = basei.Substring(5);
385
                    }
386
                    FileStream file = new FileStream(basei, FileMode.Open, FileAccess.Read); //new File(base);
387

  
388
                    //System.SetProperty("expath.base.directory", file.ToString());
389
                }
390
            }
391
        }
392

  
393
        private static bool LoadSchemaDocuments(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment, SchemaManager manager)
394
        {
395
            bool validateSources = false;
396
            XmlUrlResolver res = new XmlUrlResolver();
397
            foreach (XdmNode schema in env.Children("schema"))
398
            {
399
                String role = schema.GetAttributeValue(new QName("role"));
400
                String xsdVersion =  schema.GetAttributeValue(new QName("xsd-version"));
401
                if (manager == null) {
402
                    driver.println("** Processor is not schema aware **");
403
                    environment.usable = false;
404
                    return false;
405
                }
406
                if (xsdVersion != null)
407
                {
408
                    manager.XsdVersion = xsdVersion;
409
                }
410
                if (!"secondary".Equals(role))
411
                {
412
                    String href = ((XdmNode)schema).GetAttributeValue(new QName("file"));
413
                    String ns = schema.GetAttributeValue("uri");
414
                    if (href == null)
415
                    {
416
                        Uri uri = res.ResolveUri(null, ns);
417
                        FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
418
                        try
419
                        {
420
                            manager.Compile(file, uri);
421
                        }
422
                        catch (Exception err)
423
                        {
424
                            System.Console.WriteLine("*** Failed to load schema: " + err.Message + ", Trace:" + err.StackTrace);
425
                        }
426
                    }
427
                    else {
428
                        Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, href);
429
                        FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
430
                        try
431
                        {
432
                            manager.Compile(file, uri);
433
                        }
434
                        catch (Exception err)
435
                        {
436
                            System.Console.WriteLine("*** Failed to load schema: " + err.Message + ", Trace:" + err.StackTrace);
437
                        }
438

  
439
                    }
440
                    xpc.ImportSchemaNamespace(ns);
441
                    environment.xpathCompiler.ImportSchemaNamespace(ns);
442
                    if ("source-reference".Equals(role))
443
                    {
444
                        validateSources = true;
445
                    }
446
                    if ("stylesheet-import".Equals(role)) {
447
                        environment.xsltCompiler.SchemaAware = true;
448
                    }
449
                }
450
            }
451
            return validateSources;
452
        }
453

  
454
        private static void DeclareExternalVariables(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
455
        {
456
            foreach (XdmItem param in xpc.Evaluate("param", env))
457
            {
458
                String varName = ((XdmNode)param).GetAttributeValue(new QName("name"));
459
                XdmValue value;
460
                String source = ((XdmNode)param).GetAttributeValue(new QName("source"));
461
                if (source != null)
462
                {
463
                    XdmNode sourceDoc = null;
464
                    try
465
                    {
466
                        sourceDoc = environment.sourceDocs[source];
467
                    }
468
                    catch (Exception) { }
469
                    if (sourceDoc == null)
470
                    {
471
                        driver.println("**** Unknown source document " + source);
472
                    }
473
                    value = sourceDoc;
474
                }
475
                else
476
                {
477
                    String select = ((XdmNode)param).GetAttributeValue(new QName("select"));
478
                    value = xpc.Evaluate(select, null);
479
                }
480
                bool isStatic = Xslt30TestSuiteDriver.IsTrue("static").Invoke((XdmNode)param);
481
                QName varQName;
482
                int colon = varName.IndexOf(':');
483
                if (colon >= 0)
484
                {
485

  
486
                    varQName = new QName(varName, (XdmNode)param);
487
                }
488
                else {
489
                    varQName = new QName(varName);
490
                }
491

  
492
                
493
                environment.xpathCompiler.DeclareVariable(varQName);
494
                String declared = ((XdmNode)param).GetAttributeValue(new QName("declared"));
495
                if (declared != null && "true".Equals(declared) || "1".Equals(declared))
496
                {
497
                    // no action
498
                }
499
                else
500
                {
501
                    environment.paramDeclarations.append("declare variable $" + varName + " external; ");
502
                }
503
                if (isStatic)
504
                {
505
                    environment.xsltCompiler.SetParameter(varQName, value);
506
                }
507
                else {
508
                    environment.params1.Add(varQName, value);
509

  
510
                }
511
            }
512
        }
513

  
514
        private static void RegisterDecimalFormats(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)  {
515
            foreach (XdmItem decimalFormat in xpc.Evaluate("decimal-format", env)) {
516
                //DecimalFormatManager dfm = environment.xpathCompiler..getUnderlyingStaticContext().getDecimalFormatManager();
517

  
518
                XdmNode formatElement = (XdmNode) decimalFormat;
519
                String formatName = formatElement.GetAttributeValue(new QName("name"));
520
                QName formatQName = null;
521
                if (formatName != null) {
522
                    if (formatName.IndexOf(':') < 0) {
523
                        formatQName = new QName("", "", formatName);
524
                    } else {
525
                        try {
526
                            formatQName = new QName(formatName,formatElement);
527
                        } catch (Exception e) {
528
                            driver.println("**** Invalid QName as decimal-format name");
529
                            formatQName = new QName("", "", "error-name");
530
                        }
531
                    }
532
                    environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.EQName + " ");
533
                } else {
534
                    environment.paramDecimalDeclarations.append("declare default decimal-format ");
535
                }
536
              
537
                foreach (XdmItem decimalFormatAtt in xpc.Evaluate("@* except @name", formatElement)) {
538
                    XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
539
                    String property = formatAttribute.NodeName.LocalName;
540
                    String value = formatAttribute.StringValue;
541
                    environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" ");
542
                    try {
543
                        environment.xpathCompiler.SetDecimalFormatProperty(formatQName, property, value);
544
                    }
545
                    catch (Exception e) {
546
                        driver.println("**** Error in Decimal format: "+ e.Message);
547
                    }
548
                }
549
                environment.paramDecimalDeclarations.append(";");
550
                
551

  
552
            }
553
        }
554

  
555
        private static void CreateUnparsedTextResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
556
        {
557
            Dictionary<Uri, Object> resources = new Dictionary<Uri, Object>();
558
            Dictionary<Uri, String> encodings = new Dictionary<Uri, String>();
559
            XmlUrlResolver res = new XmlUrlResolver();
560
            foreach (XdmItem resource in xpc.Evaluate("resource", env))
561
            {
562
                String uri = ((XdmNode)resource).GetAttributeValue(new QName("uri"));
563
                String href = ((XdmNode)resource).GetAttributeValue(new QName("file"));
564
                String encoding = ((XdmNode)resource).GetAttributeValue(new QName("encoding"));
565
                String mediaType = ((XdmNode)resource).GetAttributeValue(new QName("media-type"));
566
                if (href != null)
567
                {
568
                    Object obj = null;
569
                    if (href.StartsWith("http"))
570
                    {
571
                        try
572
                        {
573
                            obj = new Uri(href);
574
                        }
575
                        catch (Exception e)
576
                        {
577
                            throw e;
578
                        }
579
                    }
580
                    else
581
                    {
582
                        obj = new java.io.File(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
583
                    }
584
                    try
585
                    {
586
                        resources.Add(new Uri(uri), obj);
587
                        encodings.Add(new Uri(uri), encoding);
588
                        Uri abs = res.ResolveUri(((XdmNode)resource).BaseUri, uri);
589
                        resources.Add(abs, obj);
590
                        if (encoding == null)
591
                        {
592
                            encodings.Add(abs, encoding);
593
                        }
594
                       // environment.catalogResources.Add();
595
                    }
596
                    catch (Exception e)
597
                    {
598
                        driver.println("** Invalid URI in environment: " + e.Message);
599
                    }
600
                    if (mediaType != null && mediaType.EndsWith("xquery")) {
601
                        driver.RegisterXQueryModule(new Uri(uri), res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
602
                    }
603
                }
604
            }
605
            if (resources.Count != 0)
606
            {
607
                environment.unparsedTextResolver =
608
                   new UnparsedTextURIResolver(encodings, resources);
609
            }
610
        }
611

  
612
        public class UnparsedTextURIResolver : JUnparsedTextURIResolver
613
        {
614
            Dictionary<Uri, String> encodings;
615
            Dictionary<Uri, Object> resources;
616
            public UnparsedTextURIResolver(Dictionary<Uri, String> encodings, Dictionary<Uri, Object> resources)
617
            {
618
                this.encodings = encodings;
619
                this.resources = resources;
620
            }
621

  
622

  
623
            public Reader resolve(URI absoluteURI, string encoding, Configuration config)
624
            {
625
                if (encoding == null)
626
                {
627
                    encodings.TryGetValue(new Uri(absoluteURI.ToString()), out encoding);
628
                }
629
                if (encoding == null)
630
                {
631
                    encoding = "utf-8";
632
                }
633
                try
634
                {
635
                    // The following is necessary to ensure that encoding errors are not recovered.
636
                    java.nio.charset.Charset charset = java.nio.charset.Charset.forName(encoding);
637
                    java.nio.charset.CharsetDecoder decoder = charset.newDecoder();
638
                    decoder = decoder.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT);
639
                    decoder = decoder.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT);
640
                    Object obj;
641
                    resources.TryGetValue(new Uri(absoluteURI.ToString()), out obj);
642
                    if (obj is java.io.File)
643
                    {
644
                        return new BufferedReader(new InputStreamReader(new FileInputStream((java.io.File)obj), decoder));
645
                    }
646
                    else
647
                    {
648
                        resources.TryGetValue(new Uri(absoluteURI.ToString()), out obj);
649
                        URL resource = (URL)obj;
650
                        if (resource == null)
651
                        {
652
                            resource = absoluteURI.toURL();
653
                            //throw new XPathException("Unparsed text resource " + absoluteURI + " not registered in catalog", "FOUT1170");
654
                        }
655
                        java.io.InputStream in1 = resource.openConnection().getInputStream();
656
                        return new BufferedReader(new InputStreamReader(in1, decoder));
657
                    }
658
                    //   return new InputStreamReader(new FileInputStream(resources.get(absoluteURI)), encoding);
659
                }
660
                catch (java.lang.Exception ioe)
661
                {
662
                    throw new Exception(ioe.getMessage() + "FOUT1170");
663
                }
664
                /*catch (IllegalCharsetNameException icne)
665
                {
666
                    throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
667
                }
668
                catch (UnsupportedCharsetException uce)
669
                {
670
                    throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
671
                }*/
672
            }
673
        
674
    
675

  
676

  
677

  
678
    }
679

  
680
    private static void CreateCollectionUriResolver(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment, DocumentBuilder builder) {
681
        Dictionary<Uri, ResourceCollection> collections = new Dictionary<Uri, ResourceCollection>();
682
            JAbstractResourceCollection collectioni = null;
683
            Configuration config = environment.processor.Implementation;
684
            XmlUrlResolver res = new XmlUrlResolver();
685

  
686
            if (!environment.usable) {
687
                return;
688
            }
689
        foreach (XdmNode coll in env.Children("collection")) {
690
                List<Resource> resourcesi = new List<Resource>();
691
            String collectionURI = coll.GetAttributeValue(new QName("uri"));
692
            if (collectionURI == null) {
693
                collectionURI = "";
694
            }
695
                if (collectionURI.Equals("")) {
696
                    collectionURI = "http://www.w.org/qt3-test-suite/default.collection.uri";
697
                    config.setDefaultCollection(collectionURI);
698
                }
699
            Uri u;
700
            try {
701
                u = new Uri(collectionURI);
702
            } catch (Exception e) {
703
                driver.println("**** Invalid collection URI " + collectionURI);
704
                break;
705
				}
706
            if (!collectionURI.Equals("") && !u.IsAbsoluteUri) {
707
                u = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI);
708
                collectionURI = u.ToString();
709
            }
710

  
711
                
712
            
713
            foreach (XdmNode source in coll.Children("source")) {
714
                String href =  source.GetAttributeValue(new QName("file"));
715
                String frag = null;
716
                int hash = href.IndexOf('#');
717
                if (hash > 0) {
718
                    frag = href.Substring(hash + 1);
719
                    href = href.Substring(0, hash);
720
                }
721
                FileStream file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
722
                    
723
               // String id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
724
					String uriStr = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsoluteUri;
725
				builder.BaseUri = new Uri(uriStr);
726
                XdmNode doc = builder.Build(file);
727
                    String xinc = source.GetAttributeValue("xinclude");
728

  
729
                    XdmNode doci;
730
                  /*  if ("true".Equals(xinc)) {
731

  
732
                        XmlReader asource = XmlReader.Create(uriStr);
733
                        
734
                        doc = builder.Build(asource);
735
                       
736

  
737
                        Stream asourceii = new FileStream(uriStr, FileMode.Open);
738
                        net.sf.saxon.dotnet.DotNetInputStream stream = new net.sf.saxon.dotnet.DotNetInputStream(asourceii);
739

  
740
                        javax.xml.transform.Source sourcei = new javax.xml.transform.stream.StreamSource(stream);
741

  
742

  
743
                          AugmentedSource asourcei = net.sf.saxon.lib.AugmentedSource.makeAugmentedSource(sourcei);
744
                        asourcei.setXIncludeAware(true);
745
                        
746
                        asourcei.setSystemId(uriStr);
747
                        builder.Build();
748

  
749
                    }*/
750

  
751

  
752

  
753
                    if (frag != null) {
754
                    XdmNode selected = (XdmNode)environment.xpathCompiler.EvaluateSingle("id('" + frag + "')", doc);
755
                    if (selected == null) {
756
                        driver.println("**** Fragment not found: " + frag);
757
                        break;
758
                    }
759
                    resourcesi.Add(new net.sf.saxon.resource.XmlResource(config, selected.Implementation));
760
                } else {
761
                        resourcesi.Add(new net.sf.saxon.resource.XmlResource(config, doc.Implementation));
762
                    }
763
					environment.sourceDocs.Add(uriStr, doc);
764
            }
765
                foreach (XdmItem source in xpc.Evaluate("resources", coll))
766
                {
767
                    String uri = ((XdmNode)source).GetAttributeValue(new QName("uri"));
768
                    String href = ((XdmNode)source).GetAttributeValue(new QName("file"));
769
                    String encoding = ((XdmNode)source).GetAttributeValue(new QName("encoding"));
770
                    String media = ((XdmNode)source).GetAttributeValue(new QName("media-type"));
771
                    net.sf.saxon.resource.AbstractResourceCollection.InputDetails details = new net.sf.saxon.resource.AbstractResourceCollection.InputDetails();
772
                    details.encoding = encoding;
773
                    details.contentType = media;
774
                    FileStream file = null;
775
                    if (href != null)
776
                    {
777
                        if (href.StartsWith("http"))
778
                        {
779
                            try
780
                            {
781
                                URL url = new URL(href);
782
                                URLConnection connection = url.openConnection();
783
                                if (details.contentType == null)
784
                                {
785
                                    details.contentType = connection.getContentType();
786
                                }
787
                                details.contentType = connection.getContentType();
788
                            }
789
                            catch (Exception e)
790
                            {
791
                                throw new Exception (e.StackTrace);
792
                            }
793
                          
794
                        }
795
                        else
796
                        {
797
                            
798
                            
799
                            try
800
                            {   file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
801
                                Resource resourcej = collectioni.MakeResource(config, details, res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
802
                                if (resourcej != null)
803
                                {
804
                                    resourcesi.Add(resourcej);
805
                                }
806
                                else
807
                                {
808
                                    driver.println("** Error in building collection environment: Resource " + href + " not found: ");
809
                                }
810
                            }
811
                            catch (Exception e)
812
                            {
813
                                driver.println("** IO Error in building collection environment: " + e.Message);
814

  
815
                            }
816
                           
817
                            if (media != null && href.EndsWith("xquery"))
818
                            {
819
                                driver.RegisterXQueryModule(res.ResolveUri(((XdmNode)env).BaseUri, href), res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
820
                            }
821
                        }
822

  
823
                    }
824
                }
825
                collectioni = new JAbstractResourceCollection(collectionURI, resourcesi);
826
                try {
827
                collections.Add(new Uri(collectionURI), collectioni);
828
            } catch (Exception e) {
829
                driver.println("**** Invalid collection URI " + collectionURI);
830
				}
831

  
832
        }
833
        if (collections.Count != 0) {
834
                environment.processor.Implementation.setCollectionFinder(new CollectionFinder(collections));
835
        }
836
    }
837

  
838
		// Methods
839
		//
840
		public override object GetEntity (Uri href, string role, Type ofObjectToReturn)
841
		{
842
			XdmNode node = null;
843
			String hrefStr = href.ToString();
844
			//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
845

  
846
			bool foundDoc = sourceDocs.TryGetValue(hrefStr, out node);
847

  
848
            if (!foundDoc) {
849
                 hrefStr = hrefStr.Substring(hrefStr.LastIndexOf('/') + 1);
850
                 foundDoc = sourceDocs.TryGetValue(hrefStr, out node);
851
            }
852

  
853
			if (!foundDoc) {
854

  
855
				string val;
856
				hrefStr = href.ToString();
857
				//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
858

  
859
				bool foundSecDoc = streamedSecondaryDocs.TryGetValue(hrefStr, out val);
860
                if(!foundSecDoc)
861
                {
862
                    hrefStr = hrefStr.Substring(hrefStr.LastIndexOf('/') + 1);
863
                    foundSecDoc = streamedSecondaryDocs.TryGetValue(hrefStr, out val);
864
                }
865

  
866
				if (foundSecDoc) {
867

  
868

  
869
                    //string hrefStr = href.ToString ();
870
                    String hrefStri = (hrefStr.StartsWith("file:///") ? hrefStr.Substring(8) : hrefStr);
871
                    Stream sourceii = new FileStream(hrefStri, FileMode.Open);
872
                    net.sf.saxon.dotnet.DotNetInputStream stream = new net.sf.saxon.dotnet.DotNetInputStream(sourceii);
873

  
874
                    javax.xml.transform.Source sourcei = new javax.xml.transform.stream.StreamSource(stream);
875

  
876
				
877
					 if(!val.Equals("skip")){
878
					
879
						sourcei = net.sf.saxon.lib.AugmentedSource.makeAugmentedSource(sourcei);
880
							((net.sf.saxon.lib.AugmentedSource) sourcei).setSchemaValidationMode(net.sf.saxon.lib.Validation.getCode(val));
881

  
882
					}
883
					sourcei.setSystemId(hrefStr) ;
884
					return sourcei;
885
				} else {
886
					return null;
887
				}
888
			} else {
889
				return node.Implementation;
890
			}
891
		}
892

  
893
		public override Uri ResolveUri (Uri basei, string href)
894
		{
895

  
896
			return base.ResolveUri (basei, href);
897
		}
898

  
899
    private static void LoadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder, SchemaManager manager, bool validateSources) {
900
        XmlUrlResolver res = new XmlUrlResolver();
901
        foreach (XdmItem source in xpc.Evaluate("source", env)) {
902
            XdmNode doc = null;
903

  
904
            String uri = ((XdmNode) source).GetAttributeValue(new QName("uri"));
905
            String mime = ((XdmNode) source).GetAttributeValue(new QName("media-type"));
906
            if (mime != null && "application/xml".Equals(mime)) {
907
                continue;
908
            }
909
            String validation = ((XdmNode) source).GetAttributeValue(new QName("", "validation"));
910
            if (validation == null) {
911
                validation = "skip";
912
            }
913
            String streaming = ((XdmNode) source).GetAttributeValue(new QName("", "streaming"));
914
            if (!validateSources && validation.Equals("skip")) {
915
                builder.SchemaValidationMode = SchemaValidationMode.None;
916
                    builder.SchemaValidator = null;
917
            } else {
918
                SchemaValidator validator = manager.NewSchemaValidator();
919
                if("lax".Equals(validation)) {
920
                    validator.IsLax = true;
921
                        builder.SchemaValidator = validator;
922
                        builder.SchemaValidationMode = SchemaValidationMode.Lax;
923
                } else
924
                {
925
                        builder.SchemaValidator = validator;
926
                        builder.SchemaValidationMode = SchemaValidationMode.Strict;
927
                }
928
                environment.xpathCompiler.SchemaAware = true;
929
                environment.xqueryCompiler.SchemaAware = true;
930
				if (environment.xsltCompiler != null) {
931
					environment.xsltCompiler.SchemaAware = true;
932
				}
933
            }
934

  
935
            String role = ((XdmNode) source).GetAttributeValue(new QName("role"));
936
            String href = ((XdmNode) source).GetAttributeValue(new QName("file"));
937
            if ("true".Equals(streaming)) {
938
                if (".".Equals(role)) {
939
						if (href == null) {
940
							environment.streamedContent = xpc.Evaluate ("string(content)", source).ToString();
941
						} else {
942
							environment.streamedPath = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsolutePath;
943
						}
944
                        environment.streamedInputValidation = validation;
945
                } else {
946
                    try
947
                    {
948
							System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
949
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri);
950
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).ToString());
951
							environment.streamedSecondaryDocs.Add(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri, validation);
952
                    }catch(Exception){}
953
                }
954
            } else {
955
                Stream ss;
956
                /*if (uri != null) {
957
                    uri = res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri;
958
                }*/
959
                if (href != null) {
960
                        try
961
                        {
962
                            Uri fileLoc = res.ResolveUri(((XdmNode) env).BaseUri, href);
963
                    FileStream file = null;
964
                    if (fileLoc.Scheme.Equals("file")) {
965
                        file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
966
                        if (uri == null) {
967
								uri = fileLoc.AbsoluteUri;
968
                        }
969
                    }
970
                   
971
                        ss = (file == null ? new FileStream(fileLoc.ToString(), FileMode.Open, FileAccess.Read)
972
                                           : file);
973
                        
974
							builder.BaseUri = ((XdmNode) env).BaseUri;
975
                    } catch (Exception e) {
976
                        driver.println("*** failed to find source document " + href + ", Exception:" + e.Message);
977
                        continue;
978
                    }
979
                } else {
980
                    // content is inline in the catalog
981
                    if (uri == null) {
982
                        uri = ((XdmNode) env).BaseUri.AbsolutePath;
983
                    }
984
                    string content = xpc.Evaluate("string(content)", source).ToString();
985
                    byte[] byteArray = Encoding.ASCII.GetBytes(content);
986
                    ss = new MemoryStream(byteArray);
987
                    builder.BaseUri = ((XdmNode)env).BaseUri;
988
                }
989

  
990

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

  
999
                XdmItem selectedItem = doc;
1000
                String select = ((XdmNode) source).GetAttributeValue(new QName("select"));
1001
                if (select != null) {
1002
                    XPathSelector selector = environment.xpathCompiler.Compile(select).Load();
1003
                    selector.ContextItem = selectedItem;
1004
                    selectedItem = selector.EvaluateSingle();
1005
                }
1006

  
1007

  
1008
                if (role != null) {
1009
                    if (".".Equals(role)) {
1010
                        environment.contextItem = selectedItem;
1011
                    } else if (role.StartsWith("$")) {
1012
                        String varName = role.Substring(1);
1013
                        environment.params1.Add(new QName(varName), selectedItem);
1014
                        environment.xpathCompiler.DeclareVariable(new QName(varName));
1015
                        environment.paramDeclarations.append("declare variable $" + varName + " external; ");
1016
                    }
1017
                }
1018
            }
1019
            String definesStylesheet = ((XdmNode) source).GetAttributeValue(new QName("defines-stylesheet"));
1020
            if (definesStylesheet != null) {
1021
                definesStylesheet = definesStylesheet.Trim();
1022
            }
1023
            if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet)) {
1024
                // try using an embedded stylesheet from the source document
1025
                try {
1026
                    
1027
                    //environment.xsltExecutable = environment.xsltCompiler.Compile(XdmNode.Wrap(JPreparedStylesheet.getAssociatedStylesheet(
1028
                    //        environment.processor.Implementation,
1029
                    //        ((XdmNode) environment.contextItem), null, null, null)));
1030
                    environment.xsltExecutable = environment.xsltCompiler.CompileAssociatedStylesheet(((XdmNode)environment.contextItem));
1031
                    
1032
                } catch (Exception) {
1033
                    driver.println("*** failed to compile stylesheet referenced in source document " + href);
1034
                }
1035
            }
1036
        }
1037
    }
1038

  
1039
        public class JAbstractResourceCollection : ResourceCollection
1040

  
1041
        {
1042
            private String cURI;
1043
            private List<Resource> resourcesOrig;
1044
            private java.util.List resourcesi = new java.util.ArrayList();
1045
            public JAbstractResourceCollection(String uri, List<Resource> ri) {
1046
               
1047
                resourcesOrig = ri;
1048
                cURI = uri;
1049
               
1050
            }
1051

  
1052
            public Iterator getResources(XPathContext value)
1053
            {
1054
                resourcesi.clear();
1055
                foreach (Resource r in resourcesOrig)
1056
                {
1057
                    resourcesi.add(r);
1058
                }
1059

  
1060
                return resourcesi.iterator();
1061
            }
1062

  
1063
            public Iterator getResourceURIs(XPathContext value)
1064
            {
1065
                java.util.ArrayList resourceUris = new java.util.ArrayList();
1066
                foreach (Resource r in resourcesOrig)
1067
                {
1068
                    resourcesi.add(r.getResourceURI());
1069
                }
1070
                return resourcesi.iterator();
1071
            }
1072

  
1073
            string ResourceCollection.getCollectionURI()
1074
            {
1075
                return cURI;
1076
            }
1077

  
1078
            Iterator ResourceCollection.getResources(XPathContext xpc)
1079
            {
1080
                java.util.ArrayList resourceUris = new java.util.ArrayList();
1081
                foreach (Resource r in resourcesOrig)
1082
                {
1083
                    resourcesi.add(r);
1084
                }
1085
                return resourcesi.iterator();
1086
            }
1087

  
1088
            Iterator ResourceCollection.getResourceURIs(XPathContext xpc)
1089
            {
1090
                java.util.ArrayList resourceUris = new java.util.ArrayList();
1091
                foreach (Resource r in resourcesOrig)
1092
                {
1093
                    resourcesi.add(r.getResourceURI());
1094
                }
1095
                return resourcesi.iterator();
1096
            }
1097

  
1098
            bool ResourceCollection.isStable(XPathContext xpc)
1099
            {
1100
                return false;
1101
            }
1102

  
1103
            bool ResourceCollection.stripWhitespace(SpaceStrippingRule ssr)
1104
            {
1105
                throw new NotImplementedException();
1106
            }
1107

  
1108
            internal Resource MakeResource(JConfiguration config, AbstractResourceCollection.InputDetails details, string absolutePath)
1109
            {
1110
                net.sf.saxon.lib.ResourceFactory factory = null;
1111
                String contentType = details.contentType;
1112
                if (contentType != null) {
1113
                    factory = config.getResourceFactoryForMediaType(contentType);
1114
                }
1115
                if (factory == null) {
1116
                    factory = BinaryResource.FACTORY;
1117
                }
1118
                return factory.makeResource(config, details);
1119
            }
1120
        }
1121

  
1122

  
1123
        public class CollectionFinder : net.sf.saxon.lib.CollectionFinder
1124
        {
1125

  
1126
            Dictionary<Uri, ResourceCollection> collections;
1127
            public CollectionFinder(Dictionary<Uri, ResourceCollection> collections)
1128
            {
1129
                this.collections = collections;
1130
            }
1131
            public ResourceCollection findCollection(XPathContext xpc, string str)
1132
            {
1133
                if (str == null) {
1134
                    str = "";
1135
                }
1136
                return (ResourceCollection)collections[new Uri(str)];
1137
            }
1138
        }
1139

  
1140

  
1141

  
1142
        public class CollectionResolver /*:net.sf.saxon.lib.CollectionURIResolver */{
1143
            System.Collections.Hashtable collections;
1144
            public CollectionResolver(System.Collections.Hashtable collections)
1145
            { 
1146
                this.collections = collections;
1147
            }
1148
                            public net.sf.saxon.om.SequenceIterator resolve(string href, string baseStr, net.sf.saxon.expr.XPathContext context)  {
1149
                                try {
1150
                                    List<Uri> docs;
1151
                                    if (href == null) {
1152
                                        docs = (List<Uri>)collections[new Uri("http://www.saxonica.com/defaultCollection")];
1153
                                    } else {
1154
                                        XmlUrlResolver res = new XmlUrlResolver();
1155
                                        Uri abs= res.ResolveUri(new Uri(baseStr), href);
1156
                                        try
1157
                                        {
1158
                                            docs = (List<Uri>)collections[abs];
1159
                                        }
1160
                                        catch (Exception) {
1161
                                            docs = null;
1162
                                        }
1163
                                    }
1164
                                    if (docs == null) {
1165
                                        return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1166
                                    } else {
1167
                                        java.util.List list = new java.util.ArrayList();
1168
                                        foreach(Uri uri in docs){
1169
                                            list.add(new net.sf.saxon.value.AnyURIValue(uri.ToString()));
1170
                                        }
1171
                                        
1172
                                        return new net.sf.saxon.tree.iter.ListIterator(list);
1173
                                    }
1174
                                } catch (java.net.URISyntaxException e) {
1175
                                    System.Console.WriteLine("** Invalid Uri: " + e.Message);
1176
                                    return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1177
                                }
1178
                            }
1179
                        }
1180

  
1181
        /**
1182
         * The environment acts as a URIResolver
1183
         */
1184

  
1185
        /*public Source resolve(string href, string base) throws TransformerException {
1186
            XdmNode node = sourceDocs.get(href);
1187
            if (node == null) {
1188
                string uri;
1189
                try {
1190
                    uri = new URI(base).resolve(href).tostring();
1191
                } catch (URISyntaxException e) {
1192
                    uri = href;
1193
                } catch (IllegalArgumentException e) {
1194
                    uri = href;
1195
                }
1196
                string val = streamedSecondaryDocs.get(uri);
1197
                if (val != null) {
1198
                    Source source = new StreamSource(uri);
1199
                    if (!val.Equals("skip")) {
1200
                        source = AugmentedSource.makeAugmentedSource(source);
1201
                        ((AugmentedSource)source).setSchemaValidationMode(Validation.getCode(val));
1202
                    }
1203
                    return source;
1204
                } else {
1205
                    return null;
1206
                }
1207
            } else {
1208
                return node.asSource();
1209
            }
1210
        }*/
1211

  
1212

  
1213
        /* private class LazyLiteralInjector: JCodeInjector {
1214
             public JExpression inject(JExpression exp, StaticContext env, int construct, JStructuredQName qName) {
1215
                 if (exp is net.sf.saxon.expr.Literal) {
1216
                     JStructuredQName name = new JStructuredQName("saxon", JNamespaceConstant.SAXON, "lazy-literal");
1217
                     com.saxonica.expr.JavaExtensionFunctionCall wrapper = new com.saxonica.expr.JavaExtensionFunctionCall();
1218
                     try {
1219
                         wrapper.init(name, FOTestSuiteDriver.class,
1220
                                 FOTestSuiteDriver.class.getMethod("lazyLiteral", Sequence.class),
1221
                                 env.getConfiguration());
1222
                         wrapper.setArguments(new Expression[]{exp});
1223
                     } catch (NoSuchMethodException e) {
1224
                         throw new IllegalStateException(e);
1225
                     }
1226
                     return wrapper;
1227
                 } else {
1228
                     return exp;
1229
                 }
1230
             }
1231

  
1232
             public Clause injectClause(Clause target, StaticContext env, Container container) {
1233
                 return null;
1234
             }
1235
         } */
1236

  
1237
        public delegate void ResetAction(Environment env);
1238
       
1239

  
1240
        
1241

  
1242

  
1243
}
1244
}
1245

  
src/samples/cs/TestRunner10.0/ErrorCollector.cs
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using Saxon.Api;
6
using JXPathException = net.sf.saxon.trans.XPathException;
7

  
8
namespace TestRunner
9
{
10
   
11

  
12

  
13
	public class ErrorCollector : IMessageListener {
14

  
15
		private IList<QName> errorCodes = new List<QName>();
16

  
17
		TestOutcome outcome1;
18

  
19
		public ErrorCollector(TestOutcome out1)
20
			: base()
21
		{
22
			outcome1 = out1;
23
		}
24

  
25
		public void Message(XdmNode content, bool terminate, IXmlLocation location)
26
		{
27
			outcome1.AddXslMessage(content);
28
		}
29

  
30
    
31
    public void error(Exception exception) {
32
        addErrorCode(exception);
33
        //super.error(exception);
34
    }
35

  
36

  
37

  
38
    
39
    public void fatalError(Exception exception)  {
40
        addErrorCode(exception);
41
        //super.fatalError(exception);
42
    }
43

  
44
    /**
45
     * Make a clean copy of this ErrorListener. This is necessary because the
46
     * standard error listener is stateful (it remembers how many errors there have been)
47
     *
48
     * @param hostLanguage the host language (not used by this implementation)
49
     * @return a copy of this error listener
50
     */
51
    
52
    public ErrorCollector makeAnother(int hostLanguage) {
53
        return this;
54
    }
55

  
56
    private void addErrorCode(Exception exception) {
57
			if (exception is JXPathException) {
58
            String errorCode = ((JXPathException) exception).getErrorCodeLocalPart();
59
            if (errorCode != null) {
60
                String ns = ((JXPathException) exception).getErrorCodeNamespace();
61
					if (ns != null && !net.sf.saxon.lib.NamespaceConstant.ERR.Equals(ns)) {
62
                    errorCode = "Q{" + ns + "}" + errorCode;
63
                }
64
					errorCodes.Add(new QName(errorCode));
65
            } else {
66
					errorCodes.Add(new QName("ZZZZ9999"));
67
            }
68
        }
69
    }
70

  
71
	public IList<QName> getErrorCodes() {
72
        return errorCodes;
73
    }
74

  
75

  
76
}
77
}
src/samples/cs/TestRunner10.0/FileComparer.cs
1
using System;
2
using System.IO;
3
using System.Collections;
4
using System.Xml;
5
using System.Collections.Generic;
6
using System.Text;
7
using Saxon.Api;
8

  
9
namespace TestRunner
10
{
11
    /// <summary>
12
    /// Code to compare actual results of a test (outfile) with reference results (reffile).
13
    /// The parameter comparator is the name of a comparison method: xml, html, xml-frag, xhtml, inspect.
14
    /// The return value is "OK" if the files compare equal. Any string starting with "#" indicates the files are
15
    /// considered equal but with a comment (e.g. that they are equal after removing whitespace). Any other string indicates
16
    /// not equal, with an explanation of why.
17
    /// </summary>
18

  
19
    
20
    class FileComparer
21
    {
22
        private Processor processor;
23
        private String comparerDir = "e:/tests/comparers/";
24
        bool debug = false;
25

  
26
        public FileComparer(Processor processor, String testSuiteDir)
27
        {
28
            this.processor = processor;
29
            //this.testSuiteDir = testSuiteDir;
30
        }
31

  
32
        public String compare(String outfile, String reffile, String comparator)
33
        {
34
            if (comparator == "Ignore")
35
            {
36
                return "OK";
37
            }
38
            if (reffile == null || !File.Exists(reffile))
39
            {
40
                Console.WriteLine("*** No reference results available");
41
                return "No reference results available";
42
            }
43

  
44
            // try direct comparison first
45

  
46
            String refResult = null;
47
            String actResult = null;
48

  
49
            try
50
            {
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff