Project

Profile

Help

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

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

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 ResetAction resetAction = null;
72
        public bool outputTree = true;
73
        public bool outputSerialize = false;
74
        public String streamedInputValidation = "skip";
75

    
76

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

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

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

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

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

    
208
            // set the base URI if specified
209

    
210
            SetBaseUri(driver, xpc, env, environment);
211

    
212
            // set any requested collations
213

    
214
            RegisterCollations(xpc, env, environment);
215

    
216
            // declare the requested namespaces
217

    
218
            DeclareNamespaces(xpc, env, environment);
219

    
220
            // load the requested schema documents
221

    
222
            SchemaManager manager = environment.processor.SchemaManager;
223
            bool validateSources = LoadSchemaDocuments(xpc, env, manager);
224

    
225
            // load the requested source documents
226

    
227
            LoadSourceDocuments(driver, xpc, env, environment, builder, manager, validateSources);
228

    
229
            // create a collection URI resolver to handle the requested collections
230

    
231
            CreateCollectionUriResolver(driver, xpc, env, environment, builder);
232

    
233
            // create an unparsed text resolver to handle any unparsed text resources
234

    
235
            CreateUnparsedTextResolver(driver, xpc, env, environment);
236

    
237
            // register any required decimal formats
238

    
239
             RegisterDecimalFormats(driver, xpc, env, environment);
240

    
241
            // declare any variables
242

    
243
            DeclareExternalVariables(driver, xpc, env, environment);
244

    
245
            // declare any output controls
246
            DeclareOutputControls(driver, xpc, env, environment);
247

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

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

    
273

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

    
300
            return environment;
301
        }
302

    
303

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

    
328
        private static void RegisterCollations(XPathCompiler xpc, XdmItem env, Environment environment)
329
        {
330
            CompareInfo info = CultureInfo.CurrentCulture.CompareInfo;
331
            CompareOptions options = CompareOptions.IgnoreCase;
332
            foreach (XdmItem basei in xpc.Evaluate("collation", env))
333
            {
334
                string uri = ((XdmNode)basei).GetAttributeValue(new QName("uri"));
335
                String defaultAtt = ((XdmNode)basei).GetAttributeValue(new QName("default"));
336
                bool isDefault = defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1"));
337
                if (uri.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") ||
338
                        uri.Equals("http://www.w3.org/xslts/collation/caseblind"))
339
                {
340
                    JConfiguration config = xpc.Processor.Implementation;
341
                    JStringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", config);
342

    
343
                    environment.xpathCompiler.DeclareCollation(new Uri(uri), info, options, isDefault);//(Collator) ((SimpleCollation) collator.).getCollation());
344
                    environment.xqueryCompiler.DeclareCollation(new Uri(uri), info, options, isDefault);
345
                    if (environment.xsltCompiler != null)
346
                    {
347
                        environment.xsltCompiler.DeclareCollation(new Uri(uri), info, options, isDefault);
348
                    }
349
                }
350
            }
351
        }
352

    
353
        private static void DeclareNamespaces(XPathCompiler xpc, XdmItem env, Environment environment)
354
        {
355
            foreach (XdmItem nsElement in xpc.Evaluate("namespace", env))
356
            {
357
                String prefix = ((XdmNode)nsElement).GetAttributeValue(new QName("prefix"));
358
                String uri = ((XdmNode)nsElement).GetAttributeValue(new QName("uri"));
359
                environment.xpathCompiler.DeclareNamespace(prefix, uri);
360
                environment.xqueryCompiler.DeclareNamespace(prefix, uri);
361
                if (uri.Equals("http://expath.org/ns/file"))
362
                {
363
                    // For EXPath file tests, set the EXPath base directory to the catalog directory
364
                    string basei = ((XdmNode)nsElement).BaseUri.ToString();
365
                    if (basei.StartsWith("file:///"))
366
                    {
367
                        basei = basei.Substring(7);
368
                    }
369
                    else if (basei.StartsWith("file:/"))
370
                    {
371
                        basei = basei.Substring(5);
372
                    }
373
                    FileStream file = new FileStream(basei, FileMode.Open, FileAccess.Read); //new File(base);
374

    
375
                    //System.SetProperty("expath.base.directory", file.ToString());
376
                }
377
            }
378
        }
