Debian Codegraph @

net/sf/saxon/trans/XsltController.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.trans;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.PreparedStylesheet;
13 import net.sf.saxon.event.*;
14 import net.sf.saxon.expr.*;
15 import net.sf.saxon.expr.accum.AccumulatorManager;
16 import net.sf.saxon.expr.instruct.*;
17 import net.sf.saxon.expr.parser.ExplicitLocation;
18 import net.sf.saxon.lib.*;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.s9api.Destination;
21 import net.sf.saxon.serialize.Emitter;
22 import net.sf.saxon.serialize.MessageEmitter;
23 import net.sf.saxon.serialize.PrincipalOutputGatekeeper;
24 import net.sf.saxon.style.StylesheetPackage;
25 import net.sf.saxon.tree.iter.EmptyIterator;
26 import net.sf.saxon.tree.iter.ManualIterator;
27 import net.sf.saxon.tree.iter.SingletonIterator;
28 import net.sf.saxon.tree.wrapper.SpaceStrippedDocument;
29 import net.sf.saxon.tree.wrapper.SpaceStrippedNode;
30 import net.sf.saxon.tree.wrapper.TypeStrippedDocument;
31 import org.xml.sax.SAXParseException;
32
33 import javax.xml.transform.OutputKeys;
34 import javax.xml.transform.Source;
35 import javax.xml.transform.sax.SAXSource;
36 import javax.xml.transform.stream.StreamSource;
37 import java.util.*;
38 import java.util.function.Supplier;
39
40 /**
41 * This class is an extension of the Controller class, used when executing XSLT stylesheets.
42 *
43 * @since 9.9
44 */
45
46 public class XsltController extends Controller {
47
48 private final Map<StructuredQName, Integer> messageCounters = new HashMap<>();
49 private Receiver explicitMessageReceiver = null;
50 private Supplier<Receiver> messageFactory = MessageEmitter::new;
51 private boolean assertionsEnabled = true;
52 private ResultDocumentResolver resultDocumentResolver;
53 private HashSet<DocumentURI> allOutputDestinations;
54 private Component.M initialMode = null;
55 private Function initialFunction = null;
56 private int recoveryPolicy;
57 private Map<StructuredQName, Sequence<?>> initialTemplateParams;
58 private Map<StructuredQName, Sequence<?>> initialTemplateTunnelParams;
59 private Map<Long, Stack<AttributeSet>> attributeSetEvaluationStacks = new HashMap<>();
60 private AccumulatorManager accumulatorManager = new AccumulatorManager();
61 private PrincipalOutputGatekeeper gatekeeper = null;
62 private Destination principalDestination;
63
64 public XsltController(Configuration config, PreparedStylesheet pss) {
65 super(config, pss);
66 }
67
68 /**
69 * <p>Reset this <code>Transformer</code> to its original configuration.</p>
70 * <p><code>Transformer</code> is reset to the same state as when it was created with
71 * {@link javax.xml.transform.TransformerFactory#newTransformer()},
72 * {@link javax.xml.transform.TransformerFactory#newTransformer(javax.xml.transform.Source source)} or
73 * {@link javax.xml.transform.Templates#newTransformer()}.
74 * <code>reset()</code> is designed to allow the reuse of existing <code>Transformer</code>s
75 * thus saving resources associated with the creation of new <code>Transformer</code>s.</p>
76 * <p><i>The above is from the JAXP specification. With Saxon, it's unlikely that reusing a Transformer will
77 * give any performance benefits over creating a new one. The one case where it might be beneficial is
78 * to reuse the document pool (the set of documents that have been loaded using the doc() or document()
79 * functions). Therefore, this method does not clear the document pool. If you want to clear the document
80 * pool, call the method {@link #clearDocumentPool} as well.</i></p>
81 * <p>The reset <code>Transformer</code> is not guaranteed to have the same {@link javax.xml.transform.URIResolver}
82 * or {@link javax.xml.transform.ErrorListener} <code>Object</code>s, e.g. {@link Object#equals(Object obj)}.
83 * It is guaranteed to have a functionally equal <code>URIResolver</code>
84 * and <code>ErrorListener</code>.</p>
85 *
86 * @since 1.5
87 */
88
89 public void reset() {
90 super.reset();
91 Configuration config = getConfiguration();
92 //outputURIResolver = config.getOutputURIResolver();
93 setErrorListener(config.getErrorListener());
94 recoveryPolicy = config.getRecoveryPolicy();
95 validationMode = config.getSchemaValidationMode();
96 accumulatorManager = new AccumulatorManager();
97 if (errorListener instanceof StandardErrorListener) {
98 // if using a standard error listener, make a fresh one
99 // for each transformation, because it is stateful - and also because the
100 // host language is now known (a Configuration can serve multiple host languages)
101 Logger ps = ((StandardErrorListener) errorListener).getLogger();
102 errorListener = ((StandardErrorListener) errorListener).makeAnother(executable.getHostLanguage());
103 ((StandardErrorListener) errorListener).setLogger(ps);
104 ((StandardErrorListener) errorListener).setRecoveryPolicy(recoveryPolicy);
105 }
106
107 traceListener = null;
108 TraceListener tracer;
109 try {
110 tracer = config.makeTraceListener();
111 } catch (XPathException err) {
112 throw new IllegalStateException(err.getMessage());
113 }
114 if (tracer != null) {
115 addTraceListener(tracer);
116 }
117
118 setModel(config.getParseOptions().getModel());
119
120 globalContextItem = null;
121 initialMode = null;
122 clearPerTransformationData();
123 }
124
125 /**
126 * Reset variables that need to be reset for each transformation if the controller
127 * is serially reused
128 */
129
130 protected synchronized void clearPerTransformationData() {
131 super.clearPerTransformationData();
132 principalResult = null;
133 allOutputDestinations = null;
134 if (messageCounters != null) {
135 messageCounters.clear();
136 }
137 }
138
139 /**
140 * Set the initial mode for the transformation.
141 * <p>XSLT 2.0 allows a transformation to be started in a mode other than the default mode.
142 * The transformation then starts by looking for the template rule in this mode that best
143 * matches the initial context node.</p>
144 * <p>This method may eventually be superseded by a standard JAXP method.</p>
145 *
146 * @param expandedModeName the name of the initial mode. The mode is
147 * supplied as an expanded QName. Two special values are recognized, in the
148 * reserved XSLT namespace:
149 * xsl:unnamed to indicate the mode with no name, and xsl:default to indicate the
150 * mode defined in the stylesheet header as the default mode.
151 * The value null also indicates the unnamed mode.
152 * @throws XPathException if the requested mode is not defined in the stylesheet
153 * @since 8.4 Changed in 9.6 to accept a StructuredQName, and to throw an error if the mode
154 * has not been defined. Changed in 9.7 so that null indicates the default mode, which defaults
155 * to the unnamed mode but can be set otherwise in the stylesheet.
156 */
157
158 public void setInitialMode(StructuredQName expandedModeName) throws XPathException {
159 if (expandedModeName == null || expandedModeName.equals(Mode.UNNAMED_MODE_NAME)) {
160 Mode initial = ((PreparedStylesheet) executable).getRuleManager().obtainMode(Mode.UNNAMED_MODE_NAME, true);
161 initialMode = initial.getDeclaringComponent();
162 } else {
163 StylesheetPackage topLevelPackage = (StylesheetPackage) executable.getTopLevelPackage();
164 if (expandedModeName.equals(Mode.DEFAULT_MODE_NAME)) {
165 StructuredQName defaultModeName = topLevelPackage.getDefaultMode();
166 if (!expandedModeName.equals(defaultModeName)) {
167 setInitialMode(defaultModeName);
168 }
169 } else {
170 //initialMode = ((PreparedStylesheet) executable).getRuleManager().obtainMode(expandedModeName, false);
171 boolean declaredModes = topLevelPackage.isDeclaredModes();
172 SymbolicName sn = new SymbolicName(StandardNames.XSL_MODE, expandedModeName);
173 Component.M c = (Component.M)topLevelPackage.getComponent(sn);
174 if (c == null) {
175 throw new XPathException("Requested initial mode " + expandedModeName + " is not defined in the stylesheet", "XTDE0045");
176 }
177 if (!((PreparedStylesheet)executable).isEligibleInitialMode(c)) {
178 //if (declaredModes && c.getVisibility() == Visibility.PRIVATE) {
179 throw new XPathException("Requested initial mode " + expandedModeName + " is private in the top-level package", "XTDE0045");
180 }
181 initialMode = c;
182 if (!declaredModes && initialMode.getActor().isEmpty() && !expandedModeName.equals(topLevelPackage.getDefaultMode())) {
183 throw new XPathException("Requested initial mode " + expandedModeName + " contains no template rules", "XTDE0045");
184 }
185 }
186 }
187 }
188
189 /**
190 * Get the name of the initial mode for the transformation
191 *
192 * @return the name of the initial mode; null indicates
193 * that the initial mode is the unnamed mode.
194 */
195
196 public StructuredQName getInitialModeName() {
197 return initialMode == null ? null : initialMode.getActor().getModeName();
198 }
199
200 /**
201 * Get the initial mode for the transformation
202 *
203 * @return the initial mode. This will be the default/unnamed mode if no specific mode
204 * has been requested
205 */
206
207 /*@NotNull*/
208 public Mode getInitialMode() {
209 if (initialMode == null) {
210 StylesheetPackage top = (StylesheetPackage) executable.getTopLevelPackage();
211 StructuredQName defaultMode = top.getDefaultMode();
212 if (defaultMode == null) {
213 defaultMode = Mode.UNNAMED_MODE_NAME;
214 }
215 Component.M c = (Component.M) top.getComponent(new SymbolicName(StandardNames.XSL_MODE, defaultMode));
216 initialMode = c;
217 return c.getActor();
218 } else {
219 return initialMode.getActor();
220 }
221 }
222
223 /**
224 * Get the accumulator manager for this transformation. May be null if no accumulators are in use
225 *
226 * @return the accumulator manager, which holds dynamic information about the values of each
227 * accumulator for each document
228 */
229
230 public AccumulatorManager getAccumulatorManager() {
231 return accumulatorManager;
232 }
233
234 /**
235 * Check that an output destination has not been used before, optionally adding
236 * this URI to the set of URIs that have been used.
237 * <p>This method is intended for internal use only.</p>
238 *
239 * @param uri the URI to be used as the output destination
240 * @return true if the URI is available for use; false if it has already been used.
241 */
242
243 public synchronized boolean checkUniqueOutputDestination(/*@Nullable*/ DocumentURI uri) {
244 if (uri == null) {
245 return true; // happens when writing say to an anonymous StringWriter
246 }
247 if (allOutputDestinations == null) {
248 allOutputDestinations = new HashSet<>(20);
249 }
250
251 return !allOutputDestinations.contains(uri);
252 }
253
254 /**
255 * Add a URI to the set of output destinations that cannot be written to, either because
256 * they have already been written to, or because they have been read
257 *
258 * @param uri A URI that is not available as an output destination
259 */
260
261 public void addUnavailableOutputDestination(DocumentURI uri) {
262 if (allOutputDestinations == null) {
263 allOutputDestinations = new HashSet<>(20);
264 }
265 allOutputDestinations.add(uri);
266 }
267
268 /**
269 * Remove a URI from the set of output destinations that cannot be written to or read from.
270 * Used to support saxon:discard-document()
271 *
272 * @param uri A URI that is being made available as an output destination
273 */
274
275 public void removeUnavailableOutputDestination(DocumentURI uri) {
276 if (allOutputDestinations != null) {
277 allOutputDestinations.remove(uri);
278 }
279 }
280
281 /**
282 * Determine whether an output URI is available for use. This method is intended
283 * for use by applications, via an extension function.
284 *
285 * @param uri A uri that the application is proposing to use in the href attribute of
286 * xsl:result-document: if this function returns false, then the xsl:result-document
287 * call will fail saying the URI has already been used.
288 * @return true if the URI is available for use. Note that this function is not "stable":
289 * it may return different results for the same URI at different points in the transformation.
290 */
291
292 public boolean isUnusedOutputDestination(DocumentURI uri) {
293 return allOutputDestinations == null || !allOutputDestinations.contains(uri);
294 }
295
296 /**
297 * Set parameters for the initial template (whether this is a named template, or a template
298 * rule invoked to process the initial input item)
299 *
300 * @param params Tunnel or non-tunnel parameters to be supplied to the initial template. The supplied
301 * values will be converted to the required type using the function conversion rules.
302 * Any surplus parameters are silently ignored. May be null.
303 * @param tunnel true if these are tunnel parameters; false if they are non-tunnel parameters
304 * @since 9.6
305 */
306
307 public void setInitialTemplateParameters(Map<StructuredQName, Sequence<?>> params, boolean tunnel) {
308 if (tunnel) {
309 this.initialTemplateTunnelParams = params;
310 } else {
311 this.initialTemplateParams = params;
312 }
313
314 }
315
316 /**
317 * Get the parameters for the initial template
318 *
319 * @param tunnel true if the parameters to be returned are the tunnel parameters; false for the non-tunnel parameters
320 * @return the parameters supplied using {@link #setInitialTemplateParameters(Map, boolean)}.
321 * May be null.
322 * @since 9.6
323 */
324
325 public Map<StructuredQName, Sequence<?>> getInitialTemplateParameters(boolean tunnel) {
326 return tunnel ? initialTemplateTunnelParams : initialTemplateParams;
327 }
328
329 /**
330 * Supply a factory function that is called every time xsl:message is executed; the factory function
331 * is responsible for creating a {@link Receiver} that receives the content of the message, and does
332 * what it will with it.
333 * @param messageReceiverFactory a factory function whose job it is to create a {@link Receiver} for
334 * xsl:message output; the function should supply a new {@code Receiver}
335 * each time it is called, because xsl:message calls may arise in different
336 * threads and the Receiver is unlikely to be thread-safe.
337 */
338
339 public void setMessageFactory(Supplier<Receiver> messageReceiverFactory) {
340 this.messageFactory = messageReceiverFactory;
341 }
342
343 /**
344 * Set the message receiver class name. This is an alternative way (retained for compatibility)
345 * of providing a factory for message receivers; it causes a message factory to be established
346 * that instantiates the supplied class
347 *
348 * @param name the full name of the class to be instantiated to provide a receiver for xsl:message output. The name must
349 * be the name of a class that implements the {@link net.sf.saxon.event.Receiver} interface
350 */
351
352 public void setMessageReceiverClassName(String name) {
353 if (!name.equals(MessageEmitter.class.getName())) {
354 this.messageFactory = () -> {
355 try {
356 Object messageReceiver = getConfiguration().getInstance(name, null);
357 if (!(messageReceiver instanceof Receiver)) {
358 throw new XPathException(name + " is not a Receiver");
359 }
360 return (Receiver) messageReceiver;
361 } catch (XPathException e) {
362 throw new UncheckedXPathException(e);
363 }
364 };
365 }
366 }
367
368 /**
369 * Make a Receiver to be used for xsl:message output.
370 * <p>This method is intended for internal use only. From 9.9.0.2 (bug 3979) this method
371 * is called to obtain a new Receiver each time an xsl:message instruction is evaluated.</p>
372 *
373 * @return The newly constructed message Receiver
374 * @throws XPathException if any dynamic error occurs; in
375 * particular, if the registered MessageEmitter class is not an
376 * Emitter
377 */
378
379 /*@NotNull*/
380 public Receiver makeMessageReceiver() throws XPathException {
381 return messageFactory.get();
382 // Object messageReceiver = getConfiguration().getInstance(messageReceiverClassName, null);
383 // if (!(messageReceiver instanceof Receiver)) {
384 // throw new XPathException(messageReceiverClassName + " is not a Receiver");
385 // }
386 // ((Receiver) messageReceiver).setPipelineConfiguration(makePipelineConfiguration());
387 // setMessageEmitter((Receiver) messageReceiver);
388 // return (Receiver) messageReceiver;
389 }
390
391 /**
392 * Set the Receiver to be used for xsl:message output.
393 * <p>
394 * Recent versions of the JAXP interface specify that by default the
395 * output of xsl:message is sent to the registered ErrorListener. Saxon
396 * does not implement this convention. Instead, the output is sent
397 * to a default message emitter, which is a slightly customised implementation
398 * of the standard Saxon Emitter interface.</p>
399 * <p>
400 * This interface can be used to change the way in which Saxon outputs
401 * xsl:message output.</p>
402 * <p>
403 * It is not necessary to use this interface in order to change the destination
404 * to which messages are written: that can be achieved by obtaining the standard
405 * message emitter and calling its {@link Emitter#setWriter} method.</p>
406 * <p>
407 * Although any <code>Receiver</code> can be supplied as the destination for messages,
408 * applications may find it convenient to implement a subclass of {@link net.sf.saxon.event.SequenceWriter},
409 * in which only the abstract <code>write()</code> method is implemented. This will have the effect that the
410 * <code>write()</code> method is called to output each message as it is generated, with the <code>Item</code>
411 * that is passed to the <code>write()</code> method being the document node at the root of an XML document
412 * containing the contents of the message.
413 * <p>
414 * This method is intended for use by advanced applications. The Receiver interface
415 * itself is subject to change in new Saxon releases.</p>
416 * <p>
417 * The supplied Receiver will have its open() method called once at the start of
418 * the transformation, and its close() method will be called once at the end of the
419 * transformation. Each individual call of an xsl:message instruction is wrapped by
420 * calls of startDocument() and endDocument(). If terminate="yes" is specified on the
421 * xsl:message call, the properties argument of the startDocument() call will be set
422 * to the value {@link ReceiverOptions#TERMINATE}.</p>
423 *
424 * @param receiver The receiver to receive xsl:message output.
425 * @since 8.4; changed in 8.9 to supply a Receiver rather than an Emitter. Changed
426 * in 9.9.0.2 so it is no longer supported in a configuration that allows multi-threading.
427 */
428
429 public void setMessageEmitter(Receiver receiver) {
430 if (getConfiguration().getBooleanProperty(Feature.ALLOW_MULTITHREADING)) {
431 throw new IllegalStateException("XsltController#setMessageEmitter() is not supported for a configuration that allows multi-threading. Use setMessageFactory() instead");
432 }
433 final Receiver messageReceiver = explicitMessageReceiver = receiver;
434 receiver.setPipelineConfiguration(makePipelineConfiguration());
435 if (receiver instanceof Emitter && ((Emitter) receiver).getOutputProperties() == null) {
436 try {
437 Properties props = new Properties();
438 props.setProperty(OutputKeys.METHOD, "xml");
439 props.setProperty(OutputKeys.INDENT, "yes");
440 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
441 ((Emitter) receiver).setOutputProperties(props);
442 } catch (XPathException e) {
443 // no action
444 }
445 }
446 setMessageFactory(() -> new ProxyReceiver(messageReceiver) {
447 /**
448 * End of output. Note that closing this receiver also closes the rest of the
449 * pipeline.
450 */
451 @Override
452 public void close() {
453 //super.close();
454 }
455 });
456
457 }
458
459 /**
460 * Get the Receiver used for xsl:message output. This returns the emitter
461 * previously supplied to the {@link #setMessageEmitter} method, or the
462 * default message emitter otherwise.
463 *
464 * @return the Receiver being used for xsl:message output
465 * @since 8.4; changed in 8.9 to return a Receiver rather than an Emitter
466 * @deprecated since 9.9.0.2; always returns null.
467 */
468
469 /*@Nullable*/
470 public Receiver getMessageEmitter() {
471 return explicitMessageReceiver;
472 }
473
474 /**
475 * Increment a counter in the message counters. This method is called automatically
476 * when xsl:message is executed, to increment the counter associated with a given
477 * error code used in the xsl:message. The counters are available (in Saxon-PE and -EE)
478 * using the saxon:message-counter() extension function.
479 *
480 * @param code the error code whose counter is to be incremented
481 */
482
483 public void incrementMessageCounter(StructuredQName code) {
484 synchronized(messageCounters) {
485 Integer c = messageCounters.get(code);
486 int n = c == null ? 1 : c + 1;
487 messageCounters.put(code, n);
488 }
489 }
490
491 /**
492 * Get the message counters
493 *
494 * @return a snapshot copy of the table of message counters, indicating the number of times xsl:message
495 * has been called for each distinct error code
496 */
497
498 public Map<StructuredQName, Integer> getMessageCounters() {
499 synchronized(messageCounters) {
500 return new HashMap<>(messageCounters);
501 }
502 }
503
504 /**
505 * Set the policy for handling recoverable XSLT errors.
506 * <p>Since 9.3 this call has no effect unless the error listener in use is a {@link StandardErrorListener}
507 * or a subclass thereof. Calling this method then results in a call to the StandardErrorListener
508 * to set the recovery policy, and the action that is taken on calls of the various methods
509 * error(), fatalError(), and warning() is then the responsibility of the ErrorListener itself.</p>
510 * <p>Since 9.2 the policy for handling the most common recoverable error, namely the ambiguous template
511 * match that arises when a node matches more than one match pattern, is a compile-time rather than run-time
512 * setting, and can be controlled using {@link CompilerInfo#setRecoveryPolicy(int)} </p>
513 *
514 * @param policy the recovery policy to be used. The options are {@link Configuration#RECOVER_SILENTLY},
515 * {@link Configuration#RECOVER_WITH_WARNINGS}, or {@link Configuration#DO_NOT_RECOVER}.
516 * @since 8.7.1
517 */
518
519 public void setRecoveryPolicy(int policy) {
520 recoveryPolicy = policy;
521 if (errorListener instanceof StandardErrorListener) {
522 ((StandardErrorListener) errorListener).setRecoveryPolicy(policy);
523 }
524 }
525
526 /**
527 * Get the policy for handling recoverable errors
528 *
529 * @return the current policy. If none has been set with this Controller, the value registered with the
530 * Configuration is returned.
531 * @since 8.7.1
532 */
533
534 public int getRecoveryPolicy() {
535 return recoveryPolicy;
536 }
537
538 /**
539 * Report a recoverable error. This is an XSLT concept: by default, such an error results in a warning
540 * message, and processing continues. In XQuery, however, there are no recoverable errors so a fatal
541 * error is reported.
542 * <p>This method is intended for internal use only.</p>
543 *
544 * @param err An exception holding information about the error
545 * @throws XPathException if the error listener decides not to
546 * recover from the error
547 */
548
549 @Override
550 public void recoverableError(XPathException err) throws XPathException {
551 if (recoveryPolicy == Configuration.DO_NOT_RECOVER) {
552 throw err;
553 } else {
554 errorListener.warning(err);
555 }
556 }
557
558 /**
559 * Set the URI resolver for secondary output documents.
560 * <p>XSLT 2.0 introduces the <code>xsl:result-document</code> instruction,
561 * allowing a transformation to have multiple result documents. JAXP does
562 * not yet support this capability. This method allows an OutputURIResolver
563 * to be specified that takes responsibility for deciding the destination
564 * (and, if it wishes, the serialization properties) of secondary output files.</p>
565 * <p>In Saxon 9.5, because xsl:result-document is now multi-threaded, the
566 * supplied resolver is cloned each time a new result document is created.
567 * The cloned resolved is therefore able to maintain information about
568 * the specific result document for use when its close() method is called,
569 * without worrying about thread safety.</p>
570 *
571 * @param resolver An object that implements the OutputURIResolver
572 * interface, or null.
573 * @since 8.4. Retained for backwards compatibility in 9.9, but superseded
574 * by {@link #setResultDocumentResolver(ResultDocumentResolver)}
575 */
576
577 public void setOutputURIResolver(/*@Nullable*/ OutputURIResolver resolver) {
578 OutputURIResolver our = resolver == null ? getConfiguration().getOutputURIResolver() : resolver;
579 setResultDocumentResolver(new OutputURIResolverWrapper(our));
580 }
581
582 public ResultDocumentResolver getResultDocumentResolver() {
583 return resultDocumentResolver;
584 }
585
586 public void setResultDocumentResolver(ResultDocumentResolver resultDocumentResolver) {
587 this.resultDocumentResolver = resultDocumentResolver;
588 }
589
590 /**
591 * Get the output URI resolver.
592 *
593 * @return the user-supplied URI resolver if there is one, or the
594 * system-defined one otherwise.
595 * @see #setOutputURIResolver
596 * @since 8.4. Retained for backwards compatibility in 9.9; superseded by
597 * {@link #getResultDocumentResolver()}
598 */
599
600 /*@Nullable*/
601 public OutputURIResolver getOutputURIResolver() {
602 if (resultDocumentResolver instanceof OutputURIResolverWrapper) {
603 return ((OutputURIResolverWrapper) resultDocumentResolver).getOutputURIResolver();
604 } else {
605 return getConfiguration().getOutputURIResolver();
606 }
607 }
608
609 /**
610 * Supply the Controller with information about the principal destination of the transformation
611 *
612 * @param destination the principal destination
613 */
614
615 public void setPrincipalDestination(Destination destination) {
616 principalDestination = destination;
617 }
618
619 /**
620 * Get the principal destination that was supplied to the Controller
621 * @return the principal destination
622 */
623
624 public Destination getPrincipalDestination() {
625 return principalDestination;
626 }
627
628
629 /**
630 * Ask whether assertions (xsl:assert instructions) have been enabled at run time. By default
631 * they are disabled at compile time. If assertions are enabled at compile time, then by
632 * default they will also be enabled at run time; but they can be disabled at run time by
633 * specific request. At compile time, assertions can be enabled for some packages and
634 * disabled for others; at run-time, they can only be enabled or disabled globally.
635 *
636 * @return true if assertions are enabled at run time
637 * @since 9.7
638 */
639
640 public boolean isAssertionsEnabled() {
641 return assertionsEnabled;
642 }
643
644 /**
645 * Ask whether assertions (xsl:assert instructions) have been enabled at run time. By default
646 * they are disabled at compile time. If assertions are enabled at compile time, then by
647 * default they will also be enabled at run time; but they can be disabled at run time by
648 * specific request. At compile time, assertions can be enabled for some packages and
649 * disabled for others; at run-time, they can only be enabled or disabled globally.
650 *
651 * @param enabled true if assertions are to be enabled at run time; this has no effect
652 * if assertions were disabled (for a particular package) at compile time
653 * @since 9.7
654 */
655
656 public void setAssertionsEnabled(boolean enabled) {
657 this.assertionsEnabled = enabled;
658 }
659
660 @Override
661 public void preEvaluateGlobals(XPathContext context) throws XPathException {
662 openMessageEmitter();
663 super.preEvaluateGlobals(context);
664 closeMessageEmitter();
665 }
666
667 /**
668 * Perform a transformation from a Source document to a Result document.
669 *
670 * @param source The input for the source tree. May be null if and only if an
671 * initial template has been supplied.
672 * @param out The destination for the result sequence. The events that are written to this
673 * {@code Receiver} will form a <em>regular event sequence</em>
674 * as defined in {@link RegularSequenceChecker}. This event sequence represents
675 * the <em>raw results</em> of the transformation; subsequent processing
676 * such as sequence normalization (to construct a document node) is the
677 * responsibility of the Receiver itself.
678 * @throws XPathException if the transformation fails. As a
679 * special case, the method throws a TerminationException (a subclass
680 * of XPathException) if the transformation was terminated using
681 * xsl:message terminate="yes".
682 */
683
684 public void applyTemplates(Sequence<?> source, Receiver out) throws XPathException {
685
686 checkReadiness();
687 openMessageEmitter();
688
689 try {
690 out = prepareOutputReceiver(out);
691
692 XPathContextMajor initialContext = newXPathContext();
693 initialContext.createThreadManager();
694 initialContext.setOrigin(this);
695 initialContext.setReceiver(out);
696
697 boolean close = false;
698
699 Mode mode = getInitialMode();
700 if (mode == null) {
701 throw new XPathException("Requested initial mode " +
702 (initialMode == null ? "#unnamed" : initialMode.getActor().getModeName().getDisplayName()) +
703 " does not exist", "XTDE0045");
704 }
705 //if (!mode.isUnnamedMode()) {
706 // Visibility vis = mode.getDeclaredVisibility();
707 // if (vis != null && !(vis == Visibility.PUBLIC || vis == Visibility.FINAL)) {
708 // throw new XPathException("Requested initial mode " +
709 // (mode.getModeName().getDisplayName()) +
710 // " is not public or final", "XTDE0045");
711 // }
712 if (!((PreparedStylesheet)executable).isEligibleInitialMode(initialMode)) {
713 throw new XPathException("Requested initial mode " +
714 (mode.getModeName().getDisplayName()) +
715 " is not public or final", "XTDE0045");
716 }
717 //}
718
719 warningIfStreamable(mode);
720
721 // Determine whether we need to close the output stream at the end. We
722 // do this if the Result object is a StreamResult and is supplied as a
723 // system ID, not as a Writer or OutputStream
724
725 boolean mustClose = false;
726
727 // Process the source document by applying template rules to the initial context node
728
729 ParameterSet ordinaryParams = null;
730 if (initialTemplateParams != null) {
731 ordinaryParams = new ParameterSet(initialTemplateParams);
732 }
733 ParameterSet tunnelParams = null;
734 if (initialTemplateTunnelParams != null) {
735 tunnelParams = new ParameterSet(initialTemplateTunnelParams);
736 }
737
738 SequenceIterator<?> iter = source.iterate();
739
740 MappingFunction<Item<?>, Item<?>> preprocessor = getInputPreprocessor(mode);
741 iter = new MappingIterator<>(iter, preprocessor);
742
743 initialContext.trackFocus(iter);
744 initialContext.setCurrentMode(initialMode);
745 initialContext.setCurrentComponent(initialMode);
746
747 TailCall tc = mode.applyTemplates(ordinaryParams, tunnelParams, initialContext, ExplicitLocation.UNKNOWN_LOCATION);
748 while (tc != null) {
749 tc = tc.processLeavingTail();
750 }
751
752 initialContext.waitForChildThreads();
753
754 out.close();
755
756 } catch (TerminationException err) {
757 //System.err.println("Processing terminated using xsl:message");
758 if (!err.hasBeenReported()) {
759 reportFatalError(err);
760 }
761 throw err;
762 } catch (XPathException err) {
763 Throwable cause = err.getException();
764 if (cause instanceof SAXParseException) {
765 // This generally means the error was already reported.
766 // But if a RuntimeException occurs in Saxon during a callback from
767 // the Crimson parser, Crimson wraps this in a SAXParseException without
768 // reporting it further.
769 SAXParseException spe = (SAXParseException) cause;
770 cause = spe.getException();
771 if (cause instanceof RuntimeException) {
772 reportFatalError(err);
773 }
774 } else {
775 reportFatalError(err);
776 }
777 throw err;
778 } finally {
779 inUse = false;
780 closeMessageEmitter();
781 if (traceListener != null) {
782 traceListener.close();
783 }
784 principalResultURI = null;
785 }
786 }
787
788 /**
789 * Takes a Receiver that expects raw output (such as might be obtained from {@link Destination#getReceiver})
790 * and prepends a pipeline of receivers needed to support transformation tasks, especially a
791 * {@link ComplexContentOutputter}.
792 * @param out a receiver expecting raw output
793 * @return a receiver to which instructions in the stylesheet can write events. This receiver will have
794 * been opened.
795 * @throws XPathException if any failure occurs
796 */
797
798 private Receiver prepareOutputReceiver(Receiver out) throws XPathException {
799 principalResult = out;
800 if (principalResultURI == null) {
801 principalResultURI = out.getSystemId();
802 }
803
804 //out = new RegularSequenceChecker(out); // uncomment for debugging
805 //out = new TracingFilter(out); // uncomment for debugging
806 NamespaceReducer nr = new NamespaceReducer(out);
807 ComplexContentOutputter cco = new ComplexContentOutputter(nr);
808 cco.setSystemId(out.getSystemId());
809 out = cco;
810
811
812 if (getExecutable().createsSecondaryResult()) {
813 // This is for the case where the stylesheet writes no output to the primary destination,
814 // and then calls xsl:result-document with a null or empty href, in which case the xsl:result-document
815 // output is sent to the primary output destination, but with different serialization properties.
816 out = this.gatekeeper = new PrincipalOutputGatekeeper(this, out);
817 }
818
819 out.open();
820 return out;
821 }
822
823 /**
824 * Get the Gatekeeper object, which is used to ensure that we don't write a secondary
825 * result document to the same destination as the principal result document
826 * @return the gatekeeper object, or null if none is in use
827 */
828
829 public PrincipalOutputGatekeeper getGatekeeper() {
830 return gatekeeper;
831 }
832
833 private MappingFunction<Item<?>, Item<?>> getInputPreprocessor(Mode finalMode) {
834 return item -> {
835 if (item instanceof NodeInfo) {
836 NodeInfo node = (NodeInfo) item;
837 if (node.getConfiguration() == null) {
838 // must be a non-standard document implementation
839 throw new XPathException("The supplied source document must be associated with a Configuration");
840 }
841
842 if (!node.getConfiguration().isCompatible(executable.getConfiguration())) {
843 throw new XPathException(
844 "Source document and stylesheet must use the same or compatible Configurations",
845 SaxonErrorCode.SXXP0004);
846 }
847
848 if (node.getTreeInfo().isTyped() && !executable.isSchemaAware()) {
849 throw new XPathException("Cannot use a schema-validated source document unless the stylesheet is schema-aware");
850 }
851
852 if (isStylesheetStrippingTypeAnnotations() && node != globalContextItem) {
853 TreeInfo docInfo = node.getTreeInfo();
854 if (docInfo.isTyped()) {
855 TypeStrippedDocument strippedDoc = new TypeStrippedDocument(docInfo);
856 node = strippedDoc.wrap(node);
857 }
858 }
859
860 SpaceStrippingRule spaceStrippingRule = getSpaceStrippingRule();
861 if (isStylesheetContainingStripSpace() && isStripSourceTree() && !(node instanceof SpaceStrippedNode)
862 && node != globalContextItem && node.getTreeInfo().getSpaceStrippingRule() != spaceStrippingRule) {
863 SpaceStrippedDocument strippedDoc = new SpaceStrippedDocument(node.getTreeInfo(), spaceStrippingRule);
864 // Edge case: the item might itself be a whitespace text node that is stripped
865 if (!SpaceStrippedNode.isPreservedNode(node, strippedDoc, node.getParent())) {
866 return EmptyIterator.emptyIterator();
867 }
868 node = strippedDoc.wrap(node);
869 }
870
871 if (getAccumulatorManager() != null) {
872 getAccumulatorManager().setApplicableAccumulators(node.getTreeInfo(), finalMode.getAccumulators());
873 }
874 return SingletonIterator.makeIterator(node);
875 } else {
876 return SingletonIterator.makeIterator(item);
877 }
878 };
879 }
880
881 private void warningIfStreamable(Mode mode) {
882 if (mode.isDeclaredStreamable()) {
883 warning((initialMode == null ? "" : getInitialMode().getModeTitle()) +
884 " is streamable, but the input is not supplied as a stream", null, null);
885 }
886 }
887
888 /**
889 * Execute a transformation by evaluating a named template and delivering
890 * the "raw result".
891 *
892 * <p>If any child threads are started (as a result of calls to xsl:result-document)
893 * the method will wait for these to finish before returning to the caller.</p>
894 *
895 * @param initialTemplateName the entry point, the name of a named template
896 * @param out The destination for the result sequence. The events that are written to this
897 * {@code Receiver} will form a <em>regular event sequence</em>
898 * as defined in {@link RegularSequenceChecker}. This event sequence represents
899 * the <em>raw results</em> of the transformation; subsequent processing
900 * such as sequence normalization (to construct a document node) is the
901 * responsibility of the Receiver itself.
902 * @throws XPathException if any dynamic error occurs (in this thread or in a child thread).
903 * This includes the case where the named template does not exist.
904 */
905
906 public void callTemplate(StructuredQName initialTemplateName, Receiver out)
907 throws XPathException {
908 checkReadiness();
909 openMessageEmitter();
910
911 try {
912 out = prepareOutputReceiver(out);
913
914 XPathContextMajor initialContext = newXPathContext();
915 initialContext.createThreadManager();
916 initialContext.setOrigin(this);
917 initialContext.setReceiver(out);
918
919 if (globalContextItem != null) {
920 initialContext.setCurrentIterator(new ManualIterator<>(globalContextItem));
921 }
922
923 // Process the source document by invoking the initial named template
924
925 ParameterSet ordinaryParams = null;
926 if (initialTemplateParams != null) {
927 ordinaryParams = new ParameterSet(initialTemplateParams);
928 }
929 ParameterSet tunnelParams = null;
930 if (initialTemplateTunnelParams != null) {
931 tunnelParams = new ParameterSet(initialTemplateTunnelParams);
932 }
933
934 StylesheetPackage pack = (StylesheetPackage) executable.getTopLevelPackage();
935 Component initialComponent = pack.getComponent(new SymbolicName(StandardNames.XSL_TEMPLATE, initialTemplateName));
936 if (initialComponent == null) {
937 throw new XPathException("Template " + initialTemplateName.getDisplayName() + " does not exist", "XTDE0040");
938 }
939 if (!pack.isImplicitPackage() && !(initialComponent.getVisibility() == Visibility.PUBLIC || initialComponent.getVisibility() == Visibility.FINAL)) {
940 throw new XPathException("Template " + initialTemplateName.getDisplayName() + " is " + initialComponent.getVisibility().show(), "XTDE0040");
941 }
942 NamedTemplate t = (NamedTemplate) initialComponent.getActor();
943
944 XPathContextMajor c2 = initialContext.newContext();
945 initialContext.setOrigin(this);
946 c2.setCurrentComponent(initialComponent);
947 c2.openStackFrame(t.getStackFrameMap());
948 c2.setLocalParameters(ordinaryParams);
949 c2.setTunnelParameters(tunnelParams);
950
951
952 TailCall tc = t.expand(c2);
953 while (tc != null) {
954 tc = tc.processLeavingTail();
955 }
956
957 initialContext.waitForChildThreads();
958 out.close();
959
960 } finally {
961 if (traceListener != null) {
962 traceListener.close();
963 }
964 closeMessageEmitter();
965 inUse = false;
966 }
967 }
968
969 /**
970 * Perform a transformation by applying templates in a streamable mode to a streamable
971 * input document.
972 *
973 * @param source The input for the source tree. Must be (or resolve to) a StreamSource
974 * or SAXSource.
975 * @param out The destination for the result sequence. The events that are written to this
976 * {@code Receiver} will form a <em>regular event sequence</em>
977 * as defined in {@link RegularSequenceChecker}. This event sequence represents
978 * the <em>raw results</em> of the transformation; subsequent processing
979 * such as sequence normalization (to construct a document node) is the
980 * responsibility of the Receiver itself.
981 * @throws XPathException if the transformation fails. As a
982 * special case, the method throws a TerminationException (a subclass
983 * of XPathException) if the transformation was terminated using
984 * xsl:message terminate="yes".
985 */
986
987 public void applyStreamingTemplates(Source source, Receiver out) throws XPathException {
988 checkReadiness();
989 openMessageEmitter();
990
991 out = prepareOutputReceiver(out);
992
993 boolean close = false;
994 try {
995 int validationMode = getSchemaValidationMode();
996
997 Source underSource = source;
998 if (source instanceof AugmentedSource) {
999 close = ((AugmentedSource) source).isPleaseCloseAfterUse();
1000 int localValidate = ((AugmentedSource) source).getSchemaValidation();
1001 if (localValidate != Validation.DEFAULT) {
1002 validationMode = localValidate;
1003 }
1004 underSource = ((AugmentedSource) source).getContainedSource();
1005 }
1006 Configuration config = getConfiguration();
1007 Source s2 = config.getSourceResolver().resolveSource(underSource, config);
1008 if (s2 != null) {
1009 underSource = s2;
1010 }
1011 if (!(source instanceof SAXSource || source instanceof StreamSource || source instanceof EventSource)) {
1012 throw new IllegalArgumentException("Streaming requires a SAXSource, StreamSource, or EventSource");
1013 }
1014 if (!initialMode.getActor().isDeclaredStreamable()) {
1015 throw new IllegalArgumentException("Initial mode is not streamable");
1016 }
1017 if (source instanceof SAXSource && config.getBooleanProperty(Feature.IGNORE_SAX_SOURCE_PARSER)) {
1018 // This option is provided to allow the parser set by applications such as Ant to be overridden by
1019 // the parser requested using FeatureKeys.SOURCE_PARSER
1020 ((SAXSource) source).setXMLReader(null);
1021 }
1022
1023 XPathContextMajor initialContext = newXPathContext();
1024 initialContext.createThreadManager();
1025 initialContext.setOrigin(this);
1026 initialContext.setReceiver(out);
1027
1028 // Process the source document by applying template rules to the initial context node
1029
1030 ParameterSet ordinaryParams = null;
1031 if (initialTemplateParams != null) {
1032 ordinaryParams = new ParameterSet(initialTemplateParams);
1033 }
1034 ParameterSet tunnelParams = null;
1035 if (initialTemplateTunnelParams != null) {
1036 tunnelParams = new ParameterSet(initialTemplateTunnelParams);
1037 }
1038
1039 Receiver despatcher = config.makeStreamingTransformer(initialContext, initialMode.getActor(), ordinaryParams, tunnelParams);
1040 if (config.isStripsAllWhiteSpace() || isStylesheetContainingStripSpace()) {
1041 despatcher = makeStripper(despatcher);
1042 }
1043 PipelineConfiguration pipe = despatcher.getPipelineConfiguration();
1044 pipe.getParseOptions().setSchemaValidationMode(this.validationMode);
1045 boolean verbose = getConfiguration().isTiming();
1046 if (verbose) {
1047 getConfiguration().getLogger().info("Streaming " + source.getSystemId());
1048 }
1049 try {
1050 Sender.send(source, despatcher, null);
1051 } catch (QuitParsingException e) {
1052 if (verbose) {
1053 getConfiguration().getLogger().info("Streaming " + source.getSystemId() + " : early exit");
1054 }
1055 }
1056
1057 initialContext.waitForChildThreads();
1058 out.close();
1059
1060
1061 } catch (TerminationException err) {
1062 //System.err.println("Processing terminated using xsl:message");
1063 if (!err.hasBeenReported()) {
1064 reportFatalError(err);
1065 }
1066 throw err;
1067 } catch (XPathException err) {
1068 Throwable cause = err.getException();
1069 if (cause instanceof SAXParseException) {
1070 // This generally means the error was already reported.
1071 // But if a RuntimeException occurs in Saxon during a callback from
1072 // the Crimson parser, Crimson wraps this in a SAXParseException without
1073 // reporting it further.
1074 SAXParseException spe = (SAXParseException) cause;
1075 cause = spe.getException();
1076 if (cause instanceof RuntimeException) {
1077 reportFatalError(err);
1078 }
1079 } else {
1080 reportFatalError(err);
1081 }
1082 throw err;
1083 } finally {
1084 inUse = false;
1085 if (close && source instanceof AugmentedSource) {
1086 ((AugmentedSource) source).close();
1087 }
1088 if (traceListener != null) {
1089 traceListener.close();
1090 }
1091 }
1092 }
1093
1094 /**
1095 * Get a receiver to which the input to this transformation can be supplied
1096 * as a stream of events, causing the transformation to be executed in streaming mode. <br>
1097 *
1098 * @param mode the initial mode, which must be a streaming mode
1099 * @param result The output destination
1100 * @return a receiver to which events can be streamed
1101 * @throws XPathException if any dynamic error occurs
1102 */
1103
1104 /*@Nullable*/
1105 public Receiver getStreamingReceiver(Mode mode, Receiver result)
1106 throws XPathException {
1107 // System.err.println("*** TransformDocument");
1108
1109 checkReadiness();
1110 openMessageEmitter();
1111
1112 // Determine whether we need to close the output stream at the end. We
1113 // do this if the Result object is a StreamResult and is supplied as a
1114 // system ID, not as a Writer or OutputStream
1115
1116 result = prepareOutputReceiver(result);
1117
1118 final XPathContextMajor initialContext = newXPathContext();
1119 initialContext.setOrigin(this);
1120 initialContext.setReceiver(result);
1121
1122 globalContextItem = null;
1123
1124 // Process the source document by applying template rules to the initial context node
1125
1126 if (!mode.isDeclaredStreamable()) {
1127 throw new XPathException("mode supplied to getStreamingReceiver() must be streamable");
1128 }
1129 Configuration config = getConfiguration();
1130 Receiver despatcher = config.makeStreamingTransformer(initialContext, mode, null, null);
1131 if (despatcher == null) {
1132 throw new XPathException("Streaming requires Saxon-EE");
1133 }
1134 if (config.isStripsAllWhiteSpace() || isStylesheetContainingStripSpace()) {
1135 despatcher = makeStripper(despatcher);
1136 }
1137 despatcher.setPipelineConfiguration(makePipelineConfiguration());
1138
1139 final Receiver finalResult = result;
1140 return new ProxyReceiver(despatcher) {
1141 public void close() throws XPathException {
1142 if (traceListener != null) {
1143 traceListener.close();
1144 }
1145 closeMessageEmitter();
1146 finalResult.close();
1147 inUse = false;
1148 }
1149 };
1150
1151 }
1152
1153 private void openMessageEmitter() throws XPathException {
1154 if (explicitMessageReceiver != null) {
1155 explicitMessageReceiver.open();
1156 if (explicitMessageReceiver instanceof Emitter && ((Emitter) explicitMessageReceiver).getWriter() == null) {
1157 ((Emitter) explicitMessageReceiver).setStreamResult(getConfiguration().getLogger().asStreamResult());
1158 }
1159 }
1160 // if (getMessageEmitter() == null) {
1161 // Receiver me = makeMessageReceiver();
1162 // setMessageEmitter(me);
1163 // if (me instanceof Emitter && ((Emitter) me).getWriter() == null) {
1164 // ((Emitter) me).setStreamResult(getConfiguration().getLogger().asStreamResult());
1165 // }
1166 // }
1167 // getMessageEmitter().open();
1168 }
1169
1170 private void closeMessageEmitter() throws XPathException {
1171 if (explicitMessageReceiver != null) {
1172 explicitMessageReceiver.close();
1173 }
1174 }
1175
1176 /**
1177 * Get the stack of attribute sets being evaluated (for detection of cycles)
1178 *
1179 * @return the attribute set evaluation stack
1180 */
1181
1182 public synchronized Stack<AttributeSet> getAttributeSetEvaluationStack() {
1183 long thread = Thread.currentThread().getId();
1184 return attributeSetEvaluationStacks.computeIfAbsent(thread, k -> new Stack<>());
1185 }
1186
1187 public synchronized void releaseAttributeSetEvaluationStack() {
1188 long thread = Thread.currentThread().getId();
1189 attributeSetEvaluationStacks.remove(thread);
1190 }
1191 }
1192