Debian Codegraph @

net/sf/saxon/expr/instruct/ResultDocument.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.expr.instruct;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.*;
13 import net.sf.saxon.expr.*;
14 import net.sf.saxon.expr.parser.*;
15 import net.sf.saxon.functions.IriToUri;
16 import net.sf.saxon.functions.ResolveURI;
17 import net.sf.saxon.lib.*;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.serialize.CharacterMapIndex;
20 import net.sf.saxon.serialize.PrincipalOutputGatekeeper;
21 import net.sf.saxon.serialize.SerializationProperties;
22 import net.sf.saxon.style.StylesheetPackage;
23 import net.sf.saxon.style.XSLResultDocument;
24 import net.sf.saxon.trace.ExpressionPresenter;
25 import net.sf.saxon.trans.Err;
26 import net.sf.saxon.trans.XPathException;
27 import net.sf.saxon.trans.XsltController;
28 import net.sf.saxon.tree.iter.AxisIterator;
29 import net.sf.saxon.type.ErrorType;
30 import net.sf.saxon.type.ItemType;
31 import net.sf.saxon.type.SchemaType;
32 import net.sf.saxon.value.Whitespace;
33
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Result;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.dom.DOMResult;
38 import javax.xml.transform.sax.SAXResult;
39 import javax.xml.transform.stream.StreamResult;
40 import java.io.IOException;
41 import java.io.StringWriter;
42 import java.util.ArrayList;
43 import java.util.HashMap;
44 import java.util.Map;
45 import java.util.Properties;
46
47
48 /**
49 * The compiled form of an xsl:result-document element in the stylesheet.
50 * <p>The xsl:result-document element takes an attribute href="filename". The filename will
51 * often contain parameters, e.g. {position()} to ensure that a different file is produced
52 * for each element instance.</p>
53 * <p>There is a further attribute "format" which determines the format of the
54 * output file, it identifies the name of an xsl:output element containing the output
55 * format details. In addition, individual serialization properties may be specified as attributes.
56 * These are attribute value templates, so they may need to be computed at run-time.</p>
57 */
58
59 public class ResultDocument extends Instruction
60 implements ValidatingInstruction, InstructionWithComplexContent, ContextOriginator {
61
62 private Operand hrefOp;
63 private Operand formatOp; // null if format was known at compile time
64 private Operand contentOp;
65 private boolean async = false;
66 protected final Properties globalProperties;
67 protected final Properties localProperties;
68 protected ParseOptions validationOptions;
69 protected final Map<StructuredQName, Operand> serializationAttributes;
70 protected boolean resolveAgainstStaticBase = false; // used with fn:put()
71 protected final CharacterMapIndex characterMapIndex;
72
73
74 /**
75 * Create a result-document instruction
76 *
77 * @param globalProperties properties defined on static xsl:output
78 * @param localProperties non-AVT properties defined on result-document element
79 * @param href href attribute of instruction
80 * @param formatExpression format attribute of instruction
81 * @param validationAction for example {@link net.sf.saxon.lib.Validation#STRICT}
82 * @param schemaType schema type against which output is to be validated
83 * @param serializationAttributes computed local properties
84 */
85
86 public ResultDocument(Properties globalProperties, // properties defined on static xsl:output
87 Properties localProperties, // non-AVT properties defined on result-document element
88 Expression href,
89 Expression formatExpression, // AVT defining the output format
90 int validationAction,
91 SchemaType schemaType,
92 Map<StructuredQName, Expression> serializationAttributes, // computed local properties only
93 CharacterMapIndex characterMapIndex) {
94 this.globalProperties = globalProperties;
95 this.localProperties = localProperties;
96 if (href != null) {
97 hrefOp = new Operand(this, href, OperandRole.SINGLE_ATOMIC);
98 }
99 if (formatExpression != null) {
100 formatOp = new Operand(this, formatExpression, OperandRole.SINGLE_ATOMIC);
101 }
102 setValidationAction(validationAction, schemaType);
103 this.serializationAttributes = new HashMap<>(serializationAttributes.size());
104 for (Map.Entry<StructuredQName, Expression> entry : serializationAttributes.entrySet()) {
105 this.serializationAttributes.put(entry.getKey(), new Operand(this, entry.getValue(), OperandRole.SINGLE_ATOMIC));
106 }
107 this.characterMapIndex = characterMapIndex;
108 //this.nsResolver = nsResolver;
109 for (Expression e : serializationAttributes.values()) {
110 adoptChildExpression(e);
111 }
112 }
113
114 /**
115 * Set the expression that constructs the content
116 *
117 * @param content the expression defining the content of the result document
118 */
119
120 public void setContentExpression(Expression content) {
121 contentOp = new Operand(this, content, OperandRole.SINGLE_ATOMIC);
122 }
123
124 /**
125 * Set the schema type to be used for validation
126 *
127 * @param type the type to be used for validation. (For a document constructor, this is the required
128 * type of the document element)
129 */
130
131 public void setSchemaType(SchemaType type) {
132 if (validationOptions == null) {
133 validationOptions = new ParseOptions();
134 }
135 validationOptions.setSchemaValidationMode(Validation.BY_TYPE);
136 validationOptions.setTopLevelType(type);
137 }
138
139 /**
140 * Get the schema type chosen for validation; null if not defined
141 *
142 * @return the type to be used for validation. (For a document constructor, this is the required
143 * type of the document element)
144 */
145
146 public SchemaType getSchemaType() {
147 return validationOptions == null ? null : validationOptions.getTopLevelType();
148 }
149
150
151 public boolean isResolveAgainstStaticBase() {
152 return resolveAgainstStaticBase;
153 }
154
155 /**
156 * Get the validation options
157 *
158 * @return the validation options for the content of the constructed node. May be null if no
159 * validation was requested.
160 */
161
162 public ParseOptions getValidationOptions() {
163 return validationOptions;
164 }
165
166 /**
167 * Set the validation mode for the new document
168 *
169 * @param mode the validation mode, for example {@link Validation#STRICT}
170 * @param schemaType the required type (for validation by type). Null if not
171 * validating by type
172 */
173
174
175 public void setValidationAction(int mode, /*@Nullable*/ SchemaType schemaType) {
176 boolean preservingTypes = mode == Validation.PRESERVE && schemaType == null;
177 if (!preservingTypes) {
178 if (validationOptions == null) {
179 validationOptions = new ParseOptions();
180 validationOptions.setSchemaValidationMode(mode);
181 validationOptions.setTopLevelType(schemaType);
182 }
183 }
184 }
185
186
187 /**
188 * Get the validation mode for this instruction
189 *
190 * @return the validation mode, for example {@link Validation#STRICT} or {@link Validation#PRESERVE}
191 */
192 public int getValidationAction() {
193 return validationOptions == null ? Validation.PRESERVE : validationOptions.getSchemaValidationMode();
194 }
195
196
197 public Expression getFormatExpression() {
198 return formatOp == null ? null : formatOp.getChildExpression();
199 }
200
201 /**
202 * Set whether the the instruction should resolve the href relative URI against the static
203 * base URI (rather than the dynamic base output URI)
204 *
205 * @param staticBase set to true by fn:put(), to resolve against the static base URI of the query.
206 * Default is false, which causes resolution against the base output URI obtained dynamically
207 * from the Controller
208 */
209
210 public void setUseStaticBaseUri(boolean staticBase) {
211 resolveAgainstStaticBase = staticBase;
212 }
213
214
215 public void setAsynchronous(boolean async) {
216 this.async = async;
217 }
218
219 /**
220 * Ask if the instruction is to be asynchronous
221 *
222 * @return true unless saxon:asynchronous="no" was specified (regardless of other options that might
223 * suppress asychronous operation)
224 */
225
226 public boolean isAsynchronous() {
227 return async;
228 }
229
230 @Override
231 public boolean isMultiThreaded(Configuration config) {
232 return isAsynchronous() && config.isLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION)
233 && config.getBooleanProperty(Feature.ALLOW_MULTITHREADING);
234 }
235
236 /*@NotNull*/
237 public Expression typeCheck(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
238 typeCheckChildren(visitor, contextInfo);
239 String method = getStaticSerializationProperty(XSLResultDocument.METHOD);
240 boolean contentDependentMethod = method == null && formatOp == null &&
241 !serializationAttributes.containsKey(XSLResultDocument.METHOD);
242 boolean buildTree = "yes".equals(getStaticSerializationProperty(XSLResultDocument.BUILD_TREE));
243 if (buildTree || contentDependentMethod ||
244 "xml".equals(method) || "html".equals(method) || "xhtml".equals(method) || "text".equals(method)) {
245 try {
246 DocumentInstr.checkContentSequence(visitor.getStaticContext(), contentOp, validationOptions);
247 } catch (XPathException err) {
248 err.maybeSetLocation(getLocation());
249 throw err;
250 }
251 }
252 return this;
253 }
254
255 public int getIntrinsicDependencies() {
256 return StaticProperty.HAS_SIDE_EFFECTS;
257 }
258
259 @Override
260 public Expression optimize(ExpressionVisitor visitor, ContextItemStaticInfo contextInfo) throws XPathException {
261 optimizeChildren(visitor, contextInfo);
262 if (isAsynchronous()) {
263 Expression e = getParentExpression();
264 while (e != null) {
265 if (e instanceof LetExpression && ExpressionTool.dependsOnVariable(
266 getContentExpression(), new Binding[]{(LetExpression) e})) {
267 ((LetExpression) e).setNeedsEagerEvaluation(true);
268 }
269 e = e.getParentExpression();
270 }
271
272 }
273 return this;
274 }
275
276 /**
277 * Copy an expression. This makes a deep copy.
278 *
279 * @param rebindings variable bindings that need to be changed
280 * @return the copy of the original expression
281 */
282
283 /*@NotNull*/
284 public Expression copy(RebindingMap rebindings) {
285 Map<StructuredQName, Expression> map = new HashMap<>();
286 for (Map.Entry<StructuredQName, Operand> entry : serializationAttributes.entrySet()) {
287 map.put(entry.getKey(), entry.getValue().getChildExpression().copy(rebindings));
288 }
289 ResultDocument r = new ResultDocument(
290 globalProperties,
291 localProperties,
292 getHref() == null ? null : getHref().copy(rebindings),
293 getFormatExpression() == null ? null : getFormatExpression().copy(rebindings),
294 getValidationAction(),
295 getSchemaType(),
296 map,
297 characterMapIndex);
298 ExpressionTool.copyLocationInfo(this, r);
299 r.setContentExpression(getContentExpression().copy(rebindings));
300 r.resolveAgainstStaticBase = resolveAgainstStaticBase;
301 r.async = async;
302 return r;
303 }
304
305 /**
306 * Get the name of this instruction for diagnostic and tracing purposes
307 * (the string "xsl:result-document")
308 */
309
310 public int getInstructionNameCode() {
311 return StandardNames.XSL_RESULT_DOCUMENT;
312 }
313
314 /**
315 * Get the item type of the items returned by evaluating this instruction
316 *
317 * @return the static item type of the instruction. This is empty: the result-document instruction
318 * returns nothing.
319 */
320
321 /*@NotNull*/
322 public ItemType getItemType() {
323 return ErrorType.getInstance();
324 }
325
326 @Override
327 public Iterable<Operand> operands() {
328 ArrayList<Operand> list = new ArrayList<>(6);
329 list.add(contentOp);
330 if (hrefOp != null) {
331 list.add(hrefOp);
332 }
333 if (formatOp != null) {
334 list.add(formatOp);
335 }
336 list.addAll(serializationAttributes.values());
337 return list;
338 }
339
340 /**
341 * Add a representation of this expression to a PathMap. The PathMap captures a map of the nodes visited
342 * by an expression in a source tree.
343 * <p>The default implementation of this method assumes that an expression does no navigation other than
344 * the navigation done by evaluating its subexpressions, and that the subexpressions are evaluated in the
345 * same context as the containing expression. The method must be overridden for any expression
346 * where these assumptions do not hold. For example, implementations exist for AxisExpression, ParentExpression,
347 * and RootExpression (because they perform navigation), and for the doc(), document(), and collection()
348 * functions because they create a new navigation root. Implementations also exist for PathExpression and
349 * FilterExpression because they have subexpressions that are evaluated in a different context from the
350 * calling expression.</p>
351 *
352 * @param pathMap the PathMap to which the expression should be added
353 * @param pathMapNodeSet the PathMapNodeSet to which the paths embodied in this expression should be added
354 * @return the pathMapNodeSet representing the points in the source document that are both reachable by this
355 * expression, and that represent possible results of this expression. For an expression that does
356 * navigation, it represents the end of the arc in the path map that describes the navigation route. For other
357 * expressions, it is the same as the input pathMapNode.
358 */
359
360 public PathMap.PathMapNodeSet addToPathMap(PathMap pathMap, PathMap.PathMapNodeSet pathMapNodeSet) {
361 PathMap.PathMapNodeSet result = super.addToPathMap(pathMap, pathMapNodeSet);
362 result.setReturnable(false);
363 return new PathMap.PathMapNodeSet(pathMap.makeNewRoot(this));
364 }
365
366
367 public TailCall processLeavingTail(XPathContext context) throws XPathException {
368 process(getContentExpression(), context);
369 return null;
370 }
371
372 public void process(Expression content, XPathContext context) throws XPathException {
373 checkNotTemporaryOutputState(context);
374 context.getConfiguration().processResultDocument(this, content, context);
375 }
376
377 /**
378 * Evaluation method designed for calling from compiled bytecode.
379 *
380 * @param content The content expression. When called from bytecode, this will be the compiled version
381 * of the interpreted content expression
382 * @param context dynamic evaluation context
383 * @throws XPathException if a dynamic error occurs
384 */
385
386 public void processInstruction(Expression content, XPathContext context) throws XPathException {
387 final XsltController controller = (XsltController) context.getController();
388 assert controller != null;
389 final Configuration config = controller.getConfiguration();
390 Receiver saved = context.getReceiver();
391 PipelineConfiguration pipe = saved.getPipelineConfiguration();
392 String savedOutputUri = context.getCurrentOutputUri();
393 Receiver out = processLeft(context);
394 boolean failed = false;
395 try {
396 content.process(context);
397 } catch (XPathException err) {
398 failed = true;
399 err.maybeSetContext(context);
400 err.maybeSetLocation(getLocation());
401 throw err;
402 } finally {
403 try {
404 out.close();
405 } catch (XPathException e) {
406 if (!failed) {
407 //noinspection ThrowFromFinallyBlock
408 throw e;
409 }
410 // Otherwise no further action; report the original error in preference. Bug 4227
411 }
412 }
413 context.setReceiver(saved);
414 context.setCurrentOutputUri(savedOutputUri);
415
416 }
417
418 public Receiver processLeft(XPathContext context) throws XPathException {
419 XsltController controller = (XsltController)context.getController();
420 Configuration config = controller.getConfiguration();
421 checkNotTemporaryOutputState(context);
422
423 Properties computedLocalProps = gatherOutputProperties(context);
424 if (getStaticBaseURIString() != null) {
425 computedLocalProps.setProperty(SaxonOutputKeys.PARAMETER_DOCUMENT_BASE_URI, getStaticBaseURIString());
426 }
427 SerializationProperties serParams = new SerializationProperties(computedLocalProps, characterMapIndex);
428
429 // If validation was requested, create a function that instantiates a validator
430 // which can then be injected at an appropriate point into the output pipeline
431
432 if (validationOptions != null && validationOptions.getSchemaValidationMode() != Validation.PRESERVE) {
433 serParams.setValidationFactory(
434 output -> {
435 // Validation can add redundant namespace declarations so we
436 // need to follow it with a namespace reducer
437 NamespaceReducer nr = new NamespaceReducer(output);
438 return config.getDocumentValidator(
439 nr, output.getSystemId(), validationOptions, getLocation());
440 }
441 );
442 }
443
444 Receiver out = null;
445 ResultDocumentResolver resolver = null;
446 String hrefValue = "";
447 if (getHref() != null) {
448 hrefValue = IriToUri.iriToUri(getHref().evaluateAsString(context)).toString();
449 }
450 if (hrefValue.isEmpty() || hrefValue.equals(controller.getBaseOutputURI())) {
451 PrincipalOutputGatekeeper gateKeeper = controller.getGatekeeper();
452 if (gateKeeper != null) {
453 gateKeeper.useAsSecondary();
454 out = gateKeeper.makeReceiver(serParams);
455 }
456 }
457
458 if (out == null) {
459 try {
460 resolver = controller.getResultDocumentResolver();
461 out = makeReceiver(hrefValue, getStaticBaseURIString(), context,
462 resolver, serParams, resolveAgainstStaticBase);
463 traceDestination(context, out);
464 } catch (XPathException e) {
465 e.maybeSetLocation(getLocation());
466 e.maybeSetContext(context);
467 throw e;
468 }
469 }
470 out.getPipelineConfiguration().setController(controller);
471 String systemId = out.getSystemId();
472
473 NamespaceReducer nr = new NamespaceReducer(out);
474 out = new ComplexContentOutputter(nr);
475 out.setSystemId(systemId);
476 context.setReceiver(out);
477 context.setCurrentOutputUri(systemId);
478
479 out.open();
480 return out;
481 }
482
483 public CharacterMapIndex getCharacterMapIndex() {
484 return characterMapIndex;
485 }
486
487 private void checkNotTemporaryOutputState(XPathContext context) throws XPathException {
488 if (context.getTemporaryOutputState() != 0) {
489 XPathException err = new XPathException("Cannot execute xsl:result-document while evaluating xsl:" +
490 context.getNamePool().getLocalName(context.getTemporaryOutputState()));
491 err.setErrorCode("XTDE1480");
492 err.setLocation(getLocation());
493 throw err;
494 }
495 }
496
497 public static Receiver makeReceiver(String hrefValue, String baseURI,
498 XPathContext context, ResultDocumentResolver resolver,
499 SerializationProperties params,
500 boolean resolveAgainstStaticBase) throws XPathException {
501 String resultURI = null;
502 Controller controller = context.getController();
503 try {
504 String base;
505 if (resolveAgainstStaticBase) {
506 base = baseURI;
507 } else {
508 base = controller.getBaseOutputURI();
509 }
510
511 try {
512 Receiver out = resolver.resolve(context, hrefValue, base, params);
513 String systemId = out.getSystemId();
514 if (systemId == null) {
515 systemId = ResolveURI.makeAbsolute(hrefValue, base).toASCIIString();
516 out.setSystemId(systemId);
517 }
518 checkAcceptableUri(context, systemId);
519 return out;
520 } catch (XPathException e) {
521 throw e;
522 } catch (Exception err) {
523 err.printStackTrace();
524 throw new XPathException("Exception thrown by output resolver", err);
525 }
526 } catch (TransformerException e) {
527 throw XPathException.makeXPathException(e);
528 }
529
530 }
531
532 public static void traceDestination(XPathContext context, Result result) {
533 Configuration config = context.getConfiguration();
534 boolean timing = config.isTiming();
535 if (timing) {
536 String dest = result.getSystemId();
537 if (dest == null) {
538 if (result instanceof StreamResult) {
539 dest = "anonymous output stream";
540 } else if (result instanceof SAXResult) {
541 dest = "SAX2 ContentHandler";
542 } else if (result instanceof DOMResult) {
543 dest = "DOM tree";
544 } else {
545 dest = result.getClass().getName();
546 }
547 }
548 config.getStandardErrorOutput().println("Writing to " + dest);
549 }
550 }
551
552 public static void checkAcceptableUri(XPathContext context, String uri) throws XPathException {
553 XsltController controller = (XsltController) context.getController();
554 assert controller != null;
555 if (uri != null) {
556 if (controller.getDocumentPool().find(uri) != null) {
557 XPathException err = new XPathException("Cannot write to a URI that has already been read: " +
558 (uri.equals(Controller.ANONYMOUS_PRINCIPAL_OUTPUT_URI) ? "(implicit output URI)" : uri));
559 err.setXPathContext(context);
560 err.setErrorCode("XTDE1500");
561 throw err;
562 }
563
564 DocumentURI documentKey = new DocumentURI(uri);
565 //noinspection SynchronizationOnLocalVariableOrMethodParameter
566 synchronized(controller) {
567 if (!controller.checkUniqueOutputDestination(documentKey)) {
568 XPathException err = new XPathException("Cannot write more than one result document to the same URI: " +
569 (uri.equals(Controller.ANONYMOUS_PRINCIPAL_OUTPUT_URI) ? "(implicit output URI)" : uri));
570 err.setXPathContext(context);
571 err.setErrorCode("XTDE1490");
572 throw err;
573 } else {
574 controller.addUnavailableOutputDestination(documentKey);
575 }
576 }
577 }
578 }
579
580 /**
581 * Create a properties object that combines the serialization properties specified
582 * on the xsl:result-document itself with those specified in the referenced xsl:output declaration
583 *
584 * @param context The XPath evaluation context
585 * @return the assembled properties
586 * @throws XPathException if invalid properties are found
587 */
588
589 public Properties gatherOutputProperties(XPathContext context) throws XPathException {
590 Controller controller = context.getController();
591 assert controller != null;
592 Configuration config = context.getConfiguration();
593 Properties computedGlobalProps = globalProperties;
594 NamespaceResolver nsResolver = getRetainedStaticContext();
595 assert nsResolver != null;
596
597 if (getFormatExpression() != null) {
598 // format was an AVT and now needs to be computed
599 StructuredQName qName;
600 String format = getFormatExpression().evaluateAsString(context).toString();
601 if (format.startsWith("Q{")) {
602 qName = StructuredQName.fromEQName(format);
603 } else {
604 String[] parts;
605 try {
606 parts = NameChecker.getQNameParts(format);
607 } catch (QNameException e) {
608 XPathException err = new XPathException("The requested output format " + Err.wrap(format) + " is not a valid QName");
609 err.maybeSetLocation(getFormatExpression().getLocation());
610 err.setErrorCode("XTDE1460");
611 err.setXPathContext(context);
612 throw err;
613 }
614 String uri = nsResolver.getURIForPrefix(parts[0], false);
615 if (uri == null) {
616 XPathException err = new XPathException("The namespace prefix in the format name " + format + " is undeclared");
617 err.maybeSetLocation(getFormatExpression().getLocation());
618 err.setErrorCode("XTDE1460");
619 err.setXPathContext(context);
620 throw err;
621 }
622 qName = new StructuredQName(parts[0], uri, parts[1]);
623 }
624 computedGlobalProps = ((StylesheetPackage) getRetainedStaticContext().getPackageData()).getNamedOutputProperties(qName);
625 if (computedGlobalProps == null) {
626 XPathException err = new XPathException("There is no xsl:output format named " + format);
627 err.setErrorCode("XTDE1460");
628 err.setXPathContext(context);
629 throw err;
630 }
631
632 }
633
634 // Now combine the properties specified on xsl:result-document with those specified on xsl:output
635
636 Properties computedLocalProps = new Properties(computedGlobalProps);
637
638 // First handle the properties with fixed values on xsl:result-document
639
640 for (Object keyo : localProperties.keySet()) {
641 String key = (String) keyo;
642 StructuredQName qName = StructuredQName.fromClarkName(key);
643 try {
644 setSerializationProperty(computedLocalProps, qName.getURI(), qName.getLocalPart(),
645 localProperties.getProperty(key), nsResolver, true, config);
646 } catch (XPathException e) {
647 e.setErrorCode("XTDE0030");
648 e.maybeSetLocation(getLocation());
649 throw e;
650 }
651 }
652
653 // Now add the properties that were specified as AVTs
654
655 if (!serializationAttributes.isEmpty()) {
656 for (Map.Entry<StructuredQName, Operand> entry : serializationAttributes.entrySet()) {
657 String value = entry.getValue().getChildExpression().evaluateAsString(context).toString();
658 String lname = entry.getKey().getLocalPart();
659 String uri = entry.getKey().getURI();
660 try {
661 setSerializationProperty(computedLocalProps, uri, lname, value, nsResolver, false, config);
662 } catch (XPathException e) {
663 e.setErrorCode("XTDE0030");
664 e.maybeSetLocation(getLocation());
665 e.maybeSetContext(context);
666 if (NamespaceConstant.SAXON.equals(e.getErrorCodeNamespace()) &&
667 "SXWN".equals(e.getErrorCodeLocalPart().substring(0, 4))) {
668 controller.getErrorListener().warning(e);
669 } else {
670 throw e;
671 }
672 }
673 }
674 }
675
676 return computedLocalProps;
677 }
678
679 /**
680 * Get the value of a serialization property if it is statically known
681 *
682 * @param name the name of the serialization property
683 * @return the value of the serialization property if known statically; or null otherwise
684 */
685
686 public String getStaticSerializationProperty(StructuredQName name) {
687 String clarkName = name.getClarkName();
688 String local = localProperties.getProperty(clarkName);
689 if (local != null) {
690 return local;
691 }
692 if (serializationAttributes.containsKey(name)) {
693 return null; // value is computed dynamically
694 }
695 return globalProperties.getProperty(clarkName);
696 }
697
698 /**
699 * Validate a serialization property and add its value to a Properties collection
700 *
701 * @param details the properties to be updated
702 * @param uri the uri of the property name
703 * @param lname the local part of the property name
704 * @param value the value of the serialization property. In the case of QName-valued values,
705 * this will use lexical QNames if prevalidated is false and a NamespaceResolver is supplied;
706 * otherwise they will use Clark-format names
707 * @param nsResolver resolver for lexical QNames; not needed if prevalidated, or if QNames are supplied in Clark
708 * format
709 * @param prevalidated true if values are already known to be valid and lexical QNames have been
710 * expanded into Clark notation
711 * @param config the Saxon configuration
712 * @throws XPathException if any serialization property has an invalid value
713 */
714
715 public static void setSerializationProperty(Properties details, String uri, String lname,
716 String value, /*@Nullable*/ NamespaceResolver nsResolver,
717 boolean prevalidated, Configuration config)
718 throws XPathException {
719 SerializerFactory sf = config.getSerializerFactory();
720 String clarkName = lname;
721 if (!uri.isEmpty()) {
722 clarkName = "{" + uri + "}" + lname;
723 }
724 if (uri.isEmpty() || NamespaceConstant.SAXON.equals(uri)) {
725 switch (clarkName) {
726 case "method":
727 value = Whitespace.trim(value);
728 if (value.startsWith("Q{}") && value.length() > 3) {
729 value = value.substring(3);
730 }
731 if (value.equals("xml") || value.equals("html") ||
732 value.equals("text") || value.equals("xhtml") ||
733 value.equals("json") || value.equals("adaptive") ||
734 prevalidated || value.startsWith("{")) {
735 details.setProperty(OutputKeys.METHOD, value);
736 } else if (value.startsWith("Q{")) {
737 details.setProperty(OutputKeys.METHOD, value.substring(1));
738 } else {
739 String[] parts;
740 try {
741 parts = NameChecker.getQNameParts(value);
742 String prefix = parts[0];
743 if (prefix.isEmpty()) {
744 XPathException err = new XPathException("method must be xml, html, xhtml, text, json, adaptive, or a prefixed name");
745 err.setErrorCode("SEPM0016");
746 err.setIsStaticError(true);
747 throw err;
748 } else if (nsResolver != null) {
749 String muri = nsResolver.getURIForPrefix(prefix, false);
750 if (muri == null) {
751 XPathException err = new XPathException("Namespace prefix '" + prefix + "' has not been declared");
752 err.setErrorCode("SEPM0016");
753 err.setIsStaticError(true);
754 throw err;
755 }
756 details.setProperty(OutputKeys.METHOD, '{' + muri + '}' + parts[1]);
757 } else {
758 details.setProperty(OutputKeys.METHOD, value);
759 }
760 } catch (QNameException e) {
761 XPathException err = new XPathException("Invalid method name. " + e.getMessage());
762 err.setErrorCode("SEPM0016");
763 err.setIsStaticError(true);
764 throw err;
765 }
766 }
767 break;
768 case "use-character-maps":
769 // The use-character-maps attribute is always turned into a Clark-format name at compile time
770 String existing = details.getProperty(SaxonOutputKeys.USE_CHARACTER_MAPS);
771 if (existing == null) {
772 existing = "";
773 }
774 details.setProperty(SaxonOutputKeys.USE_CHARACTER_MAPS, existing + value);
775 break;
776 case "cdata-section-elements":
777 processListOfNodeNames(details, clarkName, value, nsResolver, true, prevalidated, false);
778 break;
779 case "suppress-indentation":
780 processListOfNodeNames(details, clarkName, value, nsResolver, true, prevalidated, false);
781 break;
782 case SaxonOutputKeys.DOUBLE_SPACE:
783 processListOfNodeNames(details, clarkName, value, nsResolver, true, prevalidated, false);
784 break;
785 case SaxonOutputKeys.ATTRIBUTE_ORDER:
786 processListOfNodeNames(details, clarkName, value, nsResolver, false, prevalidated, true);
787 break;
788 case SaxonOutputKeys.NEXT_IN_CHAIN:
789 // XPathException e = new XPathException("saxon:next-in-chain property is available only on xsl:output");
790 // e.setErrorCodeQName(
791 // new StructuredQName("saxon", NamespaceConstant.SAXON, SaxonErrorCode.SXWN9004));
792 // throw e;
793 break;
794 default:
795 // all other properties in the default or Saxon namespaces
796 if (clarkName.equals("output-version")) {
797 clarkName = "version";
798 }
799 if (!prevalidated) {
800 try {
801 if (!SaxonOutputKeys.isUnstrippedProperty(clarkName)) {
802 // TODO: whitespace rules seem to vary for different interfaces
803 value = Whitespace.trim(value);
804 }
805 value = sf.checkOutputProperty(clarkName, value);
806 } catch (XPathException err) {
807 err.maybeSetErrorCode("SEPM0016");
808 throw err;
809 }
810 }
811 details.setProperty(clarkName, value);
812 break;
813 }
814 } else {
815 // properties in user-defined namespaces
816 details.setProperty('{' + uri + '}' + lname, value);
817 }
818
819 }
820
821 private static void processListOfNodeNames(Properties details, String key, String value,
822 NamespaceResolver nsResolver, boolean useDefaultNS,
823 boolean prevalidated, boolean allowStar) throws XPathException {
824 String existing = details.getProperty(key);
825 if (existing == null) {
826 existing = "";
827 }
828 String s = SaxonOutputKeys.parseListOfNodeNames(value, nsResolver, useDefaultNS, prevalidated, allowStar, "SEPM0016");
829 details.setProperty(key, existing + s);
830 }
831
832 /**
833 * Diagnostic print of expression structure. The abstract expression tree
834 * is written to the supplied output destination.
835 */
836
837 public void export(ExpressionPresenter out) throws XPathException {
838 out.startElement("resultDoc", this);
839 out.emitAttribute("global", exportProperties(globalProperties));
840 out.emitAttribute("local", exportProperties(localProperties));
841 if (getValidationAction() != Validation.SKIP && getValidationAction() != Validation.BY_TYPE) {
842 out.emitAttribute("validation", Validation.toString(getValidationAction()));
843 }
844 final SchemaType schemaType = getSchemaType();
845 if (schemaType != null) {
846 out.emitAttribute("type", schemaType.getStructuredQName());
847 }
848 if (getHref() != null) {
849 out.setChildRole("href");
850 getHref().export(out);
851 }
852 if (getFormatExpression() != null) {
853 out.setChildRole("format");
854 getFormatExpression().export(out);
855 }
856 for (Map.Entry<StructuredQName, Operand> p : serializationAttributes.entrySet()) {
857 StructuredQName name = p.getKey();
858 Expression value = p.getValue().getChildExpression();
859 out.setChildRole(name.getEQName());
860 value.export(out);
861 }
862 out.setChildRole("content");
863 getContentExpression().export(out);
864 out.endElement();
865 }
866
867 private String exportProperties(Properties props) {
868 try {
869 StringWriter writer = new StringWriter();
870 props.store(writer, "");
871 return writer.toString();
872 } catch (IOException e) {
873 throw new AssertionError(e);
874 }
875 }
876
877 /**
878 * Construct a set of output properties from an xsl:output element supplied at run-time
879 *
880 * @param element an xsl:output element
881 * @param props Properties object to which will be added the values of those serialization properties
882 * that were specified
883 * @param c the XPath dynamic context
884 * @throws net.sf.saxon.trans.XPathException if a dynamic error occurs
885 */
886
887 public static void processXslOutputElement(NodeInfo element, Properties props, XPathContext c) throws XPathException {
888 AxisIterator iter = element.iterateAxis(AxisInfo.ATTRIBUTE);
889 NamespaceResolver resolver = new InscopeNamespaceResolver(element);
890 iter.forEachOrFail(att -> {
891 String uri = att.getURI();
892 String local = att.getLocalPart();
893 String val = Whitespace.trim(att.getStringValueCS());
894 setSerializationProperty(props, uri, local, val, resolver, false, c.getConfiguration());
895 });
896 }
897
898 /**
899 * Get the (partial) name of a class that supports streaming of this kind of expression
900 *
901 * @return the partial name of a class that can be instantiated to provide streaming support in Saxon-EE,
902 * or null if there is no such class
903 */
904 @Override
905 public String getStreamerName() {
906 return "ResultDocument";
907 }
908
909
910 public Expression getHref() {
911 return hrefOp == null ? null : hrefOp.getChildExpression();
912 }
913
914 public void setHref(Expression href) {
915 hrefOp.setChildExpression(href);
916 }
917
918 public void setFormatExpression(Expression formatExpression) {
919 formatOp.setChildExpression(formatExpression);
920 }
921
922 public Expression getContentExpression() {
923 return contentOp.getChildExpression();
924 }
925
926 }
927