379

    
380
        private static bool LoadSchemaDocuments(XPathCompiler xpc, XdmItem env, SchemaManager manager)
381
        {
382
            bool validateSources = false;
383
            XmlUrlResolver res = new XmlUrlResolver();
384
            foreach (XdmItem schema in xpc.Evaluate("schema", env))
385
            {
386
                String role = ((XdmNode)schema).GetAttributeValue(new QName("role"));
387
                String xsdVersion = ((XdmNode)schema).GetAttributeValue(new QName("xsd-version"));
388
                if (xsdVersion != null)
389
                {
390
                    manager.XsdVersion = xsdVersion;
391
                }
392
                if (!"secondary".Equals(role))
393
                {
394
                    String href = ((XdmNode)schema).GetAttributeValue(new QName("file"));
395
                    Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, href);
396
                    FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
397
                    try
398
                    {
399
                        manager.Compile(file, uri);
400
                    }
401
                    catch (Exception err)
402
                    {
403
                        System.Console.WriteLine("*** Failed to load schema: " + err.Message + ", Trace:" + err.StackTrace);
404
                    }
405

    
406
                    if ("source-reference".Equals(role))
407
                    {
408
                        validateSources = true;
409
                    }
410
                }
411
            }
412
            return validateSources;
413
        }
414

    
415
        private static void DeclareExternalVariables(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
416
        {
417
            foreach (XdmItem param in xpc.Evaluate("param", env))
418
            {
419
                String varName = ((XdmNode)param).GetAttributeValue(new QName("name"));
420
                XdmValue value;
421
                String source = ((XdmNode)param).GetAttributeValue(new QName("source"));
422
                if (source != null)
423
                {
424
                    XdmNode sourceDoc = null;
425
                    try
426
                    {
427
                        sourceDoc = environment.sourceDocs[source];
428
                    }
429
                    catch (Exception) { }
430
                    if (sourceDoc == null)
431
                    {
432
                        driver.println("**** Unknown source document " + source);
433
                    }
434
                    value = sourceDoc;
435
                }
436
                else
437
                {
438
                    String select = ((XdmNode)param).GetAttributeValue(new QName("select"));
439
                    value = xpc.Evaluate(select, null);
440
                }
441
                QName varQName;
442
                int colon = varName.IndexOf(':');
443
                if (colon >= 0)
444
                {
445

    
446
                    varQName = new QName(varName, (XdmNode)param);
447
                }
448
                else {
449
                    varQName = new QName(varName);
450
                }
451

    
452
                environment.params1.Add(varQName, value);
453
                environment.xpathCompiler.DeclareVariable(varQName);
454
                String declared = ((XdmNode)param).GetAttributeValue(new QName("declared"));
455
                if (declared != null && "true".Equals(declared) || "1".Equals(declared))
456
                {
457
                    // no action
458
                }
459
                else
460
                {
461
                    environment.paramDeclarations.append("declare variable $" + varName + " external; ");
462
                }
463
            }
464
        }
465

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

    
470
                XdmNode formatElement = (XdmNode) decimalFormat;
471
                String formatName = formatElement.GetAttributeValue(new QName("name"));
472
                QName formatQName = null;
473
                if (formatName != null) {
474
                    if (formatName.IndexOf(':') < 0) {
475
                        formatQName = new QName("", "", formatName);
476
                    } else {
477
                        try {
478
                            formatQName = new QName(formatName,formatElement);
479
                        } catch (Exception e) {
480
                            driver.println("**** Invalid QName as decimal-format name");
481
                            formatQName = new QName("", "", "error-name");
482
                        }
483
                    }
484
                    environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.EQName + " ");
485
                } else {
486
                    environment.paramDecimalDeclarations.append("declare default decimal-format ");
487
                }
488
              
489
                foreach (XdmItem decimalFormatAtt in xpc.Evaluate("@* except @name", formatElement)) {
490
                    XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
491
                    String property = formatAttribute.NodeName.LocalName;
492
                    String value = formatAttribute.StringValue;
493
                    environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" ");
494
                    try {
495
                        environment.xpathCompiler.SetDecimalFormatProperty(formatQName, property, value);
496
                    }
497
                    catch (Exception e) {
498
                        driver.println("**** Error in Decimal format: "+ e.Message);
499
                    }
