Project

Profile

Help

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

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

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

    
30

    
31
namespace TestRunner
32
{
33

    
34
/**
35
 * This class represents a collection of resources (source documents, schemas, collections etc) used for a number
36
 * of test cases.
37
 */
38

    
39
public class
40
        Environment: XmlUrlResolver {
41

    
42
    private class MyEnvironment{
43

    
44
    }
45

    
46
    public Processor processor;
47
    public Dictionary<string, XdmNode> sourceDocs = new Dictionary<string, XdmNode>();
48
    public Dictionary<string, string> streamedSecondaryDocs = new Dictionary<string, string>();
49
    public string streamedPath;
50
	public string streamedContent;
51
    public XPathCompiler xpathCompiler;
52
    public XQueryCompiler xqueryCompiler;
53
    public XsltCompiler xsltCompiler;
54
    public XsltExecutable xsltExecutable;
55
    public XdmItem contextItem;
56
    public Dictionary<QName, XdmValue> params1 = new Dictionary<QName, XdmValue>();
57
    public bool xml11 = false;
58
    public bool usable = true;
59
    public JFastStringBuffer paramDeclarations = new JFastStringBuffer(256);
60
    public JFastStringBuffer paramDecimalDeclarations = new JFastStringBuffer(256);
61
    public JUnparsedTextURIResolver unparsedTextResolver;
62
    public ResetAction resetAction = null;
63
	public bool outputTree = true;
64
	public bool outputSerialize = false;
65

    
66

    
67
    /**
68
     * Construct a local default environment for a test set
69
     */
70

    
71
		public static Environment createLocalEnvironment(Uri baseURI, int generateByteCode, bool unfolded, Spec spec) {
72
        Environment environment = new Environment();
73
        environment.processor = new Processor(true);
74
        //AutoActivate.activate(environment.processor);
75
        if (generateByteCode == 1) {
76
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
77
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
78
        } else if (generateByteCode == 2) {
79
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
80
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
81
            //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
82
        } else {
83
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
84
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
85
        }
86
        //environment.processor.SetProperty(JFeatureKeys.TRACE_EXTERNAL_FUNCTIONS, "true");
87
        environment.xpathCompiler = environment.processor.NewXPathCompiler();
88
        environment.xpathCompiler.BaseUri = baseURI.ToString(); //TODO: Check that this is OK
89
        environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
90
		environment.xqueryCompiler.BaseUri  = baseURI.AbsolutePath;
91
        environment.xsltCompiler = environment.processor.NewXsltCompiler();
92
        environment.xsltCompiler.BaseUri = new Uri(baseURI.ToString());
93
		if (spec.Equals (Spec.XT30)) {
94
			environment.xsltCompiler.XsltLanguageVersion = "3.0";
95
		} else {
96
				environment.xsltCompiler.XsltLanguageVersion = "2.0";
97
		}
98
        if (unfolded) {
99
           // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
100
        }
101
        environment.processor.Implementation.setDefaultCollection(null);
102
        return environment;
103
    }
104

    
105
	private static void DeclareOutputControls(TestRunner.TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) {
106
			String needsTree = xpc.Evaluate("string((output/@tree,'yes')[1])", env).ToString();
107
			environment.outputTree = "yes".Equals(needsTree);
108
			String needsSerialization = xpc.Evaluate("string((output/@serialize,'no')[1])", env).ToString();
109
			environment.outputSerialize = "yes".Equals(needsSerialization);
110
	}
111

    
112
    /**
113
     * Construct an Environment
114
     *
115
     * @param xpc          the XPathCompiler used to process the catalog file
116
     * @param env          the Environment element in the catalog file
117
     * @param environments the set of environments to which this one should be added (may be null)
118
     * @return the constructed Environment object
119
     * @throws SaxonApiException
120
     */
121

    
122
    public static Environment processEnvironment(TestRunner.TestDriver driver,
123
            XPathCompiler xpc, XdmItem env, Dictionary<string, Environment> environments, Environment defaultEnvironment) {
124
        Environment environment = new Environment();
125
        String name = ((XdmNode) env).GetAttributeValue(new QName("name"));
126
        if (name != null) {
127
            System.Console.WriteLine("Loading environment " + name);
128
        }
129
        environment.processor = new Processor(true);
130
        if (defaultEnvironment != null) {
131
            environment.processor.SetProperty(JFeatureKeys.XSD_VERSION,
132
                    defaultEnvironment.processor.Implementation.getConfigurationProperty(JFeatureKeys.XSD_VERSION).ToString());
133
        }
134
       // AutoActivate.activate(environment.processor);
135
        if (driver.GenerateByteCode == 1) {
136
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
137
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
138
        } else if (driver.GenerateByteCode == 2) {
139
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
140
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
141
            //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
142
        } else {
143
            environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
144
            environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
145
        }
146
        environment.xpathCompiler = environment.processor.NewXPathCompiler();
147
        environment.xpathCompiler.BaseUri = ((XdmNode) env).BaseUri.ToString();
148
        environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
149
		environment.xqueryCompiler.BaseUri = ((XdmNode) env).BaseUri.AbsolutePath;
150
			if (driver.Spec.ToString().Contains ("XT")) {
151
				environment.xsltCompiler = environment.processor.NewXsltCompiler();
152
				environment.xsltCompiler.XsltLanguageVersion = ((SpecAttr)(driver.Spec.GetAttr())).version;	
153
		}
154
        if (driver.Unfolded) {
155
           // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
156
        }
157
        DocumentBuilder builder = environment.processor.NewDocumentBuilder();
158
        builder.TreeModel = driver.TreeModel;
159
        environment.sourceDocs = new Dictionary<string,XdmNode>();
160
        if (environments != null && name != null) {
161
            try
162
            {
163
                environments.Add(name, environment);
164
            } catch(Exception){}
165
        }
166
        foreach (XdmItem dependency in xpc.Evaluate("dependency", env)) {
167
            if (!driver.dependencyIsSatisfied((XdmNode) dependency, environment)) {
168
                environment.usable = false;
169
            }
170
        }
171

    
172
        // set the base URI if specified
173

    
174
        SetBaseUri(driver, xpc, env, environment);
175

    
176
        // set any requested collations
177

    
178
        RegisterCollations(xpc, env, environment);
179

    
180
        // declare the requested namespaces
181

    
182
        DeclareNamespaces(xpc, env, environment);
183

    
184
        // load the requested schema documents
185

    
186
        SchemaManager manager = environment.processor.SchemaManager;
187
        bool validateSources = LoadSchemaDocuments(xpc, env, manager);
188

    
189
        // load the requested source documents
190

    
191
        LoadSourceDocuments(driver, xpc, env, environment, builder, manager, validateSources);
192

    
193
        // create a collection URI resolver to handle the requested collections
194

    
195
        CreateCollectionUriResolver(driver, xpc, env, environment, builder);
196

    
197
        // create an unparsed text resolver to handle any unparsed text resources
198

    
199
        CreateUnparsedTextResolver(driver, xpc, env, environment);
200

    
201
        // register any required decimal formats
202

    
203
       // registerDecimalFormats(driver, xpc, env, environment);
204

    
205
        // declare any variables
206

    
207
        DeclareExternalVariables(driver, xpc, env, environment);
208

    
209
		// declare any output controls
210
		DeclareOutputControls(driver, xpc, env, environment);
211

    
212
        // handle requested context item
213
        foreach (XdmItem param in xpc.Evaluate("context-item", env)) {
214
            String select = ((XdmNode) param).GetAttributeValue(new QName("select"));
215
            XdmValue value = xpc.Evaluate(select, null);
216
            environment.contextItem = (XdmItem)value;
217
        }
218

    
219
            XmlUrlResolver res = new XmlUrlResolver();
220
        // compile any stylesheet defined as part of the environment (only one allowed)
221
            DocumentBuilder builder1 = environment.processor.NewDocumentBuilder();
222
        foreach (XdmItem stylesheet in xpc.Evaluate("stylesheet[not(@role='secondary')]", env)) {
223
            string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
224
            try
225
            {
226
                XdmNode styleSource = builder1.Build(res.ResolveUri(((XdmNode)env).BaseUri, fileName));
227
                environment.xsltExecutable = environment.xsltCompiler.Compile(styleSource);
228
            } catch (Exception e) {
229
                driver.println("**** failure while compiling environment-defined stylesheet " + fileName);
230
            }
231
        }
232

    
233

    
234
			// compile any stylesheet packages defined as part of the environment
235
			// Support this only in EE - an unusable environment in PE/HE
236
			foreach (XdmItem stylesheet in xpc.Evaluate("package[@role='secondary']", env)) {
237
				if(!"EE".Equals(environment.processor.Edition)) {
238
					environment.usable = false;
239
					break;
240
				}
241
				string fileName = ((XdmNode) stylesheet).GetAttributeValue(new QName("file"));
242
				Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, fileName);
243
				FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
244
				try {
245
					XsltPackage pkg = environment.xsltCompiler.CompilePackage(file);
246
					environment.xsltCompiler.ImportPackage(pkg);
247
				} catch (Exception e) {
248
					//e.printStackTrace();
249
					driver.println("**** failure while compiling environment-defined stylesheet package " + fileName);
250
					driver.println("****Failure "+ e.Message+ " in compiling environment "+ name);
251
					environment.usable = false;
252
				}
253
			}
254

    
255
        return environment;
256
    }
257

    
258

    
259
    private static void SetBaseUri(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) {
260
        foreach (XdmItem basei in xpc.Evaluate("static-base-uri", env)) {
261
            string uri = ((XdmNode) basei).GetAttributeValue(new QName("uri"));
262
            if (uri == null || "#UNDEFINED".Equals(uri)) {
263
                driver.println("**** Error: The BaseURI null and #UNDEFINED is not supported");
264
            } else {
265
                try {
266
                    environment.xpathCompiler.BaseUri = uri;
267
                    environment.xqueryCompiler.BaseUri = uri;
268
                } catch (Exception e) {
269
                    driver.println("**** invalid base URI " + uri);
270
                } 
271
            }
272
        }
273
    }
274

    
275
    private static void RegisterCollations(XPathCompiler xpc, XdmItem env, Environment environment) {
276
        CompareInfo info = CultureInfo.CurrentCulture.CompareInfo;
277
        CompareOptions options = CompareOptions.IgnoreCase;
278
        foreach (XdmItem basei in xpc.Evaluate("collation", env)) {
279
            string uri = ((XdmNode) basei).GetAttributeValue(new QName("uri"));
280
            String defaultAtt = ((XdmNode) basei).GetAttributeValue(new QName("default"));
281
            bool isDefault = defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1"));
282
            if (uri.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") ||
283
                    uri.Equals("http://www.w3.org/xslts/collation/caseblind")) {
284
                JConfiguration config = xpc.Processor.Implementation;
285
                JStringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", config);
286
                
287
                environment.xpathCompiler.DeclareCollation(new Uri(uri),info , options, isDefault);//(Collator) ((SimpleCollation) collator.).getCollation());
288
                environment.xqueryCompiler.DeclareCollation(new Uri(uri),info , options, isDefault);
289
				if (environment.xsltCompiler != null) {
290
					environment.xsltCompiler.DeclareCollation (new Uri (uri), info, options, isDefault);
291
				}
292
            }
293
        }
294
    }
295

    
296
    private static void DeclareNamespaces(XPathCompiler xpc, XdmItem env, Environment environment)  {
297
        foreach (XdmItem nsElement in xpc.Evaluate("namespace", env)) {
298
            String prefix = ((XdmNode) nsElement).GetAttributeValue(new QName("prefix"));
299
            String uri = ((XdmNode) nsElement).GetAttributeValue(new QName("uri"));
300
            environment.xpathCompiler.DeclareNamespace(prefix, uri);
301
            environment.xqueryCompiler.DeclareNamespace(prefix, uri);
302
            if (uri.Equals("http://expath.org/ns/file")) {
303
                // For EXPath file tests, set the EXPath base directory to the catalog directory
304
                string basei = ((XdmNode) nsElement).BaseUri.ToString();
305
                if (basei.StartsWith("file:///")) {
306
                    basei = basei.Substring(7);
307
                } else if (basei.StartsWith("file:/")) {
308
                    basei = basei.Substring(5);
309
                }
310
                FileStream file = new FileStream(basei, FileMode.Open, FileAccess.Read); //new File(base);
311
                
312
                //System.SetProperty("expath.base.directory", file.ToString());
313
            }
314
        }
315
    }
316

    
317
    private static bool LoadSchemaDocuments(XPathCompiler xpc, XdmItem env, SchemaManager manager){
318
        bool validateSources = false;
319
        XmlUrlResolver res = new XmlUrlResolver();
320
        foreach (XdmItem schema in xpc.Evaluate("schema", env)) {
321
            String role = ((XdmNode) schema).GetAttributeValue(new QName("role"));
322
            String xsdVersion = ((XdmNode) schema).GetAttributeValue(new QName("xsd-version"));
323
            if (xsdVersion != null) {
324
                manager.XsdVersion = xsdVersion;
325
            }
326
            if (!"secondary".Equals(role)) {
327
                String href = ((XdmNode) schema).GetAttributeValue(new QName("file"));
328
                Uri uri = res.ResolveUri(((XdmNode)env).BaseUri, href);
329
                FileStream file = new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read);
330
                try {
331
                    manager.Compile(file, uri);
332
                } catch (Exception err) {
333
                    System.Console.WriteLine("*** Failed to load schema: " + err.Message + ", Trace:"+ err.StackTrace);
334
                }
335

    
336
                if ("source-reference".Equals(role)) {
337
                    validateSources = true;
338
                }
339
            }
340
        }
341
        return validateSources;
342
    }
