Debian Codegraph @

net/sf/saxon/Configuration.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;
9
10 import net.sf.saxon.event.*;
11 import net.sf.saxon.expr.*;
12 import net.sf.saxon.expr.accum.AccumulatorRegistry;
13 import net.sf.saxon.expr.compat.TypeChecker10;
14 import net.sf.saxon.expr.instruct.*;
15 import net.sf.saxon.expr.number.Numberer_en;
16 import net.sf.saxon.expr.parser.*;
17 import net.sf.saxon.expr.sort.AlphanumericCollator;
18 import net.sf.saxon.expr.sort.CodepointCollator;
19 import net.sf.saxon.expr.sort.HTML5CaseBlindCollator;
20 import net.sf.saxon.functions.*;
21 import net.sf.saxon.functions.registry.*;
22 import net.sf.saxon.lib.*;
23 import net.sf.saxon.ma.arrays.ArrayFunctionSet;
24 import net.sf.saxon.ma.map.MapFunctionSet;
25 import net.sf.saxon.ma.map.MapItem;
26 import net.sf.saxon.om.*;
27 import net.sf.saxon.pattern.PatternParser30;
28 import net.sf.saxon.pull.PullSource;
29 import net.sf.saxon.query.QueryModule;
30 import net.sf.saxon.query.StaticQueryContext;
31 import net.sf.saxon.query.XQueryExpression;
32 import net.sf.saxon.query.XQueryParser;
33 import net.sf.saxon.regex.RegularExpression;
34 import net.sf.saxon.resource.*;
35 import net.sf.saxon.s9api.Xslt30Transformer;
36 import net.sf.saxon.serialize.CharacterMap;
37 import net.sf.saxon.serialize.SerializationProperties;
38 import net.sf.saxon.serialize.charcode.CharacterSetFactory;
39 import net.sf.saxon.serialize.charcode.XMLCharacterData;
40 import net.sf.saxon.style.*;
41 import net.sf.saxon.sxpath.IndependentContext;
42 import net.sf.saxon.trace.ExpressionPresenter;
43 import net.sf.saxon.trace.TraceCodeInjector;
44 import net.sf.saxon.trace.XSLTTraceCodeInjector;
45 import net.sf.saxon.trans.*;
46 import net.sf.saxon.trans.packages.IPackageLoader;
47 import net.sf.saxon.tree.tiny.TreeStatistics;
48 import net.sf.saxon.tree.util.DocumentNumberAllocator;
49 import net.sf.saxon.type.*;
50 import net.sf.saxon.value.*;
51 import net.sf.saxon.z.IntHashSet;
52 import net.sf.saxon.z.IntSet;
53 import org.xml.sax.*;
54 import org.xml.sax.ext.DefaultHandler2;
55 import org.xml.sax.ext.LexicalHandler;
56
57 import javax.xml.parsers.ParserConfigurationException;
58 import javax.xml.parsers.SAXParser;
59 import javax.xml.parsers.SAXParserFactory;
60 import javax.xml.transform.*;
61 import javax.xml.transform.dom.DOMSource;
62 import javax.xml.transform.sax.SAXSource;
63 import javax.xml.transform.stax.StAXSource;
64 import javax.xml.transform.stream.StreamSource;
65 import java.io.*;
66 import java.net.URISyntaxException;
67 import java.net.URL;
68 import java.net.URLDecoder;
69 import java.util.*;
70 import java.util.concurrent.ConcurrentLinkedQueue;
71 import java.util.function.IntPredicate;
72
73
74 /**
75 * This class holds details of user-selected configuration options for a set of transformations
76 * and/or queries. When running XSLT, the preferred way of setting configuration options is via
77 * the JAXP TransformerFactory interface, but the Configuration object provides a finer
78 * level of control. As yet there is no standard API for XQuery, so the only way of setting
79 * Configuration information is to use the methods on this class directly.
80 * <p>As well as holding configuration settings, this class acts as a factory for classes
81 * providing service in particular areas: error handling, URI resolution, and the like. Some
82 * of these services are chosen on the basis of the current platform (Java or .NET), some vary
83 * depending whether the environment is schema-aware or not.</p>
84 * <p>The <code>Configuration</code> provides access to a {@link NamePool} which is used to manage
85 * all the names used in stylesheets, queries, schemas, and source and documents: the NamePool
86 * allocates integer codes to these names allowing efficient storage and comparison. Normally
87 * there will be a one-to-one relationship between a <code>NamePool</code> and a <code>Configuration</code>.
88 * It is possible, however, for several <code>Configuration</code> objects to share the same
89 * <code>NamePool</code>. Until Saxon 8.9, by default all <code>Configuration</code> objects
90 * shared a single <code>NamePool</code> unless configured otherwise; this changed in 8.9 so that
91 * the default is to allocate a new <code>NamePool</code> for each <code>Configuration</code>.</p>
92 * <p>The <code>Configuration</code> establishes the scope within which node identity is managed.
93 * Every document belongs to a <code>Configuration</code>, and every node has a distinct identity
94 * within that <code>Configuration</code>. In consequence, it is not possible for any query or
95 * transformation to manipulate multiple documents unless they all belong to the same
96 * <code>Configuration</code>.</p>
97 * <p>Saxon-EE has a subclass of the <code>Configuration</code> class which provides the additional
98 * services needed for schema-aware processing. The {@link com.saxonica.config.EnterpriseConfiguration}
99 * also holds a cache of loaded schema components used for compiling schema-aware transformations
100 * and queries, and for validating instance documents.</p>
101 * <p>Since Saxon 8.4, the JavaDoc documentation for Saxon attempts to identify interfaces
102 * that are considered stable, and will only be changed in a backwards-incompatible way
103 * if there is an overriding reason to do so. These interfaces and methods are labelled
104 * with the JavaDoc "since" tag. The value 8.n indicates a method in this category that
105 * was introduced in Saxon version 8.n: or in the case of 8.4, that was present in Saxon 8.4
106 * and possibly in earlier releases. (In some cases, these methods have been unchanged for
107 * a long time.) Methods without a "since" tag, although public, are provided for internal
108 * use or for use by advanced users, and are subject to change from one release to the next.
109 * The presence of a "since" tag on a class or interface indicates that there are one or more
110 * methods in the class that are considered stable; it does not mean that all methods are
111 * stable.</p>
112 *
113 * @since 8.4
114 */
115
116
117 public class Configuration implements SourceResolver, NotationSet {
118
119 protected static Set<Feature> booleanFeatures = new HashSet<>(40);
120 private transient ApiProvider apiProcessor = null;
121 private transient CharacterSetFactory characterSetFactory;
122
123 private Map<String, StringCollator> collationMap = new HashMap<>(10);
124 private CollationURIResolver collationResolver = new StandardCollationURIResolver();
125 private String defaultCollationName = NamespaceConstant.CODEPOINT_COLLATION_URI;
126
127 protected CollectionFinder collectionFinder = new StandardCollectionFinder();
128 private EnvironmentVariableResolver environmentVariableResolver = new StandardEnvironmentVariableResolver();
129 private String defaultCollection = null;
130 private ParseOptions defaultParseOptions = new ParseOptions();
131
132 protected transient StaticQueryContext defaultStaticQueryContext;
133 private StaticQueryContextFactory staticQueryContextFactory = new StaticQueryContextFactory();
134 protected OptimizerOptions optimizerOptions = OptimizerOptions.FULL_HE_OPTIMIZATION;
135 protected CompilerInfo defaultXsltCompilerInfo = makeCompilerInfo();
136
137 private String label = null;
138
139
140 private DocumentNumberAllocator documentNumberAllocator = new DocumentNumberAllocator();
141 /*@Nullable*/
142 private transient Debugger debugger = null;
143 private String defaultLanguage = Locale.getDefault().getLanguage();
144
145
146 private String defaultCountry = Locale.getDefault().getCountry();
147 private Properties defaultOutputProperties = new Properties();
148 private transient DynamicLoader dynamicLoader = new DynamicLoader();
149
150 private IntSet enabledProperties = new IntHashSet(64);
151
152 private List<ExternalObjectModel> externalObjectModels = new ArrayList<>(4);
153
154 private DocumentPool globalDocumentPool = new DocumentPool();
155 private IntegratedFunctionLibrary integratedFunctionLibrary = new IntegratedFunctionLibrary();
156 private transient LocalizerFactory localizerFactory;
157 private NamePool namePool = new NamePool();
158
159 protected Optimizer optimizer = null;
160
161
162 private SerializerFactory serializerFactory = new SerializerFactory(this);
163 private volatile ConcurrentLinkedQueue<XMLReader> sourceParserPool = new ConcurrentLinkedQueue<>();
164 private volatile ConcurrentLinkedQueue<XMLReader> styleParserPool = new ConcurrentLinkedQueue<>();
165 private String sourceParserClass;
166 private transient SourceResolver sourceResolver = this;
167 private transient Logger traceOutput = new StandardLogger();
168 private ModuleURIResolver standardModuleURIResolver = Version.platform.makeStandardModuleURIResolver(this);
169 private String styleParserClass;
170 private final StandardURIResolver systemURIResolver = new StandardURIResolver(this);
171 private UnparsedTextURIResolver unparsedTextURIResolver = new StandardUnparsedTextResolver();
172
173 private transient XPathContext theConversionContext = null;
174 private ConversionRules theConversionRules = null;
175 private transient TraceListener traceListener = null;
176 private String traceListenerClass = null;
177 private String traceListenerOutput = null;
178 private String defaultRegexEngine = "S";
179 protected transient TypeHierarchy typeHierarchy;
180 private TypeChecker typeChecker = new TypeChecker();
181 private TypeChecker10 typeChecker10 = new TypeChecker10();
182
183 private transient URIResolver uriResolver;
184 protected FunctionLibraryList builtInExtensionLibraryList;
185 protected int xsdVersion = XSD11;
186 private int xmlVersion = XML10;
187 private int xpathVersionForXsd = 20;
188 private int xpathVersionForXslt = 31;
189 // Plug-in to allow media queries in an xml-stylesheet processing instruction to be evaluated
190 private Comparator<String> mediaQueryEvaluator = (o1, o2) -> 0;
191 private Map<String, String> fileExtensions = new HashMap<>();
192 private Map<String, ResourceFactory> resourceFactoryMapping = new HashMap<>();
193 private Map<String, FunctionAnnotationHandler> functionAnnotationHandlers = new HashMap<>();
194 protected int byteCodeThreshold = 100;
195 private int regexBacktrackingLimit = 10000000;
196
197 private TreeStatistics treeStatistics = new TreeStatistics();
198
199 /**
200 * Constant indicating that the processor should take the recovery action
201 * when a recoverable error occurs, with no warning message.
202 */
203 public static final int RECOVER_SILENTLY = 0;
204 /**
205 * Constant indicating that the processor should produce a warning
206 * when a recoverable error occurs, and should then take the recovery
207 * action and continue.
208 */
209 public static final int RECOVER_WITH_WARNINGS = 1;
210 /**
211 * Constant indicating that when a recoverable error occurs, the
212 * processor should not attempt to take the defined recovery action,
213 * but should terminate with an error.
214 */
215 public static final int DO_NOT_RECOVER = 2;
216
217 /**
218 * Constant indicating the XML Version 1.0
219 */
220
221 public static final int XML10 = 10;
222
223 /**
224 * Constant indicating the XML Version 1.1
225 */
226
227 public static final int XML11 = 11;
228
229 /**
230 * Constant indicating that the host language is XSLT
231 */
232 public static final int XSLT = 50;
233
234 /**
235 * Constant indicating that the host language is XQuery
236 */
237 public static final int XQUERY = 51;
238
239 /**
240 * Constant indicating that the "host language" is XML Schema
241 */
242 public static final int XML_SCHEMA = 52;
243
244 /**
245 * Constant indicating that the host language is Java: that is, this is a free-standing
246 * Java application with no XSLT or XQuery content
247 */
248 public static final int JAVA_APPLICATION = 53;
249
250 /**
251 * Constant indicating that the host language is XPATH itself - that is, a free-standing XPath environment
252 */
253 public static final int XPATH = 54;
254
255 /**
256 * Language versions for XML Schema
257 */
258 public static final int XSD10 = 10;
259 public static final int XSD11 = 11;
260
261
262 /**
263 * Create a non-schema-aware configuration object with default settings for all options.
264 *
265 * @since 8.4
266 */
267
268 public Configuration() {
269 init();
270 }
271
272 /**
273 * Factory method to create a Configuration, of the class defined using conditional
274 * compilation tags when compiling this version of Saxon: that is,
275 * the type of Configuration appropriate to the edition of the software
276 * being used. This method does not check that the Configuration is licensed.
277 *
278 * @return a Configuration object of the class appropriate to the Saxon edition in use.
279 * @since 9.2
280 */
281
282 public static Configuration newConfiguration() {
283 Class<? extends Configuration> configurationClass = Configuration.class;
284 //#if PE==true
285 configurationClass = com.saxonica.config.ProfessionalConfiguration.class;
286 //#endif
287 //#if EE==true
288 configurationClass = com.saxonica.config.EnterpriseConfiguration.class;
289 //#endif
290 try {
291 return configurationClass.newInstance();
292 } catch (Exception e) {
293 e.printStackTrace();
294 throw new RuntimeException("Cannot instantiate a Configuration", e);
295 }
296 }
297
298 /**
299 * Read a resource file issued with the Saxon product
300 *
301 * @param filename the filename of the file to be read
302 * @param messages List to be populated with messages in the event of failure
303 * @param loaders List to be populated with the ClassLoader that succeeded in loading the resource
304 * @return an InputStream for reading the file/resource
305 */
306
307 /*@Nullable*/
308 public static InputStream locateResource(String filename, List<String> messages, List<ClassLoader> loaders) {
309 filename = "net/sf/saxon/data/" + filename;
310 ClassLoader loader = null;
311 try {
312 loader = Thread.currentThread().getContextClassLoader();
313 } catch (Exception err) {
314 messages.add("Failed to getContextClassLoader() - continuing\n");
315 }
316
317 InputStream in = null;
318
319 if (loader != null) {
320 URL u = loader.getResource(filename);
321 in = loader.getResourceAsStream(filename);
322 if (in == null) {
323 messages.add("Cannot read " + filename + " file located using ClassLoader " +
324 loader + " - continuing\n");
325 }
326 }
327
328 if (in == null) {
329 loader = Configuration.class.getClassLoader();
330 if (loader != null) {
331 in = loader.getResourceAsStream(filename);
332 if (in == null) {
333 messages.add("Cannot read " + filename + " file located using ClassLoader " +
334 loader + " - continuing\n");
335 }
336 }
337 }
338
339 if (in == null) {
340 // Means we're in a very strange class-loading environment, things are getting desperate
341 URL url = ClassLoader.getSystemResource(filename);
342 if (url != null) {
343 try {
344 in = url.openStream();
345 } catch (IOException ioe) {
346 messages.add("IO error " + ioe.getMessage() +
347 " reading " + filename + " located using getSystemResource(): using defaults");
348 in = null;
349 }
350 }
351 }
352 loaders.add(loader);
353 return in;
354
355 }
356
357 /**
358 * Read a resource file issued with the Saxon product, returning a StreamSource with bound systemId
359 * This means it can be an XSLT stylesheet which uses inclusions etc.
360 *
361 * @param filename the filename of the file to be read
362 * @param messages List to be populated with messages in the event of failure
363 * @param loaders List to be populated with the ClassLoader that succeeded in loading the resource
364 * @return a StreamSource for reading the file/resource, with URL set appropriately
365 */
366
367 /*@Nullable*/
368 public static StreamSource locateResourceSource(String filename, List<String> messages, List<ClassLoader> loaders) {
369 ClassLoader loader = null;
370 try {
371 loader = Thread.currentThread().getContextClassLoader();
372 } catch (Exception err) {
373 messages.add("Failed to getContextClassLoader() - continuing\n");
374 }
375
376 InputStream in = null;
377 URL url = null;
378 if (loader != null) {
379 url = loader.getResource(filename);
380 in = loader.getResourceAsStream(filename);
381 if (in == null) {
382 messages.add("Cannot read " + filename + " file located using ClassLoader " +
383 loader + " - continuing\n");
384 }
385 }
386
387 if (in == null) {
388 loader = Configuration.class.getClassLoader();
389 if (loader != null) {
390 in = loader.getResourceAsStream(filename);
391 if (in == null) {
392 messages.add("Cannot read " + filename + " file located using ClassLoader " +
393 loader + " - continuing\n");
394 }
395 }
396 }
397
398
399 loaders.add(loader);
400 return new StreamSource(in, url.toString());
401
402 }
403
404 /**
405 * Factory method to construct a Configuration object by reading a configuration file.
406 *
407 * @param source Source object containing the configuration file
408 * @return the resulting Configuration
409 * @throws net.sf.saxon.trans.XPathException if the configuration file cannot be read
410 * or is invalid
411 */
412
413 public static Configuration readConfiguration(Source source) throws XPathException {
414 Configuration tempConfig = newConfiguration();
415 return tempConfig.readConfigurationFile(source);
416 }
417
418 /**
419 * Factory method to construct a Configuration object by reading a configuration file.
420 * This version of the method creates a configuration that is "compatible" with the
421 * supplied configuration, in that it shares the same NamePool and DocumentNumberAllocator,
422 * and also the same licensing details. (This is used by fn:transform)
423 *
424 * @param source Source object containing the configuration file
425 * @param baseConfiguration an existing configuration whose NamePool and DocumentNumberAllocator
426 * will be used in the new Configuration
427 * @return the resulting Configuration
428 * @throws net.sf.saxon.trans.XPathException if the configuration file cannot be read
429 * or is invalid
430 */
431
432 public static Configuration readConfiguration(Source source, Configuration baseConfiguration) throws XPathException {
433 Configuration tempConfig = newConfiguration();
434 return tempConfig.readConfigurationFile(source, baseConfiguration);
435 }
436
437 /**
438 * Instantiate a Configuration object with a given class name
439 * @param className the class name
440 * @param classLoader the class loader to be used
441 * @return a Configuration of the required class
442 * @throws ClassNotFoundException if the class is not found
443 * @throws InstantiationException if the class cannot be instantiated
444 * @throws IllegalAccessException if the class is not accessible
445 */
446
447 public static Configuration instantiateConfiguration(String className, ClassLoader classLoader) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
448 Class theClass;
449 ClassLoader loader = classLoader;
450 if (loader == null) {
451 try {
452 loader = Thread.currentThread().getContextClassLoader();
453 } catch (Exception err) {
454 System.err.println("Failed to getContextClassLoader() - continuing");
455 }
456 }
457 if (loader != null) {
458 try {
459 theClass = loader.loadClass(className);
460 } catch (Exception ex) {
461 theClass = Class.forName(className);
462 }
463 } else {
464 theClass = Class.forName(className);
465 }
466 return (Configuration) theClass.newInstance();
467 }
468
469 /**
470 * Ask if Java is being run with assertions enabled (-ea option)
471 * @return true if the -ea option is set
472 */
473
474 public static boolean isAssertionsEnabled() {
475 // Highly devious logic here. If assertions are enabled, the assertion is false, and a deliberate side-effect
476 // of evaluating the assertion is that assertsEnabled is set to true. If assertions are not enabled, the assert
477 // statement is not executed, so assertsEnabled is left as false.
478 boolean assertsEnabled = false;
479 //noinspection AssertWithSideEffects
480 assert assertsEnabled = true;
481 return assertsEnabled;
482 }
483
484
485 /**
486 * Read the configuration file an construct a new Configuration (the real one)
487 *
488 * @param source the source of the configuration file
489 * @return the Configuration that will be used for real work
490 * @throws XPathException if the configuration file cannot be read or is invalid
491 */
492
493 protected Configuration readConfigurationFile(Source source) throws XPathException {
494 return new ConfigurationReader().makeConfiguration(source);
495 }
496
497 protected Configuration readConfigurationFile(Source source, Configuration baseConfiguration) throws XPathException {
498 ConfigurationReader reader = makeConfigurationReader();
499 reader.setBaseConfiguration(baseConfiguration);
500 return reader.makeConfiguration(source);
501 }
502
503 protected ConfigurationReader makeConfigurationReader() {
504 return new ConfigurationReader();
505 }
506
507
508 protected void init() {
509 Version.platform.initialize(this);
510 defaultXsltCompilerInfo.setURIResolver(getSystemURIResolver());
511 StandardEntityResolver resolver = new StandardEntityResolver();
512 resolver.setConfiguration(this);
513 defaultParseOptions.setEntityResolver(resolver);
514 internalSetBooleanProperty(Feature.PREFER_JAXP_PARSER, true);
515 internalSetBooleanProperty(Feature.ALLOW_EXTERNAL_FUNCTIONS, true);
516 internalSetBooleanProperty(Feature.DISABLE_XSL_EVALUATE, true);
517 //internalSetBooleanProperty(FeatureKeys.STABLE_COLLECTION_URI, true);
518
519
520 registerFileExtension("xml", "application/xml");
521 registerFileExtension("html", "application/html");
522 registerFileExtension("atom", "application/atom");
523 registerFileExtension("xsl", "application/xml+xslt");
524 registerFileExtension("xslt", "application/xml+xslt");
525 registerFileExtension("xsd", "application/xml+xsd");
526 registerFileExtension("txt", "text/plain");
527 registerFileExtension("MF", "text/plain");
528 registerFileExtension("class", "application/java");
529 registerFileExtension("json", "application/json");
530 registerFileExtension("", "application/binary");
531
532 registerMediaType("application/xml", XmlResource.FACTORY);
533 registerMediaType("text/xml", XmlResource.FACTORY);
534 registerMediaType("application/html", XmlResource.FACTORY);
535 registerMediaType("text/html", XmlResource.FACTORY);
536 registerMediaType("application/atom", XmlResource.FACTORY);
537 registerMediaType("application/xml+xslt", XmlResource.FACTORY);
538 registerMediaType("application/xml+xsd", XmlResource.FACTORY);
539 registerMediaType("application/rdf+xml", XmlResource.FACTORY);
540 registerMediaType("text/plain", UnparsedTextResource.FACTORY);
541 registerMediaType("application/java", BinaryResource.FACTORY);
542 registerMediaType("application/binary", BinaryResource.FACTORY);
543 registerMediaType("application/json", JSONResource.FACTORY);
544
545 registerFunctionAnnotationHandler(new XQueryFunctionAnnotationHandler());
546 }
547
548 /**
549 * Static method to instantiate a professional or enterprise configuration.
550 * <p>This method fails if the specified configuration class cannot be loaded,
551 * but it does not check whether there is a license available.
552 *
553 * @param classLoader - the class loader to be used. If null, the context class loader for the current
554 * thread is used.
555 * @param className - the name of the configuration class. Defaults to
556 * "com.saxonica.config.ProfessionalConfiguration" if null is supplied. This allows an assembly
557 * qualified name to be supplied under .NET. The class, once instantiated, must be an instance
558 * of Configuration.
559 * @return the new ProfessionalConfiguration or EnterpriseConfiguration
560 * @throws RuntimeException if the required Saxon edition cannot be loaded
561 * @since 9.2 (renamed from makeSchemaAwareConfiguration)
562 */
563
564 public static Configuration makeLicensedConfiguration(ClassLoader classLoader, /*@Nullable*/ String className)
565 throws RuntimeException {
566 if (className == null) {
567 className = "com.saxonica.config.ProfessionalConfiguration";
568 }
569 try {
570 return instantiateConfiguration(className, classLoader);
571 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
572 throw new RuntimeException(e);
573 }
574 }
575
576 public void importLicenseDetails(Configuration config) {
577 // No action for an HE configuration
578 }
579
580 /**
581 * Get the edition code identifying this configuration: "HE", "PE" or "EE"
582 *
583 * @return the code identifying the Saxon edition associated with this configuration
584 */
585
586 public String getEditionCode() {
587 return "HE";
588 }
589
590 /**
591 * Marker interface to represent an API that is provided as a layer on top of this
592 * {@code Configuration}
593 */
594
595 public interface ApiProvider {}
596
597 /**
598 * Save the ApiProvider object that owns this {@code Configuration} in the relevant API.
599 * <p>Note: it is possible to use multiple APIs over the same {@code Configuration}. This mechanism
600 * is only capable of holding one of these, and is therefore only really useful in cases where
601 * the API in use is homogeneous.</p>
602 *
603 * @param processor This can be any ApiProvider, but it is typically one of the
604 * following:
605 * <ul>
606 * <li>When using the Java s9api interface, the <code>net.sf.saxon.s9api.Processor</code></li>
607 * <li>When using the .NET interface, the <code>Saxon.Api.Processor</code></li>
608 * <li>When using the JAXP transformation interface, the JAXP <code>TransformerFactory</code></li>
609 * <li>When using the JAXP XPath interface, the JAXP <code>XPathFactory</code></li>
610 * <li>When using the JAXP Schema interface, the JAXP <code>SchemaFactory</code></li>
611 * <li>When using XQJ, the <code>XQDataSource</code></li>
612 * </ul>
613 * @since 9.2. Changed in 9.9 to require an {@link ApiProvider} rather than any Object.
614 */
615
616 public void setProcessor(ApiProvider processor) {
617 this.apiProcessor = processor;
618 }
619
620 /**
621 * Get the Processor object that created this Configuration in the relevant API.
622 * <p>The main purpose of this interface is to allow extension functions called from
623 * a stylesheet or query to get access to the originating processor. This is particularly
624 * useful when methods are static as there is then limited scope for passing data from the
625 * calling application to the code of the extension function.</p>
626 *
627 * @return the processor that was supplied to the {@link #setProcessor(ApiProvider)} method, or null
628 * if this method has not been called. In practice this property is used to hold one of the
629 * following:
630 * <ul>
631 * <li>When using the Java s9api interface, the <code>net.sf.saxon.s9api.Processor</code></li>
632 * <li>When using the .NET interface, the <code>Saxon.Api.Processor</code></li>
633 * <li>When using the JAXP transformation interface, the JAXP <code>TransformerFactory</code></li>
634 * <li>When using the JAXP XPath interface, the JAXP <code>XPathFactory</code></li>
635 * <li>When using the JAXP Schema interface, the JAXP <code>SchemaFactory</code></li>
636 * <li>When using XQJ, the <code>XQDataSource</code></li>
637 * </ul>
638 * @since 9.2. Changed in 9.9 to return an {@link ApiProvider} rather than any Object.
639 */
640
641 /*@Nullable*/
642 public ApiProvider getProcessor() {
643 return apiProcessor;
644 }
645
646 /**
647 * Get a message used to identify this product when a transformation is run using the -t option
648 *
649 * @return A string containing both the product name and the product
650 * version
651 * @since 8.4
652 */
653
654 public String getProductTitle() {
655 return "Saxon-" + getEditionCode() + " " + Version.getProductVersion() +
656 Version.platform.getPlatformSuffix() + " from Saxonica";
657 }
658
659 /**
660 * Check whether a particular feature is licensed, with a fatal error if it is not
661 *
662 * @param feature the feature in question, identified by a constant in class {@link LicenseFeature}
663 * @param name the name of the feature for use in diagnostics
664 * @param localLicenseId identifies an embedded license, or -1 if not applicable
665 * @throws LicenseException if the feature is not licensed. This is a RunTimeException, so it will normally be fatal.
666 */
667
668 public void checkLicensedFeature(int feature, String name, int localLicenseId) throws LicenseException {
669 String require = feature == LicenseFeature.PROFESSIONAL_EDITION ? "PE" : "EE";
670 String message = "Requested feature (" + name + ") requires Saxon-" + require;
671 if (!Version.softwareEdition.equals("HE")) {
672 message += ". You are using Saxon-" + Version.softwareEdition + " software, but the Configuration is an instance of " +
673 getClass().getName() + "; to use this feature you need to create an instance of " +
674 (feature == LicenseFeature.PROFESSIONAL_EDITION ?
675 "com.saxonica.config.ProfessionalConfiguration" :
676 "com.saxonica.config.EnterpriseConfiguration");
677 }
678 throw new LicenseException(message, LicenseException.WRONG_CONFIGURATION);
679 }
680
681 /**
682 * Instruct Saxon to run as if no license is available. This method is provided for testing purposes,
683 * so that tests with and without a license can be run without making changes to the classpath.
684 */
685
686 public void disableLicensing() {
687 }
688
689 /**
690 * Ask whether a particular feature is enabled by an embedded license (embedded in a SEF file)
691 * @param localLicenseId the identifier of the embedded license
692 * @param feature the feature in question, identified by a constant in class {@link net.sf.saxon.Configuration.LicenseFeature}
693 *
694 * @return true if the embedded license exists and enables the requested feature
695 */
696
697 public boolean isFeatureAllowedBySecondaryLicense(int localLicenseId, int feature) {
698 return false;
699 }
700
701 /**
702 * Determine if a particular feature is licensed.
703 *
704 * @param feature the feature in question, identified by a constant in class {@link net.sf.saxon.Configuration.LicenseFeature}
705 * @return true if the feature is licensed, false if it is not.
706 */
707
708 public boolean isLicensedFeature(int feature) {
709 // changing this to true will do no good; it will cause Saxon to attempt to use the unavailable feature, rather than
710 // recovering from its absence.
711 return false;
712 }
713
714 /**
715 * Get the value of a named license feature
716 *
717 * @param name the name of the feature
718 * @return the value of the feature if present, or null otherwise
719 */
720
721 public String getLicenseFeature(String name) {
722 return null;
723 }
724
725 /**
726 * Display a message about the license status
727 */
728
729 public void displayLicenseMessage() {
730 }
731
732 /**
733 * Register a local license file (for use within a single transformation (etc))
734 *
735 * @param dmk the license in encoded form
736 * @return an integer identifying this license uniquely within the configuration, or -1 if not accepted
737 */
738
739 public int registerLocalLicense(String dmk) {
740 return -1;
741 }
742
743 /**
744 * Set the DynamicLoader to be used. By default an instance of {@link DynamicLoader} is used
745 * for all dynamic loading of Java classes. This method allows the actions of the standard
746 * DynamicLoader to be overridden
747 *
748 * @param dynamicLoader the DynamicLoader to be used by this Configuration
749 */
750
751 public void setDynamicLoader(DynamicLoader dynamicLoader) {
752 this.dynamicLoader = dynamicLoader;
753 }
754
755 /**
756 * Get the DynamicLoader used by this Configuration. By default the standard system-supplied
757 * dynamic loader is returned.
758 *
759 * @return the DynamicLoader in use - either a user-supplied DynamicLoader, or the standard one
760 * supplied by the system.
761 */
762
763 public DynamicLoader getDynamicLoader() {
764 return dynamicLoader;
765 }
766
767 /**
768 * Load a class using the class name provided.
769 * Note that the method does not check that the object is of the right class.
770 * <p>This method is intended for internal use only. The call is delegated to the
771 * <code>DynamicLoader</code>, which may be overridden by a user-defined <code>DynamicLoader</code>.</p>
772 *
773 * @param className A string containing the name of the
774 * class, for example "com.microstar.sax.LarkDriver"
775 * @param tracing true if diagnostic tracing is required
776 * @param classLoader The ClassLoader to be used to load the class, or null to
777 * use the ClassLoader selected by the DynamicLoader.
778 * @return an instance of the class named, or null if it is not
779 * loadable.
780 * @throws XPathException if the class cannot be loaded.
781 */
782
783 public Class getClass(String className, boolean tracing, /*@Nullable*/ ClassLoader classLoader) throws XPathException {
784 return dynamicLoader.getClass(className, tracing ? traceOutput : null, classLoader);
785 }
786
787 /**
788 * Instantiate a class using the class name provided.
789 * Note that the method does not check that the object is of the right class.
790 * <p>This method is intended for internal use only. The call is delegated to the
791 * <code>DynamicLoader</code>, which may be overridden by a user-defined <code>DynamicLoader</code>.</p>
792 * <p>Diagnostic output is produced if the option "isTiming" is set (corresponding to the -t option on
793 * the command line).</p>
794 *
795 * @param className A string containing the name of the
796 * class, for example "com.microstar.sax.LarkDriver"
797 * @param classLoader The ClassLoader to be used to load the class, or null to
798 * use the ClassLoader selected by the DynamicLoader.
799 * @return an instance of the class named, or null if it is not
800 * loadable.
801 * @throws XPathException if the class cannot be loaded.
802 */
803
804 public Object getInstance(String className, /*@Nullable*/ ClassLoader classLoader) throws XPathException {
805 return dynamicLoader.getInstance(className, isTiming() ? traceOutput : null, classLoader);
806 }
807
808 /**
809 * Get the URIResolver used in this configuration
810 *
811 * @return the URIResolver. If no URIResolver has been set explicitly, the
812 * default URIResolver is used.
813 * @since 8.4
814 */
815
816 public URIResolver getURIResolver() {
817 if (uriResolver == null) {
818 return systemURIResolver;
819 }
820 return uriResolver;
821 }
822
823 /**
824 * Set the URIResolver to be used in this configuration. This will be used to
825 * resolve the URIs used statically (e.g. by xsl:include) and also the URIs used
826 * dynamically by functions such as document() and doc(). Note that the URIResolver
827 * does not resolve the URI in the sense of RFC 2396 (which is also the sense in which
828 * the resolve-uri() function uses the term): rather it dereferences an absolute URI
829 * to obtain an actual resource, which is returned as a Source object.
830 *
831 * @param resolver The URIResolver to be used.
832 * @since 8.4
833 */
834
835 public void setURIResolver(URIResolver resolver) {
836 uriResolver = resolver;
837 if (resolver instanceof StandardURIResolver) {
838 ((StandardURIResolver) resolver).setConfiguration(this);
839 }
840 defaultXsltCompilerInfo.setURIResolver(resolver);
841 }
842
843 /**
844 * Set the URIResolver to a URI resolver that allows query parameters after the URI,
845 * and in the case of Saxon-EE, that inteprets the file extension .ptree
846 */
847
848 public void setParameterizedURIResolver() {
849 getSystemURIResolver().setRecognizeQueryParameters(true);
850 }
851
852 /**
853 * Get the system-defined URI Resolver. This is used when the user-defined URI resolver
854 * returns null as the result of the resolve() method
855 *
856 * @return the system-defined URI resolver
857 */
858
859 public StandardURIResolver getSystemURIResolver() {
860 return systemURIResolver;
861 }
862
863 /**
864 * Create an instance of a URIResolver with a specified class name.
865 * Note that this method does not register the URIResolver with this Configuration.
866 *
867 * @param className The fully-qualified name of the URIResolver class
868 * @return The newly created URIResolver
869 * @throws TransformerException if the requested class does not
870 * implement the javax.xml.transform.URIResolver interface
871 */
872 public URIResolver makeURIResolver(String className) throws TransformerException {
873 Object obj = dynamicLoader.getInstance(className, null);
874 if (obj instanceof StandardURIResolver) {
875 ((StandardURIResolver) obj).setConfiguration(this);
876 }
877 if (obj instanceof URIResolver) {
878 return (URIResolver) obj;
879 }
880 throw new XPathException("Class " + className + " is not a URIResolver");
881 }
882
883 /**
884 * Get the ErrorListener used in this configuration. If no ErrorListener
885 * has been supplied explicitly, the default ErrorListener is used.
886 *
887 * @return the ErrorListener. Note that this is not necessarily the ErrorListener that was supplied
888 * to the {@link #setErrorListener(ErrorListener)} method; if that was not an {@link UnfailingErrorListener},
889 * it will have been wrapped in a {@link DelegatingErrorListener}, and it is the DelegatingErrorListener
890 * that this method returns.
891 * @since 8.4
892 */
893
894 public UnfailingErrorListener getErrorListener() {
895 UnfailingErrorListener listener = defaultParseOptions.getErrorListener();
896 if (listener == null) {
897 listener = new StandardErrorListener();
898 ((StandardErrorListener) listener).setLogger(traceOutput);
899 ((StandardErrorListener) listener).setRecoveryPolicy(defaultXsltCompilerInfo.getRecoveryPolicy());
900 defaultParseOptions.setErrorListener(listener);
901 }
902 return listener;
903 }
904
905 /**
906 * Set the ErrorListener to be used in this configuration. The ErrorListener
907 * is informed of all static and dynamic errors detected, and can decide whether
908 * run-time warnings are to be treated as fatal.
909 *
910 * @param listener the ErrorListener to be used
911 * @since 8.4
912 */
913
914 public void setErrorListener(ErrorListener listener) {
915 defaultParseOptions.setErrorListener(listener);
916 getDefaultXsltCompilerInfo().setErrorListener(listener); // bug 2215
917 getDefaultStaticQueryContext().setErrorListener(listener);
918 }
919
920 public Logger getLogger() {
921 return traceOutput;
922 }
923
924
925 /**
926 * Report a fatal error
927 *
928 * @param err the exception to be reported
929 */
930
931 public void reportFatalError(XPathException err) {
932 if (!err.hasBeenReported()) {
933 getErrorListener().fatalError(err);
934 err.setHasBeenReported(true);
935 }
936 }
937
938 /**
939 * Set the standard error output to be used in all cases where no more specific destination
940 * is defined. This defaults to System.err.
941 *
942 * @param out the stream to be used for error output where no more specific destination
943 * has been supplied. The caller is responsible for closing this stream after use
944 * (if necessary).
945 * @since 9.3
946 */
947
948 public void setStandardErrorOutput(PrintStream out) {
949 if (!(traceOutput instanceof StandardLogger)) {
950 traceOutput = new StandardLogger();
951 }
952 ((StandardLogger) traceOutput).setPrintStream(out);
953 }
954
955
956 /**
957 * Register a new logger to be used in the Saxon event logging mechanism
958 *
959 * @param logger the Logger to be used as default. The caller is responsible for
960 * ensuring that this is closed after use (if necessary), which can
961 * be achieved by calling either {@link Logger#close} or
962 * {@link Configuration#close};
963 * @since 9.6
964 */
965 public void setLogger(Logger logger) {
966 traceOutput = logger;
967 }
968
969
970 /**
971 * Get the standard error output to be used in all cases where no more specific destination
972 * is defined. This defaults to System.err.
973 *
974 * @return the stream to be used for error output where no more specific destination
975 * has been supplied
976 * @since 9.3
977 */
978
979 public /*@NotNull*/ PrintStream getStandardErrorOutput() {
980 if (traceOutput instanceof StandardLogger) {
981 return ((StandardLogger) traceOutput).getPrintStream();
982 } else {
983 return null;
984 }
985 }
986
987
988 /**
989 * Set the XML version to be used by default for validating characters and names.
990 * Note that source documents specifying xml version="1.0" or "1.1" are accepted
991 * regardless of this setting. The effect of this switch is to change the validation
992 * rules for types such as Name and NCName, to change the meaning of \i and \c in
993 * regular expressions, and to determine whether the serializer allows XML 1.1 documents
994 * to be constructed.
995 *
996 * @param version one of the constants XML10 or XML11
997 * @since 8.6
998 */
999
1000 public void setXMLVersion(int version) {
1001 xmlVersion = version;
1002 theConversionRules = null;
1003 }
1004
1005 /**
1006 * Get the XML version to be used by default for validating characters and names
1007 *
1008 * @return one of the constants {@link #XML10} or {@link #XML11}
1009 * @since 8.6
1010 */
1011
1012 public int getXMLVersion() {
1013 return xmlVersion;
1014 }
1015
1016 /**
1017 * Get the parsing and document building options defined in this configuration
1018 *
1019 * @return the parsing and document building options. Note that any changes to this
1020 * ParseOptions object will be reflected back in the Configuration; if changes are to be made
1021 * locally, the caller should create a copy.
1022 * @since 9.2
1023 */
1024
1025 public ParseOptions getParseOptions() {
1026 return defaultParseOptions;
1027 }
1028
1029 /**
1030 * Set a comparator which can be used to assess whether the media pseudo-attribute
1031 * in an xml-stylesheet processing instruction matches the media requested in the API
1032 * for the transformation
1033 *
1034 * @param comparator a comparator which returns 0 (equals) when the first argument of the compare
1035 * method is the value of the media attribute in the xml-stylesheet processing
1036 * instruction, and the second argument is the value of the required media given
1037 * in the calling API. The default implementation always returns 0, indicating that
1038 * the media pseudo-attribute is ignored. An alternative implementation, consistent
1039 * with previous Saxon releases, would be compare the strings for equality. A fully
1040 * conformant implementation could implement the syntax and semantics of media queries
1041 * as defined in CSS 3.
1042 */
1043 public void setMediaQueryEvaluator(Comparator<String> comparator) {
1044 this.mediaQueryEvaluator = comparator;
1045 }
1046
1047 /**
1048 * Get a comparator which can be used to assess whether the media pseudo-attribute
1049 * in an xml-stylesheet processing instruction matches the media requested in the API
1050 * for the transformation
1051 *
1052 * @return a comparator which returns 0 (equals) when the first argument of the compare
1053 * method is the value of the media attribute in the xml-stylesheet processing
1054 * instruction, and the second argument is the value of the required media given
1055 * in the calling API. The default implementation always returns 0, indicating that
1056 * the media pseudo-attribute is ignored. An alternative implementation, consistent
1057 * with previous Saxon releases, would be compare the strings for equality. A fully
1058 * conformant implementation could implement the syntax and semantics of media queries
1059 * as defined in CSS 3.
1060 */
1061
1062 public Comparator<String> getMediaQueryEvaluator() {
1063 return mediaQueryEvaluator;
1064 }
1065
1066 /**
1067 * Set the conversion rules to be used to convert between atomic types. By default,
1068 * The rules depend on the versions of XML and XSD in use by the configuration.
1069 *
1070 * @param rules the conversion rules to be used
1071 * @since 9.3
1072 */
1073
1074 public void setConversionRules(/*@NotNull*/ ConversionRules rules) {
1075 this.theConversionRules = rules;
1076 }
1077
1078 /**
1079 * Get the conversion rules used to convert between atomic types. By default, the rules depend on the versions
1080 * of XML and XSD in use by the configuration
1081 *
1082 * @return the appropriate conversion rules
1083 * @since 9.3
1084 */
1085
1086 /*@NotNull*/
1087 public ConversionRules getConversionRules() {
1088 if (theConversionRules == null) {
1089 synchronized(this) {
1090 ConversionRules cv = new ConversionRules();
1091 cv.setTypeHierarchy(getTypeHierarchy());
1092 cv.setNotationSet(this);
1093 if (xsdVersion == XSD10) {
1094 cv.setStringToDoubleConverter(StringToDouble.getInstance());
1095 cv.setURIChecker(StandardURIChecker.getInstance());
1096 // In XSD 1.1, there is no checking
1097 } else {
1098 cv.setStringToDoubleConverter(StringToDouble11.getInstance());
1099 }
1100 cv.setAllowYearZero(xsdVersion != XSD10);
1101 return theConversionRules = cv;
1102 }
1103 } else {
1104 return theConversionRules;
1105 }
1106 }
1107
1108 /**
1109 * Get the version of XML Schema to be used
1110 *
1111 * @return {@link #XSD10} or {@link #XSD11}
1112 * @since 9.2
1113 */
1114
1115 public int getXsdVersion() {
1116 return xsdVersion;
1117 }
1118
1119 /**
1120 * Get an XPathContext object with sufficient capability to perform comparisons and conversions
1121 *
1122 * @return a dynamic context for performing conversions
1123 */
1124
1125 /*@NotNull*/
1126 public XPathContext getConversionContext() {
1127 if (theConversionContext == null) {
1128 theConversionContext = new EarlyEvaluationContext(this);
1129 }
1130 return theConversionContext;
1131 }
1132
1133 /**
1134 * Get an IntPredicate that tests whether a given character is valid in the selected
1135 * version of XML
1136 *
1137 * @return an IntPredicate whose matches() method tests a character for validity against
1138 * the version of XML (1.0 or 1.1) selected by this configuration
1139 */
1140
1141 public IntPredicate getValidCharacterChecker() {
1142 if (xmlVersion == XML10) {
1143 return XMLCharacterData::isValid10;
1144 } else {
1145 return XMLCharacterData::isValid11;
1146 }
1147 }
1148
1149 /**
1150 * Get the Tree Model used by this Configuration. This is either
1151 * {@link Builder#LINKED_TREE}, {@link Builder#TINY_TREE}, or {@link Builder#TINY_TREE_CONDENSED}.
1152 * The default is <code>Builder.TINY_TREE</code>.
1153 *
1154 * @return the selected Tree Model
1155 * @since 8.4 (Condensed tinytree added in 9.2)
1156 */
1157
1158 public int getTreeModel() {
1159 return defaultParseOptions.getModel().getSymbolicValue();
1160 }
1161
1162 /**
1163 * Set the Tree Model used by this Configuration. This is either
1164 * {@link Builder#LINKED_TREE} or {@link Builder#TINY_TREE}, or {@link Builder#TINY_TREE_CONDENSED}.
1165 * The default is <code>Builder.TINY_TREE</code>.
1166 *
1167 * @param treeModel the integer constant representing the selected Tree Model
1168 * @since 8.4 (Condensed tinytree added in 9.2)
1169 */
1170
1171 public void setTreeModel(int treeModel) {
1172 defaultParseOptions.setModel(TreeModel.getTreeModel(treeModel));
1173 }
1174
1175 /**
1176 * Determine whether source documents will maintain line numbers, for the
1177 * benefit of the saxon:line-number() extension function as well as run-time
1178 * tracing.
1179 *
1180 * @return true if line numbers are maintained in source documents
1181 * @since 8.4
1182 */
1183
1184 public boolean isLineNumbering() {
1185 return defaultParseOptions.isLineNumbering();
1186 }
1187
1188 /**
1189 * Determine whether source documents will maintain line numbers, for the
1190 * benefit of the saxon:line-number() extension function as well as run-time
1191 * tracing.
1192 *
1193 * @param lineNumbering true if line numbers are maintained in source documents
1194 * @since 8.4
1195 */
1196
1197 public void setLineNumbering(boolean lineNumbering) {
1198 defaultParseOptions.setLineNumbering(lineNumbering);
1199 }
1200
1201 /**
1202 * Set whether or not source documents (including stylesheets and schemas) are have
1203 * XInclude processing applied to them, or not. Default is false.
1204 *
1205 * @param state true if XInclude elements are to be expanded, false if not
1206 * @since 8.9
1207 */
1208
1209 public void setXIncludeAware(boolean state) {
1210 defaultParseOptions.setXIncludeAware(state);
1211 }
1212
1213 /**
1214 * Test whether or not source documents (including stylesheets and schemas) are to have
1215 * XInclude processing applied to them, or not
1216 *
1217 * @return true if XInclude elements are to be expanded, false if not
1218 * @since 8.9
1219 */
1220
1221 public boolean isXIncludeAware() {
1222 return defaultParseOptions.isXIncludeAware();
1223 }
1224
1225 /**
1226 * Get the TraceListener used for run-time tracing of instruction execution.
1227 *
1228 * @return the TraceListener that was set using {@link #setTraceListener} if set.
1229 * Otherwise, returns null.
1230 * @since 8.4. Modified in 9.1.
1231 */
1232
1233 /*@Nullable*/
1234 public TraceListener getTraceListener() {
1235 return traceListener;
1236 }
1237
1238
1239 /**
1240 * Get or create the TraceListener used for run-time tracing of instruction execution.
1241 *
1242 * @return If a TraceListener has been set using {@link #setTraceListener(net.sf.saxon.lib.TraceListener)},
1243 * returns that TraceListener. Otherwise, if a TraceListener class has been set using
1244 * {@link #setTraceListenerClass(String)}, returns a newly created instance of that class.
1245 * Otherwise, returns null.
1246 * @throws XPathException if the supplied TraceListenerClass cannot be instantiated as an instance
1247 * of TraceListener
1248 * @since 9.1.
1249 */
1250
1251 /*@Nullable*/
1252 public TraceListener makeTraceListener() throws XPathException {
1253 if (traceListener != null) {
1254 return traceListener;
1255 } else if (traceListenerClass != null) {
1256 try {
1257 return makeTraceListener(traceListenerClass);
1258 } catch (ClassCastException e) {
1259 throw new XPathException(e);
1260 }
1261 } else {
1262 return null;
1263 }
1264 }
1265
1266 /**
1267 * Set the TraceListener to be used for run-time tracing of instruction execution.
1268 * <p>Note: this method should not be used if the Configuration is multithreading. In that situation,
1269 * use {@link #setCompileWithTracing(boolean)} to force stylesheets and queries to be compiled
1270 * with trace code enabled, and use {@link Controller#addTraceListener(net.sf.saxon.lib.TraceListener)} to
1271 * supply a TraceListener at run time.</p>
1272 *
1273 * @param traceListener The TraceListener to be used. If null is supplied, any existing TraceListener is removed
1274 * @since 8.4
1275 */
1276
1277 public void setTraceListener(/*@Nullable*/ TraceListener traceListener) {
1278 this.traceListener = traceListener;
1279 setCompileWithTracing(traceListener != null);
1280 internalSetBooleanProperty(Feature.ALLOW_MULTITHREADING, false);
1281 }
1282
1283 /**
1284 * Set the name of the trace listener class to be used for run-time tracing of instruction
1285 * execution. A new instance of this class will be created for each query or transformation
1286 * that requires tracing. The class must be an instance of {@link TraceListener}.
1287 *
1288 * @param className the name of the trace listener class. If null, any existing trace listener is
1289 * removed from the configuration.
1290 * @throws IllegalArgumentException if the class cannot be instantiated or does not implement
1291 * TraceListener
1292 * @since 9.1. Changed in 9.4 to allow null to be supplied.
1293 */
1294
1295 public void setTraceListenerClass(/*@Nullable*/ String className) {
1296 if (className == null) {
1297 traceListenerClass = null;
1298 setCompileWithTracing(false);
1299 } else {
1300 try {
1301 makeTraceListener(className);
1302 } catch (XPathException err) {
1303 throw new IllegalArgumentException(className + ": " + err.getMessage());
1304 }
1305 this.traceListenerClass = className;
1306 setCompileWithTracing(true);
1307 }
1308 }
1309
1310 /**
1311 * Get the name of the trace listener class to be used for run-time tracing of instruction
1312 * execution. A new instance of this class will be created for each query or transformation
1313 * that requires tracing. The class must be an instance of {@link net.sf.saxon.lib.TraceListener}.
1314 *
1315 * @return the name of the trace listener class, or null if no trace listener class
1316 * has been nominated.
1317 * @since 9.1
1318 */
1319
1320 /*@Nullable*/
1321 @SuppressWarnings({"UnusedDeclaration"})
1322 public String getTraceListenerClass() {
1323 return traceListenerClass;
1324 }
1325
1326 /**
1327 * Set the name of the file to be used for TraceListener output. (By default,
1328 * it is sent to System.err)
1329 *
1330 * @param filename the filename for TraceListener output
1331 * @since 9.8
1332 */
1333
1334 public void setTraceListenerOutputFile(String filename) {
1335 traceListenerOutput = filename;
1336 }
1337
1338 /**
1339 * Get the name of the file to be used for TraceListener output. Returns
1340 * null if no value has been set
1341 *
1342 * @return the filename to be used for TraceListener output, or null
1343 * if none has been set
1344 * @since 9.8
1345 */
1346
1347 public String getTraceListenerOutputFile() {
1348 return traceListenerOutput;
1349 }
1350
1351 /**
1352 * Determine whether compile-time generation of trace code was requested
1353 *
1354 * @return true if compile-time generation of code was requested at the Configuration level.
1355 * Note that tracing can also be requested at the XQueryCompiler or XsltCompiler level.
1356 * @since 8.8
1357 */
1358
1359 public boolean isCompileWithTracing() {
1360 return getBooleanProperty(Feature.COMPILE_WITH_TRACING);
1361 }
1362
1363 /**
1364 * Request compile-time generation of trace code (or not)
1365 *
1366 * @param trace true if compile-time generation of trace code is required
1367 * @since 8.8
1368 */
1369
1370 public void setCompileWithTracing(boolean trace) {
1371 internalSetBooleanProperty(Feature.COMPILE_WITH_TRACING, trace);
1372 if (defaultXsltCompilerInfo != null) {
1373 if (trace) {
1374 defaultXsltCompilerInfo.setCodeInjector(new XSLTTraceCodeInjector());
1375 } else {
1376 defaultXsltCompilerInfo.setCodeInjector(null);
1377 }
1378 }
1379 if (defaultStaticQueryContext != null) {
1380 if (trace) {
1381 defaultStaticQueryContext.setCodeInjector(new TraceCodeInjector());
1382 } else {
1383 defaultStaticQueryContext.setCodeInjector(null);
1384 }
1385 }
1386 }
1387
1388 /**
1389 * Create an instance of a TraceListener with a specified class name
1390 *
1391 * @param className The fully qualified class name of the TraceListener to
1392 * be constructed
1393 * @return the newly constructed TraceListener
1394 * @throws net.sf.saxon.trans.XPathException if the requested class does not
1395 * implement the net.sf.saxon.trace.TraceListener interface
1396 */
1397
1398 public TraceListener makeTraceListener(String className)
1399 throws XPathException {
1400 Object obj = dynamicLoader.getInstance(className, null);
1401 if (obj instanceof TraceListener) {
1402 String destination = getTraceListenerOutputFile();
1403 if (destination != null) {
1404 try {
1405 ((TraceListener) obj).setOutputDestination(new StandardLogger(new PrintStream(destination)));
1406 } catch (FileNotFoundException e) {
1407 throw new XPathException(e);
1408 }
1409 }
1410 return (TraceListener) obj;
1411 }
1412 throw new XPathException("Class " + className + " is not a TraceListener");
1413 }
1414
1415 public BuiltInFunctionSet getXSLT30FunctionSet() {
1416 return XSLT30FunctionSet.getInstance();
1417 }
1418
1419 public BuiltInFunctionSet getUseWhenFunctionSet() {
1420 return UseWhen30FunctionSet.getInstance();
1421 }
1422
1423 public BuiltInFunctionSet getXPath30FunctionSet() {
1424 return XPath30FunctionSet.getInstance();
1425 }
1426
1427 public BuiltInFunctionSet getXPath31FunctionSet() {
1428 return XPath31FunctionSet.getInstance();
1429 }
1430
1431 public BuiltInFunctionSet getXQueryUpdateFunctionSet() {
1432 return null;
1433 }
1434
1435 /**
1436 * Make a function in the "fn" namespace
1437 *
1438 * @param localName the local name of the function
1439 * @param arity the arity of the function
1440 * @return the function
1441 */
1442
1443 public SystemFunction makeSystemFunction(String localName, int arity) {
1444 try {
1445 return getXSLT30FunctionSet().makeFunction(localName, arity);
1446 } catch (XPathException e) {
1447 return null;
1448 }
1449 }
1450
1451 /**
1452 * Register an extension function that is to be made available within any stylesheet, query,
1453 * or XPath expression compiled under the control of this processor. This method
1454 * registers an extension function implemented as an instance of
1455 * {@link net.sf.saxon.lib.ExtensionFunctionDefinition}, using an arbitrary name and namespace.
1456 * This supplements the ability to call arbitrary Java methods using a namespace and local name
1457 * that are related to the Java class and method name.
1458 *
1459 * @param function the object that implements the extension function.
1460 * @since 9.2
1461 */
1462
1463 public void registerExtensionFunction(ExtensionFunctionDefinition function) {
1464 integratedFunctionLibrary.registerFunction(function);
1465 }
1466
1467 /**
1468 * Get the IntegratedFunction library containing integrated extension functions
1469 *
1470 * @return the IntegratedFunctionLibrary
1471 * @since 9.2
1472 */
1473
1474 /*@NotNull*/
1475 public IntegratedFunctionLibrary getIntegratedFunctionLibrary() {
1476 return integratedFunctionLibrary;
1477 }
1478
1479
1480 public FunctionLibraryList getBuiltInExtensionLibraryList() {
1481 if (builtInExtensionLibraryList == null) {
1482 builtInExtensionLibraryList = new FunctionLibraryList();
1483 builtInExtensionLibraryList.addFunctionLibrary(VendorFunctionSetHE.getInstance());
1484 builtInExtensionLibraryList.addFunctionLibrary(MathFunctionSet.getInstance());
1485 builtInExtensionLibraryList.addFunctionLibrary(MapFunctionSet.getInstance());
1486 builtInExtensionLibraryList.addFunctionLibrary(ArrayFunctionSet.getInstance());
1487 builtInExtensionLibraryList.addFunctionLibrary(ExsltCommonFunctionSet.getInstance());
1488 }
1489 return builtInExtensionLibraryList;
1490 }
1491
1492 /**
1493 * Add the registered extension binders to a function library.
1494 * This method is intended primarily for internal use
1495 *
1496 * @param list the function library list
1497 */
1498
1499 public void addExtensionBinders(FunctionLibraryList list) {
1500 // no action in this class
1501 }
1502
1503 /**
1504 * Get a system function. This can be any function defined in XPath 3.1 functions and operators,
1505 * including functions in the math, map, and array namespaces. It can also be a Saxon extension
1506 * function, provided a licensed Processor is used.
1507 *
1508 * @param name the name of the required function
1509 * @param arity the arity of the required function
1510 * @return the requested function, or null if there is no such function. Note that some functions
1511 * (those with particular context dependencies) may be unsuitable for dynamic calling.
1512 * @throws XPathException if dynamic function calls are not permitted by this Saxon Configuration
1513 */
1514
1515 public Function getSystemFunction(StructuredQName name, int arity) throws XPathException {
1516 throw new XPathException("Dynamic functions require Saxon-PE or higher");
1517 }
1518
1519 /**
1520 * Make a UserFunction object.
1521 * This method is for internal use.
1522 *
1523 * @param memoFunction true if the function is to be a memo function, This option is ignored
1524 * in Saxon-HE.
1525 * @param streamability the declared streamability of the function
1526 * @return a new UserFunction object
1527 */
1528
1529 public UserFunction newUserFunction(boolean memoFunction, FunctionStreamability streamability) {
1530 return new UserFunction();
1531 }
1532
1533 /**
1534 * Register a collation. Collation URIs registered using this interface will be
1535 * picked up before calling the CollationURIResolver.
1536 *
1537 * @param collationURI the URI of the collation. This should be an absolute URI,
1538 * though it is not checked
1539 * @param collator the implementation of the collation
1540 * @since 9.6
1541 */
1542
1543 public void registerCollation(String collationURI, StringCollator collator) {
1544 collationMap.put(collationURI, collator);
1545 }
1546
1547 /**
1548 * Set a CollationURIResolver to be used to resolve collation URIs (that is,
1549 * to take a URI identifying a collation, and return the corresponding collation).
1550 * Note that Saxon attempts first to resolve a collation URI using the resolver
1551 * registered with the Controller; if that returns null, it tries again using the
1552 * resolver registered with the Configuration.
1553 * <p>Note that it is undefined whether collation URIs are resolved at compile time
1554 * or at run-time. It is therefore inadvisable to change the CollationURIResolver after
1555 * compiling a query or stylesheet and before running it.</p>
1556 *
1557 * @param resolver the collation URI resolver to be used. This replaces any collation
1558 * URI resolver previously registered.
1559 * @since 8.5
1560 */
1561
1562 public void setCollationURIResolver(CollationURIResolver resolver) {
1563 collationResolver = resolver;
1564 }
1565
1566 /**
1567 * Get the collation URI resolver associated with this configuration. This will
1568 * return the CollationURIResolver previously set using the {@link #setCollationURIResolver}
1569 * method; if this has not been called, it returns the system-defined collation URI resolver
1570 *
1571 * @return the registered CollationURIResolver
1572 * @since 8.5
1573 */
1574
1575 public CollationURIResolver getCollationURIResolver() {
1576 return collationResolver;
1577 }
1578
1579 /**
1580 * Get the collation with a given collation name. If the collation name has
1581 * not been registered in this CollationMap, the CollationURIResolver registered
1582 * with the Configuration is called. If this cannot resolve the collation name,
1583 * it should return null.
1584 *
1585 * @param collationName the collation name as an absolute URI
1586 * @return the StringCollator with this name if known, or null if not known
1587 * @throws XPathException if the collation URI is recognized but is invalid; for example,
1588 * if it is a URI that takes parameters, and the parameters are invalid. If a user-supplied
1589 * collation URI resolver is in use, then any exception thrown by that resolver is passed
1590 * on to the caller.
1591 */
1592
1593
1594 public StringCollator getCollation(String collationName) throws XPathException {
1595 if (collationName == null || collationName.equals(NamespaceConstant.CODEPOINT_COLLATION_URI)) {
1596 return CodepointCollator.getInstance();
1597 }
1598 if (collationName.equals(NamespaceConstant.HTML5_CASE_BLIND_COLLATION_URI)) {
1599 return HTML5CaseBlindCollator.getInstance();
1600 }
1601 if (collationName.startsWith(AlphanumericCollator.PREFIX)) {
1602 return new AlphanumericCollator(getCollation(
1603 collationName.substring(AlphanumericCollator.PREFIX.length())));
1604 }
1605 StringCollator collator = collationMap.get(collationName);
1606 if (collator == null) {
1607 collator = getCollationURIResolver().resolve(collationName, this);
1608 }
1609 return collator;
1610 }
1611
1612 /**
1613 * Get the collation with a given collation name, supplying a relative URI and base
1614 * URI separately. If the collation name has
1615 * not been registered in this CollationMap, the CollationURIResolver registered
1616 * with the Configuration is called. If this cannot resolve the collation name,
1617 * it should return null.
1618 *
1619 * @param collationURI the collation name as a relative or absolute URI
1620 * @param baseURI the base URI to be used to resolve the collationURI if it is relative
1621 * @return the StringCollator with this name if known, or null if not known
1622 * @throws XPathException if a failure occurs during URI resolution
1623 */
1624
1625
1626 public StringCollator getCollation(String collationURI, String baseURI) throws XPathException {
1627 if (collationURI.equals(NamespaceConstant.CODEPOINT_COLLATION_URI)) {
1628 return CodepointCollator.getInstance();
1629 }
1630 try {
1631 String absoluteURI = ResolveURI.makeAbsolute(collationURI, baseURI).toString();
1632 return getCollation(absoluteURI);
1633 } catch (URISyntaxException e) {
1634 throw new XPathException("Collation name is not a valid URI: " + collationURI +
1635 " (base = " + baseURI + ")", "FOCH0002");
1636 }
1637 }
1638
1639 /**
1640 * Get the collation with a given collation name, supplying a relative URI and base
1641 * URI separately, and throwing an error if it cannot be found. If the collation name has
1642 * not been registered in this CollationMap, the CollationURIResolver registered
1643 * with the Configuration is called. If this cannot resolve the collation name,
1644 * it should return null.
1645 *
1646 * @param collationURI the collation name as a relative or absolute URI
1647 * @param baseURI the base URI to be used to resolve the collationURI if it is relative;
1648 * may be null if the supplied collationURI is known to be absolute
1649 * @param errorCode the error to raise if the collation is not known
1650 * @return the StringCollator with this name if known, or null if not known
1651 * @throws XPathException if a failure occurs during URI resolution
1652 */
1653
1654
1655 public StringCollator getCollation(String collationURI, String baseURI, String errorCode) throws XPathException {
1656 if (collationURI.equals(NamespaceConstant.CODEPOINT_COLLATION_URI)) {
1657 return CodepointCollator.getInstance();
1658 }
1659 try {
1660 String absoluteURI = collationURI;
1661 if (baseURI != null) {
1662 absoluteURI = ResolveURI.makeAbsolute(collationURI, baseURI).toString();
1663 }
1664 StringCollator collator = getCollation(absoluteURI);
1665 if (collator == null) {
1666 throw new XPathException("Unknown collation " + absoluteURI, errorCode);
1667 }
1668 return collator;
1669 } catch (URISyntaxException e) {
1670 throw new XPathException("Collation name is not a valid URI: " + collationURI +
1671 " (base = " + baseURI + ")", errorCode);
1672 }
1673 }
1674
1675
1676 /**
1677 * Get the name of the global default collation
1678 *
1679 * @return the name of the default collation. If none has been set, returns
1680 * the URI of the Unicode codepoint collation
1681 */
1682
1683 public String getDefaultCollationName() {
1684 return defaultCollationName;
1685 }
1686
1687 /**
1688 * Set the default collection.
1689 * <p>If no default collection URI is specified, then a request for the default collection
1690 * is handled by calling the registered collection URI resolver with an argument of null.</p>
1691 *
1692 * @param uri the URI of the default collection. Calling the collection() function
1693 * with no arguments is equivalent to calling collection() with this URI as an argument.
1694 * The URI will be dereferenced by passing it to the registered CollectionURIResolver.
1695 * If null is supplied, any existing default collection is removed.
1696 * @since 9.2
1697 */
1698
1699 public void setDefaultCollection(/*@Nullable*/ String uri) {
1700 defaultCollection = uri;
1701 }
1702
1703 /**
1704 * Get the URI of the default collection. Returns null if no default collection URI has
1705 * been registered.
1706 *
1707 * @return the default collection URI. This is dereferenced in the same way as a normal
1708 * collection URI (via the CollectionURIResolver) to return a sequence of nodes
1709 * @since 9.2
1710 */
1711
1712 /*@Nullable*/
1713 public String getDefaultCollection() {
1714 return defaultCollection;
1715 }
1716
1717 /**
1718 * Set a CollectionURIResolver to be used to resolve collection URIs (that is,
1719 * the URI supplied in a call to the collection() function).
1720 * <p>Collection URIs are always resolved at run-time, using the CollectionURIResolver
1721 * in force at the time the collection() function is called.</p>
1722 * <p>Calling this method has the effect of calling {@link #setCollectionFinder(CollectionFinder)}
1723 * with a <code>CollectionFinder</code> that wraps this <code>CollectionURIResolver</code>. </p>
1724 *
1725 * @param resolver the collection URI resolver to be used. This replaces any collection
1726 * URI resolver previously registered. The value must not be null.
1727 * @since 8.5
1728 * @deprecated since 9.7. Use {@link #setCollectionFinder(CollectionFinder)}
1729 */
1730
1731 public void setCollectionURIResolver(/*@NotNull*/ CollectionURIResolver resolver) {
1732 setCollectionFinder(new CollectionURIResolverWrapper(resolver));
1733 }
1734
1735 /**
1736 * Get the collection URI resolver associated with this configuration. This will
1737 * return the CollectionURIResolver previously set using the {@link #setCollectionURIResolver}
1738 * method; if this has not been called, it returns the system-defined collection URI resolver
1739 * <p>Calling this method has the effect of calling {@link #getCollectionFinder()}; if the result
1740 * is a <code>CollectionFinder</code> that wraps a <code>CollectionURIResolver</code>, then
1741 * the wrapped <code>CollectionURIFinder is returned.</code></p>
1742 *
1743 * @return the registered CollectionURIResolver
1744 * @since 8.5
1745 * @deprecated since 9.7. Use {@link #getCollectionFinder()}
1746 */
1747
1748 /*@NotNull*/
1749 public CollectionURIResolver getCollectionURIResolver() {
1750 if (collectionFinder instanceof CollectionURIResolverWrapper) {
1751 return ((CollectionURIResolverWrapper) collectionFinder).getCollectionURIResolver();
1752 }
1753 return null;
1754 }
1755
1756 /**
1757 * Set the collection finder associated with this configuration. This is used to dereference
1758 * collection URIs used in the fn:collection and fn:uri-collection functions
1759 *
1760 * @param cf the CollectionFinder to be used
1761 * @since 9.7
1762 */
1763
1764 public void setCollectionFinder(CollectionFinder cf) {
1765 collectionFinder = cf;
1766 }
1767
1768 /**
1769 * Get the collection finder associated with this configuration. This is used to dereference
1770 * collection URIs used in the fn:collection and fn:uri-collection functions
1771 *
1772 * @return the CollectionFinder to be used
1773 * @since 9.7
1774 */
1775
1776 public CollectionFinder getCollectionFinder() {
1777 return collectionFinder;
1778 }
1779
1780 /**
1781 * Register a specific URI and bind it to a specific ResourceCollection. This method only works
1782 * if the {@link CollectionFinder} in use is a {@link StandardCollectionFinder}.
1783 *
1784 * @param collectionURI the collection URI to be registered. Must not be null.
1785 * @param collection the ResourceCollection to be associated with this URI. Must not be null.
1786 * @throws IllegalStateException if the {@link CollectionFinder} in use is not a
1787 * {@link StandardCollectionFinder}
1788 * @since 9.7.0.2
1789 */
1790
1791 public void registerCollection(String collectionURI, ResourceCollection collection) {
1792 if (!(collectionFinder instanceof StandardCollectionFinder)) {
1793 throw new IllegalStateException("Current CollectionFinder is not a StandardCollectionFinder");
1794 }
1795 ((StandardCollectionFinder) collectionFinder).registerCollection(collectionURI, collection);
1796 }
1797
1798 /**
1799 * Set the media type to be associated with a file extension by the standard
1800 * collection handler
1801 *
1802 * @param extension the file extension, for example "xml". The value "" sets
1803 * the default media type to be used for unregistered file extensions.
1804 * @param mediaType the corresponding media type, for example "application/xml". The
1805 * choice of media type determines how a resource with this extension
1806 * gets parsed, when the file appears as part of a collection.
1807 * @since 9.7.0.1
1808 */
1809
1810 public void registerFileExtension(String extension, String mediaType) {
1811 fileExtensions.put(extension, mediaType);
1812 }
1813
1814 /**
1815 * Associate a media type with a resource factory. This method may
1816 * be called to customize the behaviour of a collection to recognize different file extensions
1817 *
1818 * @param contentType a media type or MIME type, for example application/xsd+xml
1819 * @param factory a ResourceFactory used to parse (or otherwise process) resources of that type
1820 * @since 9.7.0.6
1821 */
1822
1823 public void registerMediaType(String contentType, ResourceFactory factory) {
1824 resourceFactoryMapping.put(contentType, factory);
1825 }
1826
1827 /**
1828 * Get the media type to be associated with a file extension by the standard
1829 * collection handler
1830 *
1831 * @param extension the file extension, for example "xml". The value "" gets
1832 * the default media type to be used for unregistered file extensions.
1833 * the default media type is also returned if the supplied file
1834 * extension is not registered.
1835 * @return the corresponding media type, for example "application/xml". The
1836 * choice of media type determines how a resource with this extension
1837 * gets parsed, when the file appears as part of a collection.
1838 * @since 9.7.0.1
1839 */
1840
1841 public String getMediaTypeForFileExtension(String extension) {
1842 String mediaType = fileExtensions.get(extension);
1843 if (mediaType == null) {
1844 mediaType = fileExtensions.get("");
1845 }
1846 return mediaType;
1847 }
1848
1849 /**
1850 * Get the resource factory associated with a media type
1851 *
1852 * @param mediaType the media type or MIME type, for example "application/xml"
1853 * @return the associated resource factory if one has been registered for this media type,
1854 * or null otherwise
1855 */
1856
1857 public ResourceFactory getResourceFactoryForMediaType(String mediaType) {
1858 return resourceFactoryMapping.get(mediaType);
1859 }
1860
1861 /**
1862 * Set the localizer factory to be used
1863 *
1864 * @param factory the LocalizerFactory
1865 * @since 9.2
1866 */
1867
1868 public void setLocalizerFactory(LocalizerFactory factory) {
1869 this.localizerFactory = factory;
1870 }
1871
1872 /**
1873 * Get the localizer factory in use
1874 *
1875 * @return the LocalizerFactory, if any. If none has been set, returns null.
1876 * @since 9.2
1877 */
1878
1879 public LocalizerFactory getLocalizerFactory() {
1880 return localizerFactory;
1881 }
1882
1883
1884 /**
1885 * Set the default language to be used for number and date formatting when no language is specified.
1886 * If none is set explicitly, the default Locale for the Java Virtual Machine is used.
1887 *
1888 * @param language the default language to be used, as an ISO code for example "en" or "fr-CA"
1889 * @throws IllegalArgumentException if not valid as an xs:language instance.
1890 * @since 9.2. Validated from 9.7 against xs:language type.
1891 */
1892
1893 public void setDefaultLanguage(String language) {
1894 ValidationFailure vf = StringConverter.StringToLanguage.INSTANCE.validate(language);
1895 if (vf != null) {
1896 throw new IllegalArgumentException("The default language must be a valid language code");
1897 }
1898 defaultLanguage = language;
1899 }
1900
1901 /**
1902 * Get the default language. Unless an explicit default is set, this will be the language
1903 * of the default Locale for the Java Virtual Machine
1904 *
1905 * @return the default language
1906 * @since 9.2
1907 */
1908
1909 public String getDefaultLanguage() {
1910 return defaultLanguage;
1911 }
1912
1913 /**
1914 * Set the default country to be used for number and date formatting when no country is specified.
1915 * If none is set explicitly, the default Locale for the Java Virtual Machine is used.
1916 *
1917 * @param country the default country to be used, as an ISO code for example "US" or "GB"
1918 * @since 9.2
1919 */
1920
1921 public void setDefaultCountry(String country) {
1922 defaultCountry = country;
1923 }
1924
1925 /**
1926 * Get the default country to be used for number and date formatting when no country is specified.
1927 * If none is set explicitly, the default Locale for the Java Virtual Machine is used.
1928 *
1929 * @return the default country to be used, as an ISO code for example "US" or "GB"
1930 * @since 9.2
1931 */
1932
1933 public String getDefaultCountry() {
1934 return defaultCountry;
1935 }
1936
1937 /**
1938 * Set the default regular expression engine to be used
1939 *
1940 * @param engine the default regular expression engine to be used. The value must be one of:
1941 * <ul>
1942 * <li>S - the Saxon regular expression engine (derived form Apache Jakarta)</li>
1943 * <li>J - the Java JDK regular expression engine</li>
1944 * <li>N - (on .NET only) - the .NET regular expression engine</li>
1945 * </ul>
1946 */
1947
1948 public void setDefaultRegexEngine(String engine) {
1949 if (!("J".equals(engine) || "N".equals(engine) || "S".equals(engine))) {
1950 throw new IllegalArgumentException("Regex engine must be S|J|N");
1951 }
1952 defaultRegexEngine = engine;
1953 }
1954
1955 /**
1956 * Get the default regular expression to be used
1957 *
1958 * @return the default regular expression to be used. Returns "S" if no value has been
1959 * explicitly set.
1960 */
1961
1962 public String getDefaultRegexEngine() {
1963 return defaultRegexEngine;
1964 }
1965
1966 /**
1967 * Compile a regular expression (or, in some configurations, get a compiled
1968 * regular expression from a cache
1969 *
1970 * @param regex the regular expression as a string
1971 * @param flags the value of the flags attribute
1972 * @param hostLanguage one of "XSD10", "XSD11", XP20" or "XP30". Also allow combinations, e.g. "XP20/XSD11".
1973 * @param warnings if non-null, any warnings from the regular expression compiler will be added to this list.
1974 * If null, the warnings are ignored.
1975 * @return the compiled regular expression
1976 * @throws XPathException if the regular expression or the flags are invalid
1977 */
1978
1979 public RegularExpression compileRegularExpression(CharSequence regex, String flags, String hostLanguage, List<String> warnings)
1980 throws XPathException {
1981 return Version.platform.compileRegularExpression(this, regex, flags, hostLanguage, warnings);
1982 }
1983
1984 /**
1985 * Load a Numberer class for a given language and check it is OK.
1986 * This method is provided primarily for internal use.
1987 *
1988 * @param language the language for which a Numberer is required. May be null,
1989 * indicating default language
1990 * @param country the country for which a Numberer is required. May be null,
1991 * indicating default country
1992 * @return a suitable numberer. If no specific numberer is available
1993 * for the language, the default numberer (normally English) is used.
1994 */
1995
1996 public Numberer makeNumberer(/*@Nullable*/ String language, /*@Nullable*/ String country) {
1997 if (localizerFactory == null) {
1998 Numberer_en numberer = new Numberer_en();
1999 if (language != null) {
2000 numberer.setLanguage(language);
2001 }
2002 if (country != null) {
2003 numberer.setCountry(country);
2004 }
2005 return numberer;
2006 } else {
2007 Numberer numberer = localizerFactory.getNumberer(language, country);
2008 if (numberer == null) {
2009 numberer = new Numberer_en();
2010 }
2011 return numberer;
2012 }
2013 }
2014
2015
2016 /**
2017 * Set a user-defined ModuleURIResolver for resolving URIs used in "import module"
2018 * declarations in an XQuery prolog.
2019 * This acts as the default value for the ModuleURIResolver in the StaticQueryContext, and may be
2020 * overridden by a more specific ModuleURIResolver nominated as part of the StaticQueryContext.
2021 *
2022 * @param resolver the URI resolver for XQuery modules. May be null, in which case any existing
2023 * Module URI Resolver is removed from the configuration
2024 */
2025
2026 public void setModuleURIResolver(/*@Nullable*/ ModuleURIResolver resolver) {
2027 getDefaultStaticQueryContext().setModuleURIResolver(resolver);
2028 }
2029
2030 /**
2031 * Create and register an instance of a ModuleURIResolver with a specified class name.
2032 * This will be used for resolving URIs in XQuery "import module" declarations, unless
2033 * a more specific ModuleURIResolver has been nominated as part of the StaticQueryContext.
2034 *
2035 * @param className The fully-qualified name of the LocationHintResolver class
2036 * @throws TransformerException if the requested class does not
2037 * implement the net.sf.saxon.LocationHintResolver interface
2038 */
2039 public void setModuleURIResolver(String className) throws TransformerException {
2040 Object obj = dynamicLoader.getInstance(className, null);
2041 if (obj instanceof ModuleURIResolver) {
2042 setModuleURIResolver((ModuleURIResolver) obj);
2043 } else {
2044 throw new XPathException("Class " + className + " is not a ModuleURIResolver");
2045 }
2046 }
2047
2048 /**
2049 * Get the user-defined ModuleURIResolver for resolving URIs used in "import module"
2050 * declarations in the XQuery prolog; returns null if none has been explicitly set.
2051 *
2052 * @return the resolver for Module URIs
2053 */
2054
2055 /*@Nullable*/
2056 public ModuleURIResolver getModuleURIResolver() {
2057 return getDefaultStaticQueryContext().getModuleURIResolver();
2058 }
2059
2060 /**
2061 * Get the standard system-defined ModuleURIResolver for resolving URIs used in "import module"
2062 * declarations in the XQuery prolog.
2063 *
2064 * @return the standard system-defined ModuleURIResolver for resolving URIs
2065 */
2066
2067 public ModuleURIResolver getStandardModuleURIResolver() {
2068 return standardModuleURIResolver;
2069 }
2070
2071 /**
2072 * Get the URI resolver used for resolving URIs passed to the unparsed-text(),
2073 * unparsed-text-available(), and unparsed-text-lines() functions
2074 *
2075 * @return the URI resolver set for these functions, if one has been set, or the
2076 * standard system-supplied resolver otherwise
2077 */
2078
2079 public UnparsedTextURIResolver getUnparsedTextURIResolver() {
2080 return unparsedTextURIResolver;
2081 }
2082
2083 /**
2084 * Set the URI resolver to be used for resolving URIs passed to the unparsed-text(),
2085 * unparsed-text-available(), and unparsed-text-lines() functions
2086 * @param resolver the URI resolver to be used for these functions.
2087 */
2088
2089 public void setUnparsedTextURIResolver(UnparsedTextURIResolver resolver) {
2090 this.unparsedTextURIResolver = resolver;
2091 }
2092
2093
2094 /**
2095 * Get the default options for XSLT compilation
2096 *
2097 * @return the default options for XSLT compilation. The CompilerInfo object will reflect any options
2098 * set using other methods available for this Configuration object
2099 */
2100
2101 public CompilerInfo getDefaultXsltCompilerInfo() {
2102 if (defaultXsltCompilerInfo.getErrorListener() == null) {
2103 defaultXsltCompilerInfo.setErrorListener(getErrorListener());
2104 }
2105 return defaultXsltCompilerInfo;
2106 }
2107
2108 /**
2109 * Get the default options for XQuery compilation
2110 *
2111 * @return the default XQuery static context for this configuration
2112 */
2113
2114 public StaticQueryContext getDefaultStaticQueryContext() {
2115 if (defaultStaticQueryContext == null) {
2116 defaultStaticQueryContext = makeStaticQueryContext(false);
2117 }
2118 return defaultStaticQueryContext;
2119 }
2120
2121 /**
2122 *
2123 * Make a new static query context object using the factory registered with this configuration
2124 * @param copyFromDefault true if the new static query context is to copy the properties
2125 * of the default static query context held in the configuration
2126 * @return the new static query context object
2127 */
2128
2129 protected StaticQueryContext makeStaticQueryContext(boolean copyFromDefault) {
2130 return staticQueryContextFactory.newStaticQueryContext(this, copyFromDefault);
2131 }
2132
2133 /**
2134 * Register a FunctionAnnotationHandler to handle XQuery function annotations
2135 * in a particular namespace
2136 *
2137 * @param handler a function annotation handler to be invoked in respect of function
2138 * annotations in the relevant namespace
2139 */
2140
2141 public void registerFunctionAnnotationHandler(FunctionAnnotationHandler handler) {
2142 functionAnnotationHandlers.put(handler.getAssertionNamespace(), handler);
2143 }
2144
2145 /**
2146 * Get the FunctionAnnotationHandler used to handle XQuery function annotations
2147 * in a particular namespace
2148 *
2149 * @param namespace the namespace
2150 * @return a function annotation handler to be invoked in respect of function
2151 * annotations in the relevant namespace, or null if none has
2152 * been registered
2153 */
2154
2155 public FunctionAnnotationHandler getFunctionAnnotationHandler(String namespace) {
2156 return functionAnnotationHandlers.get(namespace);
2157 }
2158
2159 /**
2160 * Determine how recoverable run-time errors are to be handled. This applies
2161 * only if the standard ErrorListener is used.
2162 *
2163 * @return the current recovery policy. The options are {@link #RECOVER_SILENTLY},
2164 * {@link #RECOVER_WITH_WARNINGS}, or {@link #DO_NOT_RECOVER}.
2165 * @since 8.4
2166 */
2167
2168 public int getRecoveryPolicy() {
2169 return defaultXsltCompilerInfo.getRecoveryPolicy();
2170 }
2171
2172 /**
2173 * Determine how recoverable run-time errors are to be handled. This applies
2174 * only if the standard ErrorListener is used. The recovery policy applies to
2175 * errors classified in the XSLT 2.0 specification as recoverable dynamic errors,
2176 * but only in those cases where Saxon provides a choice over how the error is handled:
2177 * in some cases, Saxon makes the decision itself.
2178 *
2179 * @param recoveryPolicy the recovery policy to be used. The options are {@link #RECOVER_SILENTLY},
2180 * {@link #RECOVER_WITH_WARNINGS}, or {@link #DO_NOT_RECOVER}.
2181 * @since 8.4
2182 */
2183
2184 public void setRecoveryPolicy(int recoveryPolicy) {
2185 defaultXsltCompilerInfo.setRecoveryPolicy(recoveryPolicy);
2186 }
2187
2188 /**
2189 * Get the streamability rules to be applied.
2190 *
2191 * @return 0 indicating that streaming is not available with this Saxon Configuration
2192 * @since 9.6
2193 */
2194
2195 public int getStreamability() {
2196 return 0;
2197 }
2198
2199 /**
2200 * Get the name of the class that will be instantiated to create a MessageEmitter,
2201 * to process the output of xsl:message instructions in XSLT.
2202 *
2203 * @return the full class name of the message emitter class.
2204 * @since 8.4
2205 */
2206
2207 public String getMessageEmitterClass() {
2208 return defaultXsltCompilerInfo.getMessageReceiverClassName();
2209 }
2210
2211 /**
2212 * Set the name of the class that will be instantiated to
2213 * to process the output of xsl:message instructions in XSLT.
2214 *
2215 * @param messageReceiverClassName the full class name of the message receiver. This
2216 * must implement net.sf.saxon.event.Receiver.
2217 * @since 8.4
2218 */
2219
2220 public void setMessageEmitterClass(String messageReceiverClassName) {
2221 defaultXsltCompilerInfo.setMessageReceiverClassName(messageReceiverClassName);
2222 }
2223
2224 /**
2225 * Get the name of the class that will be instantiated to create an XML parser
2226 * for parsing source documents (for example, documents loaded using the document()
2227 * or doc() functions).
2228 * <p>This method is retained in Saxon for backwards compatibility, but the preferred way
2229 * of choosing an XML parser is to use JAXP interfaces, for example by supplying a
2230 * JAXP SAXSource object initialized with an appropriate implementation of org.xml.sax.XMLReader.</p>
2231 *
2232 * @return the fully qualified name of the XML parser class
2233 */
2234
2235 public String getSourceParserClass() {
2236 return sourceParserClass;
2237 }
2238
2239 /**
2240 * Set the name of the class that will be instantiated to create an XML parser
2241 * for parsing source documents (for example, documents loaded using the document()
2242 * or doc() functions).
2243 * <p>This method is retained in Saxon for backwards compatibility, but the preferred way
2244 * of choosing an XML parser is to use JAXP interfaces, for example by supplying a
2245 * JAXP SAXSource object initialized with an appropriate implementation of org.xml.sax.XMLReader.</p>
2246 *
2247 * @param sourceParserClass the fully qualified name of the XML parser class. This must implement
2248 * the SAX2 XMLReader interface.
2249 */
2250
2251 public void setSourceParserClass(String sourceParserClass) {
2252 this.sourceParserClass = sourceParserClass;
2253 }
2254
2255 /**
2256 * Get the name of the class that will be instantiated to create an XML parser
2257 * for parsing stylesheet modules.
2258 * <p>This method is retained in Saxon for backwards compatibility, but the preferred way
2259 * of choosing an XML parser is to use JAXP interfaces, for example by supplying a
2260 * JAXP Source object initialized with an appropriate implementation of org.xml.sax.XMLReader.</p>
2261 *
2262 * @return the fully qualified name of the XML parser class
2263 */
2264
2265 public String getStyleParserClass() {
2266 return styleParserClass;
2267 }
2268
2269 /**
2270 * Set the name of the class that will be instantiated to create an XML parser
2271 * for parsing stylesheet modules.
2272 * <p>This method is retained in Saxon for backwards compatibility, but the preferred way
2273 * of choosing an XML parser is to use JAXP interfaces, for example by supplying a
2274 * JAXP Source object initialized with an appropriate implementation of org.xml.sax.XMLReader.</p>
2275 *
2276 * @param parser the fully qualified name of the XML parser class
2277 */
2278
2279 public void setStyleParserClass(String parser) {
2280 this.styleParserClass = parser;
2281 }
2282
2283 /**
2284 * Get the OutputURIResolver that will be used to resolve URIs used in the
2285 * href attribute of the xsl:result-document instruction.
2286 *
2287 * @return the OutputURIResolver. If none has been supplied explicitly, the
2288 * default OutputURIResolver is returned.
2289 * @since 8.4
2290 */
2291
2292 public OutputURIResolver getOutputURIResolver() {
2293 return defaultXsltCompilerInfo.getOutputURIResolver();
2294 }
2295
2296 /**
2297 * Set the OutputURIResolver that will be used to resolve URIs used in the
2298 * href attribute of the xsl:result-document instruction.
2299 *
2300 * @param outputURIResolver the OutputURIResolver to be used.
2301 * @since 8.4
2302 * @deprecated since 9.9. Use {@link Xslt30Transformer#setResultDocumentHandler(java.util.function.Function)}
2303 * or {@link XsltController#setResultDocumentResolver(ResultDocumentResolver)} instead.
2304 */
2305
2306 public void setOutputURIResolver(OutputURIResolver outputURIResolver) {
2307 defaultXsltCompilerInfo.setOutputURIResolver(outputURIResolver);
2308 }
2309
2310 /**
2311 * Set a custom SerializerFactory. This will be used to create a serializer for a given
2312 * set of output properties and result destination.
2313 *
2314 * @param factory a custom SerializerFactory
2315 * @since 8.8
2316 */
2317
2318 public void setSerializerFactory(SerializerFactory factory) {
2319 serializerFactory = factory;
2320 }
2321
2322 /**
2323 * Get the SerializerFactory. This returns the standard built-in SerializerFactory, unless
2324 * a custom SerializerFactory has been registered.
2325 *
2326 * @return the SerializerFactory in use
2327 * @since 8.8
2328 */
2329
2330 public SerializerFactory getSerializerFactory() {
2331 return serializerFactory;
2332 }
2333
2334 /**
2335 * Get the CharacterSetFactory. Note: at present this cannot be changed.
2336 *
2337 * @return the CharacterSetFactory in use.
2338 * @since 9.2
2339 */
2340
2341 public CharacterSetFactory getCharacterSetFactory() {
2342 if (characterSetFactory == null) {
2343 characterSetFactory = new CharacterSetFactory();
2344 }
2345 return characterSetFactory;
2346 }
2347
2348 /**
2349 * Set the default serialization properties.
2350 * <p>The method name is a misnomer, retained for backwards compatibility. A {@link SerializationProperties}
2351 * object contains a set of {@link Properties} holding simple properties, together with an optional
2352 * {@link CharacterMap} holding a character map. This method returns the simple properties only.
2353 * In fact the default properties held in the <code>Configuration</code> only contain simple properties,
2354 * and never a character map.</p>
2355 *
2356 * @param props the default properties
2357 */
2358
2359 public void setDefaultSerializationProperties(Properties props) {
2360 defaultOutputProperties = props;
2361 }
2362
2363 /**
2364 * Get the default output properties. The returned value can be modified in-situ using
2365 * methods such as {@link Properties#setProperty(String, String)} to change the defaults
2366 * in force for the {@code Configuration}.
2367 * <p>The method name is a misnomer, retained for backwards compatibility. A {@link SerializationProperties}
2368 * object contains a set of {@link Properties} holding simple properties, together with an optional
2369 * {@link CharacterMap} holding a character map. This method returns the simple properties only.
2370 * In fact the default properties held in the <code>Configuration</code> only contain simple properties,
2371 * and never a character map.</p>
2372 *
2373 * @return the default output properties.
2374 */
2375
2376 public Properties getDefaultSerializationProperties() {
2377 return defaultOutputProperties;
2378 }
2379
2380 /**
2381 * Obtain a default <code>SerializationProperties</code> object.
2382 *
2383 * @return the default serialization properties. This is obtained by wrapping the default output
2384 * properties maintained in the {@code Configuration} within a {@link SerializationProperties} wrapper.
2385 * The returned value can be modified in-situ using
2386 * methods such as {@link SerializationProperties#setProperty(String, String)} to change the defaults
2387 * in force for the {@code Configuration}.
2388 */
2389
2390 public SerializationProperties obtainDefaultSerializationProperties() {
2391 return new SerializationProperties(defaultOutputProperties);
2392 }
2393
2394 /**
2395 * Process an xsl:result-document instruction. The Saxon-HE version of this method simply executes the instruction.
2396 * The Saxon-EE version starts a new thread, and executes the instruction in that thread.
2397 *
2398 * @param instruction the instruction to be executed
2399 * @param content the expression that defines the content of the new result document
2400 * @param context the evaluation context
2401 * @throws XPathException if any dynamic error occurs
2402 */
2403
2404 public void processResultDocument(ResultDocument instruction, Expression content, XPathContext context) throws XPathException {
2405 instruction.processInstruction(content, context);
2406 }
2407
2408 /**
2409 * Get an item mapping iterator suitable for multi-threaded execution, if this is permitted
2410 *
2411 * @param base iterator over the input sequence
2412 * @param action mapping function to be applied to each item in the input sequence.
2413 * @return an iterator over the result sequence
2414 * @throws XPathException if (for example) a dynamic error occurs while priming the queue
2415 */
2416
2417 public <F extends Item<?>, T extends Item<?>> SequenceIterator<T> getMultithreadedItemMappingIterator(
2418 SequenceIterator<F> base, ItemMappingFunction<F, T> action) throws XPathException {
2419 return new ItemMappingIterator<>(base, action);
2420 }
2421
2422 /**
2423 * Determine whether brief progress messages and timing information will be output.
2424 *
2425 * <p>This method is provided largely for internal use. Progress messages are normally
2426 * controlled directly from the command line interfaces, and are not normally used when
2427 * driving Saxon from the Java API.</p>
2428 *
2429 * @return true if these messages are to be output.
2430 */
2431
2432 public boolean isTiming() {
2433 return enabledProperties.contains(FeatureCode.TIMING);
2434 }
2435
2436 /**
2437 * Determine whether brief progress messages and timing information will be output.
2438 * <p>This method is provided largely for internal use. Progress messages are normally
2439 * controlled directly from the command line interfaces, and are not normally used when
2440 * running from a Java application.</p>
2441 * <p>The name of the method is poorly chosen, since many of the progress messages that
2442 * are output have little to do with timing or instrumentation.</p>
2443 * <p>If enabled, the relevant messages will be sent either to the destination set using
2444 * {@link #setLogger(Logger)} or to the destination set using {@link #setStandardErrorOutput(PrintStream)},
2445 * depending on the message.</p>
2446 *
2447 * @param timing true if these messages are to be output.
2448 */
2449
2450 public void setTiming(boolean timing) {
2451 if (timing) {
2452 enabledProperties.add(FeatureCode.TIMING);
2453 } else {
2454 enabledProperties.remove(FeatureCode.TIMING);
2455 }
2456 }
2457
2458 /**
2459 * Determine whether a warning is to be output when running against a stylesheet labelled
2460 * as version="1.0". The XSLT specification requires such a warning unless the user disables it.
2461 *
2462 * @return true if these messages are to be output.
2463 * @since 8.4
2464 */
2465
2466 public boolean isVersionWarning() {
2467 return defaultXsltCompilerInfo.isVersionWarning();
2468 }
2469
2470 /**
2471 * Determine whether a warning is to be output when the version attribute of the stylesheet does
2472 * not match the XSLT processor version. (In the case where the stylesheet version is "1.0",
2473 * the XSLT specification requires such a warning unless the user disables it.)
2474 *
2475 * @param warn true if these warning messages are to be output.
2476 * @since 8.4
2477 */
2478
2479 public void setVersionWarning(boolean warn) {
2480 defaultXsltCompilerInfo.setVersionWarning(warn);
2481 }
2482
2483 /**
2484 * Determine whether the XML parser for source documents will be asked to perform
2485 * validation of source documents
2486 *
2487 * @return true if DTD validation is requested.
2488 * @since 8.4
2489 */
2490
2491 public boolean isValidation() {
2492 return defaultParseOptions.getDTDValidationMode() == Validation.STRICT ||
2493 defaultParseOptions.getDTDValidationMode() == Validation.LAX;
2494 }
2495
2496 /**
2497 * Determine whether the XML parser for source documents will be asked to perform
2498 * DTD validation of source documents
2499 *
2500 * @param validation true if DTD validation is to be requested.
2501 * @since 8.4
2502 */
2503
2504 public void setValidation(boolean validation) {
2505 defaultParseOptions.setDTDValidationMode(validation ? Validation.STRICT : Validation.STRIP);
2506 }
2507
2508 /**
2509 * Create a document projector for a given path map root. Document projection is available only
2510 * in Saxon-EE, so the Saxon-HE version of this method throws an exception
2511 *
2512 * @param map a path map root in a path map. This might represent the call to the initial
2513 * context item for a query, or it might represent a call on the doc() function. The path map
2514 * contains information about the paths that the query uses within this document.
2515 * @return a push filter that implements document projection
2516 * @throws UnsupportedOperationException if this is not a schema-aware configuration, or
2517 * if no Saxon-EE license is available
2518 */
2519
2520 public FilterFactory makeDocumentProjector(PathMap.PathMapRoot map) {
2521 throw new UnsupportedOperationException("Document projection requires Saxon-EE");
2522 }
2523
2524 /**
2525 * Create a document projector for the document supplied as the initial context item
2526 * in a query. Document projection is available only
2527 * in Saxon-EE, so the Saxon-HE version of this method throws an exception
2528 *
2529 * @param exp an XQuery expression. The document projector that is returned will
2530 * be for the document supplied as the context item to this query.
2531 * @return a push filter that implements document projection
2532 * @throws UnsupportedOperationException if this is not a schema-aware configuration, or
2533 * if no Saxon-EE license is available
2534 */
2535
2536 public FilterFactory makeDocumentProjector(XQueryExpression exp) {
2537 throw new UnsupportedOperationException("Document projection requires Saxon-EE");
2538 }
2539
2540 /**
2541 * Ask whether source documents (supplied as a StreamSource or SAXSource)
2542 * should be subjected to schema validation, and if so, in what validation mode
2543 *
2544 * @return the schema validation mode previously set using setSchemaValidationMode(),
2545 * or the default mode {@link Validation#STRIP} otherwise.
2546 */
2547
2548 public int getSchemaValidationMode() {
2549 return defaultParseOptions.getSchemaValidationMode();
2550 }
2551
2552 /**
2553 * Say whether source documents (supplied as a StreamSource or SAXSource)
2554 * should be subjected to schema validation, and if so, in what validation mode.
2555 * This value may be overridden at the level of a Controller for an individual transformation or query.
2556 *
2557 * @param validationMode the validation (or construction) mode to be used for source documents.
2558 * One of {@link Validation#STRIP}, {@link Validation#PRESERVE}, {@link Validation#STRICT},
2559 * {@link Validation#LAX}
2560 * @since 8.4
2561 */
2562
2563 public void setSchemaValidationMode(int validationMode) {
2564 // switch (validationMode) {
2565 // case Validation.STRIP:
2566 // case Validation.PRESERVE:
2567 // break;
2568 // case Validation.LAX:
2569 // if (!isLicensedFeature(LicenseFeature.SCHEMA_VALIDATION)) {
2570 // // if schema processing isn't supported, then there's never a schema, so lax validation is a no-op.
2571 // validationMode = Validation.STRIP;
2572 // }
2573 // break;
2574 // case Validation.STRICT:
2575 // checkLicensedFeature(LicenseFeature.SCHEMA_VALIDATION, "strict validation", -1);
2576 // break;
2577 // default:
2578 // throw new IllegalArgumentException("Unsupported validation mode " + validationMode);
2579 // }
2580 defaultParseOptions.setSchemaValidationMode(validationMode);
2581 }
2582
2583 /**
2584 * Indicate whether schema validation failures on result documents are to be treated
2585 * as fatal errors or as warnings. Note that all validation
2586 * errors are reported to the error() method of the ErrorListener, and processing always
2587 * continues except when that method chooses to throw an exception. At the end of the document,
2588 * a fatal error is thrown if (a) there have been any validation errors, and (b) this option
2589 * is not set.
2590 *
2591 * @param warn true if schema validation failures are to be treated as warnings; false if they
2592 * are to be treated as fatal errors.
2593 * @since 8.4
2594 */
2595
2596 public void setValidationWarnings(boolean warn) {
2597 defaultParseOptions.setContinueAfterValidationErrors(warn);
2598 }
2599
2600 /**
2601 * Determine whether schema validation failures on result documents are to be treated
2602 * as fatal errors or as warnings. Note that all validation
2603 * errors are reported to the error() method of the ErrorListener, and processing always
2604 * continues except when that method chooses to throw an exception. At the end of the document,
2605 * a fatal error is thrown if (a) there have been any validation errors, and (b) this option
2606 * is not set.
2607 *
2608 * @return true if validation errors are to be treated as warnings (that is, the
2609 * validation failure is reported but processing continues as normal); false
2610 * if validation errors are fatal.
2611 * @since 8.4
2612 */
2613
2614 public boolean isValidationWarnings() {
2615 return defaultParseOptions.isContinueAfterValidationErrors();
2616 }
2617
2618 /**
2619 * Indicate whether attributes that have a fixed or default value are to be expanded when
2620 * generating a final result tree. By default (and for conformance with the W3C specifications)
2621 * it is required that fixed and default values should be expanded. However, there are use cases
2622 * for example when generating XHTML when this serves no useful purpose and merely bloats the output.
2623 * <p>This option can be overridden at the level of a PipelineConfiguration</p>
2624 *
2625 * @param expand true if fixed and default values are to be expanded as required by the W3C
2626 * specifications; false if this action is to be disabled. Note that this only affects the validation
2627 * of final result trees; it is not possible to suppress expansion of fixed or default values on input
2628 * documents, as this would make the type annotations on input nodes unsound.
2629 * @since 9.0
2630 */
2631
2632 public void setExpandAttributeDefaults(boolean expand) {
2633 defaultParseOptions.setExpandAttributeDefaults(expand);
2634 }
2635
2636 /**
2637 * Determine whether elements and attributes that have a fixed or default value are to be expanded.
2638 * This option applies both to DTD-defined attribute defaults and to schema-defined defaults for
2639 * elements and attributes. If an XML parser is used that does not report whether defaults have
2640 * been used, this option is ignored.
2641 * <p>This option can be overridden at the level of a PipelineConfiguration</p>
2642 *
2643 * @return true if elements and attributes that have a fixed or default value are to be expanded,
2644 * false if defaults are not to be expanded. The default value is true. Note that the setting "false"
2645 * is potentially non-conformant with the W3C specifications.
2646 * @since 9.0
2647 */
2648
2649 public boolean isExpandAttributeDefaults() {
2650 return defaultParseOptions.isExpandAttributeDefaults();
2651 }
2652
2653
2654 /**
2655 * Get the target namepool to be used for stylesheets/queries and for source documents.
2656 *
2657 * @return the target name pool. If no NamePool has been specified explicitly, the
2658 * default NamePool is returned.
2659 * @since 8.4
2660 */
2661
2662 public NamePool getNamePool() {
2663 return namePool;
2664 }
2665
2666 /**
2667 * Set the NamePool to be used for stylesheets/queries and for source documents.
2668 * <p> Using this method allows several Configurations to share the same NamePool. This
2669 * was the normal default arrangement until Saxon 8.9, which changed the default so
2670 * that each Configuration uses its own NamePool.</p>
2671 * <p>Sharing a NamePool creates a potential bottleneck, since changes to the namepool are
2672 * synchronized.</p>
2673 *
2674 * @param targetNamePool The NamePool to be used.
2675 * @since 8.4
2676 */
2677
2678 public void setNamePool(NamePool targetNamePool) {
2679 namePool = targetNamePool;
2680 }
2681
2682 /**
2683 * Get the TypeHierarchy: a cache holding type information
2684 *
2685 * @return the type hierarchy cache
2686 */
2687
2688 public TypeHierarchy getTypeHierarchy() {
2689 if (typeHierarchy == null) {
2690 typeHierarchy = new TypeHierarchy(this);
2691 }
2692 return typeHierarchy;
2693 }
2694
2695 /**
2696 * Get an appropriate type-checker. The type-checker that is
2697 * returned depends on whether backwards compatible (XPath 1.0) mode
2698 * is enabled (which requires Saxon-PE or higher)
2699 *
2700 * @param backwardsCompatible set to true if XPath 1.0 compatibility mode is required
2701 * @return a suitable TypeChecker
2702 */
2703
2704 public TypeChecker getTypeChecker(boolean backwardsCompatible) {
2705 if (backwardsCompatible) {
2706 return typeChecker10;
2707 } else {
2708 return typeChecker;
2709 }
2710 }
2711
2712 /**
2713 * Make a TypeAliasManager appropriate to the type of Configuration
2714 *
2715 * @return a new TypeAliasManager
2716 */
2717
2718 public TypeAliasManager makeTypeAliasManager() {
2719 return new TypeAliasManager();
2720 }
2721
2722 /**
2723 * Get the document number allocator.
2724 * <p>The document number allocator is used to allocate a unique number to each document built under this
2725 * configuration. The document number forms the basis of all tests for node identity; it is therefore essential
2726 * that when two documents are accessed in the same XPath expression, they have distinct document numbers.
2727 * Normally this is ensured by building them under the same Configuration. Using this method together with
2728 * {@link #setDocumentNumberAllocator}, however, it is possible to have two different Configurations that share
2729 * a single DocumentNumberAllocator</p>
2730 *
2731 * @return the current DocumentNumberAllocator
2732 * @since 9.0
2733 */
2734
2735 public DocumentNumberAllocator getDocumentNumberAllocator() {
2736 return documentNumberAllocator;
2737 }
2738
2739 /**
2740 * Set the document number allocator.
2741 * <p>The document number allocator is used to allocate a unique number to each document built under this
2742 * configuration. The document number forms the basis of all tests for node identity; it is therefore essential
2743 * that when two documents are accessed in the same XPath expression, they have distinct document numbers.
2744 * Normally this is ensured by building them under the same Configuration. Using this method together with
2745 * {@link #getDocumentNumberAllocator}, however, it is possible to have two different Configurations that share
2746 * a single DocumentNumberAllocator</p>
2747 * <p>This method is for advanced applications only. Misuse of the method can cause problems with node identity.
2748 * The method should not be used except while initializing a Configuration, and it should be used only to
2749 * arrange for two different configurations to share the same DocumentNumberAllocators. In this case they
2750 * should also share the same NamePool.</p>
2751 *
2752 * @param allocator the DocumentNumberAllocator to be used
2753 * @since 9.0
2754 */
2755
2756 public void setDocumentNumberAllocator(DocumentNumberAllocator allocator) {
2757 documentNumberAllocator = allocator;
2758 }
2759
2760 /**
2761 * Determine whether two Configurations are compatible. When queries, transformations, and path expressions
2762 * are run, all the Configurations used to build the documents and to compile the queries and stylesheets
2763 * must be compatible. Two Configurations are compatible if they share the same NamePool and the same
2764 * DocumentNumberAllocator.
2765 *
2766 * @param other the other Configuration to be compared with this one
2767 * @return true if the two configurations are compatible
2768 */
2769
2770 public boolean isCompatible(Configuration other) {
2771 return namePool == other.namePool && documentNumberAllocator == other.documentNumberAllocator;
2772 }
2773
2774 /**
2775 * Get the global document pool. This is used for documents preloaded during query or stylesheet
2776 * compilation. The user application can preload documents into the global pool, where they will be found
2777 * if any query or stylesheet requests the specified document using the doc() or document() function.
2778 *
2779 * @return the global document pool
2780 * @since 9.1
2781 */
2782
2783 public DocumentPool getGlobalDocumentPool() {
2784 return globalDocumentPool;
2785 }
2786
2787 /**
2788 * Determine whether whitespace-only text nodes are to be stripped unconditionally
2789 * from source documents.
2790 *
2791 * @return true if the space stripping rules for the default parseOptions cause whitespace text
2792 * nodes to be stripped from all elements.
2793 * @since 8.4
2794 */
2795
2796 public boolean isStripsAllWhiteSpace() {
2797 return defaultParseOptions.getSpaceStrippingRule() == AllElementsSpaceStrippingRule.getInstance();
2798 }
2799
2800 /**
2801 * Determine whether whitespace-only text nodes are to be stripped unconditionally
2802 * from source documents.
2803 *
2804 * @param stripsAllWhiteSpace if all whitespace-only text nodes are to be stripped. Passing
2805 * the value false causes no change to the current settings.
2806 * @since 8.4
2807 * @deprecated since 9.8: use getParseOptions().setSpaceStrippingRule(AllElementsSpaceStrippingRule.getInstance())
2808 */
2809
2810 public void setStripsAllWhiteSpace(boolean stripsAllWhiteSpace) {
2811 if (stripsAllWhiteSpace) {
2812 defaultParseOptions.setSpaceStrippingRule(AllElementsSpaceStrippingRule.getInstance());
2813 }
2814 }
2815
2816 /**
2817 * Get an XML parser for source documents.
2818 * <p>This method is intended primarily for internal use.</p>
2819 *
2820 * @return a parser
2821 */
2822
2823 public XMLReader createXMLParser() {
2824 XMLReader parser;
2825
2826 if (getSourceParserClass() != null) {
2827 parser = makeParser(getSourceParserClass());
2828 } else {
2829 parser = loadParser();
2830 }
2831 return parser;
2832
2833 }
2834
2835
2836 /**
2837 * Get a parser for source documents. The parser is allocated from a pool if any are available
2838 * from the pool: the client should ideally return the parser to the pool after use, so that it
2839 * can be reused.
2840 * <p>This method is intended primarily for internal use.</p>
2841 *
2842 * @return a parser, in which the namespace properties must be set as follows:
2843 * namespaces=true; namespace-prefixes=false. The DTD validation feature of the parser will be set
2844 * on or off depending on the {@link #setValidation(boolean)} setting.
2845 * @throws javax.xml.transform.TransformerFactoryConfigurationError if a failure occurs
2846 * configuring the parser for use.
2847 */
2848
2849 public XMLReader getSourceParser() throws TransformerFactoryConfigurationError {
2850 if (sourceParserPool == null) {
2851 sourceParserPool = new ConcurrentLinkedQueue<>();
2852 }
2853 XMLReader parser = sourceParserPool.poll();
2854 if (parser != null) {
2855 return parser;
2856 }
2857
2858 if (getSourceParserClass() != null) {
2859 parser = makeParser(getSourceParserClass());
2860 } else {
2861 parser = loadParser();
2862 }
2863 if (isTiming()) {
2864 reportParserDetails(parser);
2865 }
2866 try {
2867 Sender.configureParser(parser);
2868 } catch (XPathException err) {
2869 throw new TransformerFactoryConfigurationError(err);
2870 }
2871 if (isValidation()) {
2872 try {
2873 parser.setFeature("http://xml.org/sax/features/validation", true);
2874 } catch (SAXException err) {
2875 throw new TransformerFactoryConfigurationError("The XML parser does not support validation");
2876 }
2877 }
2878
2879 return parser;
2880 }
2881
2882 /**
2883 * Report the parser details to the standard error output
2884 *
2885 * @param reader the parser
2886 */
2887
2888 private void reportParserDetails(XMLReader reader) {
2889 String name = reader.getClass().getName();
2890 // if (name.equals("com.sun.org.apache.xerces.internal.parsers.SAXParser")) {
2891 // name += " version " + com.sun.org.apache.xerces.internal.impl.Version.getVersion();
2892 // }
2893 traceOutput.info("Using parser " + name);
2894 }
2895
2896 /**
2897 * Return a source parser to the pool, for reuse
2898 *
2899 * @param parser The parser: the caller must not supply a parser that was obtained by any
2900 * mechanism other than calling the getSourceParser() method.
2901 * Must not be null.
2902 */
2903
2904 public synchronized void reuseSourceParser(/*@NotNull*/ XMLReader parser) {
2905 if (sourceParserPool == null) {
2906 sourceParserPool = new ConcurrentLinkedQueue<>();
2907 }
2908 try {
2909 try {
2910 // give things back to the garbage collecter
2911 parser.setContentHandler(null);
2912 if (parser.getEntityResolver() == defaultParseOptions.getEntityResolver()) {
2913 parser.setEntityResolver(null);
2914 }
2915 parser.setDTDHandler(null);
2916 parser.setErrorHandler(null);
2917 // Unfortunately setting the lexical handler to null doesn't work on Xerces, because
2918 // it tests "value instanceof LexicalHandler". So we set it to a lexical handler that
2919 // holds no references
2920 parser.setProperty("http://xml.org/sax/properties/lexical-handler", dummyLexicalHandler);
2921 } catch (SAXNotRecognizedException | SAXNotSupportedException err) {
2922 //
2923 }
2924 sourceParserPool.offer(parser);
2925 } catch (Exception e) {
2926 // setting the callbacks on an XMLReader to null doesn't always work; some parsers throw a
2927 // NullPointerException. If anything goes wrong, the simplest approach is to ignore the error
2928 // and not attempt to reuse the parser.
2929 }
2930 }
2931
2932 /**
2933 * Get a parser by instantiating the SAXParserFactory
2934 *
2935 * @return the parser (XMLReader)
2936 */
2937
2938 private static XMLReader loadParser() {
2939 return Version.platform.loadParser();
2940 }
2941
2942 /**
2943 * Get the parser for stylesheet documents. This parser is also used for schema documents.
2944 * <p>This method is intended for internal use only.</p>
2945 *
2946 * @return an XML parser (a SAX2 parser) that can be used for stylesheets and schema documents
2947 * @throws javax.xml.transform.TransformerFactoryConfigurationError if an error occurs
2948 * configuring the parser
2949 */
2950
2951 public synchronized XMLReader getStyleParser() throws TransformerFactoryConfigurationError {
2952 if (styleParserPool == null) {
2953 styleParserPool = new ConcurrentLinkedQueue<>();
2954 }
2955 XMLReader parser = styleParserPool.poll();
2956 if (parser != null) {
2957 return parser;
2958 }
2959
2960 if (getStyleParserClass() != null) {
2961 parser = makeParser(getStyleParserClass());
2962 } else {
2963 parser = loadParser();
2964 StandardEntityResolver resolver = new StandardEntityResolver();
2965 resolver.setConfiguration(this);
2966 parser.setEntityResolver(resolver);
2967 }
2968 try {
2969 parser.setFeature("http://xml.org/sax/features/namespaces", true);
2970 parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
2971 } catch (SAXNotRecognizedException | SAXNotSupportedException e) {
2972 throw new TransformerFactoryConfigurationError(e);
2973 }
2974 // Following code attempts to bypass attribute value normalization for stylesheets: see bug 2445.
2975 // It works (the XercesAdapter has been dropped, but will be found somewhere in Subversion) but
2976 // there are question marks over conformance, as there will be incompatibilities in edge cases
2977 // for example when newlines appear within string literals within XPath expressions.
2978 // if (parser.getClass().getCanonicalName().equals("org.apache.xerces.jaxp.SAXParserImpl.JAXPSAXParser")) {
2979 // try {
2980 // parser = new net.sf.saxon.event.XercesAdapter(parser);
2981 // } catch (ClassNotFoundException err) {
2982 // // ignore the error;
2983 // }
2984 // }
2985 return parser;
2986 }
2987
2988 private static LexicalHandler dummyLexicalHandler = new DefaultHandler2();
2989
2990 /**
2991 * Return a stylesheet (or schema) parser to the pool, for reuse
2992 *
2993 * @param parser The parser: the caller must not supply a parser that was obtained by any
2994 * mechanism other than calling the getStyleParser() method.
2995 */
2996
2997 public synchronized void reuseStyleParser(XMLReader parser) {
2998 if (styleParserPool == null) {
2999 styleParserPool = new ConcurrentLinkedQueue<>();
3000 }
3001 try {
3002 try {
3003 // give things back to the garbage collecter
3004 parser.setContentHandler(null);
3005 //parser.setEntityResolver(null);
3006 parser.setDTDHandler(null);
3007 parser.setErrorHandler(null);
3008 // Unfortunately setting the lexical handler to null doesn't work on Xerces, because
3009 // it tests "value instanceof LexicalHandler". Instead we set the lexical handler to one
3010 // that holds no references
3011 parser.setProperty("http://xml.org/sax/properties/lexical-handler", dummyLexicalHandler);
3012 } catch (SAXNotRecognizedException | SAXNotSupportedException err) {
3013 //
3014 }
3015 styleParserPool.offer(parser);
3016 } catch (Exception e) {
3017 // setting the callbacks on an XMLReader to null doesn't always work; some parsers throw a
3018 // NullPointerException. If anything goes wrong, the simplest approach is to ignore the error
3019 // and not attempt to reuse the parser.
3020 }
3021 }
3022
3023 /**
3024 * Simple interface to load a schema document
3025 *
3026 * @param absoluteURI the absolute URI of the location of the schema document
3027 * @throws net.sf.saxon.type.SchemaException if the schema document at the given location cannot be read or is invalid
3028 */
3029
3030 public void loadSchema(String absoluteURI) throws SchemaException {
3031 readSchema(makePipelineConfiguration(), "", absoluteURI, null);
3032 }
3033
3034 /**
3035 * Read a schema from a given schema location
3036 * <p>This method is intended for internal use.</p>
3037 *
3038 * @param pipe the PipelineConfiguration
3039 * @param baseURI the base URI of the instruction requesting the reading of the schema
3040 * @param schemaLocation the location of the schema to be read
3041 * @param expected The expected targetNamespace of the schema being read, or null if there is no expectation
3042 * @return the target namespace of the schema; null if no schema has been read
3043 * @throws UnsupportedOperationException when called in the non-schema-aware version of the product
3044 * @throws net.sf.saxon.type.SchemaException if the schema cannot be read
3045 */
3046
3047 /*@Nullable*/
3048 public String readSchema(PipelineConfiguration pipe, String baseURI, String schemaLocation, /*@Nullable*/ String expected)
3049 throws SchemaException {
3050 needEnterpriseEdition();
3051 return null;
3052 }
3053
3054 /**
3055 * Read schemas from a list of schema locations.
3056 * <p>This method is intended for internal use.</p>
3057 *
3058 * @param pipe the pipeline configuration
3059 * @param baseURI the base URI against which the schema locations are to be resolved
3060 * @param schemaLocations the relative URIs specified as schema locations
3061 * @param expected the namespace URI which is expected as the target namespace of the loaded schema
3062 * @throws net.sf.saxon.type.SchemaException if an error occurs
3063 */
3064
3065 public void readMultipleSchemas(PipelineConfiguration pipe, String baseURI, Collection<String> schemaLocations, String expected)
3066 throws SchemaException {
3067 needEnterpriseEdition();
3068 }
3069
3070
3071 /**
3072 * Read an inline schema from a stylesheet.
3073 * <p>This method is intended for internal use.</p>
3074 *
3075 * @param root the xs:schema element in the stylesheet
3076 * @param expected the target namespace expected; null if there is no
3077 * expectation.
3078 * @param errorListener The destination for error messages. May be null, in which case
3079 * the errorListener registered with this Configuration is used.
3080 * @return the actual target namespace of the schema
3081 * @throws net.sf.saxon.type.SchemaException if the schema cannot be processed
3082 */
3083
3084 /*@Nullable*/
3085 public String readInlineSchema(NodeInfo root, String expected, ErrorListener errorListener)
3086 throws SchemaException {
3087 needEnterpriseEdition();
3088 return null;
3089 }
3090
3091 /**
3092 * Throw an error indicating that a request cannot be satisfied because it requires
3093 * the schema-aware edition of Saxon
3094 */
3095
3096 protected void needEnterpriseEdition() {
3097 throw new UnsupportedOperationException(
3098 "You need the Enterprise Edition of Saxon (with an EnterpriseConfiguration) for this operation");
3099 }
3100
3101 /**
3102 * Load a schema, which will be available for use by all subsequent operations using
3103 * this Configuration. Any errors will be notified to the ErrorListener associated with
3104 * this Configuration.
3105 *
3106 * @param schemaSource the JAXP Source object identifying the schema document to be loaded
3107 * @throws SchemaException if the schema cannot be read or parsed or if it is invalid
3108 * @throws UnsupportedOperationException if the configuration is not schema-aware
3109 * @since 8.4
3110 */
3111
3112 public void addSchemaSource(Source schemaSource) throws SchemaException {
3113 addSchemaSource(schemaSource, getErrorListener());
3114 }
3115
3116 /**
3117 * Load a schema, which will be available for use by all subsequent operations using
3118 * this EnterpriseConfiguration.
3119 *
3120 * @param schemaSource the JAXP Source object identifying the schema document to be loaded
3121 * @param errorListener the ErrorListener to be notified of any errors in the schema.
3122 * @throws SchemaException if the schema cannot be read or parsed or if it is invalid
3123 */
3124
3125 public void addSchemaSource(Source schemaSource, ErrorListener errorListener) throws SchemaException {
3126 needEnterpriseEdition();
3127 }
3128
3129
3130 /**
3131 * Add a built-in schema for a given namespace. This is a no-op if the configuration is not schema-aware
3132 *
3133 * @param namespace the namespace. Currently built-in schemas are available for the XML and FN namespaces
3134 */
3135
3136 public void addSchemaForBuiltInNamespace(String namespace) {
3137 // no action
3138 }
3139
3140 /**
3141 * Determine whether the Configuration contains a cached schema for a given target namespace
3142 *
3143 * @param targetNamespace the target namespace of the schema being sought (supply "" for the
3144 * unnamed namespace)
3145 * @return true if the schema for this namespace is available, false if not.
3146 */
3147
3148 public boolean isSchemaAvailable(String targetNamespace) {
3149 return false;
3150 }
3151
3152 /**
3153 * Remove all schema components that have been loaded into this Configuration.
3154 * This method must not be used if any processes (such as stylesheet or query compilations
3155 * or executions) are currently active. In a multi-threaded environment, it is the user's
3156 * responsibility to ensure that this method is not called unless it is safe to do so.
3157 */
3158
3159 @SuppressWarnings({"UnusedDeclaration"})
3160 public void clearSchemaCache() {
3161 // no-op except in Saxon-EE
3162 }
3163
3164 /**
3165 * Get the set of namespaces of imported schemas
3166 *
3167 * @return a Set whose members are the namespaces of all schemas in the schema cache, as
3168 * String objects
3169 */
3170
3171 public Set<String> getImportedNamespaces() {
3172 return Collections.emptySet();
3173 }
3174
3175 /**
3176 * Mark a schema namespace as being sealed. This is done when components from this namespace
3177 * are first used for validating a source document or compiling a source document or query. Once
3178 * a namespace has been sealed, it is not permitted to change the schema components in that namespace
3179 * by redefining them, deriving new types by extension, or adding to their substitution groups.
3180 *
3181 * @param namespace the namespace URI of the components to be sealed
3182 */
3183
3184 public void sealNamespace(String namespace) {
3185 //
3186 }
3187
3188 /**
3189 * Get the set of saxon:param schema parameters declared in the schema held by this Configuration.
3190 *
3191 * @return the set of parameters. May return null if none have been declared.
3192 */
3193
3194 public Collection<GlobalParam> getDeclaredSchemaParameters() {
3195 return null;
3196 }
3197
3198 /**
3199 * Get the set of complex types that have been defined as extensions of a given type.
3200 * Note that we do not seal the schema namespace, so this list is not necessarily final; we must
3201 * assume that new extensions of built-in simple types can be added at any time
3202 *
3203 * @param type the type whose extensions are required
3204 * @return an iterator over the types that are derived from the given type by extension
3205 */
3206
3207 public Iterator<? extends SchemaType> getExtensionsOfType(SchemaType type) {
3208 Set<SchemaType> e = Collections.emptySet();
3209 return e.iterator();
3210 }
3211
3212 /**
3213 * Import a precompiled Schema Component Model from a given Source. The schema components derived from this schema
3214 * document are added to the cache of schema components maintained by this SchemaManager
3215 *
3216 * @param source the XML file containing the schema component model, as generated by a previous call on
3217 * {@link #exportComponents}
3218 * @throws net.sf.saxon.trans.XPathException if an error occurs
3219 */
3220
3221 public void importComponents(Source source) throws XPathException {
3222 needEnterpriseEdition();
3223 }
3224
3225 /**
3226 * Export a precompiled Schema Component Model containing all the components (except built-in components)
3227 * that have been loaded into this Processor.
3228 *
3229 * @param out the destination to recieve the precompiled Schema Component Model in the form of an
3230 * XML document
3231 * @throws net.sf.saxon.trans.XPathException if a failure occurs
3232 */
3233
3234 public void exportComponents(Receiver out) throws XPathException {
3235 needEnterpriseEdition();
3236 }
3237
3238 /**
3239 * Get information about the schema in the form of a function item. Supports the extension function
3240 * saxon:schema
3241 *
3242 * @return null for a non-schema-aware configuration
3243 */
3244
3245 public Function getSchemaAsFunctionItem() {
3246 return null;
3247 }
3248
3249 /**
3250 * Get information about the schema in the form of a function item. Supports the extension function
3251 * saxon:schema
3252 *
3253 * @param kind the component kind, e.g. "element declaration"
3254 * @param name the component name
3255 * @return null for a non-schema-aware configuration
3256 * @throws XPathException if an error occurs
3257 */
3258
3259 public Function getSchemaComponentAsFunctionItem(String kind, QNameValue name) throws XPathException {
3260 return null;
3261 }
3262
3263 /**
3264 * Get a global element declaration by fingerprint
3265 *
3266 * @param fingerprint the NamePool fingerprint of the element name
3267 * @return the element declaration whose name matches the given
3268 * fingerprint, or null if no element declaration with this name has
3269 * been registered.
3270 */
3271
3272 public SchemaDeclaration getElementDeclaration(int fingerprint) {
3273 return null;
3274 }
3275
3276 /**
3277 * Get a global element declaration by name.
3278 *
3279 * @param qName the name of the required
3280 * element declaration
3281 * @return the element declaration whose name matches the given
3282 * name, or null if no element declaration with this name has
3283 * been registered.
3284 */
3285
3286
3287 public SchemaDeclaration getElementDeclaration(StructuredQName qName) {
3288 return null;
3289 }
3290
3291 /**
3292 * Get a global attribute declaration by fingerprint
3293 *
3294 * @param fingerprint the NamePool fingerprint of the element name
3295 * @return the attribute declaration whose name matches the given
3296 * fingerprint, or null if no element declaration with this name has
3297 * been registered.
3298 */
3299
3300 public SchemaDeclaration getAttributeDeclaration(int fingerprint) {
3301 return null;
3302 }
3303
3304 /**
3305 * Get a global attribute declaration by name
3306 *
3307 * @param attributeName the name of the required attribute declaration
3308 * @return the attribute declaration whose name matches the given
3309 * fingerprint, or null if no element declaration with this name has
3310 * been registered.
3311 */
3312
3313 public SchemaDeclaration getAttributeDeclaration(StructuredQName attributeName) {
3314 return null;
3315 }
3316
3317 /**
3318 * Get the top-level schema type definition with a given QName.
3319 *
3320 * @param name the name of the required schema type
3321 * @return the schema type , or null if there is none
3322 * with this name.
3323 * @since 9.7
3324 */
3325
3326 /*@Nullable*/
3327 public SchemaType getSchemaType(StructuredQName name) {
3328 if (name.hasURI(NamespaceConstant.SCHEMA)) {
3329 return BuiltInType.getSchemaTypeByLocalName(name.getLocalPart());
3330 }
3331 return null;
3332 }
3333
3334 /**
3335 * Make a union type with a given list of member types
3336 *
3337 * @param memberTypes the member types
3338 * @return null for a Saxon-HE or -PE Configuration
3339 */
3340
3341 public ItemType makeUserUnionType(List<AtomicType> memberTypes) {
3342 return null;
3343 }
3344
3345 /**
3346 * Ask whether a given notation has been declared in the schema
3347 *
3348 * @param uri the targetNamespace of the notation
3349 * @param local the local part of the notation name
3350 * @return true if the notation has been declared, false if not
3351 * @since 9.3
3352 */
3353
3354 public boolean isDeclaredNotation(String uri, String local) {
3355 return false;
3356 }
3357
3358 /**
3359 * Check that a type is validly derived from another type, following the rules for the Schema Component
3360 * Constraint "Is Type Derivation OK (Simple)" (3.14.6) or "Is Type Derivation OK (Complex)" (3.4.6) as
3361 * appropriate.
3362 *
3363 * @param derived the derived type
3364 * @param base the base type; the algorithm tests whether derivation from this type is permitted
3365 * @param block the derivations that are blocked by the relevant element declaration
3366 * @throws SchemaException if the derivation is not allowed
3367 */
3368
3369 public void checkTypeDerivationIsOK(SchemaType derived, SchemaType base, int block)
3370 throws SchemaException {
3371 // no action. Although the method can be used to check built-in types, it is never
3372 // needed in the non-schema-aware product
3373 }
3374
3375 /**
3376 * Set validation reporting options. Called by instructions that invoke validation
3377 * to set up an appropriat invalidity handler
3378 *
3379 * @param context the XPath evaluation context
3380 * @param options the parser options, to be updated
3381 */
3382
3383 public void prepareValidationReporting(XPathContext context, ParseOptions options) {
3384 }
3385
3386 /**
3387 * Get a document-level validator to add to a Receiver pipeline.
3388 * <p>This method is intended for internal use.</p>
3389 *
3390 * @param receiver The receiver to which events should be sent after validation
3391 * @param systemId the base URI of the document being validated
3392 * @param validationOptions Supplies options relevant to XSD validation
3393 * @param initiatingLocation The location of the expression that requested validation
3394 * @return A Receiver to which events can be sent for validation
3395 */
3396
3397 public Receiver getDocumentValidator(Receiver receiver,
3398 String systemId,
3399 ParseOptions validationOptions,
3400 Location initiatingLocation) {
3401 // non-schema-aware version
3402 return receiver;
3403 }
3404
3405 /**
3406 * Get a Receiver that can be used to validate an element, and that passes the validated
3407 * element on to a target receiver. If validation is not supported, the returned receiver
3408 * will be the target receiver.
3409 * <p>This method is intended for internal use.</p>
3410 *
3411 * @param receiver the target receiver tp receive the validated element
3412 * @param validationOptions options affecting the way XSD validation is done
3413 * @param locationId current location in the stylesheet or query
3414 * @return The target receiver, indicating that with this configuration, no validation
3415 * is performed.
3416 * @throws net.sf.saxon.trans.XPathException if a validator for the element cannot be created
3417 */
3418
3419 public Receiver getElementValidator(Receiver receiver,
3420 ParseOptions validationOptions,
3421 Location locationId)
3422 throws XPathException {
3423 return receiver;
3424 }
3425
3426 /**
3427 * Validate an attribute value.
3428 * <p>This method is intended for internal use.</p>
3429 *
3430 * @param nodeName the name of the attribute
3431 * @param value the value of the attribute as a string
3432 * @param validation STRICT or LAX
3433 * @return the type annotation to apply to the attribute node
3434 * @throws ValidationException if the value is invalid
3435 */
3436
3437 public SimpleType validateAttribute(StructuredQName nodeName, CharSequence value, int validation)
3438 throws ValidationException, MissingComponentException {
3439 return BuiltInAtomicType.UNTYPED_ATOMIC;
3440 }
3441
3442 /**
3443 * Add to a pipeline a receiver that strips all type annotations. This
3444 * has a null implementation in the Saxon-HE product, because type annotations
3445 * can never arise.
3446 * <p>This method is intended for internal use.</p>
3447 *
3448 * @param destination the Receiver that events will be written to after whitespace stripping
3449 * @return the Receiver to which events should be sent for stripping
3450 */
3451
3452 public Receiver getAnnotationStripper(Receiver destination) {
3453 return destination;
3454 }
3455
3456 /**
3457 * Create a new SAX XMLReader object using the class name provided.
3458 * <p>The named class must exist and must implement the
3459 * org.xml.sax.XMLReader or Parser interface.</p>
3460 * <p>This method returns an instance of the parser named.</p>
3461 * <p>This method is intended for internal use.</p>
3462 *
3463 * @param className A string containing the name of the
3464 * SAX parser class, for example "com.microstar.sax.LarkDriver"
3465 * @return an instance of the Parser class named, or null if it is not
3466 * loadable or is not a Parser.
3467 * @throws javax.xml.transform.TransformerFactoryConfigurationError if a failure
3468 * occurs configuring the parser of this class
3469 */
3470 public XMLReader makeParser(String className)
3471 throws TransformerFactoryConfigurationError {
3472 try {
3473 Object obj = dynamicLoader.getInstance(className, null);
3474 if (obj instanceof XMLReader) {
3475 return (XMLReader) obj;
3476 }
3477 if (obj instanceof SAXParserFactory) {
3478 try {
3479 SAXParser saxParser = ((SAXParserFactory) obj).newSAXParser();
3480 return saxParser.getXMLReader();
3481 } catch (ParserConfigurationException | SAXException e) {
3482 throw new XPathException(e);
3483 }
3484 }
3485 } catch (XPathException err) {
3486 throw new TransformerFactoryConfigurationError(err);
3487 }
3488
3489 throw new TransformerFactoryConfigurationError("Class " + className +
3490 " is not a SAX2 XMLReader or SAXParserFactory");
3491 }
3492
3493 /**
3494 * Make an expression Parser for a specified version of XPath or XQuery
3495 *
3496 * @param language set to "XP" (XPath) or "XQ" (XQuery) or "PATTERN" (XSLT Patterns)
3497 * @param updating indicates whether or not XQuery update syntax may be used. Note that XQuery Update
3498 * is supported only in Saxon-EE
3499 * @param languageVersion the required version (e.g 10 for "1.0", 30 for "3.0", 31 for "3.1").
3500 * A request for XQuery 1.0 or 3.0 delivers an XQuery 3.1 parser. The values
3501 * supported for XPath are 20 (=2.0), 30 (=3.0), 31 (=3.1), and 305 (=XPath 3.0
3502 * plus the syntax extensions defined in XSLT 3.0).
3503 * @return the QueryParser
3504 * @throws net.sf.saxon.trans.XPathException if this version of Saxon does not support the
3505 * requested options
3506 */
3507
3508 public XPathParser newExpressionParser(String language, boolean updating, int languageVersion) throws XPathException {
3509 if ("XQ".equals(language)) {
3510 if (updating) {
3511 throw new XPathException("XQuery Update is supported only in Saxon-EE");
3512 } else if (languageVersion == 31 || languageVersion == 30 || languageVersion == 10) {
3513 XQueryParser parser = new XQueryParser();
3514 parser.setLanguage(XPathParser.XQUERY, 31);
3515 return parser;
3516 } else {
3517 throw new XPathException("Unknown XQuery version " + languageVersion);
3518 }
3519 } else if ("XP".equals(language)) {
3520 if (languageVersion == 31 || languageVersion == 30 || languageVersion == 305 || languageVersion == 20) {
3521 XPathParser parser = new XPathParser();
3522 parser.setLanguage(XPathParser.XPATH, languageVersion);
3523 return parser;
3524 } else {
3525 throw new XPathException("Unknown XPath version " + languageVersion);
3526 }
3527 } else if ("PATTERN".equals(language)) {
3528 if (languageVersion == 30 || languageVersion == 20 || languageVersion == 305 || languageVersion == 31) {
3529 return new PatternParser30();
3530 } else {
3531 throw new XPathException("Unknown XPath version " + languageVersion);
3532 }
3533 } else {
3534 throw new XPathException("Unknown expression language " + language);
3535 }
3536 }
3537
3538 /**
3539 * Get a new ExpressionPresenter capable of exporting a compiled stylesheet
3540 * @param target the target environment, e.g. EE, JS, JS2
3541 * @param destination the destination for the output file
3542 * @param rootPackage the root package of the export
3543 * @return a suitable Expression Presenter
3544 * @throws XPathException if none is available (e.g. because this is not Saxon-EE)
3545 */
3546
3547 public ExpressionPresenter newExpressionExporter(String target, OutputStream destination, StylesheetPackage rootPackage) throws XPathException {
3548 throw new XPathException("Exporting a stylesheet requires Saxon-EE");
3549 }
3550
3551 /**
3552 * Set the debugger to be used.
3553 * <p>This method is provided for advanced users only, and is subject to change.</p>
3554 *
3555 * @param debugger the debugger to be used, or null if no debugger is to be used
3556 */
3557
3558 @SuppressWarnings({"UnusedDeclaration"})
3559 public void setDebugger(/*@Nullable*/ Debugger debugger) {
3560 this.debugger = debugger;
3561 }
3562
3563 /**
3564 * Get the debugger in use. This will be null if no debugger has been registered.
3565 * <p>This method is provided for advanced users only, and is subject to change.</p>
3566 *
3567 * @return the debugger in use, or null if none is in use
3568 */
3569
3570 /*@Nullable*/
3571 @SuppressWarnings({"UnusedDeclaration"})
3572 public Debugger getDebugger() {
3573 return debugger;
3574 }
3575
3576 /**
3577 * Factory method to create a SlotManager.
3578 * <p>This method is provided for advanced users only, and is subject to change.</p>
3579 *
3580 * @return a SlotManager (which is a skeletal stack frame representing the mapping of variable
3581 * names to slots on the stack frame)
3582 */
3583
3584 public SlotManager makeSlotManager() {
3585 if (debugger == null) {
3586 return new SlotManager();
3587 } else {
3588 return debugger.makeSlotManager();
3589 }
3590 }
3591
3592 /**
3593 * Create a streaming transformer
3594 *
3595 * @param context the initial XPath context
3596 * @param mode the initial mode, which must be a streaming mode
3597 * @param ordinaryParams the parameters that are not tunnel parameters
3598 * @param tunnelParams the tunnel parameters
3599 * @return a Receiver to which the streamed input document will be pushed
3600 * @throws XPathException if a streaming transformer cannot be created (which
3601 * is always the case in Saxon-HE and Saxon-PE)
3602 */
3603
3604 /*@NotNull*/
3605 public Receiver makeStreamingTransformer(XPathContext context, Mode mode, ParameterSet ordinaryParams, ParameterSet tunnelParams) throws XPathException {
3606 throw new XPathException("Streaming is only available in Saxon-EE");
3607 }
3608
3609 public Expression makeStreamInstruction(Expression hrefExp, Expression body, boolean streaming, ParseOptions options,
3610 PackageData packageData, Location location, RetainedStaticContext rsc) throws XPathException {
3611 SourceDocument si = new SourceDocument(hrefExp, body, options);
3612 si.setLocation(location);
3613 si.setRetainedStaticContext(rsc);
3614 return si;
3615 }
3616
3617 /**
3618 * Get a factory function that can be used to wrap a SequenceIterator in a FocusTrackingIterator. This
3619 * is called by the {@link Controller} to get a default factory function; the value can be overridden
3620 * by the application using {@link Controller#setFocusTrackerFactory(java.util.function.Function)}.
3621 * The {@link FocusTrackingIterator} that is created by the factory must be thread-safe if it is
3622 * to be used for iterating over a sequence where the items might be processed asynchronously using
3623 * <code>xsl:result-document</code>; for this reason this method is overridden for a Saxon-EE configuration.
3624 * @param exec the executable; supplied so that the factory can be sensitive to whether calls on xsl:result-document
3625 * are possible
3626 * @param multithreaded set to true to get a factory suitable for creating focus tracking iterators for a
3627 * multi-threaded xsl:for-each instruction
3628 * @return a suitable factory function
3629 */
3630
3631 public java.util.function.Function<SequenceIterator<?>, FocusTrackingIterator<?>> getFocusTrackerFactory(
3632 Executable exec, boolean multithreaded) {
3633 return FocusTrackingIterator::new;
3634 }
3635
3636 /**
3637 * Check the streamability of a template rule
3638 */
3639
3640 public void checkStrictStreamability(XSLTemplate template, Expression body) throws XPathException {
3641 // no action in Saxon-HE
3642 }
3643
3644 /**
3645 * Ask whether a given node is a streamed node
3646 * @param node the node in question
3647 * @return true if the node is a node in a streamed document
3648 */
3649
3650 public boolean isStreamedNode(NodeInfo node) {
3651 return false; // streaming needs Saxon-EE
3652 // TODO: make this a property of a node (or of a TreeInfo)
3653 }
3654
3655 /**
3656 * Get the optimization options in use
3657 * @return the configured optimization options
3658 */
3659
3660 public OptimizerOptions getOptimizerOptions() {
3661 return optimizerOptions.intersect(OptimizerOptions.FULL_HE_OPTIMIZATION);
3662 }
3663
3664 /**
3665 * Factory method to get an Optimizer.
3666 * <p>This method is intended for internal use only.</p>
3667 *
3668 * @return the optimizer used in this configuration, which is created if necessary
3669 */
3670
3671 /*@NotNull*/
3672 public Optimizer obtainOptimizer() {
3673 if (optimizer == null) {
3674 optimizer = new Optimizer(this);
3675 optimizer.setOptimizerOptions(
3676 optimizerOptions.intersect(OptimizerOptions.FULL_HE_OPTIMIZATION));
3677 return optimizer;
3678 } else {
3679 return optimizer;
3680 }
3681 }
3682
3683 /**
3684 * Factory method to get an Optimizer with specified optimizer options.
3685 * <p>This method is intended for internal use only.</p>
3686 *
3687 * @param options the optimizer options
3688 * @return a new optimizer with the specified options set (provided the optimizations
3689 * are available in this Saxon configuration)
3690 */
3691
3692 /*@NotNull*/
3693 public Optimizer obtainOptimizer(OptimizerOptions options) {
3694 Optimizer optimizer = new Optimizer(this);
3695 optimizer.setOptimizerOptions(
3696 options.intersect(OptimizerOptions.FULL_HE_OPTIMIZATION));
3697 return optimizer;
3698 }
3699
3700 /**
3701 * Generate a function sequence coercer, that is, an expression which converts a sequence of function
3702 * items to a sequence of function items satisfying a given required type; the coerced functions call the
3703 * original function with arguments converted as necessary, or fail if conversion is not possible
3704 *
3705 * @param type the required function type
3706 * @param exp the expression that delivers a sequence of function items
3707 * @param role diagnostic information
3708 * @return an expression that converts the supplied sequence of functions to the required function type
3709 * @throws XPathException if conversion is not possible
3710 */
3711
3712 public Expression makeFunctionSequenceCoercer(SpecificFunctionType type, Expression exp,
3713 RoleDiagnostic role)
3714 throws XPathException {
3715 throw new XPathException("Function coercion requires Saxon-PE or higher");
3716 }
3717
3718 /**
3719 * Factory method to make a ContextItemStaticInfo
3720 *
3721 * @param itemType the item type of the context item. If the context item is absent, set this to
3722 * {@link net.sf.saxon.type.ErrorType#getInstance()}.
3723 * @param maybeUndefined set to true if it is possible (or certain) that the context item will be absent.
3724 * @return the ContextItemStaticInfo
3725 */
3726
3727 public ContextItemStaticInfo makeContextItemStaticInfo(ItemType itemType, boolean maybeUndefined) {
3728 return new ContextItemStaticInfo(itemType, maybeUndefined);
3729 }
3730
3731 /**
3732 * Get a default ContextItemStaticInfo, indication no information is available about the context item
3733 * type
3734 *
3735 * @return the default ContextItemStaticInfo
3736 */
3737
3738 public ContextItemStaticInfo getDefaultContextItemStaticInfo() {
3739 return ContextItemStaticInfo.DEFAULT;
3740 }
3741
3742 /**
3743 * Factory method to make an XQueryExpression
3744 *
3745 * @param exp the expression forming the body of the query
3746 * @param mainModule the query module containing the expression
3747 * @param streaming true if streamed execution is requested
3748 * @return the XQueryExpression
3749 * @throws XPathException if an error occurs
3750 */
3751
3752 public XQueryExpression makeXQueryExpression(Expression exp, QueryModule mainModule, boolean streaming) throws XPathException {
3753 return new XQueryExpression(exp, mainModule, false);
3754 }
3755
3756 /**
3757 * Make a Closure, given the expected reference count
3758 *
3759 * @param expression the expression to be evaluated
3760 * @param ref the (nominal) number of times the value of the expression is required
3761 * @param context the XPath dynamic evaluation context
3762 * @return the constructed Closure
3763 * @throws XPathException if a failure occurs constructing the Closure
3764 */
3765
3766 public Sequence<?> makeClosure(Expression expression, int ref, XPathContext context) throws XPathException {
3767 if (getBooleanProperty(Feature.EAGER_EVALUATION)) {
3768 // Using eager evaluation can make for easier debugging
3769 SequenceIterator<?> iter = expression.iterate(context);
3770 return iter.materialize();
3771 }
3772
3773 Closure closure = ref > 1 ? new MemoClosure() : new Closure();
3774 closure.setExpression(expression);
3775 closure.setSavedXPathContext(context.newContext());
3776 closure.saveContext(expression, context);
3777 return closure;
3778
3779 }
3780
3781 /**
3782 * Make a SequenceExtent, given the expected reference count
3783 *
3784 * @param expression the expression to be evaluated
3785 * @param ref the (nominal) number of times the value of the expression is required
3786 * @param context the XPath dynamic evaluation context
3787 * @return the constructed SequenceExtent
3788 * @throws XPathException if evaluation of the expression fails
3789 */
3790
3791 public GroundedValue<?> makeSequenceExtent(Expression expression, int ref, XPathContext context) throws XPathException {
3792 return expression.iterate(context).materialize();
3793 }
3794
3795
3796 /**
3797 * Factory method to make the StyleNodeFactory, used for constructing elements
3798 * in a stylesheet document
3799 *
3800 * @param compilation the compilation episode (compiling one package)
3801 * @return the StyleNodeFactory used in this Configuration
3802 */
3803
3804 public StyleNodeFactory makeStyleNodeFactory(Compilation compilation) {
3805 return new StyleNodeFactory(this, compilation);
3806 }
3807
3808 /**
3809 * Make an instruction to implement xsl:evaluate
3810 */
3811
3812 public Expression makeEvaluateInstruction(XSLEvaluate source, ComponentDeclaration decl) throws XPathException {
3813 return new ErrorExpression(new XPathException("xsl:evaluate is not available in this configuration", "XTDE3175"));
3814 // Should not be called: xsl:evaluate is not supported in Saxon-HE
3815 }
3816
3817 /**
3818 * Factory method to make a StylesheetPackage
3819 *
3820 * @return a StylesheetPackage suitable for use in this Configuration
3821 */
3822
3823 public StylesheetPackage makeStylesheetPackage() {
3824 return new StylesheetPackage(this);
3825 }
3826
3827 /**
3828 * Factory method to make the AccumulatorRegistry, used for static information
3829 * about the accumulators defined in a package
3830 *
3831 * @return a new AccumulatorRegistry appropriate to this Configuration
3832 */
3833
3834 public AccumulatorRegistry makeAccumulatorRegistry() {
3835 return new AccumulatorRegistry();
3836 }
3837
3838
3839 /**
3840 * Register an external object model with this Configuration.
3841 *
3842 * @param model The external object model.
3843 * This can either be one of the system-supplied external
3844 * object models for JDOM, XOM, or DOM, or a user-supplied external object model.
3845 * <p>This method is intended for advanced users only, and is subject to change.</p>
3846 */
3847
3848 public void registerExternalObjectModel(ExternalObjectModel model) {
3849 try {
3850 getClass(model.getDocumentClassName(), false, null);
3851 } catch (XPathException e) {
3852 // If the model can't be loaded, do nothing
3853 return;
3854 }
3855 if (externalObjectModels == null) {
3856 externalObjectModels = new ArrayList<>(4);
3857 }
3858 if (!externalObjectModels.contains(model)) {
3859 externalObjectModels.add(model);
3860 }
3861 }
3862
3863 /**
3864 * Get the external object model with a given URI, if registered
3865 *
3866 * @param uri the identifying URI of the required external object model
3867 * @return the requested external object model if available, or null otherwise
3868 */
3869
3870 /*@Nullable*/
3871 public ExternalObjectModel getExternalObjectModel(String uri) {
3872 for (ExternalObjectModel model : externalObjectModels) {
3873 if (model.getIdentifyingURI().equals(uri)) {
3874 return model;
3875 }
3876 }
3877 return null;
3878 }
3879
3880 /**
3881 * Get the external object model that recognizes a particular class of node, if available
3882 *
3883 * @param nodeClass the class of the Node object in the external object model
3884 * @return the requested external object model if available, or null otherwise
3885 */
3886
3887 /*@Nullable*/
3888 public ExternalObjectModel getExternalObjectModel(Class nodeClass) {
3889 for (ExternalObjectModel model : externalObjectModels) {
3890 PJConverter converter = model.getPJConverter(nodeClass);
3891 if (converter != null) {
3892 return model;
3893 }
3894 }
3895 return null;
3896 }
3897
3898 /**
3899 * Get all the registered external object models.
3900 * <p>This method is intended for internal use only.</p>
3901 *
3902 * @return a list of external object models supported. The members of the list are of
3903 * type {@link ExternalObjectModel}
3904 */
3905
3906 public List<ExternalObjectModel> getExternalObjectModels() {
3907 return externalObjectModels;
3908 }
3909
3910 /**
3911 * Get the JavaExternalObjectType object representing a particular Java class
3912 *
3913 * @param theClass the class in question
3914 * @return the corresponding JavaExternalObjectType
3915 */
3916
3917 public synchronized JavaExternalObjectType getJavaExternalObjectType(Class theClass) {
3918 return new JavaExternalObjectType(this, theClass);
3919 }
3920
3921 /**
3922 * Make a map representing the methods defined in a class. This map is specific to the class, not to
3923 * a particular instance. The functions present in this map take an extra first argument representing
3924 * the target instance; the functions returned in the final instance-level map will be partial applications
3925 * of the functions in the class-level map.
3926 *
3927 * @param javaClass the Java class whose methods are required
3928 * @param required if non-null, indicates the key of the entry that is required in the map. If
3929 * this parameter is supplied, then the map will be limited to a single entry
3930 * with this key, since it is known that the other entries would never be used
3931 * @return a map whose entries represent public instance-level methods in the supplied Java class,
3932 * to the extent that these methods have unique names.
3933 * @throws UnsupportedOperationException except in subclasses
3934 */
3935
3936 public Map<String, Function> makeMethodMap(Class javaClass, String required) {
3937 throw new UnsupportedOperationException();
3938 }
3939
3940 /**
3941 * Convert a Java object to a map
3942 *
3943 * @param value the (wrapped) Java object to be converted
3944 * @param required if non-null, indicates the key of the entry that is required in the map. If
3945 * this parameter is supplied, then the map will be limited to a single entry
3946 * with this key, since it is known that the other entries would never be used.
3947 * @return an XDM map containing entries representing the public instance-level methods
3948 * available in the object, to the extent that they have unique names.
3949 * @throws UnsupportedOperationException except in subclasses
3950 */
3951
3952 public MapItem externalObjectAsMap(ObjectValue value, String required) {
3953 throw new UnsupportedOperationException();
3954 }
3955
3956 public Expression makeObjectLookupExpression(Expression lhs, Expression rhs) {
3957 throw new UnsupportedOperationException();
3958 }
3959
3960 /**
3961 * Get a NodeInfo corresponding to a DOM or other external Node,
3962 * either by wrapping or unwrapping the external Node.
3963 * <p>This method is intended for internal use.</p>
3964 *
3965 * @param source A Source representing the wrapped or unwrapped external Node. This will typically
3966 * be a DOMSource, but it may be a similar Source recognized by some other registered external
3967 * object model.
3968 * @return If the Source is a DOMSource and the underlying node is a wrapper around a Saxon NodeInfo,
3969 * returns the wrapped Saxon NodeInfo. If the Source is a DOMSource and the undelying node is not such a wrapper,
3970 * returns a new Saxon NodeInfo that wraps the DOM Node. If the Source is any other kind of source, it
3971 * is offered to each registered external object model for similar treatment. The result is the
3972 * NodeInfo object obtained by wrapping or unwrapping the supplied external node.
3973 * @throws IllegalArgumentException if the source object is not of a recognized class. This method does
3974 * <em>not</em> call the registered {@link SourceResolver to resolve the Source}.
3975 */
3976
3977 public NodeInfo unravel(Source source) {
3978 List<ExternalObjectModel> externalObjectModels = getExternalObjectModels();
3979 if (!(source instanceof NodeInfo)) {
3980 for (ExternalObjectModel model : externalObjectModels) {
3981 NodeInfo node = model.unravel(source, this);
3982 if (node != null) {
3983 if (!node.getConfiguration().isCompatible(this)) {
3984 throw new IllegalArgumentException("Externally supplied Node belongs to the wrong Configuration");
3985 }
3986 return node;
3987 }
3988 }
3989 }
3990 if (source instanceof NodeInfo) {
3991 if (!((NodeInfo) source).getConfiguration().isCompatible(this)) {
3992 throw new IllegalArgumentException("Externally supplied NodeInfo belongs to the wrong Configuration");
3993 }
3994 return (NodeInfo) source;
3995 }
3996
3997 throw new IllegalArgumentException("A source of class " +
3998 source.getClass() + " is not recognized by any registered object model");
3999
4000 }
4001
4002 /**
4003 * Ask whether an extension element with a particular name is available
4004 *
4005 * @param qName the extension element name
4006 * @return false (always, in the case of Saxon-HE)
4007 * @since 9.7
4008 */
4009
4010 public boolean isExtensionElementAvailable(StructuredQName qName) {
4011 return false;
4012 }
4013
4014
4015 /**
4016 * Set the StaticQueryContextFactory used for creating instances of StaticQueryContext
4017 *
4018 * @param factory the factory class to be used when a new StaticQueryContext is required.
4019 * Note that this is not used for the default StaticQueryContext held in the Configuration itself.
4020 * @since 9.5.1.2
4021 */
4022
4023 public void setStaticQueryContextFactory(StaticQueryContextFactory factory) {
4024 staticQueryContextFactory = factory;
4025 }
4026
4027 /**
4028 * Get a new StaticQueryContext (which is also the factory class for creating a query parser).
4029 * Note that this method is used to underpin the s9api and XQJ APIs for XQuery compilation, and
4030 * that modifying the behaviour of the StaticQueryContext can affect the behaviour of those APIs
4031 *
4032 * @return a new StaticQueryContext
4033 */
4034
4035 public StaticQueryContext newStaticQueryContext() {
4036 return makeStaticQueryContext(true);
4037 }
4038
4039 /**
4040 * Get a new Pending Update List
4041 *
4042 * @return the new Pending Update List
4043 * @throws UnsupportedOperationException if called when using Saxon-HE
4044 */
4045
4046 public PendingUpdateList newPendingUpdateList() {
4047 throw new UnsupportedOperationException("XQuery update is supported only in Saxon-EE");
4048 }
4049
4050 /**
4051 * Make a PipelineConfiguration from the properties of this Configuration
4052 *
4053 * @return a new PipelineConfiguration
4054 * @since 8.4
4055 */
4056
4057 public PipelineConfiguration makePipelineConfiguration() {
4058 PipelineConfiguration pipe = new PipelineConfiguration(this);
4059 pipe.setURIResolver(getURIResolver());
4060 pipe.setParseOptions(new ParseOptions(defaultParseOptions));
4061 pipe.setErrorListener(getErrorListener());
4062 return pipe;
4063 }
4064
4065 /**
4066 * Get the configuration, given the context. This is provided as a static method to make it accessible
4067 * as an extension function.
4068 *
4069 * @param context the XPath dynamic context
4070 * @return the Saxon Configuration for a given XPath dynamic context
4071 */
4072
4073 public static Configuration getConfiguration(XPathContext context) {
4074 return context.getConfiguration();
4075 }
4076
4077 /**
4078 * Supply a SourceResolver. This is used for handling unknown implementations of the
4079 * {@link javax.xml.transform.Source} interface: a user-supplied SourceResolver can handle
4080 * such Source objects and translate them to a kind of Source that Saxon understands.
4081 *
4082 * @param resolver the source resolver.
4083 */
4084
4085 public void setSourceResolver(SourceResolver resolver) {
4086 sourceResolver = resolver;
4087 }
4088
4089 /**
4090 * Get the current SourceResolver. If none has been supplied, a system-defined SourceResolver
4091 * is returned.
4092 *
4093 * @return the current SourceResolver
4094 */
4095
4096 public SourceResolver getSourceResolver() {
4097 return sourceResolver;
4098 }
4099
4100 /**
4101 * Resolve a Source.
4102 *
4103 * @param source A source object, typically the source supplied as the first
4104 * argument to {@link javax.xml.transform.Transformer#transform(javax.xml.transform.Source, javax.xml.transform.Result)}
4105 * or similar methods.
4106 * @param config The Configuration. This provides the SourceResolver with access to
4107 * configuration information; it also allows the SourceResolver to invoke the
4108 * resolveSource() method on the Configuration object as a fallback implementation.
4109 * @return a source object that Saxon knows how to process. This must be an instance of one
4110 * of the classes StreamSource, SAXSource, DOMSource, {@link net.sf.saxon.lib.AugmentedSource},
4111 * {@link net.sf.saxon.om.NodeInfo},
4112 * or {@link net.sf.saxon.pull.PullSource}. Return null if the Source object is not
4113 * recognized
4114 * @throws XPathException if the Source object is recognized but cannot be processed
4115 */
4116
4117 /*@Nullable*/
4118 public Source resolveSource(Source source, Configuration config) throws XPathException {
4119 if (source instanceof AugmentedSource) {
4120 return source;
4121 }
4122 if (source instanceof StreamSource) {
4123 return source;
4124 }
4125 if (source instanceof SAXSource) {
4126 return source;
4127 }
4128 if (source instanceof DOMSource) {
4129 return source;
4130 }
4131 if (source instanceof NodeInfo) {
4132 return source;
4133 }
4134 if (source instanceof PullSource) {
4135 return source;
4136 }
4137 if (source instanceof StAXSource) {
4138 return source;
4139 }
4140 if (source instanceof EventSource) {
4141 return source;
4142 }
4143 return null;
4144 }
4145
4146 /**
4147 * Build a document tree, using options set on this Configuration and on the supplied source
4148 * object. Options set on the source object override options set in the Configuration. The Source
4149 * object must be one of the kinds of source recognized by Saxon, or a source that can be resolved
4150 * using the registered {@link SourceResolver}. This method always constructs a new tree, it never
4151 * wraps or returns an existing tree.
4152 *
4153 * @param source the Source to be used. This may be an {@link AugmentedSource}, allowing options
4154 * to be specified for the way in which this document will be built. If an AugmentedSource
4155 * is supplied then options set in the AugmentedSource take precedence over options
4156 * set in the Configuration.
4157 * <p>If any error occurs reading or parsing the supplied Source, the error is notified
4158 * to the {@link ErrorListener} registered with this {@link Configuration}.</p>
4159 * @return the constructed document as a TreeInfo
4160 * @throws XPathException if any errors occur during document parsing or validation. Detailed
4161 * errors occurring during schema validation will be written to the ErrorListener associated
4162 * with the AugmentedSource, if supplied, or with the Configuration otherwise.
4163 * @since 9.7; based on the original {@link #buildDocument(Source)} method, but adapted to return the
4164 * TreeInfo containing information about the constructed tree, including a reference to its root node.
4165 */
4166
4167 public TreeInfo buildDocumentTree(Source source) throws XPathException {
4168
4169 if (source == null) {
4170 throw new NullPointerException("source");
4171 }
4172
4173 if (source instanceof AugmentedSource) {
4174 return buildDocumentTree(
4175 ((AugmentedSource) source).getContainedSource(),
4176 ((AugmentedSource) source).getParseOptions());
4177 } else {
4178 return buildDocumentTree(
4179 source,
4180 new ParseOptions(defaultParseOptions)); // see bug 3678
4181 }
4182 }
4183
4184 /**
4185 * Build a document, using specified options for parsing and building. This method always
4186 * constructs a new tree, it never wraps an existing document (regardless of anything in
4187 * the parseOptions)
4188 *
4189 * @param source the source of the document to be constructed. If this is an
4190 * AugmentedSource, then any parser options contained in the AugmentedSource take precedence
4191 * over options specified in the parseOptions argument.
4192 * @param parseOptions options for parsing and constructing the document. Any options that
4193 * are not explicitly set in parseOptions default first to the values supplied in the source
4194 * argument if it is an AugmentedSource, and then to the values set in this Configuration.
4195 * The supplied parseOptions object is not modified.
4196 * @return the constructed document as a TreeInfo
4197 * @throws XPathException if parsing fails, or if the Source represents a node other than
4198 * a document node
4199 * @since 9.7; based on the original {@link #buildDocument(Source, ParseOptions)} method, but adapted to return the
4200 * TreeInfo containing information about the constructed tree, including a reference to its root node.
4201 */
4202
4203 public TreeInfo buildDocumentTree(/*@Nullable*/ Source source, ParseOptions parseOptions) throws XPathException {
4204
4205 if (source == null) {
4206 throw new NullPointerException("source");
4207 }
4208
4209 boolean finallyClose = false;
4210 try {
4211 ParseOptions options = new ParseOptions(parseOptions);
4212
4213 // Resolve user-defined implementations of Source
4214 Source src2 = resolveSource(source, this);
4215 if (src2 == null) {
4216 throw new XPathException("Unknown source class " + source.getClass().getName());
4217 }
4218 source = src2;
4219
4220 if (source instanceof AugmentedSource) {
4221 options.merge(((AugmentedSource) source).getParseOptions());
4222 }
4223
4224 options.applyDefaults(this);
4225 finallyClose = options.isPleaseCloseAfterUse();
4226
4227 // Create an appropriate Builder
4228
4229 TreeModel treeModel = options.getModel();
4230
4231 // Decide whether line numbering is in use
4232
4233 boolean lineNumbering = options.isLineNumbering();
4234
4235 PipelineConfiguration pipe = makePipelineConfiguration();
4236 pipe.setParseOptions(options);
4237 Builder builder = treeModel.makeBuilder(pipe);
4238 builder.setTiming(isTiming());
4239 builder.setLineNumbering(lineNumbering);
4240 builder.setPipelineConfiguration(pipe);
4241 builder.setSystemId(source.getSystemId());
4242 Sender.send(source, new NamespaceReducer(builder), options);
4243
4244 // Get the constructed document
4245
4246 NodeInfo newdoc = builder.getCurrentRoot();
4247 if (newdoc.getNodeKind() != Type.DOCUMENT) {
4248 throw new XPathException("Source object represents a node other than a document node");
4249 }
4250
4251 // Reset the builder, detaching it from the constructed document
4252
4253 builder.reset();
4254
4255 // Return the constructed document
4256
4257 return newdoc.getTreeInfo();
4258
4259 } finally {
4260 // If requested, close the input stream
4261 if (finallyClose) {
4262 ParseOptions.close(source);
4263 }
4264 }
4265
4266 }
4267
4268 /**
4269 * Build a document tree, using options set on this Configuration and on the supplied source
4270 * object. Options set on the source object override options set in the Configuration. The Source
4271 * object must be one of the kinds of source recognized by Saxon, or a source that can be resolved
4272 * using the registered {@link SourceResolver}.
4273 *
4274 * @param source the Source to be used. This may be an {@link AugmentedSource}, allowing options
4275 * to be specified for the way in which this document will be built. If an AugmentedSource
4276 * is supplied then options set in the AugmentedSource take precedence over options
4277 * set in the Configuration.
4278 * <p>From Saxon 9.2, this method always creates a new tree, it never wraps or returns
4279 * an existing tree.</p>
4280 * <p>If any error occurs reading or parsing the supplied Source, the error is notified
4281 * to the {@link ErrorListener} registered with this {@link Configuration}.</p>
4282 * @return the document node of the constructed document. The class DocumentInfo is retained
4283 * as the result class for this method in order to preserve backwards compatibility for common use cases
4284 * of this function
4285 * @throws XPathException if any errors occur during document parsing or validation. Detailed
4286 * errors occurring during schema validation will be written to the ErrorListener associated
4287 * with the AugmentedSource, if supplied, or with the Configuration otherwise.
4288 * @since 8.9. Modified in 9.0 to avoid copying a supplied document where this is not
4289 * necessary. Modified in 9.2 so that this interface always constructs a new tree; it never
4290 * wraps an existing document, even if an AugmentedSource that requests wrapping is supplied.
4291 * In 9.7 the method is retained to provide a semblance of backwards compatibility for common
4292 * use cases; to achieve this, DocumentInfo is changed from an interface implemented by all document
4293 * nodes, to a wrapper object around the actual root of the tree.
4294 * @deprecated since 9.7: use {@link #buildDocumentTree(Source)}.
4295 */
4296
4297 public DocumentInfo buildDocument(Source source) throws XPathException {
4298 TreeInfo tree = buildDocumentTree(source);
4299 NodeInfo root = tree.getRootNode();
4300 return new DocumentInfo(root);
4301 }
4302
4303 /**
4304 * Build a document, using specified options for parsing and building. This method always
4305 * constructs a new tree, it never wraps an existing document (regardless of anything in
4306 * the parseOptions)
4307 *
4308 * @param source the source of the document to be constructed. If this is an
4309 * AugmentedSource, then any parser options contained in the AugmentedSource take precedence
4310 * over options specified in the parseOptions argument.
4311 * @param parseOptions options for parsing and constructing the document. Any options that
4312 * are not explicitly set in parseOptions default first to the values supplied in the source
4313 * argument if it is an AugmentedSource, and then to the values set in this Configuration.
4314 * The supplied parseOptions object is not modified.
4315 * @return the document node of the constructed document
4316 * @throws XPathException if parsing fails, or if the Source represents a node other than
4317 * a document node
4318 * @since 9.2. In 9.7 the method is retained to provide a semblance of backwards compatibility for common
4319 * use cases; to achieve this, DocumentInfo is changed from an interface implemented by all document
4320 * nodes, to a wrapper object around the actual root of the tree.
4321 * @deprecated since 9.7: use {@link #buildDocumentTree(Source, ParseOptions)}.
4322 */
4323
4324 public DocumentInfo buildDocument(Source source, ParseOptions parseOptions) throws XPathException {
4325 TreeInfo tree = buildDocumentTree(source, parseOptions);
4326 NodeInfo root = tree.getRootNode();
4327 return new DocumentInfo(root);
4328 }
4329
4330 /**
4331 * Get the collection of tree-builder statistics for this configuration, used
4332 * for learning suitable amounts of space to allocate for different kinds of tree
4333 * @return the object in which tree statistics are accumulated
4334 */
4335
4336 public TreeStatistics getTreeStatistics() {
4337 return treeStatistics;
4338 }
4339
4340 /**
4341 * Load a named output emitter or SAX2 ContentHandler and check it is OK.
4342 *
4343 * @param clarkName the QName of the user-supplied ContentHandler (requested as a prefixed
4344 * value of the method attribute in xsl:output, or anywhere that serialization parameters
4345 * are allowed), encoded in Clark format as {uri}local
4346 * @param props the properties to be used in the case of a dynamically-loaded ContentHandler.
4347 * @return a Receiver (despite the name, it is not required to be an Emitter)
4348 * @throws net.sf.saxon.trans.XPathException if a failure occurs creating the Emitter
4349 */
4350
4351 public Receiver makeEmitter(String clarkName, Properties props) throws XPathException {
4352 int brace = clarkName.indexOf('}');
4353 String localName = clarkName.substring(brace + 1);
4354 int colon = localName.indexOf(':');
4355 String className = localName.substring(colon + 1);
4356 Object handler;
4357 try {
4358 handler = dynamicLoader.getInstance(className, null);
4359 } catch (XPathException e) {
4360 throw new XPathException("Cannot create user-supplied output method. " + e.getMessage(),
4361 SaxonErrorCode.SXCH0004);
4362 }
4363
4364 if (handler instanceof Receiver) {
4365 return (Receiver) handler;
4366 } else if (handler instanceof ContentHandler) {
4367 ContentHandlerProxy emitter = new ContentHandlerProxy();
4368 emitter.setUnderlyingContentHandler((ContentHandler) handler);
4369 emitter.setOutputProperties(props);
4370 return emitter;
4371 } else {
4372 throw new XPathException("Output method " + className +
4373 " is neither a Receiver nor a SAX2 ContentHandler");
4374 }
4375
4376 }
4377
4378 /**
4379 * Set a property of the configuration. This method underpins the setAttribute() method of the
4380 * TransformerFactory implementation, and is provided
4381 * to enable setting of Configuration properties using URIs without instantiating a TransformerFactory:
4382 * specifically, this may be useful when running XQuery, and it is also used by the Validator API.
4383 *
4384 * <p>From Saxon 9.9, an alternative interface is available: {@link #setConfigurationProperty(Feature, Object)}.
4385 * The new interface is more efficient because it avoids expensive string comparisons. The old interface is
4386 * retained mainly for compatibility, and also because there are a few cases where it cannot easily be replaced,
4387 * for example when using composite feature URIs to delegate configuration options to the XML parser.</p>
4388 *
4389 * @param name the URI identifying the property to be set. See the class {@link FeatureKeys} for
4390 * constants representing the property names that can be set.
4391 * @param value the value of the property. Note that boolean values may be supplied either as a Boolean,
4392 * or as one of the strings "0", "1", "true", "false", "yes", "no", "on", or "off".
4393 * @throws IllegalArgumentException if the property name is not recognized or if the value is not
4394 * a valid value for the named property
4395 */
4396
4397 public void setConfigurationProperty(String name, Object value) {
4398 Feature feature = Feature.byName(name);
4399 if (feature == null) {
4400 if (name.startsWith(FeatureKeys.XML_PARSER_FEATURE)) {
4401 String uri = name.substring(FeatureKeys.XML_PARSER_FEATURE.length());
4402 try {
4403 uri = URLDecoder.decode(uri, "utf-8");
4404 } catch (UnsupportedEncodingException e) {
4405 throw new IllegalArgumentException(e);
4406 }
4407 defaultParseOptions.addParserFeature(uri, requireBoolean(name, value));
4408 } else if (name.startsWith(FeatureKeys.XML_PARSER_PROPERTY)) {
4409 String uri = name.substring(FeatureKeys.XML_PARSER_PROPERTY.length());
4410 try {
4411 uri = URLDecoder.decode(uri, "utf-8");
4412 } catch (UnsupportedEncodingException e) {
4413 throw new IllegalArgumentException(e);
4414 }
4415 defaultParseOptions.addParserProperties(uri, value);
4416
4417 } else {
4418 throw new IllegalArgumentException("Unrecognized configuration feature: " + name);
4419 }
4420 } else {
4421 //noinspection unchecked
4422 setConfigurationProperty(feature, value);
4423 }
4424 }
4425
4426
4427 /**
4428 * Set a property of the configuration. This method underpins the setAttribute() method of the
4429 * TransformerFactory implementation, and is provided
4430 * to enable setting of Configuration properties using URIs without instantiating a TransformerFactory:
4431 * specifically, this may be useful when running XQuery, and it is also used by the Validator API
4432 *
4433 * @param feature the property to be set. See the class {@link Feature} for
4434 * constants representing the property names that can be set.
4435 * @param value the value of the property. Note that boolean values may be supplied either as a Boolean,
4436 * or as one of the strings "0", "1", "true", "false", "yes", "no", "on", or "off".
4437 * @throws IllegalArgumentException if the property name is not recognized or if the value is not
4438 * a valid value for the named property
4439 */
4440
4441 public <T> void setConfigurationProperty(Feature<T> feature, T value) {
4442 String name = feature.name;
4443 if (booleanFeatures.contains(feature)) {
4444 if (feature == Feature.COMPILE_WITH_TRACING) {
4445 boolean b = requireBoolean(name, value);
4446 setCompileWithTracing(b);
4447 } else if (feature == Feature.DTD_VALIDATION) {
4448 boolean b = requireBoolean(name, value);
4449 setValidation(b);
4450 } else if (feature == Feature.EXPAND_ATTRIBUTE_DEFAULTS) {
4451 boolean b = requireBoolean(name, value);
4452 setExpandAttributeDefaults(b);
4453 }
4454 internalSetBooleanProperty(feature, value);
4455 } else {
4456 switch (feature.code) {
4457
4458 case FeatureCode.COLLATION_URI_RESOLVER:
4459 if (!(value instanceof CollationURIResolver)) {
4460 throw new IllegalArgumentException(
4461 "COLLATION_URI_RESOLVER value must be an instance of net.sf.saxon.lib.CollationURIResolver");
4462 }
4463 setCollationURIResolver((CollationURIResolver) value);
4464 break;
4465
4466 case FeatureCode.COLLATION_URI_RESOLVER_CLASS:
4467 setCollationURIResolver(
4468 (CollationURIResolver) instantiateClassName(name, value, CollationURIResolver.class));
4469 break;
4470
4471 case FeatureCode.COLLECTION_URI_RESOLVER:
4472 if (!(value instanceof CollectionURIResolver)) {
4473 throw new IllegalArgumentException(
4474 "COLLECTION_URI_RESOLVER value must be an instance of net.sf.saxon.lib.CollectionURIResolver");
4475 }
4476 setCollectionURIResolver((CollectionURIResolver) value);
4477 break;
4478
4479 case FeatureCode.COLLECTION_URI_RESOLVER_CLASS:
4480 setCollectionURIResolver(
4481 (CollectionURIResolver) instantiateClassName(name, value, CollectionURIResolver.class));
4482 break;
4483
4484 case FeatureCode.COLLECTION_FINDER:
4485 if (!(value instanceof CollectionFinder)) {
4486 throw new IllegalArgumentException(
4487 "COLLECTION_FINDER value must be an instance of net.sf.saxon.lib.ICollectionFinder");
4488 }
4489 setCollectionFinder((CollectionFinder) value);
4490 break;
4491
4492 case FeatureCode.COLLECTION_FINDER_CLASS:
4493 setCollectionFinder(
4494 (CollectionFinder) instantiateClassName(name, value, CollectionFinder.class));
4495 break;
4496
4497 case FeatureCode.DEFAULT_COLLATION:
4498 defaultCollationName = value.toString();
4499 break;
4500
4501 case FeatureCode.DEFAULT_COLLECTION:
4502 setDefaultCollection(value.toString());
4503 break;
4504
4505 case FeatureCode.DEFAULT_COUNTRY:
4506 setDefaultCountry(value.toString());
4507 break;
4508
4509 case FeatureCode.DEFAULT_LANGUAGE:
4510 setDefaultLanguage(value.toString());
4511 break;
4512
4513 case FeatureCode.DEFAULT_REGEX_ENGINE:
4514 setDefaultRegexEngine(value.toString());
4515 break;
4516
4517 case FeatureCode.DTD_VALIDATION_RECOVERABLE: {
4518 boolean b = requireBoolean(name, value);
4519 if (b) {
4520 defaultParseOptions.setDTDValidationMode(Validation.LAX);
4521 } else {
4522 defaultParseOptions.setDTDValidationMode(isValidation() ? Validation.STRICT : Validation.SKIP);
4523 }
4524 internalSetBooleanProperty(Feature.DTD_VALIDATION_RECOVERABLE, b);
4525 break;
4526 }
4527 case FeatureCode.ENTITY_RESOLVER_CLASS:
4528 if ("".equals(value)) {
4529 defaultParseOptions.setEntityResolver(null);
4530 } else {
4531 defaultParseOptions.setEntityResolver(
4532 (EntityResolver) instantiateClassName(name, value, EntityResolver.class));
4533 }
4534 break;
4535
4536 case FeatureCode.ENVIRONMENT_VARIABLE_RESOLVER:
4537 if (!(value instanceof EnvironmentVariableResolver)) {
4538 throw new IllegalArgumentException(
4539 "ENVIRONMENT_VARIABLE_RESOLVER value must be an instance of net.sf.saxon.lib.EnvironmentVariableResolver");
4540 }
4541 environmentVariableResolver = (EnvironmentVariableResolver) value;
4542 break;
4543
4544 case FeatureCode.ENVIRONMENT_VARIABLE_RESOLVER_CLASS:
4545 environmentVariableResolver =
4546 (EnvironmentVariableResolver) instantiateClassName(name, value, EnvironmentVariableResolver.class);
4547 break;
4548
4549 case FeatureCode.ERROR_LISTENER_CLASS:
4550 setErrorListener((ErrorListener) instantiateClassName(name, value, ErrorListener.class));
4551 break;
4552
4553 case FeatureCode.LINE_NUMBERING: {
4554 boolean b = requireBoolean(name, value);
4555 setLineNumbering(b);
4556 break;
4557 }
4558 case FeatureCode.MESSAGE_EMITTER_CLASS:
4559 if (!(value instanceof String)) {
4560 throw new IllegalArgumentException("MESSAGE_EMITTER_CLASS class must be a String");
4561 }
4562 setMessageEmitterClass((String) value);
4563 break;
4564
4565 case FeatureCode.MODULE_URI_RESOLVER:
4566 if (!(value instanceof ModuleURIResolver)) {
4567 throw new IllegalArgumentException(
4568 "MODULE_URI_RESOLVER value must be an instance of net.sf.saxon.lib.ModuleURIResolver");
4569 }
4570 setModuleURIResolver((ModuleURIResolver) value);
4571 break;
4572
4573 case FeatureCode.MODULE_URI_RESOLVER_CLASS:
4574 setModuleURIResolver(
4575 (ModuleURIResolver) instantiateClassName(name, value, ModuleURIResolver.class));
4576 break;
4577
4578 case FeatureCode.NAME_POOL:
4579 if (!(value instanceof NamePool)) {
4580 throw new IllegalArgumentException("NAME_POOL value must be an instance of net.sf.saxon.om.NamePool");
4581 }
4582 setNamePool((NamePool) value);
4583 break;
4584
4585 case FeatureCode.OPTIMIZATION_LEVEL:
4586 if (value instanceof Integer) {
4587 // See Saxon bug 2076. It seems Ant passes an integer value as an integer, not as a string. Not tested.
4588 // Integer values retained for compatibility: 0=none, 10 = all
4589 int v = (Integer) value;
4590 optimizerOptions = v == 0 ? new OptimizerOptions(0) : OptimizerOptions.FULL_EE_OPTIMIZATION;
4591 } else {
4592 String s = requireString(name, value);
4593 if (s.matches("[0-9]+")) {
4594 // For backwards compatibility
4595 optimizerOptions = "0".equals(s) ? new OptimizerOptions(0) : OptimizerOptions.FULL_EE_OPTIMIZATION;
4596 } else {
4597 optimizerOptions = new OptimizerOptions(s);
4598 }
4599 }
4600
4601 if (optimizer != null) {
4602 optimizer.setOptimizerOptions(optimizerOptions);
4603 }
4604 internalSetBooleanProperty(Feature.GENERATE_BYTE_CODE,
4605 optimizerOptions.isSet(OptimizerOptions.BYTE_CODE));
4606 defaultXsltCompilerInfo.setOptimizerOptions(optimizerOptions);
4607 break;
4608
4609 case FeatureCode.OUTPUT_URI_RESOLVER:
4610 if (!(value instanceof OutputURIResolver)) {
4611 throw new IllegalArgumentException(
4612 "OUTPUT_URI_RESOLVER value must be an instance of net.sf.saxon.lib.OutputURIResolver");
4613 }
4614 setOutputURIResolver((OutputURIResolver) value);
4615 break;
4616
4617 case FeatureCode.OUTPUT_URI_RESOLVER_CLASS:
4618 setOutputURIResolver(
4619 (OutputURIResolver) instantiateClassName(name, value, OutputURIResolver.class));
4620 break;
4621
4622 case FeatureCode.RECOGNIZE_URI_QUERY_PARAMETERS:
4623 boolean b = requireBoolean(name, value);
4624 getSystemURIResolver().setRecognizeQueryParameters(b);
4625 break;
4626
4627 case FeatureCode.RECOVERY_POLICY:
4628 setRecoveryPolicy(requireInteger(name, value));
4629 break;
4630
4631 case FeatureCode.RECOVERY_POLICY_NAME:
4632 if (!(value instanceof String)) {
4633 throw new IllegalArgumentException("RECOVERY_POLICY_NAME value must be a String");
4634 }
4635 int rval;
4636 if (value.equals("recoverSilently")) {
4637 rval = RECOVER_SILENTLY;
4638 } else if (value.equals("recoverWithWarnings")) {
4639 rval = RECOVER_WITH_WARNINGS;
4640 } else if (value.equals("doNotRecover")) {
4641 rval = DO_NOT_RECOVER;
4642 } else {
4643 throw new IllegalArgumentException(
4644 "Unrecognized value of RECOVERY_POLICY_NAME = '" + value +
4645 "': must be 'recoverSilently', 'recoverWithWarnings', or 'doNotRecover'");
4646 }
4647 setRecoveryPolicy(rval);
4648 break;
4649
4650 case FeatureCode.REGEX_BACKTRACKING_LIMIT:
4651 regexBacktrackingLimit = requireInteger(name, value);
4652 break;
4653
4654 case FeatureCode.SERIALIZER_FACTORY_CLASS:
4655 setSerializerFactory(
4656 (SerializerFactory) instantiateClassName(name, value, SerializerFactory.class));
4657 break;
4658
4659 case FeatureCode.SCHEMA_VALIDATION: {
4660 setSchemaValidationMode(requireInteger(feature.name, value));
4661 break;
4662 }
4663 case FeatureCode.SCHEMA_VALIDATION_MODE:
4664 String mode = requireString(feature.name, value);
4665 setSchemaValidationMode(Validation.getCode(mode));
4666 break;
4667
4668 case FeatureCode.SOURCE_PARSER_CLASS:
4669 setSourceParserClass(requireString(feature.name, value));
4670 break;
4671
4672 case FeatureCode.SOURCE_RESOLVER_CLASS:
4673 setSourceResolver(
4674 (SourceResolver) instantiateClassName(name, value, SourceResolver.class));
4675 break;
4676
4677 case FeatureCode.STANDARD_ERROR_OUTPUT_FILE:
4678 // Note, this property is write-only
4679 try {
4680 boolean append = true;
4681 boolean autoFlush = true;
4682 setStandardErrorOutput(
4683 new PrintStream(new FileOutputStream((String) value, append), autoFlush));
4684 } catch (FileNotFoundException fnf) {
4685 throw new IllegalArgumentException(fnf);
4686 }
4687 break;
4688
4689 case FeatureCode.STRIP_WHITESPACE: {
4690 String s = requireString(name, value);
4691 switch (s) {
4692 case "all":
4693 defaultParseOptions.setSpaceStrippingRule(AllElementsSpaceStrippingRule.getInstance());
4694 break;
4695 case "none":
4696 defaultParseOptions.setSpaceStrippingRule(NoElementsSpaceStrippingRule.getInstance());
4697 break;
4698 case "ignorable":
4699 defaultParseOptions.setSpaceStrippingRule(IgnorableSpaceStrippingRule.getInstance());
4700 break;
4701 default:
4702 throw new IllegalArgumentException(
4703 "Unrecognized value STRIP_WHITESPACE = '" + value +
4704 "': must be 'all', 'none', or 'ignorable'");
4705 }
4706 break;
4707 }
4708 case FeatureCode.STYLE_PARSER_CLASS:
4709 setStyleParserClass(requireString(name, value));
4710 break;
4711
4712 case FeatureCode.TIMING:
4713 setTiming(requireBoolean(name, value));
4714 break;
4715
4716 case FeatureCode.TRACE_LISTENER:
4717 if (!(value instanceof TraceListener)) {
4718 throw new IllegalArgumentException("TRACE_LISTENER is of wrong class");
4719 }
4720 setTraceListener((TraceListener) value);
4721 break;
4722
4723 case FeatureCode.TRACE_LISTENER_CLASS:
4724 setTraceListenerClass(requireString(name, value));
4725 break;
4726
4727 case FeatureCode.TRACE_LISTENER_OUTPUT_FILE:
4728 setTraceListenerOutputFile(requireString(name, value));
4729 break;
4730
4731 case FeatureCode.TREE_MODEL:
4732 setTreeModel(requireInteger(name, value));
4733 break;
4734
4735 case FeatureCode.TREE_MODEL_NAME: {
4736 String s = requireString(name, value);
4737 switch (s) {
4738 case "tinyTree":
4739 setTreeModel(Builder.TINY_TREE);
4740 break;
4741 case "tinyTreeCondensed":
4742 setTreeModel(Builder.TINY_TREE_CONDENSED);
4743 break;
4744 case "linkedTree":
4745 setTreeModel(Builder.LINKED_TREE);
4746 break;
4747 case "jdom":
4748 setTreeModel(Builder.JDOM_TREE);
4749 break;
4750 case "jdom2":
4751 setTreeModel(Builder.JDOM2_TREE);
4752 break;
4753 default:
4754 throw new IllegalArgumentException(
4755 "Unrecognized value TREE_MODEL_NAME = '" + value +
4756 "': must be linkedTree|tinyTree|tinyTreeCondensed");
4757 }
4758 break;
4759 }
4760 case FeatureCode.UNPARSED_TEXT_URI_RESOLVER:
4761 setUnparsedTextURIResolver((UnparsedTextURIResolver) value);
4762 break;
4763
4764 case FeatureCode.UNPARSED_TEXT_URI_RESOLVER_CLASS:
4765 setUnparsedTextURIResolver(
4766 (UnparsedTextURIResolver) instantiateClassName(name, value, UnparsedTextURIResolver.class));
4767 break;
4768
4769 case FeatureCode.URI_RESOLVER_CLASS:
4770 setURIResolver(
4771 (URIResolver) instantiateClassName(name, value, URIResolver.class));
4772 break;
4773
4774 case FeatureCode.USE_XSI_SCHEMA_LOCATION:
4775 defaultParseOptions.setUseXsiSchemaLocation(requireBoolean(name, value));
4776 break;
4777
4778 case FeatureCode.VALIDATION_COMMENTS:
4779 defaultParseOptions.setAddCommentsAfterValidationErrors(requireBoolean(name, value));
4780 break;
4781
4782 case FeatureCode.VALIDATION_WARNINGS:
4783 setValidationWarnings(requireBoolean(name, value));
4784 break;
4785
4786 case FeatureCode.VERSION_WARNING:
4787 setVersionWarning(requireBoolean(name, value));
4788 break;
4789
4790 case FeatureCode.XINCLUDE:
4791 setXIncludeAware(requireBoolean(name, value));
4792 break;
4793
4794 case FeatureCode.XPATH_VERSION_FOR_XSD: {
4795 int val = requireInteger(name, value);
4796 if (val != 20 && val != 30 && val != 31) {
4797 throw new IllegalArgumentException("XPath version for XSD must be 20 (XPath 2.0), 30 (XPath 3.0), or 31 (XPath 3.1)");
4798 }
4799 xpathVersionForXsd = val;
4800 break;
4801 }
4802 case FeatureCode.XPATH_VERSION_FOR_XSLT: {
4803 int val = requireInteger(name, value);
4804 if (val != 20 && val != 30 && val != 305 && val != 31) {
4805 throw new IllegalArgumentException("XPath version for XSLT must be 20 (XPath 2.0), 30 (XPath 3.0), 31 (XPath 3.1), or 305 (XPath 3.0 with XSLT-defined extensions)");
4806 }
4807 xpathVersionForXslt = val;
4808 break;
4809 }
4810 case FeatureCode.XQUERY_ALLOW_UPDATE:
4811 getDefaultStaticQueryContext().setUpdatingEnabled(requireBoolean(name, value));
4812 break;
4813
4814 case FeatureCode.XQUERY_CONSTRUCTION_MODE:
4815 getDefaultStaticQueryContext().setConstructionMode(Validation.getCode(value.toString()));
4816 break;
4817
4818 case FeatureCode.XQUERY_DEFAULT_ELEMENT_NAMESPACE:
4819 getDefaultStaticQueryContext().setDefaultElementNamespace(value.toString());
4820 break;
4821
4822 case FeatureCode.XQUERY_DEFAULT_FUNCTION_NAMESPACE:
4823 getDefaultStaticQueryContext().setDefaultFunctionNamespace(value.toString());
4824 break;
4825
4826 case FeatureCode.XQUERY_EMPTY_LEAST:
4827 getDefaultStaticQueryContext().setEmptyLeast(requireBoolean(name, value));
4828 break;
4829
4830 case FeatureCode.XQUERY_INHERIT_NAMESPACES:
4831 getDefaultStaticQueryContext().setInheritNamespaces(requireBoolean(name, value));
4832 break;
4833
4834 case FeatureCode.XQUERY_PRESERVE_BOUNDARY_SPACE:
4835 getDefaultStaticQueryContext().setPreserveBoundarySpace(requireBoolean(name, value));
4836 break;
4837
4838 case FeatureCode.XQUERY_PRESERVE_NAMESPACES:
4839 getDefaultStaticQueryContext().setPreserveNamespaces(requireBoolean(name, value));
4840 break;
4841
4842 case FeatureCode.XQUERY_REQUIRED_CONTEXT_ITEM_TYPE:
4843 XPathParser parser = new XPathParser();
4844 parser.setLanguage(XPathParser.SEQUENCE_TYPE, 31);
4845 try {
4846 SequenceType type = parser.parseSequenceType(value.toString(), new IndependentContext(this));
4847 if (type.getCardinality() != StaticProperty.EXACTLY_ONE) {
4848 throw new IllegalArgumentException("Context item type must have no occurrence indicator");
4849 }
4850 getDefaultStaticQueryContext().setRequiredContextItemType(type.getPrimaryType());
4851 } catch (XPathException err) {
4852 throw new IllegalArgumentException(err);
4853 }
4854 break;
4855
4856 case FeatureCode.XQUERY_SCHEMA_AWARE:
4857 getDefaultStaticQueryContext().setSchemaAware(requireBoolean(name, value));
4858 break;
4859
4860 case FeatureCode.XQUERY_STATIC_ERROR_LISTENER_CLASS:
4861 getDefaultStaticQueryContext().setErrorListener(
4862 (ErrorListener) instantiateClassName(name, value, ErrorListener.class));
4863 break;
4864
4865 case FeatureCode.XQUERY_VERSION:
4866 if (!"3.1".equals(value)) {
4867 getErrorListener().warning(new XPathException("XQuery version ignored: only \"3.1\" is recognized"));
4868 }
4869 getDefaultStaticQueryContext().setLanguageVersion(31);
4870 break;
4871
4872 case FeatureCode.XML_VERSION:
4873 String xv = requireString(name, value);
4874 if (!(xv.equals("1.0") || xv.equals("1.1"))) {
4875 throw new IllegalArgumentException(
4876 "XML_VERSION value must be \"1.0\" or \"1.1\" as a String");
4877
4878 }
4879 setXMLVersion(xv.equals("1.0") ? XML10 : XML11);
4880 break;
4881
4882 case FeatureCode.XSD_VERSION:
4883 String vn = requireString(name, value);
4884 if (!(vn.equals("1.0") || vn.equals("1.1"))) {
4885 throw new IllegalArgumentException(
4886 "XSD_VERSION value must be \"1.0\" or \"1.1\" as a String");
4887
4888 }
4889 xsdVersion = value.equals("1.0") ? XSD10 : XSD11;
4890 theConversionRules = null;
4891 break;
4892
4893 case FeatureCode.XSLT_ENABLE_ASSERTIONS:
4894 getDefaultXsltCompilerInfo().setAssertionsEnabled(requireBoolean(name, value));
4895 break;
4896
4897 case FeatureCode.XSLT_INITIAL_MODE: {
4898 String s = requireString(name, value);
4899 getDefaultXsltCompilerInfo().setDefaultInitialMode(StructuredQName.fromClarkName(s));
4900 break;
4901 }
4902 case FeatureCode.XSLT_INITIAL_TEMPLATE: {
4903 String s = requireString(name, value);
4904 getDefaultXsltCompilerInfo().setDefaultInitialTemplate(StructuredQName.fromClarkName(s));
4905 break;
4906 }
4907 case FeatureCode.XSLT_SCHEMA_AWARE:
4908 getDefaultXsltCompilerInfo().setSchemaAware(requireBoolean(name, value));
4909 break;
4910
4911 case FeatureCode.XSLT_STATIC_ERROR_LISTENER_CLASS:
4912 getDefaultXsltCompilerInfo().setErrorListener(
4913 (ErrorListener) instantiateClassName(name, value, ErrorListener.class));
4914 break;
4915
4916 case FeatureCode.XSLT_STATIC_URI_RESOLVER_CLASS:
4917 getDefaultXsltCompilerInfo().setURIResolver(
4918 (URIResolver) instantiateClassName(name, value, URIResolver.class));
4919 break;
4920
4921 case FeatureCode.XSLT_VERSION:
4922 int v = 0;
4923 if ("1.0".equals(value)) {
4924 v = 10;
4925 } else if ("2.0".equals(value)) {
4926 v = 20;
4927 } else if ("2.1".equals(value)) {
4928 v = 30;
4929 } else if ("3.0".equals(value)) {
4930 v = 30;
4931 } else if ("0.0".equals(value)) {
4932 v = 0;
4933 } else {
4934 throw new IllegalArgumentException("XSLT version must be 0.0, 1.0, 2.0, or 3.0");
4935 }
4936 getDefaultXsltCompilerInfo().setXsltVersion(v);
4937 break;
4938
4939 default:
4940 throw new IllegalArgumentException("Unknown configuration property " + name);
4941 }
4942 }
4943 }
4944
4945 /**
4946 * Validate a property value where the required type is boolean
4947 *
4948 * @param propertyName the name of the property
4949 * @param value the supplied value of the property. This may be either a java.lang.Boolean, or a string
4950 * taking one of the values on|off, true|false, yes|no, or 1|0 (suited to the conventions of different
4951 * configuration APIs that end up calling this method)
4952 * @return the value as a boolean
4953 * @throws IllegalArgumentException if the supplied value cannot be validated as a recognized boolean value
4954 */
4955
4956 public static boolean requireBoolean(String propertyName, Object value) {
4957 if (value instanceof Boolean) {
4958 return (Boolean) value;
4959 } else if (value instanceof String) {
4960 value = ((String)value).trim();
4961 if ("true".equals(value) || "on".equals(value) || "yes".equals(value) || "1".equals(value)) {
4962 return true;
4963 } else if ("false".equals(value) || "off".equals(value) || "no".equals(value) || "0".equals(value)) {
4964 return false;
4965 } else {
4966 throw new IllegalArgumentException(propertyName + " must be 'true' or 'false' (or on|off, yes|no, 1|0)");
4967 }
4968 } else {
4969 throw new IllegalArgumentException(propertyName + " must be a boolean (or a string representing a boolean)");
4970 }
4971 }
4972
4973 /**
4974 * Validate a property value where the required type is integer
4975 *
4976 * @param propertyName the name of the property
4977 * @param value the supplied value of the property. This may be either a java.lang.Integer, or a string
4978 * that can be parsed as an integer (suited to the conventions of different
4979 * configuration APIs that end up calling this method)
4980 * @return the value as an integer
4981 * @throws IllegalArgumentException if the supplied value cannot be validated as a recognized boolean value
4982 */
4983
4984 protected int requireInteger(String propertyName, Object value) {
4985 if (value instanceof Integer) {
4986 return (Integer) value;
4987 } else if (value instanceof String) {
4988 try {
4989 return Integer.parseInt((String) value);
4990 } catch (NumberFormatException nfe) {
4991 throw new IllegalArgumentException(propertyName + " must be an integer");
4992 }
4993 } else {
4994 throw new IllegalArgumentException(propertyName + " must be an integer (or a string representing an integer)");
4995 }
4996 }
4997
4998 /**
4999 * Set a boolean property value, without checking that it is a recognized property name
5000 *
5001 * @param property the name of the property to be set
5002 * @param value a representation of the boolean value.
5003 * This may be either a java.lang.Boolean, or a string
5004 * taking one of the values on|off, true|false, yes|no, or 1|0 (suited to the conventions of different
5005 * configuration APIs that end up calling this method)
5006 */
5007
5008 protected void internalSetBooleanProperty(Feature property, Object value) {
5009 boolean b = requireBoolean(property.name, value);
5010 if (b) {
5011 enabledProperties.add(property.code);
5012 } else {
5013 enabledProperties.remove(property.code);
5014 }
5015 }
5016
5017 /**
5018 * Get a boolean property of the configuration
5019 *
5020 * @param feature the integer code of the required property. See the class {@link FeatureCode} for
5021 * constants representing the property names that can be requested. This class only recognizes
5022 * properties whose type is boolean.
5023 * @return the value of the property. In the case of an unrecognized property name, the value returned is
5024 * false: no error is thrown.
5025 */
5026
5027 public boolean getBooleanProperty(Feature feature) {
5028 return enabledProperties.contains(feature.code);
5029 }
5030
5031 /**
5032 * Set a boolean property of the configuration
5033 *
5034 * @param propertyName the name of the required property. See the class {@link FeatureKeys} for
5035 * constants representing the property names that can be requested. This class only recognizes
5036 * properties whose type is boolean.
5037 * @param value the value of the property.
5038 * @throws IllegalArgumentException if the property name is not recognized (as a property whose expected
5039 * value is boolean)
5040 */
5041
5042 public void setBooleanProperty(String propertyName, boolean value) {
5043 setConfigurationProperty(propertyName, value);
5044 }
5045
5046 /**
5047 * Set a boolean property of the configuration
5048 *
5049 * @param feature the required property. See the class {@link Feature} for
5050 * constants representing the property names that can be requested. This class only recognizes
5051 * properties whose type is boolean.
5052 * @param value the value of the property.
5053 * @throws IllegalArgumentException if the feature is not recognized (as a feature whose expected
5054 * value is boolean)
5055 */
5056
5057 public void setBooleanProperty(Feature<Boolean> feature, boolean value) {
5058 setConfigurationProperty(feature, value);
5059 }
5060
5061 protected String requireString(String propertyName, Object value) {
5062 if (value instanceof String) {
5063 return (String) value;
5064 } else {
5065 throw new IllegalArgumentException("The value of " + propertyName + " must be a string");
5066 }
5067 }
5068
5069
5070 protected Object instantiateClassName(String propertyName, Object value, Class<?> requiredClass) {
5071 if (!(value instanceof String)) {
5072 throw new IllegalArgumentException(
5073 propertyName + " must be a String");
5074 }
5075 try {
5076 Object obj = getInstance((String) value, null);
5077 if (!requiredClass.isAssignableFrom(obj.getClass())) {
5078 throw new IllegalArgumentException("Error in " + propertyName +
5079 ": Class " + value + " does not implement " + requiredClass.getName());
5080 }
5081 return obj;
5082 } catch (XPathException err) {
5083 throw new IllegalArgumentException(
5084 "Cannot use " + value + " as the value of " + propertyName + ". " + err.getMessage());
5085 }
5086 }
5087
5088
5089 static {
5090 booleanFeatures.add(Feature.ALLOW_EXTERNAL_FUNCTIONS);
5091 booleanFeatures.add(Feature.ALLOW_MULTITHREADING);
5092 booleanFeatures.add(Feature.ALLOW_SYNTAX_EXTENSIONS);
5093 booleanFeatures.add(Feature.ASSERTIONS_CAN_SEE_COMMENTS);
5094 booleanFeatures.add(Feature.COMPILE_WITH_TRACING);
5095 booleanFeatures.add(Feature.DEBUG_BYTE_CODE);
5096 booleanFeatures.add(Feature.DISABLE_XSL_EVALUATE);
5097 booleanFeatures.add(Feature.DISPLAY_BYTE_CODE);
5098 booleanFeatures.add(Feature.DTD_VALIDATION);
5099 booleanFeatures.add(Feature.EAGER_EVALUATION);
5100 booleanFeatures.add(Feature.EXPAND_ATTRIBUTE_DEFAULTS);
5101 booleanFeatures.add(Feature.EXPATH_FILE_DELETE_TEMPORARY_FILES);
5102 booleanFeatures.add(Feature.GENERATE_BYTE_CODE);
5103 booleanFeatures.add(Feature.IGNORE_SAX_SOURCE_PARSER);
5104 booleanFeatures.add(Feature.IMPLICIT_SCHEMA_IMPORTS);
5105 booleanFeatures.add(Feature.MARK_DEFAULTED_ATTRIBUTES);
5106 booleanFeatures.add(Feature.MONITOR_HOT_SPOT_BYTE_CODE);
5107 booleanFeatures.add(Feature.MULTIPLE_SCHEMA_IMPORTS);
5108 booleanFeatures.add(Feature.PRE_EVALUATE_DOC_FUNCTION);
5109 booleanFeatures.add(Feature.PREFER_JAXP_PARSER);
5110 booleanFeatures.add(Feature.RETAIN_DTD_ATTRIBUTE_TYPES);
5111 booleanFeatures.add(Feature.STABLE_COLLECTION_URI);
5112 booleanFeatures.add(Feature.STABLE_UNPARSED_TEXT);
5113 booleanFeatures.add(Feature.STREAMING_FALLBACK);
5114 booleanFeatures.add(Feature.STRICT_STREAMABILITY);
5115 booleanFeatures.add(Feature.SUPPRESS_EVALUATION_EXPIRY_WARNING);
5116 booleanFeatures.add(Feature.SUPPRESS_XPATH_WARNINGS);
5117 booleanFeatures.add(Feature.SUPPRESS_XSLT_NAMESPACE_CHECK);
5118 booleanFeatures.add(Feature.TRACE_EXTERNAL_FUNCTIONS);
5119 booleanFeatures.add(Feature.TRACE_OPTIMIZER_DECISIONS);
5120 booleanFeatures.add(Feature.USE_PI_DISABLE_OUTPUT_ESCAPING);
5121 booleanFeatures.add(Feature.USE_TYPED_VALUE_CACHE);
5122 booleanFeatures.add(Feature.XQUERY_MULTIPLE_MODULE_IMPORTS);
5123 }
5124
5125
5126 /**
5127 * Get a property of the configuration
5128 *
5129 * @param name the name of the required property. See the class {@link FeatureKeys} for
5130 * constants representing the property names that can be requested.
5131 * @return the value of the property. Note that boolean values are returned as a Boolean,
5132 * even if the value was supplied as a string (for example "true" or "on").
5133 * @throws IllegalArgumentException thrown if the property is not one that Saxon recognizes.
5134 */
5135
5136 /*@NotNull*/
5137 public Object getConfigurationProperty(String name) {
5138 Feature<?> feature = Feature.byName(name);
5139 if (feature == null) {
5140 throw new IllegalArgumentException("Unknown configuration property " + name);
5141 } else {
5142 return getConfigurationProperty(feature);
5143 }
5144 }
5145
5146 /**
5147 * Get a property of the configuration
5148 *
5149 * @param feature the required property. See the class {@link Feature} for
5150 * constants representing the properties that can be requested.
5151 * @return the value of the property. Note that boolean values are returned as a Boolean,
5152 * even if the value was supplied as a string (for example "true" or "on").
5153 * @throws IllegalArgumentException thrown if the property is not one that Saxon recognizes.
5154 * @since 9.9
5155 */
5156
5157 /*@NotNull*/
5158 @SuppressWarnings("unchecked")
5159 public <T> T getConfigurationProperty(Feature<T> feature) {
5160 if (booleanFeatures.contains(feature)) {
5161 return (T) Boolean.valueOf(getBooleanProperty(feature));
5162 }
5163 switch (feature.code) {
5164
5165 case FeatureCode.COLLATION_URI_RESOLVER:
5166 return (T) getCollationURIResolver();
5167
5168 case FeatureCode.COLLATION_URI_RESOLVER_CLASS:
5169 return (T) getCollationURIResolver().getClass().getName();
5170
5171 case FeatureCode.COLLECTION_URI_RESOLVER:
5172 return (T) getCollectionURIResolver();
5173
5174 case FeatureCode.COLLECTION_URI_RESOLVER_CLASS:
5175 return (T) getCollectionURIResolver().getClass().getName();
5176
5177 case FeatureCode.CONFIGURATION:
5178 return (T)this;
5179
5180 case FeatureCode.DEFAULT_COLLATION:
5181 return (T) defaultCollationName;
5182
5183 case FeatureCode.DEFAULT_COLLECTION:
5184 return (T) getDefaultCollection();
5185
5186 case FeatureCode.DEFAULT_COUNTRY:
5187 return (T) getDefaultCountry();
5188
5189 case FeatureCode.DEFAULT_LANGUAGE:
5190 return (T) getDefaultLanguage();
5191
5192 case FeatureCode.DTD_VALIDATION:
5193 return (T) Boolean.valueOf(isValidation());
5194
5195 case FeatureCode.DTD_VALIDATION_RECOVERABLE:
5196 return (T) Boolean.valueOf(defaultParseOptions.getDTDValidationMode() == Validation.LAX);
5197
5198 case FeatureCode.ERROR_LISTENER_CLASS:
5199 return (T) getErrorListener().getClass().getName();
5200
5201 case FeatureCode.ENTITY_RESOLVER_CLASS:
5202 EntityResolver er = defaultParseOptions.getEntityResolver();
5203 if (er == null) {
5204 return (T) "";
5205 } else {
5206 return (T) er.getClass().getName();
5207 }
5208
5209 case FeatureCode.ENVIRONMENT_VARIABLE_RESOLVER:
5210 return (T) environmentVariableResolver;
5211
5212 case FeatureCode.ENVIRONMENT_VARIABLE_RESOLVER_CLASS:
5213 return (T) environmentVariableResolver.getClass().getName();
5214
5215 case FeatureCode.EXPAND_ATTRIBUTE_DEFAULTS:
5216 return (T) Boolean.valueOf(isExpandAttributeDefaults());
5217
5218 case FeatureCode.LINE_NUMBERING:
5219 return (T) Boolean.valueOf(isLineNumbering());
5220
5221 case FeatureCode.MESSAGE_EMITTER_CLASS:
5222 return (T) getMessageEmitterClass();
5223
5224 case FeatureCode.MODULE_URI_RESOLVER:
5225 return (T) getModuleURIResolver();
5226
5227 case FeatureCode.MODULE_URI_RESOLVER_CLASS:
5228 return (T) getModuleURIResolver().getClass().getName();
5229
5230 case FeatureCode.NAME_POOL:
5231 return (T) getNamePool();
5232
5233 case FeatureCode.OPTIMIZATION_LEVEL:
5234 return (T) optimizerOptions.toString();
5235
5236 case FeatureCode.OUTPUT_URI_RESOLVER:
5237 return (T) getOutputURIResolver();
5238
5239 case FeatureCode.OUTPUT_URI_RESOLVER_CLASS:
5240 return (T) getOutputURIResolver().getClass().getName();
5241
5242 case FeatureCode.RECOGNIZE_URI_QUERY_PARAMETERS:
5243 return (T) Boolean.valueOf(getSystemURIResolver().queryParametersAreRecognized());
5244
5245 case FeatureCode.RECOVERY_POLICY:
5246 return (T) Integer.valueOf(getRecoveryPolicy());
5247
5248 case FeatureCode.RECOVERY_POLICY_NAME:
5249 switch (getRecoveryPolicy()) {
5250 case RECOVER_SILENTLY:
5251 return (T) "recoverSilently";
5252 case RECOVER_WITH_WARNINGS:
5253 return (T) "recoverWithWarnings";
5254 case DO_NOT_RECOVER:
5255 return (T) "doNotRecover";
5256 default:
5257 throw new IllegalStateException();
5258 }
5259
5260 case FeatureCode.REGEX_BACKTRACKING_LIMIT:
5261 return (T) Integer.valueOf(regexBacktrackingLimit);
5262
5263 case FeatureCode.SCHEMA_VALIDATION:
5264 return (T) Integer.valueOf(getSchemaValidationMode());
5265
5266 case FeatureCode.SCHEMA_VALIDATION_MODE:
5267 return (T) Validation.toString(getSchemaValidationMode());
5268
5269 case FeatureCode.SERIALIZER_FACTORY_CLASS:
5270 return (T) getSerializerFactory().getClass().getName();
5271
5272 case FeatureCode.SOURCE_PARSER_CLASS:
5273 return (T) getSourceParserClass();
5274
5275 case FeatureCode.SOURCE_RESOLVER_CLASS:
5276 return (T) getSourceResolver().getClass().getName();
5277
5278 case FeatureCode.STRIP_WHITESPACE:
5279 SpaceStrippingRule rule = getParseOptions().getSpaceStrippingRule();
5280 if (rule == AllElementsSpaceStrippingRule.getInstance()) {
5281 return (T) "all";
5282 } else if (rule == null || rule == IgnorableSpaceStrippingRule.getInstance()) {
5283 return (T) "ignorable";
5284 } else {
5285 return (T) "none";
5286 }
5287
5288 case FeatureCode.STYLE_PARSER_CLASS:
5289 return (T) getStyleParserClass();
5290
5291 case FeatureCode.TIMING:
5292 return (T) Boolean.valueOf(isTiming());
5293
5294 case FeatureCode.TRACE_LISTENER:
5295 return (T) traceListener;
5296
5297 case FeatureCode.TRACE_LISTENER_CLASS:
5298 return (T) traceListenerClass;
5299
5300 case FeatureCode.TRACE_LISTENER_OUTPUT_FILE:
5301 return (T) traceListenerOutput;
5302
5303 case FeatureCode.TREE_MODEL:
5304 return (T) Integer.valueOf(getTreeModel());
5305
5306 case FeatureCode.TREE_MODEL_NAME:
5307 switch (getTreeModel()) {
5308 case Builder.TINY_TREE:
5309 default:
5310 return (T) "tinyTree";
5311 case Builder.TINY_TREE_CONDENSED:
5312 return (T) "tinyTreeCondensed";
5313 case Builder.LINKED_TREE:
5314 return (T) "linkedTree";
5315 }
5316
5317 case FeatureCode.UNPARSED_TEXT_URI_RESOLVER:
5318 return (T) getUnparsedTextURIResolver();
5319
5320 case FeatureCode.UNPARSED_TEXT_URI_RESOLVER_CLASS:
5321 return (T) getUnparsedTextURIResolver().getClass().getName();
5322
5323 case FeatureCode.URI_RESOLVER_CLASS:
5324 return (T) getURIResolver().getClass().getName();
5325
5326 case FeatureCode.USE_XSI_SCHEMA_LOCATION:
5327 return (T) Boolean.valueOf(defaultParseOptions.isUseXsiSchemaLocation());
5328
5329 case FeatureCode.VALIDATION_COMMENTS:
5330 return (T) Boolean.valueOf(defaultParseOptions.isAddCommentsAfterValidationErrors());
5331
5332 case FeatureCode.VALIDATION_WARNINGS:
5333 return (T) Boolean.valueOf(isValidationWarnings());
5334
5335 case FeatureCode.VERSION_WARNING:
5336 return (T) Boolean.valueOf(isVersionWarning());
5337
5338 case FeatureCode.XINCLUDE:
5339 return (T) Boolean.valueOf(isXIncludeAware());
5340
5341 case FeatureCode.XML_VERSION:
5342 return (T) (getXMLVersion() == XML10 ? "1.0" : "1.1");
5343
5344
5345 case FeatureCode.XQUERY_ALLOW_UPDATE:
5346 return (T)Boolean.valueOf(getDefaultStaticQueryContext().isUpdatingEnabled());
5347
5348 case FeatureCode.XQUERY_CONSTRUCTION_MODE:
5349 return (T)Integer.valueOf(getDefaultStaticQueryContext().getConstructionMode());
5350
5351 case FeatureCode.XQUERY_DEFAULT_ELEMENT_NAMESPACE:
5352 return (T)getDefaultStaticQueryContext().getDefaultElementNamespace();
5353
5354 case FeatureCode.XQUERY_DEFAULT_FUNCTION_NAMESPACE:
5355 return (T)getDefaultStaticQueryContext().getDefaultFunctionNamespace();
5356
5357 case FeatureCode.XQUERY_EMPTY_LEAST:
5358 return (T) Boolean.valueOf(getDefaultStaticQueryContext().isEmptyLeast());
5359
5360 case FeatureCode.XQUERY_INHERIT_NAMESPACES:
5361 return (T) Boolean.valueOf(getDefaultStaticQueryContext().isInheritNamespaces());
5362
5363 case FeatureCode.XQUERY_PRESERVE_BOUNDARY_SPACE:
5364 return (T) Boolean.valueOf(getDefaultStaticQueryContext().isPreserveBoundarySpace());
5365
5366 case FeatureCode.XQUERY_PRESERVE_NAMESPACES:
5367 return (T) Boolean.valueOf(getDefaultStaticQueryContext().isPreserveNamespaces());
5368
5369 case FeatureCode.XQUERY_REQUIRED_CONTEXT_ITEM_TYPE:
5370 return (T) getDefaultStaticQueryContext().getRequiredContextItemType();
5371
5372 case FeatureCode.XQUERY_SCHEMA_AWARE:
5373 return (T) Boolean.valueOf(getDefaultStaticQueryContext().isSchemaAware());
5374
5375 case FeatureCode.XQUERY_STATIC_ERROR_LISTENER_CLASS:
5376 return (T)getDefaultStaticQueryContext().getErrorListener().getClass().getName();
5377
5378 case FeatureCode.XQUERY_VERSION:
5379 return (T)"3.1";
5380
5381 case FeatureCode.XPATH_VERSION_FOR_XSD:
5382 return (T)(Integer)xpathVersionForXsd;
5383
5384 case FeatureCode.XPATH_VERSION_FOR_XSLT:
5385 return (T)(Integer)xpathVersionForXslt;
5386
5387 case FeatureCode.XSD_VERSION:
5388 return (T) (xsdVersion == XSD10 ? "1.0" : "1.1");
5389
5390 case FeatureCode.XSLT_ENABLE_ASSERTIONS:
5391 return (T)Boolean.valueOf(getDefaultXsltCompilerInfo().isAssertionsEnabled());
5392
5393 case FeatureCode.XSLT_INITIAL_MODE:
5394 return (T) getDefaultXsltCompilerInfo().getDefaultInitialMode().getClarkName();
5395
5396 case FeatureCode.XSLT_INITIAL_TEMPLATE:
5397 return (T) getDefaultXsltCompilerInfo().getDefaultInitialTemplate().getClarkName();
5398
5399 case FeatureCode.XSLT_SCHEMA_AWARE:
5400 return (T) Boolean.valueOf(getDefaultXsltCompilerInfo().isSchemaAware());
5401
5402 case FeatureCode.XSLT_STATIC_ERROR_LISTENER_CLASS:
5403 return (T) getDefaultXsltCompilerInfo().getErrorListener().getClass().getName();
5404
5405 case FeatureCode.XSLT_STATIC_URI_RESOLVER_CLASS:
5406 return (T) getDefaultXsltCompilerInfo().getURIResolver().getClass().getName();
5407
5408 case FeatureCode.XSLT_VERSION:
5409 return (T) Integer.valueOf(30);
5410
5411 }
5412 throw new IllegalArgumentException("Unknown configuration property " + feature.name);
5413 }
5414
5415
5416 /**
5417 * Ask whether bytecode should be generated. The default setting
5418 * is true in Saxon Enterprise Edition and false in all other cases. Setting the option to
5419 * true has no effect if Saxon-EE is not available (but if it is set to true, this method will
5420 * return true). Setting the option to false in Saxon-EE
5421 * is permitted if for some reason bytecode generation is to be suppressed (one possible reason
5422 * is to improve compilation performance at the expense of evaluation performance).
5423 *
5424 * @param hostLanguage one of XSLT or XQUERY
5425 * @return true if the option is switched on
5426 */
5427
5428 public boolean isGenerateByteCode(int hostLanguage) {
5429 return false;
5430 }
5431
5432 /**
5433 * Ask whether bytecode should be generated in Just-In-time compilation and therefore deferring the byte code generation. The default setting
5434 * is false. Setting the option to
5435 * true has no effect if Saxon-EE is not available (but if it is set to true, this method will
5436 * return true). Setting the option to false in Saxon-EE
5437 * is permitted and therefore byte code generation will be generated in the compile phase.
5438 *
5439 * @param hostLanguage one of XSLT or XQUERY
5440 * @return true if the option is switched on
5441 */
5442 public boolean isDeferredByteCode(int hostLanguage) {
5443 return false;
5444 }
5445
5446 /**
5447 * Ask whether just-in-time compilation of XSLT template rules is in force
5448 * @return true if just-in-time compilation is enabled (this is the default in Saxon-EE and
5449 * not available in other configurations)
5450 */
5451
5452 public boolean isJITEnabled() {
5453 return false;
5454 }
5455
5456 /**
5457 * Close any resources held by the Configuration. This implementation
5458 * closes the Logger and/or trace output file if one has been allocated.
5459 */
5460
5461 public void close() {
5462 if (traceOutput != null) {
5463 traceOutput.close();
5464 }
5465 }
5466
5467 public IPackageLoader makePackageLoader() {
5468 return new PackageLoaderHE(this);
5469 }
5470
5471 public InvalidityReportGenerator createValidityReporter() {
5472 throw new UnsupportedOperationException("Loading compiled packages requires Saxon-EE (even when no license is needed)");
5473 }
5474
5475 public int getCountDown() {
5476 return byteCodeThreshold;
5477 }
5478
5479
5480 /**
5481 * This class contains constants representing features of the software that may or may
5482 * not be licensed. (Note, this list is at a finer-grained level than the actual
5483 * purchasing options.)
5484 */
5485
5486 public static class LicenseFeature {
5487 public static final int SCHEMA_VALIDATION = 1;
5488 public static final int ENTERPRISE_XSLT = 2;
5489 public static final int ENTERPRISE_XQUERY = 4;
5490 public static final int PROFESSIONAL_EDITION = 8;
5491 }
5492
5493 /**
5494 * Make a new Mode - this can be overridden in subclasses to produce optimized variants
5495 *
5496 * @param modeName the name of the mode
5497 * @param compilerInfo information on the compiler, that can alter rule optimization
5498 * @return an instantiated Mode
5499 */
5500 public SimpleMode makeMode(StructuredQName modeName, CompilerInfo compilerInfo) {
5501 return new SimpleMode(modeName);
5502 }
5503
5504 /**
5505 * Factory method to create a Template Rule
5506 *
5507 * @return a new TemplateRule appropriate to this Configuration
5508 */
5509
5510 public TemplateRule makeTemplateRule() {
5511 return new TemplateRule();
5512 }
5513
5514
5515 /**
5516 * Make a ThreadManager for asynchronous xsl:result-document instructions
5517 *
5518 * @return a new ThreadManager (or null in the case of Saxon-HE)
5519 */
5520
5521 public XPathContextMajor.ThreadManager makeThreadManager() {
5522 return null;
5523 }
5524
5525 /**
5526 * Make an XSLT CompilerInfo object - can be overridden in a subclass to produce variants
5527 * capable of optimization
5528 *
5529 * @return a new CompilerInfo object
5530 */
5531
5532 public CompilerInfo makeCompilerInfo() {
5533 return new CompilerInfo(this);
5534 }
5535
5536 /**
5537 * Make a CompilerService object, to handle byte code generation, or null if byte code
5538 * generation is not available
5539 *
5540 * @param hostLanguage eg Configuration.XSLT
5541 * @return a CompilerService, or null
5542 */
5543 public ICompilerService makeCompilerService(int hostLanguage) {
5544 return null;
5545 }
5546
5547 /**
5548 * Generate a report on byte code instrumentation to a specified file
5549 *
5550 * @param fileName the specified file name
5551 */
5552
5553 public void createByteCodeReport(String fileName) {
5554 // no action in Saxon-HE
5555 }
5556
5557 /**
5558 * Set a label for this configuration
5559 *
5560 * @param label the label to associate
5561 */
5562 public void setLabel(String label) {
5563 this.label = label;
5564 }
5565
5566 /**
5567 * Get the associated label for this configuration
5568 *
5569 * @return the associated label
5570 */
5571 public String getLabel() {
5572 return label;
5573 }
5574 }
5575