500
                }
501
                environment.paramDecimalDeclarations.append(";");
502
                
503

    
504
            }
505
        }
506

    
507
        private static void CreateUnparsedTextResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)
508
        {
509
            Dictionary<Uri, Object> resources = new Dictionary<Uri, Object>();
510
            Dictionary<Uri, String> encodings = new Dictionary<Uri, String>();
511
            XmlUrlResolver res = new XmlUrlResolver();
512
            foreach (XdmItem resource in xpc.Evaluate("resource", env))
513
            {
514
                String uri = ((XdmNode)resource).GetAttributeValue(new QName("uri"));
515
                String href = ((XdmNode)resource).GetAttributeValue(new QName("file"));
516
                String encoding = ((XdmNode)resource).GetAttributeValue(new QName("encoding"));
517
                if (href != null)
518
                {
519
                    Object obj = null;
520
                    if (href.StartsWith("http"))
521
                    {
522
                        try
523
                        {
524
                            obj = new Uri(href);
525
                        }
526
                        catch (Exception e)
527
                        {
528
                            throw e;
529
                        }
530
                    }
531
                    else
532
                    {
533
                        obj = new java.io.File(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
534
                    }
535
                    try
536
                    {
537
                        resources.Add(new Uri(uri), obj);
538
                        encodings.Add(new Uri(uri), encoding);
539
                        Uri abs = res.ResolveUri(((XdmNode)resource).BaseUri, uri);
540
                        resources.Add(abs, obj);
541
                        encodings.Add(abs, encoding);
542
                    }
543
                    catch (Exception e)
544
                    {
545
                        driver.println("** Invalid URI in environment: " + e.Message);
546
                    }
547
                }
548
            }
549
            if (resources.Count != 0)
550
            {
551
                environment.unparsedTextResolver =
552
                   new UnparsedTextURIResolver(encodings, resources);
553
            }
554
        }
555

    
556
        public class UnparsedTextURIResolver : JUnparsedTextURIResolver
557
        {
558
            Dictionary<Uri, String> encodings;
559
            Dictionary<Uri, Object> resources;
560
            public UnparsedTextURIResolver(Dictionary<Uri, String> encodings, Dictionary<Uri, Object> resources)
561
            {
562
                this.encodings = encodings;
563
                this.resources = resources;
564
            }
565

    
566

    
567
            public Reader resolve(URI absoluteURI, string encoding, Configuration config)
568
            {
569
                if (encoding == null)
570
                {
571
                    encodings.TryGetValue(new Uri(absoluteURI.ToString()), out encoding);
572
                }
573
                if (encoding == null)
574
                {
575
                    encoding = "utf-8";
576
                }
577
                try
578
                {
579
                    // The following is necessary to ensure that encoding errors are not recovered.
580
                    java.nio.charset.Charset charset = java.nio.charset.Charset.forName(encoding);
581
                    java.nio.charset.CharsetDecoder decoder = charset.newDecoder();
582
                    decoder = decoder.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT);
583
                    decoder = decoder.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT);
584
                    Object obj;
585
                    resources.TryGetValue(new Uri(absoluteURI.ToString()), out obj);
586
                    if (obj is java.io.File)
587
                    {
588
                        return new BufferedReader(new InputStreamReader(new FileInputStream((java.io.File)obj), decoder));
589
                    }
590
                    else
591
                    {
592
                        resources.TryGetValue(new Uri(absoluteURI.ToString()), out obj);
593
                        URL resource = (URL)obj;
594
                        if (resource == null)
595
                        {
596
                            resource = absoluteURI.toURL();
597
                            //throw new XPathException("Unparsed text resource " + absoluteURI + " not registered in catalog", "FOUT1170");
598
                        }
599
                        java.io.InputStream in1 = resource.openConnection().getInputStream();
600
                        return new BufferedReader(new InputStreamReader(in1, decoder));
601
                    }
602
                    //   return new InputStreamReader(new FileInputStream(resources.get(absoluteURI)), encoding);
603
                }
604
                catch (java.lang.Exception ioe)
605
                {
606
                    throw new Exception(ioe.getMessage() + "FOUT1170");
607
                }
608
                /*catch (IllegalCharsetNameException icne)
609
                {
610
                    throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
611
                }
612
                catch (UnsupportedCharsetException uce)
613
                {
614
                    throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
615
                }*/
616
            }