343

    
344
    private static void DeclareExternalVariables(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) {
345
        foreach (XdmItem param in xpc.Evaluate("param", env)) {
346
            String varName = ((XdmNode) param).GetAttributeValue(new QName("name"));
347
            XdmValue value;
348
            String source = ((XdmNode) param).GetAttributeValue(new QName("source"));
349
            if (source != null) {
350
                XdmNode sourceDoc = null;
351
                try{
352
                sourceDoc = environment.sourceDocs[source];
353
                } catch(Exception) {}
354
                if (sourceDoc == null) {
355
                    driver.println("**** Unknown source document " + source);
356
                }
357
                value = sourceDoc;
358
            } else {
359
                String select = ((XdmNode) param).GetAttributeValue(new QName("select"));
360
                value = xpc.Evaluate(select, null);
361
            }
362
            environment.params1.Add(new QName(varName), value);
363
            environment.xpathCompiler.DeclareVariable(new QName(varName));
364
            String declared = ((XdmNode) param).GetAttributeValue(new QName("declared"));
365
            if (declared != null && "true".Equals(declared) || "1".Equals(declared)) {
366
                // no action
367
            } else {
368
                environment.paramDeclarations.append("declare variable $" + varName + " external; ");
369
            }
370
        }
371
    }
372

    
373
    /*private void RegisterDecimalFormats(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)  {
374
        foreach (XdmItem decimalFormat in xpc.Evaluate("decimal-format", env)) {
375
            DecimalFormatManager dfm = environment.xpathCompiler.getUnderlyingStaticContext().getDecimalFormatManager();
376

    
377
            XdmNode formatElement = (XdmNode) decimalFormat;
378
            String formatName = formatElement.getAttributeValue(new QName("name"));
379
            StructuredQName formatQName = null;
380
            if (formatName != null) {
381
                if (formatName.indexOf(':') < 0) {
382
                    formatQName = new StructuredQName("", "", formatName);
383
                } else {
384
                    try {
385
                        formatQName = StructuredQName.fromLexicalQName(formatName, false, true, Name11Checker.getInstance(),
386
                                new InscopeNamespaceResolver(formatElement.getUnderlyingNode()));
387
                    } catch (XPathException e) {
388
                        driver.println("**** Invalid QName as decimal-format name");
389
                        formatQName = new StructuredQName("", "", "error-name");
390
                    }
391
                }
392
                environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.getEQName() + " ");
393
            } else {
394
                environment.paramDecimalDeclarations.append("declare default decimal-format ");
395
            }
396
            DecimalSymbols symbols = (formatQName == null ? dfm.getDefaultDecimalFormat() : dfm.obtainNamedDecimalFormat(formatQName));
397
            symbols.setHostLanguage(Configuration.XQUERY);
398
            for (XdmItem decimalFormatAtt : xpc.Evaluate("@* except @name", formatElement)) {
399
                XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
400
                String property = formatAttribute.getNodeName().getLocalName();
401
                String value = formatAttribute.getStringValue();
402
                environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" ");
403
                try {
404
                    if (property.Equals("decimal-separator")) {
405
                        symbols.setDecimalSeparator(value);
406
                    } else if (property.Equals("grouping-separator")) {
407
                        symbols.setGroupingSeparator(value);
408
                    } else if (property.Equals("infinity")) {
409
                        symbols.setInfinity(value);
410
                    } else if (property.Equals("NaN")) {
411
                        symbols.setNaN(value);
412
                    } else if (property.Equals("minus-sign")) {
413
                        symbols.setMinusSign((value));
414
                    } else if (property.Equals("percent")) {
415
                        symbols.setPercent((value));
416
                    } else if (property.Equals("per-mille")) {
417
                        symbols.setPerMille((value));
418
                    } else if (property.Equals("zero-digit")) {
419
                        symbols.setZeroDigit((value));
420
                    } else if (property.Equals("digit")) {
421
                        symbols.setDigit((value));
422
                    } else if (property.Equals("pattern-separator")) {
423
                        symbols.setPatternSeparator((value));
424
                    } else {
425
                        driver.println("**** Unknown decimal format attribute " + property);
426
                    }
427
                } catch (XPathException e) {
428
                    driver.println("**** " + e.getMessage());
429
                }
430
            }
431
            environment.paramDecimalDeclarations.append(";");
432
            try {
433
                symbols.checkConsistency(formatQName);
434
            } catch (XPathException err) {
435
                driver.println("**** " + err.getMessage());
436
            }
437

    
438
        }
439
    }*/
