Debian Codegraph @

net/sf/saxon/testdriver/Environment.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.testdriver;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.dom.DocumentWrapper;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.sort.SimpleCollation;
14 import net.sf.saxon.lib.*;
15 import net.sf.saxon.om.*;
16 import net.sf.saxon.query.QueryResult;
17 import net.sf.saxon.resource.AbstractResourceCollection;
18 import net.sf.saxon.resource.XmlResource;
19 import net.sf.saxon.s9api.*;
20 import net.sf.saxon.trans.DecimalFormatManager;
21 import net.sf.saxon.trans.DecimalSymbols;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.tree.util.FastStringBuffer;
24 import org.w3c.dom.Document;
25 import org.xml.sax.InputSource;
26 import org.xml.sax.SAXException;
27
28 import javax.xml.parsers.DocumentBuilderFactory;
29 import javax.xml.parsers.ParserConfigurationException;
30 import javax.xml.transform.Source;
31 import javax.xml.transform.TransformerException;
32 import javax.xml.transform.URIResolver;
33 import javax.xml.transform.stream.StreamSource;
34 import java.io.*;
35 import java.net.*;
36 import java.nio.charset.*;
37 import java.util.*;
38
39 import static net.sf.saxon.s9api.streams.Steps.child;
40 import static net.sf.saxon.testdriver.Xslt30TestSuiteDriverHE.isTrue;
41
42 /**
43 * This class represents a collection of resources (source documents, schemas, collections etc) used for a number
44 * of test cases.
45 */
46
47 public class Environment implements URIResolver {
48
49 public static class CatalogResource {
50 public File file;
51 public URL url;
52 public String mediaType;
53 public String encoding;
54 public String uri;
55 public XdmNode doc;
56 }
57
58 public Processor processor;
59 public Map<String, XdmNode> sourceDocs = new HashMap<>();
60 public Map<String, String> streamedSecondaryDocs = new HashMap<>();
61 public String streamedContent;
62 public File streamedFile;
63 public String streamedInputValidation = "skip";
64 public XPathCompiler xpathCompiler;
65 public XQueryCompiler xqueryCompiler;
66 public XsltCompiler xsltCompiler;
67 public XsltExecutable xsltExecutable;
68 public File exportedStylesheet;
69 public XdmItem contextItem;
70 public HashMap<QName, XdmValue> params = new HashMap<>();
71 public boolean usable = true;
72 public boolean failedToBuild = false;
73 public FastStringBuffer paramDeclarations = new FastStringBuffer(256);
74 public FastStringBuffer paramDecimalDeclarations = new FastStringBuffer(256);
75 public UnparsedTextURIResolver unparsedTextResolver;
76 public List<ResetAction> resetActions = new ArrayList<>();
77 public boolean schemaAvailable = false;
78 public boolean outputTree = true;
79 public boolean outputSerialize = false;
80 public Map<String, CatalogResource> catalogResources = new HashMap<>();
81 public Map<String, List<String>> jsCollections;
82
83
84 /**
85 * Construct a local default environment for a test set
86 */
87
88 public static Environment createLocalEnvironment(URI baseURI, int generateByteCode, boolean unfolded, Spec spec, TestDriver testDriver) {
89 final Environment environment = new Environment();
90 environment.processor = new Processor(!testDriver.driverProc.getSaxonEdition().equals("HE"));
91 //testDriver.getLicensor().activate(environment.processor);
92 //AutoActivate.activate(environment.processor);
93 environment.processor.setConfigurationProperty(Feature.OPTIMIZATION_LEVEL, testDriver.optimizerFlags);
94 configureByteCode(testDriver, environment, generateByteCode);
95
96 environment.xpathCompiler = environment.processor.newXPathCompiler();
97 environment.xpathCompiler.setBaseURI(baseURI);
98 environment.xqueryCompiler = environment.processor.newXQueryCompiler();
99 environment.xqueryCompiler.setBaseURI(baseURI);
100 environment.xsltCompiler = environment.processor.newXsltCompiler();
101 if (testDriver.runWithJS) {
102 environment.xsltCompiler.setTargetEdition("JS");
103 }
104 if (environment.processor.getSaxonEdition().equals("EE")) {
105 environment.xsltCompiler.setJustInTimeCompilation(testDriver.jitFlag);
106 }
107 environment.xsltCompiler.setRelocatable(testDriver.relocatable);
108 if (spec == Spec.XT30) {
109 //environment.xsltCompiler.setXsltLanguageVersion("3.0");
110 environment.xpathCompiler.setLanguageVersion("3.1");
111 } else if (spec == Spec.XT20) {
112 throw new AssertionError("Unsupported spec: XSLT 2.0");
113 }
114 if (unfolded) {
115 testDriver.addInjection(environment.xqueryCompiler);
116 }
117 if (testDriver.tracing) {
118 environment.xsltCompiler.setCompileWithTracing(true);
119 }
120 environment.processor.getUnderlyingConfiguration().setDefaultCollection(null);
121 environment.processor.setConfigurationProperty(Feature.STABLE_UNPARSED_TEXT, true);
122 return environment;
123 }
124
125 /**
126 * Construct an Environment
127 *
128 * @param xpc the XPathCompiler used to process the catalog file
129 * @param env the Environment element in the catalog file
130 * @param environments the set of environments to which this one should be added (may be null)
131 * @return the constructed Environment object
132 * @throws SaxonApiException
133 */
134
135 public static Environment processEnvironment(
136 final TestDriver driver,
137 XPathCompiler xpc, XdmNode env, Map<String, Environment> environments, Environment defaultEnvironment)
138 throws SaxonApiException {
139 Environment environment = new Environment();
140 String name;
141 name = env.attribute("name");
142 if (name != null && !driver.quiet) {
143 System.err.println("Loading environment " + name);
144 }
145 environment.processor = new Processor(!driver.driverProc.getSaxonEdition().equals("HE"));
146 if (defaultEnvironment != null) {
147 environment.processor.setConfigurationProperty(Feature.XSD_VERSION,
148 defaultEnvironment.processor.getConfigurationProperty(Feature.XSD_VERSION));
149 }
150 driver.prepareForSQL(environment.processor);
151 //AutoActivate.activate(environment.processor);
152
153
154 // TODO temporary
155 environment.processor.setConfigurationProperty(Feature.EXPATH_FILE_DELETE_TEMPORARY_FILES, true);
156 environment.processor.setConfigurationProperty(Feature.LINE_NUMBERING, true);
157
158 configureByteCode(driver, environment, driver.generateByteCode);
159
160 environment.xpathCompiler = environment.processor.newXPathCompiler();
161 environment.xpathCompiler.setBaseURI(env.getBaseURI());
162 environment.xqueryCompiler = environment.processor.newXQueryCompiler();
163 environment.xqueryCompiler.setBaseURI(env.getBaseURI());
164 if (driver.spec.shortSpecName.equals("XT")) {
165 environment.xsltCompiler = environment.processor.newXsltCompiler();
166 //environment.xsltCompiler.setXsltLanguageVersion(driver.spec.version);
167 if (driver.runWithJS) {
168 environment.xsltCompiler.setTargetEdition("JS");
169 }
170 if (environment.processor.getSaxonEdition().equals("EE")) {
171 environment.xsltCompiler.setJustInTimeCompilation(driver.jitFlag);
172 }
173 environment.xsltCompiler.setRelocatable(driver.relocatable);
174 }
175
176 if (driver.unfolded) {
177 driver.addInjection(environment.xqueryCompiler);
178 }
179
180 DocumentBuilder builder = environment.processor.newDocumentBuilder();
181 builder.setTreeModel(driver.treeModel);
182 environment.sourceDocs = new HashMap<>();
183 if (environments != null && name != null) {
184 environments.put(name, environment);
185 }
186
187 for (XdmNode prop : env.children("http://saxon.sf.net/", "property")) {
188 String propName = prop.attribute("name");
189 String propValue = prop.attribute("value");
190 environment.processor.setConfigurationProperty(propName, propValue);
191 }
192
193 // QT3 - dependency as sibling of environment
194 for (XdmNode dependency : env.getParent().children("dependency")) {
195 if (!driver.ensureDependencySatisfied(dependency, environment)) {
196 environment.usable = false;
197 }
198 }
199
200 // XSLT3 - dependencies as sibling of environment
201 for (XdmNode dependency : env.getParent().select(child("dependencies").then(child("*"))).asList()) {
202 //xpc.evaluate("../dependencies/*", env)) {
203 if (!driver.ensureDependencySatisfied(dependency, environment)) {
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.getSchemaManager();
223 boolean validateSources = loadSchemaDocuments(driver, xpc, env, environment, 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 for (XdmNode param : env.children("context-item")) {
250 String select = param.attribute("select");
251 XdmValue value = xpc.evaluate(select, null);
252 environment.contextItem = value.itemAt(0);
253 }
254
255 // compile any stylesheet packages defined as part of the environment
256 // Support this only in EE - an unusable environment in PE/HE
257 for (XdmItem stylesheet : xpc.evaluate("package[@role='secondary']", env)) {
258 String fileName = ((XdmNode) stylesheet).attribute("file");
259 Source styleSource = new StreamSource(((XdmNode) env).getBaseURI().resolve(fileName).toString());
260 try {
261 XsltPackage pkg = environment.xsltCompiler.compilePackage(styleSource);
262 environment.xsltCompiler.importPackage(pkg);
263 // Make the package available for use from fn:transform
264 environment.processor.getUnderlyingConfiguration().getDefaultXsltCompilerInfo().getPackageLibrary().addPackage(pkg.getUnderlyingPreparedPackage());
265 } catch (SaxonApiException e) {
266 e.printStackTrace();
267 driver.println("**** failure while compiling environment-defined stylesheet package " + fileName);
268 environment.failedToBuild = true;
269 environment.usable = false;
270 } catch (Exception e) {
271 e.printStackTrace();
272 driver.println("****Failure " + e + " in compiling environment " + name);
273 environment.failedToBuild = true;
274 environment.usable = false;
275 }
276 }
277
278 // compile any stylesheet defined as part of the environment (only one allowed)
279 // use the XSLT processor version associated with the stylesheet/@version attribute
280 for (XdmItem stylesheet : xpc.evaluate("stylesheet[not(@role='secondary')]", env)) {
281 String fileName = ((XdmNode) stylesheet).attribute("file");
282 Source styleSource = new StreamSource(env.getBaseURI().resolve(fileName).toString());
283 try {
284 if (driver.export) {
285 if (driver.runWithJS) {
286 String sourceFile = env.getBaseURI().resolve(fileName).toString();
287 environment.exportedStylesheet = driver.exportStylesheet(environment.xsltCompiler, sourceFile);
288 } else if (driver.xxCompilerLocation != null && !environment.xsltCompiler.isSchemaAware()) {
289 if (driver.xxCompiler == null) {
290
291 XdmMap options = new XdmMap();
292 boolean assertionsEnabled = environment.xsltCompiler.isAssertionsEnabled();
293 options = options.put(new XdmAtomicValue("enable-assertions"), new XdmAtomicValue(assertionsEnabled));
294
295 XsltCompiler c = driver.driverProc.newXsltCompiler();
296 c.setAssertionsEnabled(true);
297 c.setParameter(new QName("FAST_JAVA_XPATH"), new XdmAtomicValue(true));
298 c.setParameter(new QName("options"), options);
299 c.setFastCompilation(true); // TODO: temporary
300
301 driver.xxCompiler = c.compile(new StreamSource(new File(driver.xxCompilerLocation)));
302 }
303 File exportFile = new File(driver.resultsDir + "/export/" + name + ".sef");
304 Xslt30Transformer transformer = driver.xxCompiler.load30();
305 transformer.setInitialMode(new QName("compile-complete"));
306 Serializer serializer = driver.driverProc.newSerializer(exportFile);
307 transformer.applyTemplates(styleSource, serializer);
308 environment.xsltExecutable = environment.xsltCompiler.loadExecutablePackage(exportFile.toURI());
309 } else {
310 File exportFile = new File(driver.resultsDir + "/export/" + name + ".sef");
311 XsltPackage compiledPack = environment.xsltCompiler.compilePackage(styleSource);
312 compiledPack.save(exportFile);
313 environment.xsltExecutable = environment.xsltCompiler.loadExecutablePackage(exportFile.toURI());
314 }
315 } else {
316 environment.xsltExecutable = environment.xsltCompiler.compile(styleSource);
317 }
318 } catch (SaxonApiException e) {
319 //e.printStackTrace();
320 driver.println("**** failure while compiling environment-defined stylesheet " + fileName);
321 environment.failedToBuild = true;
322 environment.usable = false;
323 }
324 }
325
326
327 return environment;
328 }
329
330 private static void configureByteCode(TestDriver driver, Environment environment, int generate) {
331 if (environment.processor.getSaxonEdition().equals("EE")) {
332 if (generate == 0) {
333 environment.processor.setConfigurationProperty(Feature.GENERATE_BYTE_CODE, true);
334 environment.processor.setConfigurationProperty(Feature.DEBUG_BYTE_CODE, false);
335 environment.processor.setConfigurationProperty(Feature.MAX_COMPILED_CLASSES, 1000000);
336 } else if (generate > 0) {
337 environment.processor.setConfigurationProperty(FeatureKeys.GENERATE_BYTE_CODE, generate);
338 environment.processor.setConfigurationProperty(Feature.DEBUG_BYTE_CODE, false);
339 environment.processor.setConfigurationProperty(Feature.MAX_COMPILED_CLASSES, 1000000);
340 } else {
341 environment.processor.setConfigurationProperty(Feature.GENERATE_BYTE_CODE, false);
342 environment.processor.setConfigurationProperty(Feature.DEBUG_BYTE_CODE, false);
343 //environment.processor.setConfigurationProperty(Feature.ALLOW_MULTITHREADING, "false"); // TODO should have a separate option for this
344 }
345 if (generate >= 0 && driver.isDebugByteCode()) {
346 environment.processor.setConfigurationProperty(Feature.DEBUG_BYTE_CODE, true);
347 environment.processor.setConfigurationProperty(Feature.DEBUG_BYTE_CODE_DIR, "debugByteCode");
348 environment.processor.setConfigurationProperty(Feature.MONITOR_HOT_SPOT_BYTE_CODE, true);
349 driver.driverProc.setConfigurationProperty(Feature.DEBUG_BYTE_CODE, true);
350 driver.driverProc.setConfigurationProperty(Feature.DEBUG_BYTE_CODE_DIR, "debugByteCode");
351 driver.driverProc.setConfigurationProperty(Feature.MONITOR_HOT_SPOT_BYTE_CODE, true);
352 driver.driverProc.setConfigurationProperty(Feature.OPTIMIZATION_LEVEL, "-f");
353 }
354 }
355 }
356
357 private static void declareOutputControls(TestDriver driver, XPathCompiler xpc, XdmItem env, Environment environment) throws SaxonApiException {
358 String needsSerialization = xpc.evaluate("string((output/@serialize,'no')[1])", env).toString();
359 environment.outputSerialize = "yes".equals(needsSerialization);
360 String needsTree = xpc.evaluate("string((output/@tree,'yes')[1])", env).toString();
361 environment.outputTree = "yes".equals(needsTree);
362
363 }
364
365 private static void setBaseUri(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment) {
366 for (XdmNode base : env.children("static-base-uri")) {
367 String uri = base.attribute("uri");
368 if (uri == null || "#UNDEFINED".equals(uri)) {
369 environment.xqueryCompiler.setBaseURI(null);
370 driver.println("**** Error: The BaseURI values null and #UNDEFINED are not supported in this test driver");
371 } else {
372 try {
373 environment.xpathCompiler.setBaseURI(new URI(uri));
374 environment.xqueryCompiler.setBaseURI(new URI(uri));
375 } catch (URISyntaxException | IllegalArgumentException e) {
376 driver.println("**** invalid base URI " + uri);
377 }
378 }
379 }
380 }
381
382 private static void registerCollations(XPathCompiler xpc, XdmNode env, Environment environment) throws SaxonApiException {
383 for (XdmNode base : env.children("collation")) {
384 String uri = base.attribute("uri");
385 if (uri.equals("http://www.w3.org/2010/09/qt-fots-catalog/collation/caseblind") ||
386 uri.equals("http://www.w3.org/xslts/collation/caseblind")) {
387 Configuration config = xpc.getProcessor().getUnderlyingConfiguration();
388 try {
389 StringCollator collator = config.getCollation("http://saxon.sf.net/collation?ignore-case=yes");
390 environment.processor.declareCollation(uri, ((SimpleCollation) collator).getComparator());
391 } catch (XPathException e) {
392 throw new SaxonApiException(e);
393 }
394 }
395 String defaultAtt = base.attribute("default");
396 if (defaultAtt != null && (defaultAtt.trim().equals("true") || defaultAtt.trim().equals("1"))) {
397 environment.xpathCompiler.declareDefaultCollation(uri);
398 environment.xqueryCompiler.declareDefaultCollation(uri);
399 environment.xsltCompiler.declareDefaultCollation(uri);
400 }
401 }
402 }
403
404 private static void declareNamespaces(XPathCompiler xpc, XdmNode env, Environment environment) throws SaxonApiException {
405 for (XdmNode nsElement : env.children("namespace")) {
406 String prefix = nsElement.attribute("prefix");
407 String uri = nsElement.attribute("uri");
408 environment.xpathCompiler.declareNamespace(prefix, uri);
409 environment.xqueryCompiler.declareNamespace(prefix, uri);
410 if (uri.equals("http://expath.org/ns/file")) {
411 // For EXPath file tests, set the EXPath base directory to the catalog directory
412 String base = nsElement.getBaseURI().toString();
413 if (base.startsWith("file:///")) {
414 base = base.substring(7);
415 } else if (base.startsWith("file:/")) {
416 base = base.substring(5);
417 }
418 File file = new File(base);
419 file = file.getParentFile();
420 System.setProperty("expath.base.directory", file.getAbsolutePath());
421 }
422 }
423 }
424
425 private static boolean loadSchemaDocuments(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment, SchemaManager manager) throws SaxonApiException {
426 boolean validateSources = false;
427 for (XdmNode schema : env.children("schema")) {
428 String role = schema.attribute("role");
429 String xsdVersion = schema.attribute("xsd-version");
430 if (manager == null) {
431 driver.println("*** Processor is not schema aware");
432 environment.usable = false;
433 return false;
434 }
435 if (!driver.treeModel.isSchemaAware()) {
436 driver.println("*** Tree model is not schema aware");
437 environment.usable = false;
438 return false;
439 }
440 if (xsdVersion != null) {
441 manager.setXsdVersion(xsdVersion);
442 } else {
443 manager.setXsdVersion("1.0");
444 }
445 if (!"secondary".equals(role)) {
446 String href = schema.attribute("file");
447 String ns = schema.attribute("uri");
448 if (href == null) {
449 try {
450 Source[] sources = manager.getSchemaURIResolver().resolve(ns, null, new String[0]);
451 manager.load(sources[0]);
452 } catch (Exception e) {
453 driver.println("*** Failed to load schema by URI: " + ns + " - " + e.getMessage());
454 e.printStackTrace();
455 }
456 } else {
457 File file = new File(((XdmNode) env).getBaseURI().resolve(href));
458 try {
459 manager.load(new StreamSource(file));
460 } catch (SaxonApiException err) {
461 driver.println("*** Failed to load schema: " + href + " - " + err.getMessage());
462 } catch (NullPointerException err) {
463 err.printStackTrace();
464 driver.println("*** NPE: Failed to load schema: " + href + " - " + err.getMessage());
465 }
466 }
467 xpc.importSchemaNamespace(ns);
468 environment.xpathCompiler.importSchemaNamespace(ns);
469 if ("source-reference".equals(role)) {
470 validateSources = true;
471 }
472 if ("stylesheet-import".equals(role)) {
473 environment.xsltCompiler.setSchemaAware(true);
474 }
475 }
476 }
477 return validateSources;
478 }
479
480 private static void declareExternalVariables(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment) throws SaxonApiException {
481 for (XdmNode param : env.children("param")) {
482 String varName = param.attribute("name");
483 XdmValue value;
484 String source = param.attribute("source");
485 if (source != null) {
486 XdmNode sourceDoc = environment.sourceDocs.get(source);
487 if (sourceDoc == null) {
488 driver.println("**** Unknown source document " + source);
489 }
490 value = sourceDoc;
491 } else {
492 String select = param.attribute("select");
493 value = xpc.evaluate(select, null);
494 }
495 boolean isStatic = isTrue("static").test(param);
496 QName varQName;
497 int colon = varName.indexOf(':');
498 if (colon >= 0) {
499 NamespaceResolver resolver = new InscopeNamespaceResolver(param.getUnderlyingNode());
500 String namespace = resolver.getURIForPrefix(varName.substring(0, colon), false);
501 varQName = new QName(namespace, varName);
502 } else {
503 varQName = new QName(varName);
504 }
505 environment.xpathCompiler.declareVariable(varQName);
506 if (isTrue("declared").test(param)) {
507 // no action
508 } else {
509 environment.paramDeclarations.append("declare variable $" + varName + " external; ");
510 }
511 if (isStatic) {
512 environment.xsltCompiler.setParameter(varQName, value);
513 System.err.println("set " + varQName + " = " + value);
514 } else {
515 environment.params.put(varQName, value);
516 }
517 }
518 }
519
520 private static void registerDecimalFormats(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment) throws SaxonApiException {
521 for (XdmNode decimalFormat : env.children("decimal-format")) {
522 DecimalFormatManager dfm = environment.xpathCompiler.getUnderlyingStaticContext().getDecimalFormatManager();
523
524 String formatName = decimalFormat.attribute("name");
525 StructuredQName formatQName = null;
526 if (formatName != null) {
527 if (formatName.indexOf(':') < 0) {
528 formatQName = new StructuredQName("", "", formatName);
529 } else {
530 try {
531 formatQName = StructuredQName.fromLexicalQName(formatName, false, true,
532 new InscopeNamespaceResolver(decimalFormat.getUnderlyingNode()));
533 } catch (XPathException e) {
534 driver.println("**** Invalid QName as decimal-format name");
535 formatQName = new StructuredQName("", "", "error-name");
536 }
537 }
538 environment.paramDecimalDeclarations.append("declare decimal-format " + formatQName.getEQName() + " ");
539 } else {
540 environment.paramDecimalDeclarations.append("declare default decimal-format ");
541 }
542 DecimalSymbols symbols = formatQName == null ? dfm.getDefaultDecimalFormat() : dfm.obtainNamedDecimalFormat(formatQName);
543 symbols.setHostLanguage(Configuration.XQUERY, driver.spec.getNumericVersion());
544 for (XdmItem decimalFormatAtt : xpc.evaluate("@* except @name", (XdmNode) decimalFormat)) {
545 XdmNode formatAttribute = (XdmNode) decimalFormatAtt;
546 String property = formatAttribute.getNodeName().getLocalName();
547 String value = formatAttribute.getStringValue();
548 environment.paramDecimalDeclarations.append(property + "=\"" + value + "\" ");
549 try {
550 switch (property) {
551 case "decimal-separator":
552 symbols.setDecimalSeparator(value);
553 break;
554 case "grouping-separator":
555 symbols.setGroupingSeparator(value);
556 break;
557 case "exponent-separator":
558 symbols.setExponentSeparator(value);
559 break;
560 case "infinity":
561 symbols.setInfinity(value);
562 break;
563 case "NaN":
564 symbols.setNaN(value);
565 break;
566 case "minus-sign":
567 symbols.setMinusSign(value);
568 break;
569 case "percent":
570 symbols.setPercent(value);
571 break;
572 case "per-mille":
573 symbols.setPerMille(value);
574 break;
575 case "zero-digit":
576 symbols.setZeroDigit(value);
577 break;
578 case "digit":
579 symbols.setDigit(value);
580 break;
581 case "pattern-separator":
582 symbols.setPatternSeparator(value);
583 break;
584 default:
585 driver.println("**** Unknown decimal format attribute " + property);
586 break;
587 }
588 } catch (XPathException e) {
589 driver.println("**** " + e.getMessage());
590 }
591 }
592 environment.paramDecimalDeclarations.append(";");
593 try {
594 symbols.checkConsistency(formatQName);
595 } catch (XPathException err) {
596 driver.println("**** " + err.getMessage());
597 }
598
599 }
600 }
601
602 private static void createUnparsedTextResolver(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment) throws SaxonApiException {
603 final HashMap<URI, Object> resources = new HashMap<>();
604 final HashMap<URI, String> encodings = new HashMap<>();
605 for (XdmNode resource : env.children("resource")) {
606 CatalogResource res = new CatalogResource();
607 res.uri = resource.attribute("uri");
608 String href = resource.attribute("file");
609 res.encoding = resource.attribute("encoding");
610 res.mediaType = resource.attribute("media-type");
611 if (href != null) {
612 Object obj = null;
613
614 if (href.startsWith("http")) {
615 try {
616 res.url = new URL(href);
617 obj = res.url;
618 } catch (MalformedURLException e) {
619 e.printStackTrace();
620 }
621 } else {
622 res.file = new File(((XdmNode) env).getBaseURI().resolve(href));
623 obj = res.file;
624 }
625 try {
626 resources.put(new URI(res.uri), obj);
627 encodings.put(new URI(res.uri), res.encoding);
628 URI abs = ((XdmNode) resource).getBaseURI().resolve(res.uri);
629 resources.put(abs, obj);
630 encodings.put(abs, res.encoding);
631 environment.catalogResources.put(abs.toString(), res);
632
633 } catch (URISyntaxException e) {
634 driver.println("** Invalid URI in environment: " + e.getMessage());
635 }
636 if (res.mediaType != null && res.mediaType.endsWith("xquery")) {
637 driver.registerXQueryModule(res.uri, res.file);
638 }
639 }
640
641 }
642 if (!resources.isEmpty()) {
643 environment.unparsedTextResolver =
644 (absoluteURI, encoding, config) -> {
645 if (encoding == null) {
646 encoding = encodings.get(absoluteURI);
647 }
648 if (encoding == null) {
649 encoding = "utf-8";
650 }
651 try {
652 // The following is necessary to ensure that encoding errors are not recovered.
653 Charset charset = Charset.forName(encoding);
654 CharsetDecoder decoder = charset.newDecoder();
655 decoder = decoder.onMalformedInput(CodingErrorAction.REPORT);
656 decoder = decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
657 Object obj = resources.get(absoluteURI);
658 if (obj instanceof File) {
659 return new BufferedReader(new InputStreamReader(new FileInputStream((File) obj), decoder));
660 } else {
661 URL resource = (URL) resources.get(absoluteURI);
662 if (resource == null) {
663 resource = absoluteURI.toURL();
664 //throw new XPathException("Unparsed text resource " + absoluteURI + " not registered in catalog", "FOUT1170");
665 }
666 InputStream in = resource.openConnection().getInputStream();
667 return new BufferedReader(new InputStreamReader(in, decoder));
668 }
669 // return new InputStreamReader(new FileInputStream(resources.get(absoluteURI)), encoding);
670 } catch (IOException ioe) {
671 throw new XPathException(ioe.getMessage(), "FOUT1170");
672 } catch (IllegalCharsetNameException | UnsupportedCharsetException icne) {
673 throw new XPathException("Invalid encoding name: " + encoding, "FOUT1190");
674 }
675 };
676 }
677 }
678
679 private final static String DEFAULT_COLLECTION_URI = "http://www.w3.org/qt3-test-suite/default.collection.uri";
680
681 private static void createCollectionUriResolver(final TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment, DocumentBuilder builder) throws SaxonApiException {
682 if (!environment.usable) {
683 // Can't run collection tests with XQuery 1.0
684 return;
685 }
686 final HashMap<String, ResourceCollection> collections = new HashMap<>();
687 AbstractResourceCollection collectioni = null;
688 final Configuration config = environment.processor.getUnderlyingConfiguration();
689 for (XdmNode coll : env.children("collection")) { // xpc.evaluate("collection", env)) {
690 final List<Resource> resourcesi = new ArrayList<>();
691
692 String collectionURI = coll.attribute("uri");
693 if (collectionURI == null) {
694 collectionURI = "";
695 }
696
697 if (collectionURI.isEmpty()) {
698 collectionURI = DEFAULT_COLLECTION_URI;
699 config.setDefaultCollection(DEFAULT_COLLECTION_URI);
700 }
701 URI u;
702 try {
703 u = new URI(collectionURI);
704 } catch (URISyntaxException e) {
705 driver.println("**** Invalid collection URI " + collectionURI);
706 break;
707 }
708 if (!collectionURI.equals("") && !u.isAbsolute()) {
709 u = ((XdmNode) env).getBaseURI().resolve(collectionURI);
710 collectionURI = u.toString();
711 }
712
713 final String cURI = collectionURI;
714
715 collectioni = new AbstractResourceCollection(config) {
716
717
718 public void addResource(Resource r) {
719 resourcesi.add(r);
720 }
721
722 public String getCollectionURI() {
723 return cURI;
724 }
725
726 public Iterator<String> getResourceURIs(XPathContext context) {
727 List<String> resourceUris = new ArrayList<>();
728 for (Resource resource : resourcesi) {
729 resourceUris.add(resource.getResourceURI());
730 }
731 return resourceUris.iterator();
732 }
733
734 public Iterator<Resource> getResources(XPathContext context) {
735 return resourcesi.iterator();
736 }
737
738 @Override
739 public boolean isStable(XPathContext context) {
740 return true;
741 }
742 };
743
744 for (XdmNode source : coll.children("source")) {
745 String href = source.attribute("file");
746 String frag = null;
747 int hash = href.indexOf('#');
748 if (hash > 0) {
749 frag = href.substring(hash + 1);
750 href = href.substring(0, hash);
751 }
752 File file = new File(env.getBaseURI().resolve(href));
753 String xinc = source.attribute("xinclude");
754 XdmNode doc;
755 if ("true".equals(xinc)) {
756 StreamSource ss = new StreamSource(file);
757 AugmentedSource as = AugmentedSource.makeAugmentedSource(ss);
758 as.setXIncludeAware(true);
759 doc = builder.build(as);
760 } else {
761 doc = builder.build(file);
762 }
763 if (frag != null) {
764 XdmNode selected = (XdmNode) environment.xpathCompiler.evaluateSingle("id('" + frag + "')", doc);
765 if (selected == null) {
766 driver.println("**** Fragment not found: " + frag);
767 break;
768 }
769
770 resourcesi.add(new XmlResource(config, selected.getUnderlyingNode()));
771 } else {
772 resourcesi.add(new XmlResource(config, doc.getUnderlyingNode()));
773 }
774 environment.sourceDocs.put(href, doc);
775 }
776 for (XdmNode resource : coll.children("resources")) {
777 String uri = resource.attribute("uri");
778 String href = resource.attribute("file");
779 String encoding = resource.attribute("encoding");
780 String media = resource.attribute("media-type");
781 AbstractResourceCollection.InputDetails details = new AbstractResourceCollection.InputDetails();
782 details.encoding = encoding;
783 details.contentType = media;
784 if (href != null) {
785 if (href.startsWith("http")) {
786 try {
787 URL url = new URL(href);
788 URLConnection connection = url.openConnection();
789 if (details.contentType == null) {
790 details.contentType = connection.getContentType();
791 }
792 details.inputStream = connection.getInputStream();
793 } catch (IOException e) {
794 e.printStackTrace();
795 }
796 } else {
797 File file = new File(env.getBaseURI().resolve(href));
798 try {
799 details.inputStream = new FileInputStream(file);
800 Resource resourcej = collectioni.makeResource(config, details, file.toURI().toString());
801 if (resourcej != null) {
802 resourcesi.add(resourcej);
803 } else {
804 driver.println("** Error in building collection environment: Resource " + href + " not found: ");
805 }
806 } catch (IOException e) {
807 driver.println("** IO Error in building collection environment: " + e.getMessage());
808
809 } catch (XPathException e) {
810 driver.println("** Error in building collection environment: " + e.getMessage());
811 }
812 if (media != null && href.endsWith("xquery")) {
813 driver.registerXQueryModule(uri, file);
814 }
815 }
816
817 }
818 }
819 for (XdmNode query : coll.children("query")) {
820 String queryExpr = query.getStringValue();
821 XQueryEvaluator evaluator = environment.xqueryCompiler.compile(queryExpr).load();
822 XdmValue result = evaluator.evaluate();
823
824 for (final XdmItem itemi : result) {
825 resourcesi.add(new Resource() {
826 public String getResourceURI() {
827 return "";
828 }
829
830 public Item getItem(XPathContext context) {
831 return itemi.getUnderlyingValue();
832 }
833
834 public String getContentType() {
835 return null;
836 }
837 });
838 }
839 }
840 collections.put(collectionURI, collectioni);
841
842 }
843
844 if (collections != null) {
845 environment.processor.getUnderlyingConfiguration().setCollectionFinder(new CollectionFinder() {
846 public ResourceCollection findCollection(XPathContext context, String collectionURI) throws XPathException {
847 if (collectionURI == null) {
848 collectionURI = "";
849 }
850 return collections.get(collectionURI);
851 }
852 });
853
854 }
855
856 if (driver.runWithJS) {
857 environment.jsCollections = new HashMap<>();
858 for (Map.Entry<String, ResourceCollection> entry : collections.entrySet()) {
859 String uri = entry.getKey();
860 List<String> lexicalContents = new ArrayList<>();
861 ResourceCollection contents = entry.getValue();
862 XPathContext context = environment.processor.getUnderlyingConfiguration().getConversionContext();
863 try {
864 Iterator<? extends Resource> iter = contents.getResources (context);
865 while (iter.hasNext()) {
866 Resource resource = iter.next();
867 Item item = resource.getItem(context);
868 if (item instanceof NodeInfo) {
869 String lexicalXml = QueryResult.serialize((NodeInfo)item);
870 lexicalContents.add(lexicalXml);
871 }
872 }
873 } catch (XPathException e) {
874 e.printStackTrace();
875 }
876 environment.jsCollections.put(uri, lexicalContents);
877 }
878 }
879 }
880
881 private static void loadSourceDocuments(TestDriver driver, XPathCompiler xpc, XdmNode env, Environment environment, DocumentBuilder builder, SchemaManager manager, boolean validateSources) throws SaxonApiException {
882 for (XdmNode source : env.children("source")) {
883
884 CatalogResource res = new CatalogResource();
885 String rawUri = source.attribute("uri");
886 String role = source.attribute("role");
887 if (rawUri != null) {
888 res.uri = env.getBaseURI().resolve(rawUri).toString();
889 environment.catalogResources.put(res.uri, res);
890 } else if (".".equals(role)) {
891 environment.catalogResources.put("", res);
892 }
893 res.mediaType = source.attribute("media-type");
894 if ("application/xml".equals(res.mediaType)) {
895 // MHK 2016-04-07: why??
896 continue;
897 }
898 String validation = source.attribute("validation");
899 if (validation == null) {
900 validation = "skip";
901 }
902 String streaming = source.attribute("streaming");
903 TreeModel selectedTreeModel = builder.getTreeModel();
904 if (!validateSources && validation.equals("skip")) {
905 builder.setSchemaValidator(null);
906 } else if (manager == null) {
907 environment.usable = false;
908 } else {
909 if (!selectedTreeModel.isSchemaAware()) {
910 builder.setTreeModel(TreeModel.TINY_TREE);
911 }
912 SchemaValidator validator = manager.newSchemaValidator();
913 validator.setLax("lax".equals(validation));
914 builder.setSchemaValidator(validator);
915 environment.xpathCompiler.setSchemaAware(true);
916 environment.xqueryCompiler.setSchemaAware(true);
917 if (environment.xsltCompiler != null) {
918 environment.xsltCompiler.setSchemaAware(true);
919 }
920 }
921
922 String href = source.attribute("file");
923 String select = source.attribute("select");
924 String xinc = source.attribute("xinclude");
925 if ("true".equals(streaming)) {
926 if (".".equals(role)) {
927 if (href == null) {
928 environment.streamedContent = xpc.evaluate("string(content)", source).toString();
929 } else {
930 environment.streamedFile = new File(((XdmNode) env).getBaseURI().resolve(href));
931 res.file = environment.streamedFile;
932 }
933 environment.streamedInputValidation = validation;
934 } else {
935 File file = new File(((XdmNode) env).getBaseURI().resolve(href));
936 environment.streamedSecondaryDocs.put(file.toURI().toString(), validation);
937 res.file = file;
938 }
939 } else if (driver.runWithJS || driver.isAltova) {
940 if (select != null) {
941 driver.println("source select=path not supported by this test driver");
942 environment.usable = false;
943 }
944 if (".".equals(role)) {
945 if (href == null) {
946 environment.streamedContent = xpc.evaluate("string(content)", source).toString();
947 } else {
948 environment.streamedFile = new File(((XdmNode) env).getBaseURI().resolve(href));
949 res.file = environment.streamedFile;
950 }
951 environment.streamedInputValidation = validation;
952 } else {
953 File file = new File(((XdmNode) env).getBaseURI().resolve(href));
954 environment.streamedSecondaryDocs.put(file.toURI().toString(), validation);
955 res.file = file;
956 }
957 } else {
958 Source ss;
959 File file = null;
960 FileInputStream fileInputStream = null;
961 StringReader stringReader = null;
962 String baseUri = null;
963 if (href != null) {
964 URI fileLoc = env.getBaseURI().resolve(href);
965 baseUri = fileLoc.toString();
966 if (fileLoc.getScheme().equals("file")) {
967 file = new File(env.getBaseURI().resolve(href));
968 if (res.uri == null) {
969 res.uri = file.toURI().toString();
970 }
971 res.file = file;
972 }
973 try {
974 if (file == null) {
975 ss = new StreamSource(fileLoc.toString());
976 } else {
977 fileInputStream = new FileInputStream(file);
978 ss = new StreamSource(fileInputStream, res.uri);
979 }
980 if ("true".equals(xinc)) {
981 AugmentedSource as = AugmentedSource.makeAugmentedSource(ss);
982 as.setXIncludeAware(true);
983 ss = as;
984 }
985 } catch (FileNotFoundException e) {
986 driver.println("*** failed to find source document " + href);
987 continue;
988 }
989 } else {
990 // content is inline in the catalog
991 baseUri = res.uri;
992 if (res.uri == null) {
993 baseUri = env.getBaseURI().toString();
994 }
995 String content = xpc.evaluate("string(content)", source).toString();
996 stringReader = new StringReader(content);
997 ss = new StreamSource(stringReader, baseUri);
998 }
999
1000 if (selectedTreeModel.getName().equals("DOM") || selectedTreeModel.getName().equals("DOMINO")) {
1001 // create the DOM directly. Using a SAX parser plus document builder loses
1002 // entities and doctype nodes, which will be encountered in real life
1003 Document doc = null;
1004 try {
1005 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
1006 factory.setNamespaceAware(true);
1007 javax.xml.parsers.DocumentBuilder db = factory.newDocumentBuilder();
1008 if (file != null) {
1009 doc = db.parse(file);
1010 } else if (fileInputStream != null) {
1011 InputSource is = new InputSource(fileInputStream);
1012 is.setSystemId(baseUri);
1013 doc = db.parse(is);
1014 } else if (stringReader != null) {
1015 InputSource is = new InputSource(stringReader);
1016 is.setSystemId(baseUri);
1017 doc = db.parse(is);
1018 }
1019 } catch (ParserConfigurationException | IOException | SAXException e) {
1020 e.printStackTrace();
1021 }
1022
1023 if (selectedTreeModel.getName().equals("DOM")) {
1024 NodeInfo root = new DocumentWrapper(doc, res.uri, environment.processor.getUnderlyingConfiguration()).getRootNode();
1025 res.doc = (XdmNode)XdmValue.wrap(root);
1026 } else {
1027 res.doc = driver.makeDominoTree(doc, environment.processor.getUnderlyingConfiguration(), res.uri);
1028 }
1029 environment.sourceDocs.put(res.uri, res.doc);
1030 } else {
1031 try {
1032 builder.setLineNumbering(true);
1033 res.doc = builder.build(ss);
1034 environment.sourceDocs.put(res.uri, res.doc);
1035 environment.sourceDocs.put(rawUri, res.doc);
1036
1037 } catch (SaxonApiException e) {
1038 //e.printStackTrace();
1039 driver.println("*** failed to build source document " + href + " - " + e.getMessage());
1040 }
1041 }
1042
1043 builder.setTreeModel(selectedTreeModel);
1044
1045 XdmItem selectedItem = res.doc;
1046 if (select != null) {
1047 XPathSelector selector = environment.xpathCompiler.compile(select).load();
1048 selector.setContextItem(selectedItem);
1049 selectedItem = selector.evaluateSingle();
1050 }
1051
1052
1053 if (role != null) {
1054 if (".".equals(role)) {
1055 environment.contextItem = selectedItem;
1056 } else if (role.startsWith("$")) {
1057 String varName = role.substring(1);
1058 environment.params.put(new QName(varName), selectedItem);
1059 environment.xpathCompiler.declareVariable(new QName(varName));
1060 environment.paramDeclarations.append("declare variable $" + varName + " external; ");
1061 }
1062 }
1063 }
1064 String definesStylesheet = ((XdmNode) source).attribute("defines-stylesheet");
1065 if (definesStylesheet != null) {
1066 definesStylesheet = definesStylesheet.trim();
1067 }
1068 if (("true".equals(definesStylesheet) || "1".equals(definesStylesheet)) && !driver.runWithJS) {
1069 // try using an embedded stylesheet from the source document
1070 try {
1071 Source styleSource = environment.xsltCompiler.getAssociatedStylesheet(
1072 ((XdmNode) environment.contextItem).asSource(), null, null, null);
1073 environment.xsltExecutable = environment.xsltCompiler.compile(styleSource);
1074 } catch (SaxonApiException e) {
1075 driver.println("*** failed to compile stylesheet referenced in source document " + href);
1076 }
1077 }
1078 }
1079 }
1080
1081 /**
1082 * The environment acts as a URIResolver
1083 */
1084
1085 public Source resolve(String href, String base) throws TransformerException {
1086 XdmNode node = sourceDocs.get(href);
1087 if (node == null) {
1088 String uri;
1089 if (base == null) {
1090 base = href;
1091 href = "";
1092 }
1093 try {
1094 uri = new URI(base).resolve(href).toString();
1095 } catch (URISyntaxException | IllegalArgumentException e) {
1096 uri = href;
1097 }
1098 String val = streamedSecondaryDocs.get(uri);
1099 if (val != null) {
1100 Source source = new StreamSource(uri);
1101 if (!val.equals("skip")) {
1102 source = AugmentedSource.makeAugmentedSource(source);
1103 ((AugmentedSource) source).setSchemaValidationMode(Validation.getCode(val));
1104 }
1105 return source;
1106 } else {
1107 return null;
1108 }
1109 } else {
1110 return node.asSource();
1111 }
1112 }
1113
1114 public CatalogResource getContextDocument() {
1115 return catalogResources.get("");
1116 }
1117
1118
1119 public abstract static class ResetAction {
1120 public abstract void reset(Environment env);
1121 }
1122
1123
1124 }
1125