617
        
618
    
619

    
620

    
621

    
622
    }
623

    
624
    private static void CreateCollectionUriResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder) {
625
        Dictionary<Uri, ResourceCollection> collections = new Dictionary<Uri, ResourceCollection>();
626
            JAbstractResourceCollection collectioni = null;
627
            Configuration config = environment.processor.Implementation;
628
            XmlUrlResolver res = new XmlUrlResolver();
629
        foreach (XdmItem coll in xpc.Evaluate("collection", env)) {
630
                List<Resource> resourcesi = new List<Resource>();
631
            String collectionURI = ((XdmNode) coll).GetAttributeValue(new QName("uri"));
632
            if (collectionURI == null) {
633
                collectionURI = "";
634
            }
635
                if (collectionURI.Equals("")) {
636
                    collectionURI = "http://www.w.org/qt3-test-suite/default.collection.uri";
637
                    config.setDefaultCollection(collectionURI);
638
                }
639
            Uri u;
640
            try {
641
                u = new Uri(collectionURI);
642
            } catch (Exception e) {
643
                driver.println("**** Invalid collection URI " + collectionURI);
644
                break;
645
				}
646
            if (!collectionURI.Equals("") && !u.IsAbsoluteUri) {
647
                u = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI);
648
                collectionURI = u.ToString();
649
            }
650

    
651
                
652
            
653
            foreach (XdmItem source in xpc.Evaluate("source", coll)) {
654
                String href = ((XdmNode) source).GetAttributeValue(new QName("file"));
655
                String frag = null;
656
                int hash = href.IndexOf('#');
657
                if (hash > 0) {
658
                    frag = href.Substring(hash + 1);
659
                    href = href.Substring(0, hash);
660
                }
661
                FileStream file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
662
               // String id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
663
					String uriStr = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsoluteUri;
664
				builder.BaseUri = new Uri(uriStr);
665
                XdmNode doc = builder.Build(file);
666
                if (frag != null) {
667
                    XdmNode selected = (XdmNode)environment.xpathCompiler.EvaluateSingle("id('" + frag + "')", doc);
668
                    if (selected == null) {
669
                        driver.println("**** Fragment not found: " + frag);
670
                        break;
671
                    }
672
                    resourcesi.Add(new net.sf.saxon.resource.XmlResource(config, selected.Implementation));
673
                } else {
674
                        resourcesi.Add(new net.sf.saxon.resource.XmlResource(config, doc.Implementation));
675
                    }
676
					environment.sourceDocs.Add(uriStr, doc);
677
            }
678
                foreach (XdmItem source in xpc.Evaluate("resources", coll))
679
                {
680
                    String uri = ((XdmNode)source).GetAttributeValue(new QName("uri"));
681
                    String href = ((XdmNode)source).GetAttributeValue(new QName("file"));
682
                    String encoding = ((XdmNode)source).GetAttributeValue(new QName("encoding"));
683
                    String media = ((XdmNode)source).GetAttributeValue(new QName("media-type"));
684
                    net.sf.saxon.resource.AbstractResourceCollection.InputDetails details = new net.sf.saxon.resource.AbstractResourceCollection.InputDetails();
685
                    details.encoding = encoding;
686
                    details.contentType = media;
687
                    if (href != null)
688
                    {
689
                        if (href.StartsWith("http"))
690
                        {
691
                            try
692
                            {
693
                                URL url = new URL(href);
694
                                URLConnection connection = url.openConnection();
695
                                if (details.contentType == null)
696
                                {
697
                                    details.contentType = connection.getContentType();
698
                                }
699
                                details.inputStream = connection.getInputStream();
700
                            }
701
                            catch (Exception e)
702
                            {
703
                                throw new Exception (e.StackTrace);
704
                            }
705
                          
706
                        }
707
                        else
708
                        {
709
                            
710
                            
711
                            try
712
                            {
713
                                FileStream file = new FileStream(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
714
                                Resource resourcej = collectioni.MakeResource(config, details, res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
715
                                if (resourcej != null)
716
                                {
717
                                    resourcesi.Add(resourcej);
718
                                }
719
                                else
720
                                {
721
                                    driver.println("** Error in building collection environment: Resource " + href + " not found: ");
722
                                }
723
                            }
724
                            catch (Exception e)
725
                            {
726
                                driver.println("** IO Error in building collection environment: " + e.Message);
727

    
728
                            }
729
                           
730
                            if (media != null && href.EndsWith("xquery"))
731
                            {
732
                               // driver.RegisterXQueryModule(uri, file);
733
                            }
734
                        }
735

    
736
                    }
737
                }
738
                collectioni = new JAbstractResourceCollection(collectionURI, resourcesi);
739
                try {
740
                collections.Add(new Uri(collectionURI), collectioni);
741
            } catch (Exception e) {
742
                driver.println("**** Invalid collection URI " + collectionURI);
743
				}
744

    
745
        }
746
        if (collections.Count != 0) {
747
                environment.processor.Implementation.setCollectionFinder(new CollectionFinder(collections));
748
        }
749
    }
750

    
751
		// Methods
752
		//
753
		public override object GetEntity (Uri href, string role, Type ofObjectToReturn)
754
		{
755
			XdmNode node = null;
756
			String hrefStr = href.ToString();
757
			//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
758

    
759
			bool foundDoc = sourceDocs.TryGetValue(hrefStr, out node);
760

    
761
            if (!foundDoc) {
762
                 hrefStr = hrefStr.Substring(hrefStr.LastIndexOf('/') + 1);
763
                 foundDoc = sourceDocs.TryGetValue(hrefStr, out node);
764
            }
765

    
766
			if (!foundDoc) {
767

    
768
				string val;
769
				hrefStr = href.ToString();
770
				//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
771

    
772
				bool foundSecDoc = streamedSecondaryDocs.TryGetValue(hrefStr, out val);
773
                if(!foundSecDoc)
774
                {
775
                    hrefStr = hrefStr.Substring(hrefStr.LastIndexOf('/') + 1);
776
                    foundSecDoc = streamedSecondaryDocs.TryGetValue(hrefStr, out val);
777
                }
778

    
779
				if (foundSecDoc) {
780

    
781

    
782
                    //string hrefStr = href.ToString ();
783
                    String hrefStri = (hrefStr.StartsWith("file:///") ? hrefStr.Substring(8) : hrefStr);
784
                    Stream sourceii = new FileStream(hrefStri, FileMode.Open);
785
                    net.sf.saxon.dotnet.DotNetInputStream stream = new net.sf.saxon.dotnet.DotNetInputStream(sourceii);
786

    
787
                    javax.xml.transform.Source sourcei = new javax.xml.transform.stream.StreamSource(stream);
788

    
789
				
790
					 if(!val.Equals("skip")){
791
					
792
						sourcei = net.sf.saxon.lib.AugmentedSource.makeAugmentedSource(sourcei);
793
							((net.sf.saxon.lib.AugmentedSource) sourcei).setSchemaValidationMode(net.sf.saxon.lib.Validation.getCode(val));
794

    
795
					}
796
					sourcei.setSystemId(hrefStr) ;
797
					return sourcei;
798
				} else {
799
					return null;
800
				}
801
			} else {
802
				return node.Implementation;
803
			}
804
		}
805

    
806
		public override Uri ResolveUri (Uri basei, string href)
807
		{
808

    
809
			return base.ResolveUri (basei, href);
810
		}
811

    
812
    private static void LoadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder, SchemaManager manager, bool validateSources) {
813
        XmlUrlResolver res = new XmlUrlResolver();
814
        foreach (XdmItem source in xpc.Evaluate("source", env)) {
815
            XdmNode doc = null;
816

    
817
            String uri = ((XdmNode) source).GetAttributeValue(new QName("uri"));
818
            String mime = ((XdmNode) source).GetAttributeValue(new QName("media-type"));
819
            if (mime != null && "application/xml".Equals(mime)) {
820
                continue;
821
            }
822
            String validation = ((XdmNode) source).GetAttributeValue(new QName("", "validation"));
823
            if (validation == null) {
824
                validation = "skip";
825
            }
826
            String streaming = ((XdmNode) source).GetAttributeValue(new QName("", "streaming"));
827
            if (!validateSources && validation.Equals("skip")) {
828
                builder.SchemaValidationMode = SchemaValidationMode.None;
829
                    builder.SchemaValidator = null;
830
            } else {
831
                SchemaValidator validator = manager.NewSchemaValidator();
832
                if("lax".Equals(validation)) {
833
                    validator.IsLax = true;
834
                        builder.SchemaValidator = validator;
835
                        builder.SchemaValidationMode = SchemaValidationMode.Lax;
836
                } else
837
                {
838
                        builder.SchemaValidator = validator;
839
                        builder.SchemaValidationMode = SchemaValidationMode.Strict;
840
                }
841
                environment.xpathCompiler.SchemaAware = true;
842
                environment.xqueryCompiler.SchemaAware = true;
843
				if (environment.xsltCompiler != null) {
844
					environment.xsltCompiler.SchemaAware = true;
845
				}
846
            }
847

    
848
            String role = ((XdmNode) source).GetAttributeValue(new QName("role"));
849
            String href = ((XdmNode) source).GetAttributeValue(new QName("file"));
850
            if ("true".Equals(streaming)) {
851
                if (".".Equals(role)) {
852
						if (href == null) {
853
							environment.streamedContent = xpc.Evaluate ("string(content)", source).ToString();
854
						} else {
855
							environment.streamedPath = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsolutePath;
856
						}
857
                        environment.streamedInputValidation = validation;
858
                } else {
859
                    try
860
                    {
861
							System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
862
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri);
863
                            System.Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).ToString());
864
							environment.streamedSecondaryDocs.Add(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri, validation);
865
                    }catch(Exception){}
866
                }
