| 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.s9api; |
| 9 | |
| 10 | import net.sf.saxon.event.*; |
| 11 | import net.sf.saxon.lib.NamespaceConstant; |
| 12 | import net.sf.saxon.lib.OutputURIResolver; |
| 13 | import net.sf.saxon.lib.SaxonOutputKeys; |
| 14 | import net.sf.saxon.lib.SerializerFactory; |
| 15 | import net.sf.saxon.om.StructuredQName; |
| 16 | import net.sf.saxon.query.QueryResult; |
| 17 | import net.sf.saxon.serialize.CharacterMap; |
| 18 | import net.sf.saxon.serialize.CharacterMapIndex; |
| 19 | import net.sf.saxon.serialize.SerializationProperties; |
| 20 | import net.sf.saxon.trans.XPathException; |
| 21 | |
| 22 | import javax.xml.transform.OutputKeys; |
| 23 | import javax.xml.transform.Result; |
| 24 | import javax.xml.transform.stream.StreamResult; |
| 25 | import java.io.File; |
| 26 | import java.io.OutputStream; |
| 27 | import java.io.StringWriter; |
| 28 | import java.io.Writer; |
| 29 | import java.net.URI; |
| 30 | import java.net.URISyntaxException; |
| 31 | import java.util.HashMap; |
| 32 | import java.util.Map; |
| 33 | import java.util.Objects; |
| 34 | import java.util.Properties; |
| 35 | |
| 36 | /** |
| 37 | * A Serializer takes a tree representation of XML and turns it into lexical XML markup. |
| 38 | * <p><i>Note that this is XML serialization in the sense of the W3C XSLT and XQuery specifications. |
| 39 | * This has nothing to do with the serialization of Java objects, or the {@link java.io.Serializable} |
| 40 | * interface.</i></p> |
| 41 | * <p>The serialization may be influenced by a number of serialization parameters. A parameter has a name, |
| 42 | * which is an instance of {@link net.sf.saxon.s9api.Serializer.Property}, and a value, which is expressed as a string. |
| 43 | * The effect of most of the properties is as described in the W3C specification |
| 44 | * <a href="http://www.w3.org/TR/xslt-xquery-serialization/">XSLT 3.0 and XQuery 3.1 Serialization</a>. |
| 45 | * Saxon supports all the serialization parameters defined in that specification, together with some |
| 46 | * additional parameters, whose property names are prefixed "SAXON_".</p> |
| 47 | * <p>Serialization parameters defined via this interface take precedence over any serialization parameters |
| 48 | * defined within the source of the query or stylesheet. The {@link #getReceiver} method is supplied with |
| 49 | * parameters derived from the query or stylesheet, which are merged with the parameters set on this |
| 50 | * {@code Serializer}.</p> |
| 51 | * <p><i>Changed in 9.9 so the {@code Serializer} now only holds one set of output properties. Additional |
| 52 | * (default) serialization properties (taken from the source of the query or stylesheet) can be supplied |
| 53 | * when {@link #getReceiver(PipelineConfiguration, SerializationProperties)} |
| 54 | * is called, but these are not stored within the {@code Serializer} itself.</i></p> |
| 55 | */ |
| 56 | @SuppressWarnings({"ForeachStatement"}) |
| 57 | public class Serializer extends AbstractDestination { |
| 58 | |
| 59 | private Processor processor; // never null |
| 60 | private Map<StructuredQName, String> properties = new HashMap<>(10); |
| 61 | private StreamResult result = new StreamResult(); |
| 62 | private CharacterMapIndex characterMap = null; |
| 63 | private boolean mustClose = false; |
| 64 | |
| 65 | // Index of permitted property names |
| 66 | |
| 67 | private static Map<String, Property> standardProperties = new HashMap<>(); |
| 68 | |
| 69 | // private static void z(Property prop) { |
| 70 | // standardProperties.put(prop.name, prop); |
| 71 | // } |
| 72 | |
| 73 | static { |
| 74 | for (Property p : Property.values()) { |
| 75 | standardProperties.put(p.name, p); |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /** |
| 80 | * Enumeration class defining the permitted serialization properties |
| 81 | */ |
| 82 | |
| 83 | public enum Property { |
| 84 | /** |
| 85 | * Serialization method: xml, html, xhtml, or text |
| 86 | */ |
| 87 | METHOD(OutputKeys.METHOD), |
| 88 | /** |
| 89 | * Version of output method, for example "1.0" or "1.1" for XML |
| 90 | */ |
| 91 | VERSION(OutputKeys.VERSION), |
| 92 | /** |
| 93 | * Character encoding of output stream |
| 94 | */ |
| 95 | ENCODING(OutputKeys.ENCODING), |
| 96 | /** |
| 97 | * Set to "yes" if the XML declaration is to be omitted from the output file |
| 98 | */ |
| 99 | OMIT_XML_DECLARATION(OutputKeys.OMIT_XML_DECLARATION), |
| 100 | /** |
| 101 | * Set to "yes", "no", or "omit" to indicate the required value of the standalone attribute |
| 102 | * in the XML declaration of the output file |
| 103 | */ |
| 104 | STANDALONE(OutputKeys.STANDALONE), |
| 105 | /** |
| 106 | * Set to any string to indicate that the output is to include a DOCTYPE declaration with this public id |
| 107 | */ |
| 108 | DOCTYPE_PUBLIC(OutputKeys.DOCTYPE_PUBLIC), |
| 109 | /** |
| 110 | * Set to any string to indicate that the output is to include a DOCTYPE declaration with this system id |
| 111 | */ |
| 112 | DOCTYPE_SYSTEM(OutputKeys.DOCTYPE_SYSTEM), |
| 113 | /** |
| 114 | * Space-separated list of QNames (in Clark form) of elements |
| 115 | * whose content is to be wrapped in CDATA sections |
| 116 | */ |
| 117 | CDATA_SECTION_ELEMENTS(OutputKeys.CDATA_SECTION_ELEMENTS), |
| 118 | /** |
| 119 | * Set to "yes" or "no" to indicate whether indentation is required |
| 120 | */ |
| 121 | INDENT(OutputKeys.INDENT), |
| 122 | /** |
| 123 | * Set to indicate the media type (MIME type) of the output |
| 124 | */ |
| 125 | MEDIA_TYPE(OutputKeys.MEDIA_TYPE), |
| 126 | /** |
| 127 | * List of names of character maps to be used. Character maps can only be specified in an XSLT |
| 128 | * stylesheet. |
| 129 | */ |
| 130 | USE_CHARACTER_MAPS(SaxonOutputKeys.USE_CHARACTER_MAPS), |
| 131 | /** |
| 132 | * For HTML and XHTML, set to "yes" or "no" to indicate whether a <meta> element is to be |
| 133 | * written to indicate the content type and encoding |
| 134 | */ |
| 135 | INCLUDE_CONTENT_TYPE(SaxonOutputKeys.INCLUDE_CONTENT_TYPE), |
| 136 | /** |
| 137 | * Set to "yes" or "no" to indicate (for XML 1.1) whether namespace that go out of scope should |
| 138 | * be undeclared |
| 139 | */ |
| 140 | UNDECLARE_PREFIXES(SaxonOutputKeys.UNDECLARE_PREFIXES), |
| 141 | /** |
| 142 | * Set to "yes" or "no" to indicate (for HTML and XHTML) whether URI-valued attributes should be |
| 143 | * percent-encoded |
| 144 | */ |
| 145 | ESCAPE_URI_ATTRIBUTES(SaxonOutputKeys.ESCAPE_URI_ATTRIBUTES), |
| 146 | /** |
| 147 | * Set to "yes" or "no" to indicate whether a byte order mark is to be written |
| 148 | */ |
| 149 | BYTE_ORDER_MARK(SaxonOutputKeys.BYTE_ORDER_MARK), |
| 150 | /** |
| 151 | * Set to the name of a Unicode normalization form: "NFC", "NFD", "NFKC", or "NFKD", or |
| 152 | * "none" to indicate no normalization |
| 153 | */ |
| 154 | NORMALIZATION_FORM(SaxonOutputKeys.NORMALIZATION_FORM), |
| 155 | /** |
| 156 | * Set to a string used to separate adjacent items in an XQuery result sequence |
| 157 | */ |
| 158 | ITEM_SEPARATOR(SaxonOutputKeys.ITEM_SEPARATOR), |
| 159 | /** |
| 160 | * HTML version number |
| 161 | */ |
| 162 | HTML_VERSION(SaxonOutputKeys.HTML_VERSION), |
| 163 | /** |
| 164 | * Build-tree option (XSLT only) |
| 165 | */ |
| 166 | BUILD_TREE(SaxonOutputKeys.BUILD_TREE), |
| 167 | /** |
| 168 | * Saxon extension: set to an integer (represented as a string) giving the number of spaces |
| 169 | * by which each level of nesting should be indented. Default is 3. |
| 170 | */ |
| 171 | SAXON_INDENT_SPACES(SaxonOutputKeys.INDENT_SPACES), |
| 172 | /** |
| 173 | * Saxon extension: set to an integer (represented as a string) giving the desired maximum |
| 174 | * length of lines when indenting. Default is 80. |
| 175 | */ |
| 176 | SAXON_LINE_LENGTH(SaxonOutputKeys.LINE_LENGTH), |
| 177 | /** |
| 178 | * Saxon extension: set to a space-separated list of attribute names, in Clark notation, |
| 179 | * indicating that attributes present in the list should be serialized in the order |
| 180 | * indicated, followed by attributes not present in the list (these are sorted first |
| 181 | * by namespace, then by local name). |
| 182 | */ |
| 183 | SAXON_ATTRIBUTE_ORDER(SaxonOutputKeys.ATTRIBUTE_ORDER), |
| 184 | /** |
| 185 | * Saxon extension: request canonical XML output. |
| 186 | */ |
| 187 | SAXON_CANONICAL(SaxonOutputKeys.CANONICAL), |
| 188 | /** |
| 189 | * Saxon extension: set to any string. Indicates the sequence of characters used to represent |
| 190 | * a newline in the text output method, and in newlines used for indentation in any output |
| 191 | * methods that use indentation. |
| 192 | */ |
| 193 | SAXON_NEWLINE(SaxonOutputKeys.NEWLINE), |
| 194 | /** |
| 195 | * Set to a space-separated list of element names, in Clark notation, |
| 196 | * within which no content is to be indented. This is typically because the element contains |
| 197 | * mixed content in which whitespace is significant. |
| 198 | * <p> |
| 199 | * This was originally a Saxon extension to the W3C specifications, but it then became |
| 200 | * a standard serialization attribute. The "SAXON_" prefix on the name of the enumeration |
| 201 | * constant reflects this history; the name is retained to avoid disrupting existing |
| 202 | * applications. |
| 203 | */ |
| 204 | SAXON_SUPPRESS_INDENTATION(SaxonOutputKeys.SUPPRESS_INDENTATION), |
| 205 | /** |
| 206 | * Saxon extension: set to a space-separated list of element names, in Clark notation, |
| 207 | * representing elements that will be preceded by an extra blank line in the output in addition |
| 208 | * to normal indentation. |
| 209 | */ |
| 210 | SAXON_DOUBLE_SPACE(SaxonOutputKeys.DOUBLE_SPACE), |
| 211 | /** |
| 212 | * Saxon extension for internal use: used in XSLT to tell the serializer whether the |
| 213 | * stylesheet used version="1.0" or version="2.0" |
| 214 | */ |
| 215 | SAXON_STYLESHEET_VERSION(SaxonOutputKeys.STYLESHEET_VERSION), |
| 216 | /** |
| 217 | * Saxon extension to indicate how characters outside the encoding should be represented, |
| 218 | * for example "hex" for hexadecimal character references, "decimal" for decimal character references |
| 219 | */ |
| 220 | SAXON_CHARACTER_REPRESENTATION(SaxonOutputKeys.CHARACTER_REPRESENTATION), |
| 221 | /** |
| 222 | * Saxon extension for use when writing to the text output method; this option causes the processing |
| 223 | * instructions hex and b64 to be recognized containing hexBinary or base64 data respectively. |
| 224 | */ |
| 225 | SAXON_RECOGNIZE_BINARY(SaxonOutputKeys.RECOGNIZE_BINARY), |
| 226 | /** |
| 227 | * Saxon extension for use when output is sent to a SAX ContentHandler: indicates that the output |
| 228 | * is required to be well-formed (exactly one top-level element) |
| 229 | */ |
| 230 | SAXON_REQUIRE_WELL_FORMED(SaxonOutputKeys.REQUIRE_WELL_FORMED), |
| 231 | /** |
| 232 | * Saxon extension, indicates that the output of a query is to be wrapped before serialization, |
| 233 | * such that each item in the result sequence is enclosed in an element indicating its type |
| 234 | */ |
| 235 | SAXON_WRAP(SaxonOutputKeys.WRAP), |
| 236 | /** |
| 237 | * Saxon extension for internal use in XSLT, indicates that this output document is the implicitly |
| 238 | * created result tree as distinct from a tree created using <xsl:result-document> |
| 239 | */ |
| 240 | SAXON_IMPLICIT_RESULT_DOCUMENT(SaxonOutputKeys.IMPLICIT_RESULT_DOCUMENT), |
| 241 | /** |
| 242 | * Saxon extension for interfacing with debuggers; indicates that the location information is |
| 243 | * available for events in this output stream |
| 244 | */ |
| 245 | SAXON_SUPPLY_SOURCE_LOCATOR(SaxonOutputKeys.SUPPLY_SOURCE_LOCATOR); |
| 246 | |
| 247 | private String name; |
| 248 | |
| 249 | Property(String name) { |
| 250 | this.name = name; |
| 251 | } |
| 252 | |
| 253 | /** |
| 254 | * Get the name of the property expressed as a QName in Clark notation. |
| 255 | * The namespace will be null for standard serialization properties, |
| 256 | * and will be the Saxon namespace <code>http://saxon.sf.net/</code> for Saxon extensions |
| 257 | * |
| 258 | * @return the name of the serialization property as a QName in Clark notation, {uri}local |
| 259 | */ |
| 260 | |
| 261 | public String toString() { |
| 262 | return name; |
| 263 | } |
| 264 | |
| 265 | /** |
| 266 | * Get the name of the property expressed as a QName. |
| 267 | * The namespace will be null for standard serialization properties, |
| 268 | * and will be the Saxon namespace <code>http://saxon.sf.net/</code> for Saxon extensions |
| 269 | * |
| 270 | * @return the name of the serialization property as a QName |
| 271 | */ |
| 272 | |
| 273 | public QName getQName() { |
| 274 | return QName.fromClarkName(name); |
| 275 | } |
| 276 | |
| 277 | public static Property get(String s) { |
| 278 | for (Property p : Property.values()) { |
| 279 | if (p.name.equals(s)) { |
| 280 | return p; |
| 281 | } |
| 282 | } |
| 283 | return null; |
| 284 | } |
| 285 | |
| 286 | } |
| 287 | |
| 288 | /** |
| 289 | * Create a Serializer belonging to a specific processor |
| 290 | * |
| 291 | * @param processor the processor associated with the Serializer. Must not be null. |
| 292 | */ |
| 293 | |
| 294 | protected Serializer(Processor processor) { |
| 295 | setProcessor(processor); |
| 296 | } |
| 297 | |
| 298 | /** |
| 299 | * Set the Processor associated with this Serializer. This will be called automatically if the |
| 300 | * serializer is created using one of the <code>Processor.newSerializer()</code> methods. |
| 301 | * @param processor the associated Processor (must not be null) |
| 302 | * @since 9.3 |
| 303 | */ |
| 304 | |
| 305 | public void setProcessor(Processor processor) { |
| 306 | this.processor = Objects.requireNonNull(processor); |
| 307 | } |
| 308 | |
| 309 | /** |
| 310 | * Get the Processor associated with this Serializer. |
| 311 | * @return the associated Processor. Never null. |
| 312 | */ |
| 313 | |
| 314 | public Processor getProcessor() { |
| 315 | return processor; |
| 316 | } |
| 317 | |
| 318 | /** |
| 319 | * Set output properties, from a {@link Properties} object. The keys in the supplied |
| 320 | * {@code Properties} object are QNames in Clark format, that is "{uri}local"; any QNames |
| 321 | * within the values must also be in this format. |
| 322 | * The values supplied are typically those specified in the stylesheet or query. In the case of XSLT, |
| 323 | * they are typically the properties associated with unnamed xsl:output declarations. |
| 324 | * |
| 325 | * @param suppliedProperties the output properties to be used. These overwrite any properties |
| 326 | * that have been individually specified using |
| 327 | * {@link #setOutputProperty(Property, String)} setOutputProperty} |
| 328 | */ |
| 329 | |
| 330 | public void setOutputProperties(Properties suppliedProperties) { |
| 331 | for (String name : suppliedProperties.stringPropertyNames()) { |
| 332 | properties.put(StructuredQName.fromClarkName(name), suppliedProperties.getProperty(name)); |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | /** |
| 337 | * Set output properties, from an {@link SerializationProperties} object. The keys in the contained |
| 338 | * {@code Properties} object are QNames in Clark format, that is "{uri}local"; any QNames |
| 339 | * within the values must also be in this format. |
| 340 | * <p>The values supplied are typically those specified in the stylesheet or query. In the case of XSLT, |
| 341 | * they are typically the properties associated with unnamed xsl:output declarations.</p> |
| 342 | * |
| 343 | * @param suppliedProperties the output properties to be used. These overwrite any properties |
| 344 | * that have been individually specified using |
| 345 | * {@link #setOutputProperty(Property, String)} setOutputProperty} |
| 346 | * @since 9.9 |
| 347 | */ |
| 348 | |
| 349 | public void setOutputProperties(SerializationProperties suppliedProperties) { |
| 350 | setOutputProperties(suppliedProperties.getProperties()); |
| 351 | setCharacterMap(suppliedProperties.getCharacterMapIndex()); |
| 352 | } |
| 353 | |
| 354 | |
| 355 | /** |
| 356 | * Say if the output stream should be closed on completion |
| 357 | * By default the close method closes the output stream only when the serializer created the output stream itself |
| 358 | * that is when the destination has been suppplied as a file rather than a stream. |
| 359 | * @param value - if true the output file will be closed when the close method is called |
| 360 | * if false the close method has no effect. |
| 361 | */ |
| 362 | |
| 363 | public void setCloseOnCompletion(boolean value) { |
| 364 | mustClose = value; |
| 365 | } |
| 366 | |
| 367 | /** |
| 368 | * Set a character map to be used; more specifically, supply a set of named character maps |
| 369 | * |
| 370 | * @param characterMap a set of named character maps. A character map in this set will only |
| 371 | * be used if the name of the character map is added to the value |
| 372 | * of the {@link net.sf.saxon.s9api.Serializer.Property#USE_CHARACTER_MAPS} serialization |
| 373 | * property. The character maps in this index are added to the existing |
| 374 | * set of character maps known to the serializer, unless they have the |
| 375 | * same names as existing character maps, in which case the new one |
| 376 | * overwrites the old. |
| 377 | */ |
| 378 | |
| 379 | public void setCharacterMap(CharacterMapIndex characterMap) { |
| 380 | CharacterMapIndex existingIndex = this.characterMap; |
| 381 | if (existingIndex == null || existingIndex.isEmpty()) { |
| 382 | existingIndex = characterMap; |
| 383 | } else if (characterMap != null && !characterMap.isEmpty() && existingIndex != characterMap) { |
| 384 | // Merge the character maps |
| 385 | existingIndex = existingIndex.copy(); |
| 386 | for (CharacterMap map : characterMap) { |
| 387 | existingIndex.putCharacterMap(map.getName(), map); |
| 388 | } |
| 389 | } |
| 390 | this.characterMap = existingIndex; |
| 391 | } |
| 392 | |
| 393 | /** |
| 394 | * Set the value of a serialization property. Any existing value of the property is overridden. |
| 395 | * If the supplied value is null, any existing value of the property is removed. |
| 396 | * <p>Example:</p> |
| 397 | * <p><code>serializer.setOutputProperty(Serializer.Property.METHOD, "xml");</code></p> |
| 398 | * <p>Any serialization properties supplied via this interface take precedence over serialization |
| 399 | * properties defined in the source stylesheet or query, including properties set dynamically |
| 400 | * using xsl:result-document. However, they only affect the principal output of a transformation; |
| 401 | * the serialization of secondary result documents is controlled using an {@link OutputURIResolver}.</p> |
| 402 | * |
| 403 | * @param property The name of the property to be set |
| 404 | * @param value The value of the property, as a string. The format is generally as defined |
| 405 | * in the <code>xsl:output</code> declaration in XSLT: this means that boolean properties, for |
| 406 | * example, are represented using the strings "yes" and "no". Properties whose values are QNames, |
| 407 | * such as <code>cdata-section-elements</code> are expressed using the Clark representation of |
| 408 | * a QName, that is "{uri}local". Multi-valued properties (again, <code>cdata-section-elements</code> |
| 409 | * is an example) are expressed as a space-separated list. |
| 410 | * @throws IllegalArgumentException if the value of the property is invalid. The property is |
| 411 | * validated individually; invalid combinations of properties will be detected only when the properties |
| 412 | * are actually used to serialize an XML event stream. |
| 413 | */ |
| 414 | |
| 415 | public void setOutputProperty(Property property, /*@Nullable*/ String value) { |
| 416 | SerializerFactory sf = processor.getUnderlyingConfiguration().getSerializerFactory(); |
| 417 | try { |
| 418 | value = sf.checkOutputProperty(property.toString(), value); |
| 419 | } catch (XPathException e) { |
| 420 | throw new IllegalArgumentException(e.getMessage()); |
| 421 | } |
| 422 | if (value == null) { |
| 423 | properties.remove(property.getQName().getStructuredQName()); |
| 424 | } else { |
| 425 | properties.put(property.getQName().getStructuredQName(), value); |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | /** |
| 430 | * Get the value of a serialization property |
| 431 | * |
| 432 | * @param property the name of the required property. This method only considers properties |
| 433 | * explicitly set on this Serialized object, it does not return values |
| 434 | * obtained from the stylesheet or query. |
| 435 | * @return the value of the required property as a string, or null if the property has |
| 436 | * not been given any value. |
| 437 | */ |
| 438 | |
| 439 | public String getOutputProperty(Property property) { |
| 440 | return properties.get(property.getQName().getStructuredQName()); |
| 441 | } |
| 442 | |
| 443 | /** |
| 444 | * Set the value of a serialization property. Any existing value of the property is overridden. |
| 445 | * If the supplied value is null, any existing value of the property is removed. |
| 446 | * <p>Example:</p> |
| 447 | * <p><code>serializer.setOutputProperty(new QName("method"), "xml");</code></p> |
| 448 | * <p>Any serialization properties supplied via this interface take precedence over serialization |
| 449 | * properties defined in the source stylesheet or query.</p> |
| 450 | * <p>Unlike the method {@link #setOutputProperty(Property, String)}, this method allows properties |
| 451 | * to be set whose names are not in the standard set of property names defined in the W3C specifications, |
| 452 | * nor in a recognized Saxon extension. This enables properties to be set for use by a custom serialization |
| 453 | * method.</p> |
| 454 | * |
| 455 | * @param property The name of the property to be set |
| 456 | * @param value The value of the property, as a string. The format is generally as defined |
| 457 | * in the <code>xsl:output</code> declaration in XSLT: this means that boolean properties, for |
| 458 | * example, are represented using the strings "yes" and "no". Properties whose values are QNames, |
| 459 | * such as <code>cdata-section-elements</code> are expressed using the Clark representation of |
| 460 | * a QName, that is "{uri}local". Multi-valued properties (again, <code>cdata-section-elements</code> |
| 461 | * is an example) are expressed as a space-separated list. |
| 462 | * @throws IllegalArgumentException if the value of the property is invalid. The property is |
| 463 | * validated individually; invalid combinations of properties will be detected only when the properties |
| 464 | * are actually used to serialize an XML event stream. No validation occurs unless the property |
| 465 | * name is either in no namespace, or in the Saxon namespace |
| 466 | */ |
| 467 | |
| 468 | public void setOutputProperty(QName property, String value) { |
| 469 | SerializerFactory sf = processor.getUnderlyingConfiguration().getSerializerFactory(); |
| 470 | String uri = property.getNamespaceURI(); |
| 471 | if (uri.isEmpty() || uri.equals(NamespaceConstant.SAXON)) { |
| 472 | try { |
| 473 | value = sf.checkOutputProperty(property.getClarkName(), value); |
| 474 | } catch (XPathException e) { |
| 475 | throw new IllegalArgumentException(e.getMessage()); |
| 476 | } |
| 477 | if (uri.equals(NamespaceConstant.SAXON) && property.getLocalName().equals("next-in-chain")) { |
| 478 | // reject the next-in-chain property: it's not relevant to a Serializer |
| 479 | throw new IllegalArgumentException("saxon:next-in-chain is not a serialization property"); |
| 480 | } |
| 481 | } |
| 482 | if (value == null) { |
| 483 | properties.remove(property.getStructuredQName()); |
| 484 | } else { |
| 485 | properties.put(property.getStructuredQName(), value); |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | /** |
| 490 | * Get the value of a serialization property. |
| 491 | * |
| 492 | * <p>Unlike the method {@link #getOutputProperty(Property)}, this method allows properties |
| 493 | * to be read whose names are not in the standard set of property names defined in the W3C specifications, |
| 494 | * nor in a recognized Saxon extension. This enables properties to be set for use by a custom serialization |
| 495 | * method.</p> |
| 496 | * |
| 497 | * @param property the name of the required property |
| 498 | * @return the value of the required property as a string, or null if the property has |
| 499 | * not been given any value. |
| 500 | */ |
| 501 | |
| 502 | public String getOutputProperty(QName property) { |
| 503 | return properties.get(property.getStructuredQName()); |
| 504 | } |
| 505 | |
| 506 | /** |
| 507 | * Set the destination of the serialized output, as a Writer. |
| 508 | * <p>Note that when this option is used, the serializer does not perform character |
| 509 | * encoding. This also means that it never replaces special characters with XML numeric |
| 510 | * character references. The final encoding is the responsibility of the supplied Writer.</p> |
| 511 | * <p>Closing the writer after use is the responsibility of the caller.</p> |
| 512 | * <p>Calling this method has the side-effect of setting the OutputStream and OutputFile to null.</p> |
| 513 | * |
| 514 | * @param writer the Writer to which the serialized XML output will be written. |
| 515 | */ |
| 516 | |
| 517 | public void setOutputWriter(Writer writer) { |
| 518 | result.setOutputStream(null); |
| 519 | result.setSystemId((String) null); |
| 520 | result.setWriter(writer); |
| 521 | mustClose = false; |
| 522 | } |
| 523 | |
| 524 | /** |
| 525 | * Set the destination of the serialized output, as an OutputStream. |
| 526 | * <p>Closing the output stream after use is the responsibility of the caller.</p> |
| 527 | * <p>Calling this method has the side-effect of setting the OutputWriter and OutputFile to null.</p> |
| 528 | * |
| 529 | * @param stream the OutputStream to which the serialized XML output will be written. |
| 530 | */ |
| 531 | |
| 532 | public void setOutputStream(OutputStream stream) { |
| 533 | result.setWriter(null); |
| 534 | result.setSystemId((String) null); |
| 535 | result.setOutputStream(stream); |
| 536 | mustClose = false; |
| 537 | } |
| 538 | |
| 539 | /** |
| 540 | * Set the destination of the serialized output, as a File. |
| 541 | * <p>Calling this method has the side-effect of setting the current OutputWriter |
| 542 | * and OutputStream to null.</p> |
| 543 | * <p>This method sets the destination base URI to the URI corresponding to the name of the |
| 544 | * supplied file.</p> |
| 545 | * |
| 546 | * @param file the File to which the serialized XML output will be written. |
| 547 | */ |
| 548 | |
| 549 | public void setOutputFile(File file) { |
| 550 | result.setOutputStream(null); |
| 551 | result.setWriter(null); |
| 552 | result.setSystemId(file); |
| 553 | setDestinationBaseURI(file.toURI()); |
| 554 | mustClose = true; |
| 555 | } |
| 556 | |
| 557 | /** |
| 558 | * Serialize an XdmNode to the selected output destination using this serializer |
| 559 | * |
| 560 | * @param node The node to be serialized |
| 561 | * @throws IllegalStateException if no outputStream, Writer, or File has been supplied as the |
| 562 | * destination for the serialized output |
| 563 | * @throws SaxonApiException if a serialization error or I/O error occurs |
| 564 | * @since 9.3 |
| 565 | */ |
| 566 | |
| 567 | public void serializeNode(XdmNode node) throws SaxonApiException { |
| 568 | StreamResult res = result; |
| 569 | if (res.getOutputStream() == null && res.getWriter() == null && res.getSystemId() == null) { |
| 570 | throw new IllegalStateException("Either an outputStream, or a Writer, or a File must be supplied"); |
| 571 | } |
| 572 | serializeNodeToResult(node, res); |
| 573 | } |
| 574 | |
| 575 | /** |
| 576 | * Serialize an arbitrary XdmValue to the selected output destination using this serializer. The supplied |
| 577 | * sequence is first wrapped in a document node according to the rules given in section 2 (Sequence Normalization) of the |
| 578 | * <a href="http://www.w3.org/TR/xslt-xquery-serialization/">XSLT/XQuery serialization specification</a>; the resulting |
| 579 | * document nodes is then serialized using the serialization parameters defined in this serializer. |
| 580 | * |
| 581 | * @param value The value to be serialized |
| 582 | * @throws IllegalStateException if no outputStream, Writer, or File has been supplied as the |
| 583 | * destination for the serialized output, or if no Processor is associated with the serializer |
| 584 | * @throws SaxonApiException if a serialization error or I/O error occurs |
| 585 | * @since 9.3 |
| 586 | */ |
| 587 | |
| 588 | |
| 589 | public void serializeXdmValue(XdmValue value) throws SaxonApiException { |
| 590 | if (value instanceof XdmNode) { |
| 591 | serializeNode((XdmNode) value); |
| 592 | } else { |
| 593 | try { |
| 594 | SerializationProperties properties = |
| 595 | new SerializationProperties(getLocallyDefinedProperties(), characterMap); |
| 596 | QueryResult.serializeSequence(value.getUnderlyingValue().iterate(), |
| 597 | processor.getUnderlyingConfiguration(), result, properties); |
| 598 | } catch (XPathException e) { |
| 599 | throw new SaxonApiException(e); |
| 600 | } |
| 601 | } |
| 602 | closeAndNotify(); |
| 603 | |
| 604 | } |
| 605 | |
| 606 | /** |
| 607 | * Serialize an XdmNode to a string using this serializer |
| 608 | * |
| 609 | * @param node The node to be serialized |
| 610 | * @return the serialized representation of the node as lexical XML |
| 611 | * @throws SaxonApiException if a serialization error occurs |
| 612 | * @since 9.3 |
| 613 | */ |
| 614 | |
| 615 | public String serializeNodeToString(XdmNode node) throws SaxonApiException { |
| 616 | StringWriter sw = new StringWriter(); |
| 617 | StreamResult sr = new StreamResult(sw); |
| 618 | serializeNodeToResult(node, sr); |
| 619 | return sw.toString(); |
| 620 | } |
| 621 | |
| 622 | private void serializeNodeToResult(XdmNode node, Result res) throws SaxonApiException { |
| 623 | try { |
| 624 | QueryResult.serialize(node.getUnderlyingNode(), res, getLocallyDefinedProperties()); |
| 625 | } catch (XPathException e) { |
| 626 | throw new SaxonApiException(e); |
| 627 | } |
| 628 | } |
| 629 | |
| 630 | /** |
| 631 | * Get an XMLStreamWriter that can be used for writing application-generated XML |
| 632 | * to be output via this serializer. |
| 633 | * |
| 634 | * @return a newly constructed XMLStreamWriter that pipes events into this Serializer |
| 635 | * @throws SaxonApiException if any other failure occurs |
| 636 | * @since 9.3 |
| 637 | */ |
| 638 | |
| 639 | public StreamWriterToReceiver getXMLStreamWriter() throws SaxonApiException { |
| 640 | PipelineConfiguration pipe = processor.getUnderlyingConfiguration().makePipelineConfiguration(); |
| 641 | Receiver r = getReceiver(pipe, getSerializationProperties()); |
| 642 | r = new NamespaceReducer(r); |
| 643 | return new StreamWriterToReceiver(r); |
| 644 | } |
| 645 | |
| 646 | /** |
| 647 | * Get a ContentHandler that can be used to direct the output of a SAX parser (or other |
| 648 | * source of SAX events) to this serializer. |
| 649 | * |
| 650 | * @return a newly constructed ContentHandler that pipes events into this Serializer |
| 651 | * @throws SaxonApiException if any other failure occurs |
| 652 | * @since 9.7 |
| 653 | */ |
| 654 | |
| 655 | public org.xml.sax.ContentHandler getContentHandler() throws SaxonApiException { |
| 656 | PipelineConfiguration pipe = processor.getUnderlyingConfiguration().makePipelineConfiguration(); |
| 657 | Receiver r = getReceiver(pipe, getSerializationProperties()); |
| 658 | //r = new SequenceNormalizerWithSpaceSeparator(r); |
| 659 | r = new NamespaceReducer(r); |
| 660 | ReceivingContentHandler rch = new ReceivingContentHandler(); |
| 661 | rch.setReceiver(r); |
| 662 | rch.setPipelineConfiguration(r.getPipelineConfiguration()); |
| 663 | return rch; |
| 664 | } |
| 665 | |
| 666 | /** |
| 667 | * Get the current output destination. |
| 668 | * |
| 669 | * @return an OutputStream, Writer, or File, depending on the previous calls to |
| 670 | * {@link #setOutputStream}, {@link #setOutputWriter}, or {@link #setOutputFile}; or |
| 671 | * null, if no output destination has been set up. |
| 672 | */ |
| 673 | |
| 674 | public Object getOutputDestination() { |
| 675 | if (result.getOutputStream() != null) { |
| 676 | return result.getOutputStream(); |
| 677 | } |
| 678 | if (result.getWriter() != null) { |
| 679 | return result.getWriter(); |
| 680 | } |
| 681 | String systemId = result.getSystemId(); |
| 682 | if (systemId != null) { |
| 683 | try { |
| 684 | return new File(new URI(systemId)); |
| 685 | } catch (URISyntaxException e) { |
| 686 | return null; |
| 687 | } |
| 688 | } else { |
| 689 | return null; |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | /** |
| 694 | * Return a receiver to which Saxon will send events. This method is provided |
| 695 | * primarily for internal use, though it could also be called by user applications |
| 696 | * wanting to make use of the Saxon serializer. |
| 697 | * |
| 698 | * @param pipe The Saxon configuration. This is an internal implementation object |
| 699 | * held within the {@link Processor} |
| 700 | * @param params Serialization parameters originating from the query or stylesheet |
| 701 | * (for example, xsl:output declarations or xsl:result-document attributes). |
| 702 | * These parameters are combined with those held by this {@code Serializer} itself, |
| 703 | * with properties set of the {@code Serializer} taking precedence. |
| 704 | * @return a receiver to which XML events will be sent |
| 705 | */ |
| 706 | |
| 707 | public Receiver getReceiver(PipelineConfiguration pipe, SerializationProperties params) throws SaxonApiException { |
| 708 | try { |
| 709 | SerializerFactory sf = pipe.getConfiguration().getSerializerFactory(); |
| 710 | SerializationProperties mergedParams = getSerializationProperties().combineWith(params); |
| 711 | Receiver target = sf.getReceiver(result, mergedParams, pipe); |
| 712 | if (helper.getListeners() != null) { |
| 713 | if (target instanceof SequenceNormalizer) { |
| 714 | ((SequenceNormalizer)target).onClose(helper.getListeners()); |
| 715 | } else { |
| 716 | target = new CloseNotifier(target, helper.getListeners()); |
| 717 | } |
| 718 | } |
| 719 | if (target.getSystemId() == null && getDestinationBaseURI() != null) { |
| 720 | target.setSystemId(getDestinationBaseURI().toASCIIString()); |
| 721 | } |
| 722 | return target; |
| 723 | } catch (XPathException e) { |
| 724 | throw new SaxonApiException(e); |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | /** |
| 729 | * Create a Properties object holding the defined serialization properties. This |
| 730 | * will be in the same format as JAXP interfaces such as |
| 731 | * {@link javax.xml.transform.Transformer#getOutputProperties()} |
| 732 | * |
| 733 | * @return a newly-constructed Properties object holding the declared serialization properties. Specifically, |
| 734 | * it holds the properties defined explicitly on this Serializer object, backed by the properties defined |
| 735 | * in unnamed xsl:output declarations in the stylesheet, or output declarations in XQuery. |
| 736 | */ |
| 737 | |
| 738 | public Properties getCombinedOutputProperties(Properties defaultOutputProperties) { |
| 739 | Properties props = defaultOutputProperties == null ? new Properties() : new Properties(defaultOutputProperties); |
| 740 | for (StructuredQName p : properties.keySet()) { |
| 741 | String value = properties.get(p); |
| 742 | props.setProperty(p.getClarkName(), value); |
| 743 | } |
| 744 | return props; |
| 745 | } |
| 746 | |
| 747 | |
| 748 | /** |
| 749 | * Create a Properties object holding the serialization properties explicitly declared |
| 750 | * within this Serializer object, and not including any defaults taken from the stylesheet or query. |
| 751 | * @return a newly-constructed Properties object holding the declared serialization properties. Specifically, |
| 752 | * it holds the properties defined explicitly on this Serializer object, and excludes any properties defined |
| 753 | * in named or unnamed xsl:output declarations in the stylesheet, or the equivalent in XQuery. |
| 754 | */ |
| 755 | |
| 756 | protected Properties getLocallyDefinedProperties() { |
| 757 | Properties props = new Properties(); |
| 758 | for (StructuredQName p : properties.keySet()) { |
| 759 | String value = properties.get(p); |
| 760 | props.setProperty(p.getClarkName(), value); |
| 761 | } |
| 762 | return props; |
| 763 | } |
| 764 | |
| 765 | /** |
| 766 | * Create a {@link SerializationProperties} object holding the serialization properties explicitly declared |
| 767 | * within this Serializer object (including any character map index), and not including any |
| 768 | * defaults taken from the stylesheet or query. |
| 769 | * |
| 770 | * @return a newly-constructed {@code SerializationProperties} object holding the declared |
| 771 | * serialization properties. Specifically, it holds the properties defined explicitly on this |
| 772 | * {@code Serializer} object, and excludes any properties defined in named or unnamed |
| 773 | * {@code xsl:output} declarations in the stylesheet, or the equivalent in XQuery. |
| 774 | */ |
| 775 | |
| 776 | public SerializationProperties getSerializationProperties() { |
| 777 | return new SerializationProperties(getLocallyDefinedProperties(), characterMap); |
| 778 | } |
| 779 | |
| 780 | /** |
| 781 | * Get the JAXP StreamResult object representing the output destination |
| 782 | * of this serializer |
| 783 | */ |
| 784 | |
| 785 | protected Result getResult() { |
| 786 | return result; |
| 787 | } |
| 788 | |
| 789 | /** |
| 790 | * Close any resources associated with this destination. Note that this does <b>not</b> |
| 791 | * close any user-supplied OutputStream or Writer; those must be closed explicitly |
| 792 | * by the calling application. |
| 793 | */ |
| 794 | |
| 795 | public void close() throws SaxonApiException { |
| 796 | if (mustClose) { |
| 797 | // This relies on the fact that the SerializerFactory sets the OutputStream |
| 798 | OutputStream stream = result.getOutputStream(); |
| 799 | if (stream != null) { |
| 800 | try { |
| 801 | stream.close(); |
| 802 | } catch (java.io.IOException err) { |
| 803 | throw new SaxonApiException("Failed while closing output file", err); |
| 804 | } |
| 805 | } |
| 806 | Writer writer = result.getWriter(); |
| 807 | if (writer != null) { |
| 808 | try { |
| 809 | writer.close(); |
| 810 | } catch (java.io.IOException err) { |
| 811 | throw new SaxonApiException("Failed while closing output file", err); |
| 812 | } |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | |
| 817 | /** |
| 818 | * Get the Property with a given QName |
| 819 | * |
| 820 | * @param name the QName of the required property, which must be either a standard property defined |
| 821 | * in the XSLT 3.0 / XQuery 3.0 serialization specification, or an extension property defined by |
| 822 | * Saxon in the Saxon namespace |
| 823 | * @return the corresponding Property object |
| 824 | * @throws IllegalArgumentException if the name is not a recognized serialization property name. |
| 825 | * @since 9.6 |
| 826 | */ |
| 827 | |
| 828 | public static Property getProperty(QName name) { |
| 829 | String clarkName = name.getClarkName(); |
| 830 | Property prop = standardProperties.get(clarkName); |
| 831 | if (prop != null) { |
| 832 | return prop; |
| 833 | } else { |
| 834 | throw new IllegalArgumentException("Unknown serialization property " + clarkName); |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | public boolean isMustCloseAfterUse() { |
| 839 | return mustClose; |
| 840 | } |
| 841 | } |
| 842 |