440

    
441
    private static void CreateUnparsedTextResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment)  {
442
        Dictionary<Uri, Object> resources = new Dictionary<Uri, Object>();
443
        Dictionary<Uri, String> encodings = new Dictionary<Uri, String>();
444
        XmlUrlResolver res = new XmlUrlResolver();
445
        foreach (XdmItem resource in xpc.Evaluate("resource", env)) {
446
            String uri = ((XdmNode) resource).GetAttributeValue(new QName("uri"));
447
            String href = ((XdmNode) resource).GetAttributeValue(new QName("file"));
448
            String encoding = ((XdmNode) resource).GetAttributeValue(new QName("encoding"));
449
            if (href != null) {
450
                Object obj = null;
451
                if(href.StartsWith("http")) {
452
                    try {
453
                        obj = new Uri(href);
454
                    } catch (Exception e) {
455
                        throw e;
456
                    }
457
                } else{
458
                    obj = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath,FileMode.Open, FileAccess.Read);
459
                }
460
                try {
461
                    resources.Add(new Uri(uri), obj);
462
                    encodings.Add(new Uri(uri), encoding);
463
                    Uri abs = res.ResolveUri(((XdmNode) resource).BaseUri, uri);
464
                    resources.Add(abs, obj);
465
                    encodings.Add(abs, encoding);
466
                } catch (Exception e) {
467
                    driver.println("** Invalid URI in environment: " + e.Message);
468
                }
469
            }
470
        }
471
        if (resources.Count != 0) {
472
           /* environment.unparsedTextResolver =
473
                    new UnparsedTextURIResolver() {
474
                        public Reader resolve(URI absoluteURI, String encoding, Configuration config) {
475
                            if (encoding == null) {
476
                                encoding = encodings.get(absoluteURI);
477
                            }
478
                            if (encoding == null) {
479
                                encoding = "utf-8";
480
                            }
481
                            try {
482
                                // The following is necessary to ensure that encoding errors are not recovered.
483
                                Charset charset = Charset.forName(encoding);
484
                                CharsetDecoder decoder = charset.newDecoder();
485
                                decoder = decoder.onMalformedInput(CodingErrorAction.REPORT);
486
                                decoder = decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
487
                                Object obj = resources.get(absoluteURI);
488
                                if (obj instanceof File) {
489
                                    return new BufferedReader(new InputStreamReader(new FileInputStream((File)obj), decoder));
490
                                } else {
491
                                    URL resource = (URL)resources.get(absoluteURI);
492
                                    if (resource == null) {
493
                                        resource = absoluteURI.toURL();
494
                                        //throw new XPathException("Unparsed text resource " + absoluteURI + " not registered in catalog", "FOUT1170");
495
                                    }
496
                                    InputStream in = resource.openConnection().getInputStream();
497
                                    return new BufferedReader(new InputStreamReader(in, decoder));
498
                                }
499
                                //   return new InputStreamReader(new FileInputStream(resources.get(absoluteURI)), encoding);
500
                            } catch (IOException ioe) {
501
                                throw new XPathException(ioe.getMessage(), "FOUT1170");
502
                            } catch (IllegalCharsetNameException icne) {
503
                                throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
504
                            } catch(UnsupportedCharsetException uce){
505
                                throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
506
                            }
507
                        }
508
                    };*/
509
        }
510
    }
511

    
512
    private static void CreateCollectionUriResolver(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder) {
513
        Dictionary<Uri, List<JItem>> collections = new Dictionary<Uri, List<JItem>>();
514
        XmlUrlResolver res = new XmlUrlResolver();
515
        foreach (XdmItem coll in xpc.Evaluate("collection", env)) {
516
            String collectionURI = ((XdmNode) coll).GetAttributeValue(new QName("uri"));
517
            if (collectionURI == null) {
518
                collectionURI = "";
519
            }
520
            Uri u;
521
            try {
522
                u = new Uri(collectionURI);
523
            } catch (Exception e) {
524
                driver.println("**** Invalid collection URI " + collectionURI);
525
                break;
526
				}
527
            if (!collectionURI.Equals("") && !u.IsAbsoluteUri) {
528
                u = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI);
529
                collectionURI = u.ToString();
530
            }
531
            List<JItem> docs = new List<JItem>();
532
            foreach (XdmItem source in xpc.Evaluate("source", coll)) {
533
                String href = ((XdmNode) source).GetAttributeValue(new QName("file"));
534
                String frag = null;
535
                int hash = href.IndexOf('#');
536
                if (hash > 0) {
537
                    frag = href.Substring(hash + 1);
538
                    href = href.Substring(0, hash);
539
                }
540
                FileStream file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
541
               // String id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
542
					String uriStr = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsoluteUri;
543
				builder.BaseUri = new Uri(uriStr);
544
                XdmNode doc = builder.Build(file);
545
                if (frag != null) {
546
                    XdmNode selected = (XdmNode)environment.xpathCompiler.EvaluateSingle("id('" + frag + "')", doc);
547
                    if (selected == null) {
548
                        driver.println("**** Fragment not found: " + frag);
549
                        break;
550
                    }
551
                    docs.Add(selected.Implementation);
552
                } else {
553
                    docs.Add(new JAnyURIValue(doc.DocumentUri.ToString()));
554
                }
555
					environment.sourceDocs.Add(uriStr, doc);
556
            }
557
            try {
558
                collections.Add(new Uri(collectionURI), docs);
559
            } catch (Exception e) {
560
                driver.println("**** Invalid collection URI " + collectionURI);
561
				}
562

    
563
        }
564
        if (collections.Count != 0) {
565
          /*  environment.processor.Implementation.setCollectionURIResolver(
566
                    new CollectionURIResolver() {
567
                        public SequenceIterator resolve(String href, String base, XPathContext context) throws XPathException {
568
                            try {
569
                                List<? extends Item> docs;
570
                                if (href == null || base == null) {
571
                                    docs = collections.get(new URI(""));
572
                                } else {
573
                                    URI abs = new URI(base).resolve(href);
574
                                    docs = collections.get(abs);
575
                                }
576
                                if (docs == null) {
577
                                    throw new XPathException("Collection URI not known", "FODC0002");
578
                                    //driver.println("** Collection URI " + href + " not known");
579
                                    //return EmptyIterator.getInstance();
580
                                } else {
581
                                    return new ListIterator(docs);
582
                                }
583
                            } catch (URISyntaxException e) {
584
                                driver.println("** Invalid URI: " + e.getMessage());
585
                                return EmptyIterator.getInstance();
586
                            }
587
                        }
588
                    }
589
            );*/
590
        }