867
            } else {
868
                Stream ss;
869
                /*if (uri != null) {
870
                    uri = res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri;
871
                }*/
872
                if (href != null) {
873
                        try
874
                        {
875
                            Uri fileLoc = res.ResolveUri(((XdmNode) env).BaseUri, href);
876
                    FileStream file = null;
877
                    if (fileLoc.Scheme.Equals("file")) {
878
                        file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
879
                        if (uri == null) {
880
								uri = fileLoc.AbsoluteUri;
881
                        }
882
                    }
883
                   
884
                        ss = (file == null ? new FileStream(fileLoc.ToString(), FileMode.Open, FileAccess.Read)
885
                                           : file);
886
                        
887
							builder.BaseUri = ((XdmNode) env).BaseUri;
888
                    } catch (Exception e) {
889
                        driver.println("*** failed to find source document " + href + ", Exception:" + e.Message);
890
                        continue;
891
                    }
892
                } else {
893
                    // content is inline in the catalog
894
                    if (uri == null) {
895
                        uri = ((XdmNode) env).BaseUri.AbsolutePath;
896
                    }
897
                    string content = xpc.Evaluate("string(content)", source).ToString();
898
                    byte[] byteArray = Encoding.ASCII.GetBytes(content);
899
                    ss = new MemoryStream(byteArray);
900
                    builder.BaseUri = ((XdmNode)env).BaseUri;
901
                }
902

    
903

    
904
                try {
905
					builder.BaseUri = new Uri(res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri);
906
                    doc = builder.Build(ss);
907
                    environment.sourceDocs.Add(uri, doc);
908
                } catch (Exception e) {
909
                    driver.println("*** failed to build source document " + href + ", Exception:" + e.Message);
910
                }
911

    
912
                XdmItem selectedItem = doc;
913
                String select = ((XdmNode) source).GetAttributeValue(new QName("select"));
914
                if (select != null) {
915
                    XPathSelector selector = environment.xpathCompiler.Compile(select).Load();
916
                    selector.ContextItem = selectedItem;
917
                    selectedItem = selector.EvaluateSingle();
918
                }
919

    
920

    
921
                if (role != null) {
922
                    if (".".Equals(role)) {
923
                        environment.contextItem = selectedItem;
924
                    } else if (role.StartsWith("$")) {
925
                        String varName = role.Substring(1);
926
                        environment.params1.Add(new QName(varName), selectedItem);
927
                        environment.xpathCompiler.DeclareVariable(new QName(varName));
928
                        environment.paramDeclarations.append("declare variable $" + varName + " external; ");
929
                    }
930
                }
931
            }
932
            String definesStylesheet = ((XdmNode) source).GetAttributeValue(new QName("defines-stylesheet"));
933
            if (definesStylesheet != null) {
934
                definesStylesheet = definesStylesheet.Trim();
935
            }
936
            if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet)) {
937
                // try using an embedded stylesheet from the source document
938
                try {
939
                    
940
                    //environment.xsltExecutable = environment.xsltCompiler.Compile(XdmNode.Wrap(JPreparedStylesheet.getAssociatedStylesheet(
941
                    //        environment.processor.Implementation,
942
                    //        ((XdmNode) environment.contextItem), null, null, null)));
943
                    environment.xsltExecutable = environment.xsltCompiler.CompileAssociatedStylesheet(((XdmNode)environment.contextItem));
944
                    
945
                } catch (Exception) {
946
                    driver.println("*** failed to compile stylesheet referenced in source document " + href);
947
                }
948
            }
949
        }
950
    }
951

    
952
        public class JAbstractResourceCollection : ResourceCollection
953

    
954
        {
955
            private String cURI;
956
            private List<Resource> resourcesOrig;
957
            private java.util.List resourcesi = new java.util.ArrayList();
958
            public JAbstractResourceCollection(String uri, List<Resource> ri) {
959
               
960
                resourcesOrig = ri;
961
                cURI = uri;
962
               
963
            }
964

    
965
            public Iterator getResources(XPathContext value)
966
            {
967
                resourcesi.clear();
968
                foreach (Resource r in resourcesOrig)
969
                {
970
                    resourcesi.add(r);
971
                }
972

    
973
                return resourcesi.iterator();
974
            }
975

    
976
            public Iterator getResourceURIs(XPathContext value)
977
            {
978
                java.util.ArrayList resourceUris = new java.util.ArrayList();
979
                foreach (Resource r in resourcesOrig)
980
                {
981
                    resourcesi.add(r.getResourceURI());
982
                }
983
                return resourcesi.iterator();
984
            }
985

    
986
            string ResourceCollection.getCollectionURI()
987
            {
988
                return cURI;
989
            }
990

    
991
            Iterator ResourceCollection.getResources(XPathContext xpc)
992
            {
993
                java.util.ArrayList resourceUris = new java.util.ArrayList();
994
                foreach (Resource r in resourcesOrig)
995
                {
996
                    resourcesi.add(r);
997
                }
998
                return resourcesi.iterator();
999
            }
1000

    
1001
            Iterator ResourceCollection.getResourceURIs(XPathContext xpc)
1002
            {
1003
                java.util.ArrayList resourceUris = new java.util.ArrayList();
1004
                foreach (Resource r in resourcesOrig)
1005
                {
1006
                    resourcesi.add(r.getResourceURI());
1007
                }
1008
                return resourcesi.iterator();
1009
            }
1010

    
1011
            bool ResourceCollection.isStable(XPathContext xpc)
1012
            {
1013
                return false;
1014
            }
1015

    
1016
            bool ResourceCollection.stripWhitespace(SpaceStrippingRule ssr)
1017
            {
1018
                throw new NotImplementedException();
1019
            }
1020

    
1021
            internal Resource MakeResource(JConfiguration config, AbstractResourceCollection.InputDetails details, string absolutePath)
1022
            {
1023
                net.sf.saxon.lib.ResourceFactory factory = null;
1024
                String contentType = details.contentType;
1025
                if (contentType != null) {
1026
                    factory = config.getResourceFactoryForMediaType(contentType);
1027
                }
1028
                if (factory == null) {
1029
                    factory = BinaryResource.FACTORY;
1030
                }
1031
                return factory.makeResource(config, absolutePath, contentType, details);
1032
            }
1033
        }