591
    }
592

    
593
		// Methods
594
		//
595
		public override object GetEntity (Uri href, string role, Type ofObjectToReturn)
596
		{
597
			XdmNode node = null;
598
			String hrefStr = href.ToString();
599
			//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
600

    
601
			bool foundDoc = sourceDocs.TryGetValue(hrefStr, out node);
602

    
603
			if (!foundDoc) {
604

    
605
				string val;
606
				hrefStr = href.ToString();
607
				//hrefStr = hrefStr.Substring(hrefStr.LastIndexOf ('/')+1);
608

    
609
				bool foundSecDoc = streamedSecondaryDocs.TryGetValue(hrefStr, out val);
610
				if (foundSecDoc) {
611

    
612

    
613
					//string hrefStr = href.ToString ();
614
					//hrefStr = (hrefStr.StartsWith("file://") ? hrefStr.Substring(7) : hrefStr);
615

    
616
					javax.xml.transform.Source sourcei = new javax.xml.transform.stream.StreamSource(href.ToString());
617

    
618
				
619
					 if(!val.Equals("skip")){
620
					
621
						sourcei = net.sf.saxon.lib.AugmentedSource.makeAugmentedSource((javax.xml.transform.Source)sourcei);
622
							((net.sf.saxon.lib.AugmentedSource) sourcei).setSchemaValidationMode(net.sf.saxon.lib.Validation.getCode(val));
623

    
624
					}
625
					sourcei.setSystemId(hrefStr) ;
626
					return sourcei;
627
				} else {
628
					return null;
629
				}
630
			} else {
631
				return node.Implementation;
632
			}
633
		}
634

    
635
		public override Uri ResolveUri (Uri basei, string href)
636
		{
637

    
638
			return base.ResolveUri (basei, href);
639
		}
640

    
641
    private static void LoadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment, DocumentBuilder builder, SchemaManager manager, bool validateSources) {
642
        XmlUrlResolver res = new XmlUrlResolver();
643
        foreach (XdmItem source in xpc.Evaluate("source", env)) {
644
            XdmNode doc = null;
645

    
646
            String uri = ((XdmNode) source).GetAttributeValue(new QName("uri"));
647
            String mime = ((XdmNode) source).GetAttributeValue(new QName("media-type"));
648
            if (mime != null && "application/xml".Equals(mime)) {
649
                continue;
650
            }
651
            String validation = ((XdmNode) source).GetAttributeValue(new QName("", "validation"));
652
            if (validation == null) {
653
                validation = "skip";
654
            }
655
            String streaming = ((XdmNode) source).GetAttributeValue(new QName("", "streaming"));
656
            if (!validateSources && validation.Equals("skip")) {
657
                builder.SchemaValidationMode = SchemaValidationMode.None;
658
            } else {
659
                SchemaValidator validator = manager.NewSchemaValidator();
660
                if("lax".Equals(validation)) {
661
                    validator.IsLax = true;
662
                    builder.SchemaValidationMode = SchemaValidationMode.Lax;
663
                } else
664
                {
665
                    builder.SchemaValidationMode = SchemaValidationMode.Strict;
666
                }
667
                environment.xpathCompiler.SchemaAware = true;
668
                environment.xqueryCompiler.SchemaAware = true;
669
				if (environment.xsltCompiler != null) {
670
					environment.xsltCompiler.SchemaAware = true;
671
				}
672
            }
673

    
674
            String role = ((XdmNode) source).GetAttributeValue(new QName("role"));
675
            String href = ((XdmNode) source).GetAttributeValue(new QName("file"));
676
            if ("true".Equals(streaming)) {
677
                if (".".Equals(role)) {
678
						if (href == null) {
679
							environment.streamedContent = xpc.Evaluate ("string(content)", source).ToString();
680
						} else {
681
							environment.streamedPath = res.ResolveUri (((XdmNode)env).BaseUri, href).AbsolutePath;
682
						}
683
                } else {
684
                    try
685
                    {
686
							Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsolutePath);
687
							Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri);
688
							Console.WriteLine(res.ResolveUri(((XdmNode)env).BaseUri, href).ToString());
689
							environment.streamedSecondaryDocs.Add(res.ResolveUri(((XdmNode)env).BaseUri, href).AbsoluteUri, validation);
690
                    }catch(Exception){}
691
                }
692
            } else {
693
                Stream ss;
694
                /*if (uri != null) {
695
                    uri = res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri;
696
                }*/
697
                if (href != null) {
698

    
699
                    Uri fileLoc = res.ResolveUri(((XdmNode) env).BaseUri, href);
700
                    FileStream file = null;
701
                    if (fileLoc.Scheme.Equals("file")) {
702
                        file = new FileStream(res.ResolveUri(((XdmNode) env).BaseUri, href).AbsolutePath, FileMode.Open, FileAccess.Read);
703
                        if (uri == null) {
704
								uri = fileLoc.AbsoluteUri;
705
                        }
706
                    }
707
                    try {
708
                        ss = (file == null ? new FileStream(fileLoc.ToString(), FileMode.Open, FileAccess.Read)
709
                                           : file);
710
                        
711
							builder.BaseUri = ((XdmNode) env).BaseUri;
712
                    } catch (FileNotFoundException e) {
713
                        driver.println("*** failed to find source document " + href + ", Exception:" + e.Message);
714
                        continue;
715
                    }
716
                } else {
717
                    // content is inline in the catalog
718
                    if (uri == null) {
719
                        uri = ((XdmNode) env).BaseUri.AbsolutePath;
720
                    }
721
                    string content = xpc.Evaluate("string(content)", source).ToString();
722
                    byte[] byteArray = Encoding.ASCII.GetBytes(content);
723
                    ss = new MemoryStream(byteArray);
724
                    builder.BaseUri = ((XdmNode)env).BaseUri;
725
                }
726

    
727

    
728
                try {
729
					builder.BaseUri = new Uri(res.ResolveUri(((XdmNode)env).BaseUri, uri).AbsoluteUri);
730
                    doc = builder.Build(ss);
731
                    environment.sourceDocs.Add(uri, doc);
732
                } catch (Exception e) {
733
                    driver.println("*** failed to build source document " + href + ", Exception:" + e.Message);
734
                }
735

    
736
                XdmItem selectedItem = doc;
737
                String select = ((XdmNode) source).GetAttributeValue(new QName("select"));
738
                if (select != null) {
739
                    XPathSelector selector = environment.xpathCompiler.Compile(select).Load();
740
                    selector.ContextItem = selectedItem;
741
                    selectedItem = selector.EvaluateSingle();
742
                }
743

    
744

    
745
                if (role != null) {
746
                    if (".".Equals(role)) {
747
                        environment.contextItem = selectedItem;
748
                    } else if (role.StartsWith("$")) {
749
                        String varName = role.Substring(1);
750
                        environment.params1.Add(new QName(varName), selectedItem);
751
                        environment.xpathCompiler.DeclareVariable(new QName(varName));
752
                        environment.paramDeclarations.append("declare variable $" + varName + " external; ");
753
                    }
754
                }
755
            }
756
            String definesStylesheet = ((XdmNode) source).GetAttributeValue(new QName("defines-stylesheet"));
757
            if (definesStylesheet != null) {
758
                definesStylesheet = definesStylesheet.Trim();
759
            }