1034

    
1035

    
1036
        public class CollectionFinder : net.sf.saxon.lib.CollectionFinder
1037
        {
1038

    
1039
            Dictionary<Uri, ResourceCollection> collections;
1040
            public CollectionFinder(Dictionary<Uri, ResourceCollection> collections)
1041
            {
1042
                this.collections = collections;
1043
            }
1044
            public ResourceCollection findCollection(XPathContext xpc, string str)
1045
            {
1046
                if (str == null) {
1047
                    str = "";
1048
                }
1049
                return (ResourceCollection)collections[new Uri(str)];
1050
            }
1051
        }
1052

    
1053

    
1054

    
1055
        public class CollectionResolver: net.sf.saxon.lib.CollectionURIResolver {
1056
            System.Collections.Hashtable collections;
1057
            public CollectionResolver(System.Collections.Hashtable collections)
1058
            { 
1059
                this.collections = collections;
1060
            }
1061
                            public net.sf.saxon.om.SequenceIterator resolve(string href, string baseStr, net.sf.saxon.expr.XPathContext context)  {
1062
                                try {
1063
                                    List<Uri> docs;
1064
                                    if (href == null) {
1065
                                        docs = (List<Uri>)collections[new Uri("http://www.saxonica.com/defaultCollection")];
1066
                                    } else {
1067
                                        XmlUrlResolver res = new XmlUrlResolver();
1068
                                        Uri abs= res.ResolveUri(new Uri(baseStr), href);
1069
                                        try
1070
                                        {
1071
                                            docs = (List<Uri>)collections[abs];
1072
                                        }
1073
                                        catch (Exception) {
1074
                                            docs = null;
1075
                                        }
1076
                                    }
1077
                                    if (docs == null) {
1078
                                        return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1079
                                    } else {
1080
                                        java.util.List list = new java.util.ArrayList();
1081
                                        foreach(Uri uri in docs){
1082
                                            list.add(new net.sf.saxon.value.AnyURIValue(uri.ToString()));
1083
                                        }
1084
                                        
1085
                                        return new net.sf.saxon.tree.iter.ListIterator(list);
1086
                                    }
1087
                                } catch (java.net.URISyntaxException e) {
1088
                                    System.Console.WriteLine("** Invalid Uri: " + e.Message);
1089
                                    return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1090
                                }
1091
                            }
1092
                        }
1093

    
1094
    /**
1095
     * The environment acts as a URIResolver
1096
     */
1097

    
1098
    /*public Source resolve(string href, string base) throws TransformerException {
1099
        XdmNode node = sourceDocs.get(href);
1100
        if (node == null) {
1101
            string uri;
1102
            try {
1103
                uri = new URI(base).resolve(href).tostring();
1104
            } catch (URISyntaxException e) {
1105
                uri = href;
1106
            } catch (IllegalArgumentException e) {
1107
                uri = href;
1108
            }
1109
            string val = streamedSecondaryDocs.get(uri);
1110
            if (val != null) {
1111
                Source source = new StreamSource(uri);
1112
                if (!val.Equals("skip")) {
1113
                    source = AugmentedSource.makeAugmentedSource(source);
1114
                    ((AugmentedSource)source).setSchemaValidationMode(Validation.getCode(val));
1115
                }
1116
                return source;
1117
            } else {
1118
                return null;
1119
            }
1120
        } else {
1121
            return node.asSource();
1122
        }
1123
    }*/
1124

    
1125

    
1126
   /* private class LazyLiteralInjector: JCodeInjector {
1127
        public JExpression inject(JExpression exp, StaticContext env, int construct, JStructuredQName qName) {
1128
            if (exp is net.sf.saxon.expr.Literal) {
1129
                JStructuredQName name = new JStructuredQName("saxon", JNamespaceConstant.SAXON, "lazy-literal");
1130
                com.saxonica.expr.JavaExtensionFunctionCall wrapper = new com.saxonica.expr.JavaExtensionFunctionCall();
1131
                try {
1132
                    wrapper.init(name, FOTestSuiteDriver.class,
1133
                            FOTestSuiteDriver.class.getMethod("lazyLiteral", Sequence.class),
1134
                            env.getConfiguration());
1135
                    wrapper.setArguments(new Expression[]{exp});
1136
                } catch (NoSuchMethodException e) {
1137
                    throw new IllegalStateException(e);
1138
                }
1139
                return wrapper;
1140
            } else {
1141
                return exp;
1142
            }
1143
        }
1144

    
1145
        public Clause injectClause(Clause target, StaticContext env, Container container) {
1146
            return null;
1147
        }
1148
    } */
1149

    
1150
    public abstract class ResetAction {
1151
        public abstract void reset(Environment env);
1152
    }
1153

    
1154

    
1155
}
1156
}
1157

    
(1-1/19)