760
            if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet)) {
761
                // try using an embedded stylesheet from the source document
762
                try {
763
                    
764
                    //environment.xsltExecutable = environment.xsltCompiler.Compile(XdmNode.Wrap(JPreparedStylesheet.getAssociatedStylesheet(
765
                    //        environment.processor.Implementation,
766
                    //        ((XdmNode) environment.contextItem), null, null, null)));
767
                    environment.xsltExecutable = environment.xsltCompiler.CompileAssociatedStylesheet(((XdmNode)environment.contextItem));
768
                    
769
                } catch (Exception) {
770
                    driver.println("*** failed to compile stylesheet referenced in source document " + href);
771
                }
772
            }
773
        }
774
    }
775

    
776
    //public static Environment processEnvironmentOLD_REMOVE(
777
    //       TestRunner.TestDriver driver,
778
    //        XPathCompiler xpc, XdmItem env, Dictionary<string, Environment> environments, Environment defaultEnvironment) {
779
    //    Environment environment = new Environment();
780
    //    XmlUrlResolver res = new XmlUrlResolver();
781
    //    string name = ((XdmNode) env).GetAttributeValue(new QName("name"));
782
    //    if (name != null) {
783
    //        System.Console.WriteLine("Loading environment " + name);
784
    //    }
785
    //    environment.processor = new Processor(true);
786
    //    if (defaultEnvironment != null) {
787
    //        environment.processor.SetProperty(JFeatureKeys.XSD_VERSION,
788
    //                defaultEnvironment.processor.Implementation.getConfigurationProperty(JFeatureKeys.XSD_VERSION).ToString());
789
    //    }
790
    //   // AutoActivate.activate(environment.processor);
791
    //    if (driver.GenerateByteCode == 1) {
792
    //        environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
793
    //        environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
794
    //    } else if (driver.GenerateByteCode == 2) {
795
    //        environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "true");
796
    //        environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "true");
797
    //        //environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE_DIR, "debugByteCode");
798
    //    } else {
799
    //        environment.processor.SetProperty(JFeatureKeys.GENERATE_BYTE_CODE, "false");
800
    //        environment.processor.SetProperty(JFeatureKeys.DEBUG_BYTE_CODE, "false");
801
    //    }
802
    //    environment.xpathCompiler = environment.processor.NewXPathCompiler();
803
    //    environment.xpathCompiler.BaseUri = ((XdmNode) env).BaseUri.ToString();
804
    //    environment.xqueryCompiler = environment.processor.NewXQueryCompiler();
805
    //    environment.xqueryCompiler.BaseUri = ((XdmNode) env).BaseUri.ToString();
806
    //    environment.xsltCompiler = environment.processor.NewXsltCompiler();
807
    //    if (driver.Unfolded) {
808
    //       // environment.xqueryCompiler.Implementation.setCodeInjector(new LazyLiteralInjector()); //TODO
809
    //    }
810
    //    DocumentBuilder builder = environment.processor.NewDocumentBuilder();
811
    //    builder.TreeModel = driver.TreeModel;
812
    //    environment.sourceDocs = new Dictionary<string, XdmNode>();
813
    //    if (environments != null && name != null) {
814
    //        try
815
    //        {
816
    //            environments.Add(name, environment);
817
    //        } catch(Exception){}
818
    //    }
819
    //    bool dependencySatisfied;
820
    //    foreach (XdmItem dependency in xpc.Evaluate("dependency", env)) {
821
    //        if (!driver.dependencyIsSatisfied((XdmNode) dependency, environment)) {
822
    //            environment.usable = false;
823
    //        }
824
    //    }
825

    
826
    //    // set the base URI if specified
827
    //    foreach (XdmItem basei in xpc.Evaluate("static-base-uri", env)) {
828
    //        string uri = ((XdmNode) basei).GetAttributeValue(new QName("uri"));
829
    //        if (uri == null || "#UNDEFINED".Equals(uri)) {
830
    //            environment.xpathCompiler.BaseUri = null;
831
    //            environment.xqueryCompiler.BaseUri = null;
832
    //            driver.println("**** Error: The BaseURI null and #UNDEFINED is not supported");
833
    //        } else {
834
    //            //try {
835
    //            environment.xpathCompiler.BaseUri = uri;
836
    //            environment.xqueryCompiler.BaseUri = uri; ;
837
    //            /*} catch (UriSyntaxException e) {
838
    //                driver.println("**** invalid base URI " + uri);
839
    //            } catch (IllegalArgumentException e) {
840
    //                driver.println("**** invalid base URI " + uri);
841
    //            }*/
842
    //        }
843
    //    }
844

    
845
    //    // set any requested collations
846
        
847
    //    CompareInfo compareInfo = CultureInfo.CurrentCulture.CompareInfo; //TODO check this is right to use with default Collation
848
    //    CompareOptions options = CompareOptions.IgnoreCase; //TODO check this is right to use with default Collation
849

    
850
    //    foreach (XdmItem basei in xpc.Evaluate("collation", env)) {
851
    //        string uri = ((XdmNode) basei).GetAttributeValue(new QName("uri"));
852
    //        if (uri.Equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind")) {
853
    //            JConfiguration config = xpc.Processor.Implementation;
854
    //            JStringCollator collator = config.getCollationURIResolver().resolve("http://saxon.sf.net/collation?ignore-case=yes", "", config);
855
                
856
                
857
    //            Boolean defaultCol = false;
858
    //            environment.xpathCompiler.DeclareCollation(new Uri(uri), compareInfo, options, defaultCol);
859
    //                environment.xqueryCompiler.DeclareCollation(new Uri(uri), compareInfo, options, defaultCol);
860
    //        }
861
    //        string defaultAtt = ((XdmNode) basei).GetAttributeValue(new QName("default"));
862
    //        if (defaultAtt != null && (defaultAtt.Trim().Equals("true") || defaultAtt.Trim().Equals("1"))) {
863
    //            environment.xpathCompiler.DeclareCollation(new Uri(uri), compareInfo, options, true);
864
    //            environment.xqueryCompiler.DeclareCollation(new Uri(uri), compareInfo, options, true);
865
    //        }
866
    //    }
867

    
868
    //    // declare the requested namespaces
869
    //    foreach (XdmItem nsElement in xpc.Evaluate("namespace", env)) {
870
    //        string prefix = ((XdmNode) nsElement).GetAttributeValue(new QName("prefix"));
871
    //        string uri = ((XdmNode) nsElement).GetAttributeValue(new QName("uri"));
872
    //        environment.xpathCompiler.DeclareNamespace(prefix, uri);
873
    //        environment.xqueryCompiler.DeclareNamespace(prefix, uri);
874
    //        /*if (uri.Equals(EXPathFile.NAMESPACE)) {
875
    //            // For EXPath file tests, set the EXPath base directory to the catalog directory
876
    //            string base = ((XdmNode) nsElement).BaseUri.tostring();
877
    //            if (base.startsWith("file:///")) {
878
    //                base = base.substring(7);
879
    //            } else if (base.startsWith("file:/")) {
880
    //                base = base.substring(5);
881
    //            }
882
    //            File file = new File(base);
883
    //            file = file.getParentFile();
884
    //            System.setProperty("expath.base.directory", file.getAbsolutePath());
885
    //        }*/
886
    //    }
887

    
888
    //    // load the requested schema documents
889
    //    SchemaManager manager = environment.processor.SchemaManager;
890
    //    bool validateSources = false;
891
    //    foreach (XdmItem schema in xpc.Evaluate("schema", env)) {
892
    //        string role = ((XdmNode) schema).GetAttributeValue(new QName("role"));
893
    //        string xsdVersion = ((XdmNode) schema).GetAttributeValue(new QName("xsd-version"));
894
    //        if (xsdVersion != null) {
895
    //            manager.XsdVersion = xsdVersion;
896
    //        }
897
    //        if (!"secondary".Equals(role)) {
898
    //            string href = ((XdmNode)schema).GetAttributeValue(new QName("file"));           
899
    //            try {
900
    //                manager.Compile((new Uri(((XdmNode)env).BaseUri, href)));
901
    //            } catch (Exception err) {
902
    //                System.Console.WriteLine("*** Failed to load schema: " + err.Message);
903
    //            }
904

    
905
    //            if ("source-reference".Equals(role)) {
906
    //                validateSources = true;
907
    //            }
908
    //        }
909
    //    }
910

    
911
    //    // load the requested source documents
912
    //    foreach (XdmItem source in xpc.Evaluate("source", env)) {
913
    //        XdmNode doc = null;
914
    //        string file = ((XdmNode)source).GetAttributeValue(new QName("file"));
915
    //        Uri href = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file")));
916
    //        string uri = ((XdmNode) source).GetAttributeValue(new QName("uri"));
917
    //        string mime = ((XdmNode) source).GetAttributeValue(new QName("media-type"));
918
    //        if (mime != null && "application/xml".Equals(mime)) {
919
    //            continue;
920
    //        }
921
    //        string validation = ((XdmNode) source).GetAttributeValue(new QName("", "validation"));
922
    //        if (validation == null) {
923
    //            validation = "skip";
924
    //        }
925
    //        string streaming = ((XdmNode) source).GetAttributeValue(new QName("", "streaming"));
926
    //        if (!validateSources && validation.Equals("skip")) {
927
    //            builder.SchemaValidationMode = SchemaValidationMode.None;
928
    //           // builder..setSchemaValidator(null);
929
                 
930
    //            try
931
    //                {
932
    //                    doc = builder.Build(href);
933
                       
934
    //                }
935
    //                catch (Exception e)
936
    //                {
937
    //                    System.Console.WriteLine("Error:" + e.Message+" *** failed to build source document " + href, false);
938
    //                }
939
    //        } else {
940
    //            SchemaValidator validator = manager.NewSchemaValidator();        
941
    //            XdmDestination xdmDest = new XdmDestination();
942
    //            validator.IsLax = validation.Equals("lax");
943
    //            validator.SetDestination(xdmDest);
944
    //            validator.SetSource(href);
945
    //            try
946
    //            {
947
    //                validator.Run();
948
    //            } catch(Exception ){}
949
    //            doc = xdmDest.XdmNode;
950
    //            environment.xpathCompiler.SchemaAware = true;
951
    //            environment.xqueryCompiler.SchemaAware = true;
952
    //            environment.xsltCompiler.SchemaAware = true;
953
    //        }
954

    
955
            
956
    //            if (uri != null)
957
    //            {
958
    //                environment.sourceDocs.Add(uri, doc);
959
    //            }
960
    //            string role = ((XdmNode)source).GetAttributeValue(new QName("role"));
961
    //            Uri hrefFile = res.ResolveUri(((XdmNode)env).BaseUri, ((XdmNode)source).GetAttributeValue(new QName("file")));
962
    //        if ("true".Equals(streaming)) {
963
    //            if (".".Equals(role)) {
964
    //                environment.streamedSource = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
965
    //            } else {
966
                    
967
    //                environment.streamedSecondaryDocs.Add(hrefFile.ToString(),
968
    //                        new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read));
969
    //            }
970
    //        } else {
971
    //            Stream ss = null;
972
    //            if (href != null) {
973
    //                Stream file = null;
974
    //                if (hrefFile.Scheme.Equals("file")) {
975
    //                    file = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
976
    //                    try
977
    //                    {
978
    //                        doc = builder.Build(file);
979
    //                        environment.sourceDocs.Add(uri, doc);
980
    //                    }
981
    //                    catch (Exception e)
982
    //                    {
983
    //                        driver.println("*** failed to build source document " + href);
984
    //                    }
985
    //                }
986
    //                try {
987
    //                    file = new FileStream(hrefFile.AbsolutePath, FileMode.Open, FileAccess.Read);
988
    //                    try
989
    //                    {
990
    //                        doc = builder.Build(hrefFile);
991
    //                        environment.sourceDocs.Add(uri, doc);
992
    //                    }
993
    //                    catch (Exception e)
994
    //                    {
995
    //                        driver.println("*** failed to build source document " + href);
996
    //                    }
997
    //                    /*ss = (file == null ? (Stream) new XmlTextReader(hrefFile.ToString());
998
    //                                       : file);*/
999
    //                } catch (FileNotFoundException e) {
1000
    //                    driver.println("*** failed to find source document " + href);
1001
    //                    continue;
1002
    //                }
1003
    //            } else {
1004
    //                // content is inline in the catalog
1005
    //                if (uri == null) {
1006
    //                    uri = ((XdmNode) env).BaseUri.ToString();
1007
    //                }
1008
    //                String content = xpc.Evaluate("string(content)", source).ToString();
1009
    //                TextReader textReader = new StringReader(content);
1010

    
1011
    //                try
1012
    //                {
1013
    //                    doc = builder.Build(textReader);
1014
    //                    environment.sourceDocs.Add(uri, doc);
1015
    //                }
1016
    //                catch (Exception e)
1017
    //                {
1018
    //                    driver.println("*** failed to build source document " + href);
1019
    //                }
1020
    //            }
1021

    
1022

    
1023
                
1024

    
1025
    //            XdmItem selectedItem = doc;
1026
    //            String select = ((XdmNode) source).GetAttributeValue(new QName("select"));
1027
    //            if (select != null) {
1028
    //                XPathSelector selector = environment.xpathCompiler.Compile(select).Load();
1029
    //                selector.ContextItem = selectedItem;
1030
    //                selectedItem = selector.EvaluateSingle();
1031
    //            }
1032

    
1033

    
1034
    //            try
1035
    //            {
1036
    //                if (role.StartsWith("$"))
1037
    //                {
1038
    //                    string varName = role.Substring(1);
1039
    //                    environment.params1.Add(new QName(varName), doc);
1040
    //                    environment.xpathCompiler.DeclareVariable(new QName(varName));
1041
    //                    environment.paramDeclarations.append("declare variable $" + varName + " external; ");
1042
    //                }
1043
    //            } catch(Exception){}
1044
                
1045

    
1046
           
1047
                
1048
    //        }
1049
    //        /*string definesStylesheet = ((XdmNode) source).GetAttributeValue(new QName("defines-stylesheet"));
1050
    //        if (definesStylesheet != null) {
1051
    //            definesStylesheet = definesStylesheet.Trim();
1052
    //        }
1053
    //        if ("true".Equals(definesStylesheet) || "1".Equals(definesStylesheet)) {
1054
    //            // try using an embedded stylesheet from the source document
1055
    //            try {
1056
    //                Source styleSource = PreparedStylesheet.getAssociatedStylesheet(
1057
    //                        environment.processor.getUnderlyingConfiguration(),
1058
    //                        ((XdmNode) environment.contextItem).asSource(), null, null, null);
1059
    //                environment.xsltExecutable = environment.xsltCompiler.compile(styleSource);
1060
    //            } catch (TransformerConfigurationException e) {
1061
    //                driver.println("*** failed to compile stylesheet referenced in source document " + href);
1062
    //            }
1063
    //        } */
1064
        
1065

    
1066
    //    // create a collection URI resolver to handle the requested collections
1067
    //    Hashtable collections = new Hashtable();
1068
    //    //Dictionary<Uri, List<JAnyURIValue>> collections = new Dictionary<Uri, List<JAnyURIValue>>();
1069
    //    foreach (XdmItem coll in xpc.Evaluate("collection", env)) {
1070
    //        string collectionURI = ((XdmNode) coll).GetAttributeValue(new QName("uri"));
1071
    //        if (collectionURI == null) {
1072
    //            collectionURI = "";
1073
    //        }
1074
    //        Uri u;
1075
    //        try
1076
    //        {
1077
    //            u = new Uri(collectionURI);
1078
    //        }catch(Exception) {
1079
    //            driver.println("**** Invalid collection URI " + collectionURI);
1080
    //            break;
1081
    //        }
1082
           
1083
    //        if (!collectionURI.Equals("") && !u.IsAbsoluteUri) {
1084
    //            u = res.ResolveUri(((XdmNode)env).BaseUri, collectionURI);
1085
    //            collectionURI = u.ToString();
1086
    //        }
1087
    //        List<JAnyURIValue> docs = new List<JAnyURIValue>();
1088
    //        foreach (XdmItem source1 in xpc.Evaluate("source", coll)) {
1089
    //            string href1 = ((XdmNode) source1).GetAttributeValue(new QName("file"));
1090
    //            if (href1.Contains("#")) {
1091
    //                // TODO: support fragment identifiers
1092
    //                driver.println("*** Fragment identifiers not supported");
1093
    //                continue;
1094
    //            }
1095
    //            Uri uri1 = res.ResolveUri(((XdmNode)env).BaseUri, href1);
1096
    //            //string id = ((XdmNode) source).GetAttributeValue(new QName(JNamespaceConstant.XML, "id"));
1097
    //            XdmNode doc1 = builder.Build(uri1);
1098
    //            //environment.sourceDocs.Add(id, doc);
1099
    //            docs.Add(new JAnyURIValue(doc.DocumentUri.ToString()));
1100
    //        }
1101
    //        try {
1102
    //            collections.Add(new Uri(collectionURI), docs);
1103
    //        } catch (Exception e) {
1104
    //            driver.println("**** Invalid collection URI " + collectionURI);
1105
    //        }
1106

    
1107
    //    }
1108
    //    if (collections.Count != 0) {
1109
    //           environment.processor.Implementation.setCollectionURIResolver(new CollectionResolver(collections));
1110
    //        /*environment.processor.Implementation.setCollectionURIResolver(
1111
    //                new CollectionUriResolver() {
1112
    //                    public SequenceIterator resolve(string href, string base, XPathContext context) throws XPathException {
1113
    //                        try {
1114
    //                            List<AnyURIValue> docs;
1115
    //                            if (href == null || base == null) {
1116
    //                                docs = collections.get(new URI(""));
1117
    //                            } else {
1118
    //                                URI abs = new URI(base).resolve(href);
1119
    //                                docs = collections.get(abs);
1120
    //                            }
1121
    //                            if (docs == null) {
1122
    //                                throw new XPathException("Collection URI not known", "FODC0002");
1123
    //                                //driver.println("** Collection URI " + href + " not known");
1124
    //                                //return EmptyIterator.getInstance();
1125
    //                            } else {
1126
    //                                return new ListIterator(docs);
1127
    //                            }
1128
    //                        } catch (URISyntaxException e) {
1129
    //                            driver.println("** Invalid URI: " + e.getMessage());
1130
    //                            return EmptyIterator.getInstance();
1131
    //                        }
1132
    //                    }
1133
    //                }
1134
    //        );*/
1135
    //    }
1136

    
1137
    //    // create an unparsed text resolver to handle any unparsed text resources
1138

    
1139
    //    Dictionary<Uri, Object> resources = new Dictionary<Uri, Object>();
1140
    //    Dictionary<Uri, string> encodings = new Dictionary<Uri, string>();
1141
    //    foreach (XdmItem resource in xpc.Evaluate("resource", env)) {
1142
    //        string uri1 = ((XdmNode) resource).GetAttributeValue(new QName("uri"));
1143
    //        string href1 = ((XdmNode) resource).GetAttributeValue(new QName("file"));
1144
    //        string encoding = ((XdmNode) resource).GetAttributeValue(new QName("encoding"));
1145
    //        if (href1 != null) {
1146
    //            Object obj = null;
1147
    //            if(href1.StartsWith("http")) {
1148
    //                try {
1149
    //                    obj = new Uri(href1);
1150
    //                } catch (Exception e) {
1151
    //                    System.Console.WriteLine(e.StackTrace);  //To change body of catch statement use File | Settings | File Templates.
1152
    //                }
1153
    //            } else{
1154
    //                obj = res.ResolveUri(((XdmNode) env).BaseUri, href1);
1155
    //            }
1156
    //            try {
1157
    //                resources.Add(new Uri(uri1), obj);
1158
    //                encodings.Add(new Uri(uri1), encoding);
1159
    //            } catch (Exception e) {
1160
    //                driver.println("** Invalid URI in environment: " + e.Message);
1161
    //            }
1162
    //        }
1163
    //    }
1164
    //    if (resources.Count != 0) {
1165
    //      //  environment.unparsedTextResolver = 
1166
    //               /* new UnparsedTextURIResolver() {
1167
    //                    public Reader resolve(URI absoluteURI, string encoding, Configuration config) throws XPathException {
1168
    //                        if (encoding == null) {
1169
    //                            encoding = encodings.get(absoluteURI);
1170
    //                        }
1171
    //                        if (encoding == null) {
1172
    //                            encoding = "utf-8";
1173
    //                        }
1174
    //                        try {
1175
    //                            // The following is necessary to ensure that encoding errors are not recovered.
1176
    //                            Charset charset = Charset.forName(encoding);
1177
    //                            CharsetDecoder decoder = charset.newDecoder();
1178
    //                            decoder = decoder.onMalformedInput(CodingErrorAction.REPORT);
1179
    //                            decoder = decoder.onUnDictionarypableCharacter(CodingErrorAction.REPORT);
1180
    //                            Object obj = resources.get(absoluteURI);
1181
    //                            if (obj instanceof File) {
1182
    //                                return new BufferedReader(new InputStreamReader(new FileInputStream((File)obj), decoder));
1183
    //                            } else {
1184
    //                                URL resource = (URL)resources.get(absoluteURI);
1185
    //                                if (resource == null) {
1186
    //                                    throw new XPathException("Unparsed text resource " + absoluteURI + " not registered in catalog", "FOUT1170");
1187
    //                                }
1188
    //                                InputStream in = resource.openConnection().getInputStream();
1189
    //                                return new BufferedReader(new InputStreamReader(in, decoder));
1190
    //                            }
1191
    //                            //   return new InputStreamReader(new FileInputStream(resources.get(absoluteURI)), encoding);
1192
    //                        } catch (IOException ioe) {
1193
    //                            throw new XPathException(ioe.getMessage(), "FOUT1170");
1194
    //                        } catch (IllegalCharsetNameException icne) {
1195
    //                            throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
1196
    //                        } catch(UnsupportedCharsetException uce){
1197
    //                            throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
1198
    //                        }
1199
    //                    }
1200
    //                }; */
1201
    //    }
1202

    
1203
    //    // register any required decimal formats
1204
    //   /* foreach (XdmItem decimalFormat in xpc.Evaluate("decimal-format", env)) {
1205
    //        JDecimalFormatManager dfm = environment.xpathCompiler.getUnderlyingStaticContext().getDecimalFormatManager();
1206

    
1207
    //        XdmNode formatElement = (XdmNode) decimalFormat;
1208
    //        string formatName = formatElement.GetAttributeValue(new QName("name"));
1209
    //        StructuredQName formatQName = null;
1210
    //        if (formatName != null) {
1211
    //            if (formatName.indexOf(':') < 0) {
1212
    //                formatQName = new StructuredQName("", "", formatName);
1213
    //            } else {
1214
    //                try {
1215
    //                    formatQName = StructuredQName.fromLexicalQName(formatName, false, true, Name11Checker.getInstance(),
1216
    //                            new InscopeNamespaceResolver(formatElement.getUnderlyingNode()));
1217
    //                } catch (XPathException e) {
1218
    //                    driver.println("**** Invalid QName as decimal-format name");
1219
    //                    formatQName = new StructuredQName("", "", "error-name");
1220
    //                }
1221
    //            }
1222
    //            environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.getEQName() + " ");
1223
    //        } else {
1224
    //            environment.paramDecimalDeclarations.append("declare default decimal-format ");
1225
    //        }
1226
    //        DecimalSymbols symbols = (formatQName == null ? dfm.getDefaultDecimalFormat() : dfm.obtainNamedDecimalFormat(formatQName));
1227
    //        symbols.setHostLanguage(Configuration.XQUERY);
1228
    //        for (XdmItem decimalFormatAtt : xpc.Evaluate("@* except @name", formatElement)) {
1229
    //            XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
1230
    //            string property = formatAttribute.getNodeName().getLocalName();
1231
    //            string value = formatAttribute.getstringValue();
1232
    //            environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" ");
1233
    //            try {
1234
    //                if (property.Equals("decimal-separator")) {
1235
    //                    symbols.setDecimalSeparator(value);
1236
    //                } else if (property.Equals("grouping-separator")) {
1237
    //                    symbols.setGroupingSeparator(value);
1238
    //                } else if (property.Equals("infinity")) {
1239
    //                    symbols.setInfinity(value);
1240
    //                } else if (property.Equals("NaN")) {
1241
    //                    symbols.setNaN(value);
1242
    //                } else if (property.Equals("minus-sign")) {
1243
    //                    symbols.setMinusSign((value));
1244
    //                } else if (property.Equals("percent")) {
1245
    //                    symbols.setPercent((value));
1246
    //                } else if (property.Equals("per-mille")) {
1247
    //                    symbols.setPerMille((value));
1248
    //                } else if (property.Equals("zero-digit")) {
1249
    //                    symbols.setZeroDigit((value));
1250
    //                } else if (property.Equals("digit")) {
1251
    //                    symbols.setDigit((value));
1252
    //                } else if (property.Equals("pattern-separator")) {
1253
    //                    symbols.setPatternSeparator((value));
1254
    //                } else {
1255
    //                    driver.println("**** Unknown decimal format attribute " + property);
1256
    //                }
1257
    //            } catch (XPathException e) {
1258
    //                driver.println("**** " + e.getMessage());
1259
    //            }
1260
    //        }
1261
    //        environment.paramDecimalDeclarations.append(";");
1262
    //        try {
1263
    //            symbols.checkConsistency(formatQName);
1264
    //        } catch (XPathException err) {
1265
    //            driver.println("**** " + err.getMessage());
1266
    //        }
1267

    
1268
    //    }*/
1269

    
1270
    //    // declare any variables
1271
    //    foreach (XdmItem param in xpc.Evaluate("param", env)) {
1272
    //        string varName = ((XdmNode) param).GetAttributeValue(new QName("name"));
1273
    //        XdmValue value;
1274
    //        string source1 = ((XdmNode) param).GetAttributeValue(new QName("source"));
1275
    //        if (source1 != null) {
1276
    //            XdmNode sourceDoc = environment.sourceDocs[source1];
1277
    //            if (sourceDoc == null) {
1278
    //                driver.println("**** Unknown source document " + source);
1279
    //            }
1280
    //            value = sourceDoc;
1281
    //        } else {
1282
    //            string select = ((XdmNode) param).GetAttributeValue(new QName("select"));
1283
    //            value = xpc.Evaluate(select, null);
1284
    //        }
1285
    //        environment.params1.Add(new QName(varName), value);
1286
    //        environment.xpathCompiler.DeclareVariable(new QName(varName));
1287
    //        string declared = ((XdmNode) param).GetAttributeValue(new QName("declared"));
1288
    //        if (declared != null && "true".Equals(declared) || "1".Equals(declared)) {
1289
    //            // no action
1290
    //        } else {
1291
    //            environment.paramDeclarations.append("declare variable $" + varName + " external; ");
1292
    //        }
1293
    //    }
1294

    
1295
    //    // handle requested context item
1296
    //    foreach (XdmItem param in xpc.Evaluate("context-item", env)) {
1297
    //        string select = ((XdmNode) param).GetAttributeValue(new QName("select"));
1298
    //        XdmValue value = xpc.Evaluate(select, null);
1299
    //        environment.contextItem = (XdmItem)value.Simplify;
1300
    //    }
1301

    
1302
    //    // compile any stylesheet defined as part of the environment (only one allowed)
1303
    //    foreach (XdmItem stylesheet in xpc.Evaluate("stylesheet[not(@role='secondary')]", env)) {
1304
    //        string fileName = ((XdmNode)stylesheet).GetAttributeValue(new QName("file"));
1305
            
1306
    //        try {
1307
    //            XdmNode styleSource = builder.Build(res.ResolveUri(((XdmNode)env).BaseUri, fileName));
1308
    //            environment.xsltExecutable = environment.xsltCompiler.Compile(styleSource);
1309
    //        } catch (Exception e) {
1310
    //            driver.println("**** failure while compiling environment-defined stylesheet " + fileName);
1311
    //        }
1312
    //    }
1313

    
1314
    //    return environment;
1315
    //}
1316
    //    return null;
1317
    //}
1318
        
1319
    
1320

    
1321
     public class CollectionResolver: net.sf.saxon.lib.CollectionURIResolver {
1322
            Hashtable collections;
1323
            public CollectionResolver(Hashtable collections)
1324
            { 
1325
                this.collections = collections;
1326
            }
1327
                            public net.sf.saxon.om.SequenceIterator resolve(string href, string baseStr, net.sf.saxon.expr.XPathContext context)  {
1328
                                try {
1329
                                    List<Uri> docs;
1330
                                    if (href == null) {
1331
                                        docs = (List<Uri>)collections[new Uri("http://www.saxonica.com/defaultCollection")];
1332
                                    } else {
1333
                                        XmlUrlResolver res = new XmlUrlResolver();
1334
                                        Uri abs= res.ResolveUri(new Uri(baseStr), href);
1335
                                        try
1336
                                        {
1337
                                            docs = (List<Uri>)collections[abs];
1338
                                        }
1339
                                        catch (Exception) {
1340
                                            docs = null;
1341
                                        }
1342
                                    }
1343
                                    if (docs == null) {
1344
                                        return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1345
                                    } else {
1346
                                        java.util.List list = new java.util.ArrayList();
1347
                                        foreach(Uri uri in docs){
1348
                                            list.add(new net.sf.saxon.value.AnyURIValue(uri.ToString()));
1349
                                        }
1350
                                        
1351
                                        return new net.sf.saxon.tree.iter.ListIterator(list);
1352
                                    }
1353
                                } catch (java.net.URISyntaxException e) {
1354
                                    Console.WriteLine("** Invalid Uri: " + e.Message);
1355
                                    return net.sf.saxon.tree.iter.EmptyIterator.getInstance();
1356
                                }
1357
                            }
1358
                        }
1359

    
1360
    /**
1361
     * The environment acts as a URIResolver
1362
     */
1363

    
1364
    /*public Source resolve(string href, string base) throws TransformerException {
1365
        XdmNode node = sourceDocs.get(href);
1366
        if (node == null) {
1367
            string uri;
1368
            try {
1369
                uri = new URI(base).resolve(href).tostring();
1370
            } catch (URISyntaxException e) {
1371
                uri = href;
1372
            } catch (IllegalArgumentException e) {
1373
                uri = href;
1374
            }
1375
            string val = streamedSecondaryDocs.get(uri);
1376
            if (val != null) {
1377
                Source source = new StreamSource(uri);
1378
                if (!val.Equals("skip")) {
1379
                    source = AugmentedSource.makeAugmentedSource(source);
1380
                    ((AugmentedSource)source).setSchemaValidationMode(Validation.getCode(val));
1381
                }
1382
                return source;
1383
            } else {
1384
                return null;
1385
            }
1386
        } else {
1387
            return node.asSource();
1388
        }
1389
    }*/
1390

    
1391

    
1392
   /* private class LazyLiteralInjector: JCodeInjector {
1393
        public JExpression inject(JExpression exp, StaticContext env, int construct, JStructuredQName qName) {
1394
            if (exp is net.sf.saxon.expr.Literal) {
1395
                JStructuredQName name = new JStructuredQName("saxon", JNamespaceConstant.SAXON, "lazy-literal");
1396
                com.saxonica.expr.JavaExtensionFunctionCall wrapper = new com.saxonica.expr.JavaExtensionFunctionCall();
1397
                try {
1398
                    wrapper.init(name, FOTestSuiteDriver.class,
1399
                            FOTestSuiteDriver.class.getMethod("lazyLiteral", Sequence.class),
1400
                            env.getConfiguration());
1401
                    wrapper.setArguments(new Expression[]{exp});
1402
                } catch (NoSuchMethodException e) {
1403
                    throw new IllegalStateException(e);
1404
                }
1405
                return wrapper;
1406
            } else {
1407
                return exp;
1408
            }
1409
        }
1410

    
1411
        public Clause injectClause(Clause target, StaticContext env, Container container) {
1412
            return null;
1413
        }
1414
    } */
1415

    
1416
    public abstract class ResetAction {
1417
        public abstract void reset(Environment env);
1418
    }
1419

    
1420

    
1421
}
1422
}
1423

    
(1-1/24)