Debian Codegraph @

net/sf/saxon/functions/Serialize.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.functions;
9
10 import net.sf.saxon.event.PipelineConfiguration;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.SequenceCopier;
13 import net.sf.saxon.expr.Callable;
14 import net.sf.saxon.expr.StaticProperty;
15 import net.sf.saxon.expr.XPathContext;
16 import net.sf.saxon.expr.parser.ExplicitLocation;
17 import net.sf.saxon.expr.parser.RoleDiagnostic;
18 import net.sf.saxon.lib.NamespaceConstant;
19 import net.sf.saxon.lib.SaxonOutputKeys;
20 import net.sf.saxon.lib.SerializerFactory;
21 import net.sf.saxon.ma.map.HashTrieMap;
22 import net.sf.saxon.ma.map.KeyValuePair;
23 import net.sf.saxon.ma.map.MapItem;
24 import net.sf.saxon.ma.map.MapType;
25 import net.sf.saxon.om.*;
26 import net.sf.saxon.regex.UnicodeString;
27 import net.sf.saxon.serialize.CharacterMap;
28 import net.sf.saxon.serialize.CharacterMapIndex;
29 import net.sf.saxon.serialize.SerializationProperties;
30 import net.sf.saxon.serialize.SerializationParamsHandler;
31 import net.sf.saxon.trans.Err;
32 import net.sf.saxon.trans.XPathException;
33 import net.sf.saxon.tree.iter.AtomicIterator;
34 import net.sf.saxon.type.BuiltInAtomicType;
35 import net.sf.saxon.type.Type;
36 import net.sf.saxon.type.TypeHierarchy;
37 import net.sf.saxon.value.*;
38 import net.sf.saxon.z.IntHashMap;
39
40 import javax.xml.transform.OutputKeys;
41 import javax.xml.transform.stream.StreamResult;
42 import java.io.StringWriter;
43 import java.util.HashMap;
44 import java.util.Map;
45 import java.util.Properties;
46
47 /**
48 * Implementation of fn:serialize() as defined in XPath 3.1
49 */
50
51 public class Serialize extends SystemFunction implements Callable {
52
53 public static OptionsParameter makeOptionsParameter() {
54 SequenceType listOfQNames = BuiltInAtomicType.QNAME.zeroOrMore();
55 OptionsParameter op = new OptionsParameter();
56 op.addAllowedOption("allow-duplicate-names", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
57 op.addAllowedOption("byte-order-mark", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
58 op.addAllowedOption("cdata-section-elements", listOfQNames, EmptySequence.getInstance());
59 //QNames-param-type - sequence or an array of xs:QName values. Note that an array will be converted to a sequence, as required
60 op.addAllowedOption("doctype-public", SequenceType.SINGLE_STRING); //doctype-public-param-type pubid-char-string-type
61 op.addAllowedOption("doctype-system", SequenceType.SINGLE_STRING); //doctype-system-param-type system-id-string-type
62 op.addAllowedOption("encoding", SequenceType.SINGLE_STRING); //encoding-param-type encoding-string-type
63 op.addAllowedOption("escape-uri-attributes", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
64 op.addAllowedOption("html-version", SequenceType.SINGLE_DECIMAL); //decimal-param-type
65 op.addAllowedOption("include-content-type", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
66 op.addAllowedOption("indent", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
67 op.addAllowedOption("item-separator", SequenceType.SINGLE_STRING); //string-param-type
68 op.addAllowedOption("json-node-output-method", SequenceType.SINGLE_STRING);
69 //json-node-output-method-param-type json-node-output-method-type - xs:string or xs:QName
70 op.addAllowedOption("media-type", SequenceType.SINGLE_STRING); //string-param-type
71 op.addAllowedOption("method", SequenceType.SINGLE_STRING);
72 //method-param-type method-type - xs:string or xs:QName
73 op.addAllowedOption("normalization-form", SequenceType.SINGLE_STRING);
74 //NMTOKEN-param-type BuiltInAtomicType.NMTOKEN
75 op.addAllowedOption("omit-xml-declaration", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
76 op.addAllowedOption("standalone", SequenceType.OPTIONAL_BOOLEAN); //yes-no-omit-type
77 op.addAllowedOption("suppress-indentation", listOfQNames);
78 //QNames-param-type - sequence or an array of xs:QName values. Note that an array will be converted to a sequence, as required
79 op.addAllowedOption("undeclare-prefixes", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
80 op.addAllowedOption("use-character-maps", SequenceType.makeSequenceType(MapType.ANY_MAP_TYPE, StaticProperty.EXACTLY_ONE));
81 //use-character-maps-param-type
82 op.addAllowedOption("version", SequenceType.SINGLE_STRING);
83
84 op.addAllowedOption(sx("attribute-order"), listOfQNames);
85 //eqnames
86 op.addAllowedOption(sx("character-representation"), SequenceType.SINGLE_STRING); //string
87 op.addAllowedOption(sx("double-space"), listOfQNames);
88 //eqnames
89 op.addAllowedOption(sx("indent-spaces"), SequenceType.SINGLE_INTEGER); //integer
90 op.addAllowedOption(sx("line-length"), SequenceType.SINGLE_INTEGER); //integer
91 //requiredTypes.put("next-in-chain", SequenceType.SINGLE_STRING); //uri
92 op.addAllowedOption(sx("property-order"), SequenceType.STRING_SEQUENCE);
93 op.addAllowedOption(sx("recognize-binary"), SequenceType.SINGLE_BOOLEAN); //boolean
94 op.addAllowedOption(sx("require-well-formed"), SequenceType.SINGLE_BOOLEAN); //boolean
95 op.addAllowedOption(sx("single-quotes"), SequenceType.SINGLE_BOOLEAN); //boolean
96 op.addAllowedOption(sx("supply-source-locator"), SequenceType.SINGLE_BOOLEAN); //boolean
97 return op;
98 }
99
100 private static String sx(String s) {
101 return "Q{" + NamespaceConstant.SAXON + "}" + s;
102 }
103
104 private String[] paramNames = new String[]{
105 "allow-duplicate-names", "byte-order-mark", "cdata-section-elements", "doctype-public", "doctype-system",
106 "encoding", "escape-uri-attributes", "html-version", "include-content-type", "indent", "item-separator",
107 "json-node-output-method", "media-type", "method", "normalization-form", "omit-xml-declaration", "standalone",
108 "suppress-indentation", "undeclare-prefixes", "use-character-maps", "version"
109 };
110
111 private boolean isParamName(String string) {
112 for (String s : paramNames) {
113 if (s.equals(string)) {
114 return true;
115 }
116 }
117 return false;
118 }
119
120 private String[] paramNamesSaxon = new String[]{
121 "attribute-order", "character-representation", "double-space", "indent-spaces", "line-length",
122 /*"next-in-chain",*/ "property-order", "recognize-binary", "require-well-formed", "single-quotes",
123 "supply-source-locator", "suppress-indentation"
124 };
125
126 private boolean isParamNameSaxon(String string) {
127 for (String s : paramNamesSaxon) {
128 if (s.equals(string)) {
129 return true;
130 }
131 }
132 return false;
133 }
134
135 private final static Map<String, SequenceType> requiredTypes = new HashMap<>(40);
136
137 static {
138 requiredTypes.put("allow-duplicate-names", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
139 requiredTypes.put("byte-order-mark", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
140 requiredTypes.put("cdata-section-elements", BuiltInAtomicType.QNAME.zeroOrMore());
141 //QNames-param-type - sequence or an array of xs:QName values. Note that an array will be converted to a sequence, as required
142 requiredTypes.put("doctype-public", SequenceType.SINGLE_STRING); //doctype-public-param-type pubid-char-string-type
143 requiredTypes.put("doctype-system", SequenceType.SINGLE_STRING); //doctype-system-param-type system-id-string-type
144 requiredTypes.put("encoding", SequenceType.SINGLE_STRING); //encoding-param-type encoding-string-type
145 requiredTypes.put("escape-uri-attributes", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
146 requiredTypes.put("html-version", SequenceType.SINGLE_DECIMAL); //decimal-param-type
147 requiredTypes.put("include-content-type", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
148 requiredTypes.put("indent", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
149 requiredTypes.put("item-separator", SequenceType.SINGLE_STRING); //string-param-type
150 requiredTypes.put("json-node-output-method", SequenceType.SINGLE_STRING);
151 //json-node-output-method-param-type json-node-output-method-type - xs:string or xs:QName
152 requiredTypes.put("media-type", SequenceType.SINGLE_STRING); //string-param-type
153 requiredTypes.put("method", SequenceType.SINGLE_STRING);
154 //method-param-type method-type - xs:string or xs:QName
155 requiredTypes.put("normalization-form", SequenceType.SINGLE_STRING);
156 //NMTOKEN-param-type BuiltInAtomicType.NMTOKEN
157 requiredTypes.put("omit-xml-declaration", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
158 requiredTypes.put("standalone", SequenceType.OPTIONAL_BOOLEAN); //yes-no-omit-type
159 requiredTypes.put("suppress-indentation", BuiltInAtomicType.QNAME.zeroOrMore());
160 //QNames-param-type - sequence or an array of xs:QName values. Note that an array will be converted to a sequence, as required
161 requiredTypes.put("undeclare-prefixes", SequenceType.SINGLE_BOOLEAN); //yes-no-param-type
162 requiredTypes.put("use-character-maps", SequenceType.makeSequenceType(MapType.ANY_MAP_TYPE, StaticProperty.EXACTLY_ONE));
163 //use-character-maps-param-type
164 requiredTypes.put("version", SequenceType.SINGLE_STRING); //string-param-type
165 }
166
167 private final static Map<String, SequenceType> requiredTypesSaxon = new HashMap<>(20);
168
169 static {
170 requiredTypesSaxon.put("attribute-order", BuiltInAtomicType.QNAME.zeroOrMore());
171 //eqnames
172 requiredTypesSaxon.put("character-representation", SequenceType.SINGLE_STRING); //string
173 requiredTypesSaxon.put("double-space", BuiltInAtomicType.QNAME.zeroOrMore());
174 //eqnames
175 requiredTypesSaxon.put("indent-spaces", SequenceType.SINGLE_INTEGER); //integer
176 requiredTypesSaxon.put("line-length", SequenceType.SINGLE_INTEGER); //integer
177 //requiredTypes.put("next-in-chain", SequenceType.SINGLE_STRING); //uri
178 requiredTypesSaxon.put("recognize-binary", SequenceType.SINGLE_BOOLEAN); //boolean
179 requiredTypesSaxon.put("require-well-formed", SequenceType.SINGLE_BOOLEAN); //boolean
180 requiredTypesSaxon.put("single-quotes", SequenceType.SINGLE_BOOLEAN); //boolean
181 requiredTypesSaxon.put("supply-source-locator", SequenceType.SINGLE_BOOLEAN); //boolean
182 requiredTypesSaxon.put("suppress-indentation", BuiltInAtomicType.QNAME.zeroOrMore());
183 //eqnames
184 }
185
186 /**
187 * Check the options supplied:
188 * 1. ignore any other options not in the specs;
189 * 2. validate the types of the option values supplied.
190 */
191
192 private MapItem checkOptions(MapItem map, XPathContext context) throws XPathException {
193 HashTrieMap result = new HashTrieMap();
194 TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
195
196 AtomicIterator keysIterator = map.keys();
197 AtomicValue key;
198 while ((key = keysIterator.next()) != null) {
199 if (key instanceof StringValue) {
200 String keyName = key.getStringValue();
201 if (isParamName(keyName)) {
202 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.OPTION, keyName, 0);
203 role.setErrorCode("XPTY0004");
204 //If any serialization error occurs, including the detection of an invalid value for a serialization
205 // parameter, this results in the fn:serialize call failing with a dynamic error.
206 Sequence<?> converted = th.applyFunctionConversionRules(
207 map.get(key), requiredTypes.get(keyName), role, ExplicitLocation.UNKNOWN_LOCATION);
208 result = result.addEntry(key, converted.materialize());
209 }
210 } else if (key instanceof QNameValue) {
211 if (key.getComponent(AccessorFn.Component.NAMESPACE).getStringValue().equals("")) {
212 throw new XPathException("A serialization parameter supplied with a QName key must have non-absent namespace", "SEPM0017");
213 } else if (key.getComponent(AccessorFn.Component.NAMESPACE).getStringValue().equals("http://saxon.sf.net/")) {
214 // Capture Saxon serialization parameters
215 String keyName = ((QNameValue) key).getLocalName();
216 if (isParamNameSaxon(keyName)) {
217 RoleDiagnostic role = new RoleDiagnostic(RoleDiagnostic.OPTION, keyName, 0);
218 Sequence<?> converted = th.applyFunctionConversionRules(
219 map.get(key), requiredTypesSaxon.get(keyName), role, ExplicitLocation.UNKNOWN_LOCATION);
220 result = result.addEntry(key, converted.materialize());
221 }
222 }
223 // Implementation-defined serialization parameters in an unrecognised namespace are ignored.
224 } else {
225 break;
226 }
227 }
228 return result;
229 }
230
231 // Convert a boolean value to a yes-no-type string.
232
233 private String toYesNoTypeString(Sequence<?> seqVal) throws XPathException {
234 String s;
235 boolean booleanValue = ((BooleanValue) seqVal.head()).getBooleanValue();
236 if (booleanValue) {
237 s = "yes";
238 } else {
239 s = "no";
240 }
241 return s;
242 }
243
244 // Convert a value to a yes-no-omit-type string.
245
246 private String toYesNoOmitTypeString(Sequence<?> seqVal) throws XPathException {
247 String stringVal = "";
248 if (seqVal instanceof EmptySequence) {
249 stringVal = "omit";
250 } else if (seqVal.head() instanceof BooleanValue) {
251 stringVal = toYesNoTypeString(seqVal);
252 }
253 // otherwise invalid
254 return stringVal;
255 }
256
257 // Convert a sequence of QNames to a qnames-type string (containing a space-separated list of the QNames).
258
259 private String toQNamesTypeString(Sequence<?> seqVal) throws XPathException {
260 SequenceIterator<?> iterator = seqVal.iterate();
261 Item item;
262 StringBuilder stringVal = new StringBuilder();
263 while ((item = iterator.next()) != null) {
264 QNameValue qNameValue = (QNameValue) item;
265 stringVal.append(" {")
266 .append(qNameValue.getComponent(AccessorFn.Component.NAMESPACE).getStringValue())
267 .append('}')
268 .append(qNameValue.getComponent(AccessorFn.Component.LOCALNAME).getStringValue());
269 }
270 return stringVal.toString();
271 }
272
273 // Convert a sequence of strings to a single space-separated string.
274
275 private String toSpaceSeparatedString(Sequence<?> seqVal) throws XPathException {
276 SequenceIterator<?> iterator = seqVal.iterate();
277 Item item;
278 StringBuilder stringVal = new StringBuilder();
279 while ((item = iterator.next()) != null) {
280 stringVal.append(" ").append(item.getStringValue());
281 }
282 return stringVal.toString();
283 }
284
285 // Convert a QName or string value to a method-type (or json-node-output-method-type) string.
286
287 private String toMethodTypeString(Sequence<?> seqVal) throws XPathException {
288 String stringVal;
289 if (seqVal.head() instanceof QNameValue) {
290 QNameValue qNameValue = (QNameValue) seqVal.head();
291 stringVal = '{' + qNameValue.getComponent(AccessorFn.Component.NAMESPACE).toString() + '}' + qNameValue.getComponent(AccessorFn.Component.LOCALNAME);
292 } else {
293 stringVal = seqVal.head().getStringValue();
294 }
295 return stringVal;
296 }
297
298
299 /**
300 * By the option parameter conventions, check the 'options' supplied in a character map:
301 * 1. any string is allowed as an option, QNames not recognised by product are ignored;
302 * 2. validate the types of the option values supplied (required type is always xs:string).
303 */
304
305 private static MapItem checkCharacterMapOptions(MapItem map, XPathContext context) throws XPathException {
306 TypeHierarchy th = context.getConfiguration().getTypeHierarchy();
307 for (KeyValuePair pair : map.keyValuePairs()) {
308 AtomicValue key = pair.key;
309 if (!(key instanceof StringValue)) {
310 throw new XPathException(
311 "Keys in a character map must all be strings. Found a value of type " + key.getItemType(), "XPTY0004");
312 }
313 if (((StringValue) key).getStringLength() != 1) {
314 throw new XPathException("Keys in a character map must all be one-character strings. Found " + Err.wrap(key.toString()), "SEPM0016");
315 }
316 if (!SequenceType.SINGLE_STRING.matches(pair.value, th)) {
317 throw new XPathException("Values in a character map must all be single strings. Found " + Err.wrap(key.toString()), "XPTY0004");
318 }
319 }
320 return map;
321 }
322
323 // Convert a map defining a character map to a CharacterMap
324
325 private CharacterMap toCharacterMap(Sequence<?> seqVal, XPathContext context) throws XPathException {
326 MapItem charMap = checkCharacterMapOptions((MapItem) seqVal.head(), context);
327 return toCharacterMap(charMap);
328 }
329
330 public static CharacterMap toCharacterMap(MapItem charMap) throws XPathException {
331 AtomicIterator iterator = charMap.keys();
332 AtomicValue charKey;
333 IntHashMap<String> intHashMap = new IntHashMap<>();
334 while ((charKey = iterator.next()) != null) {
335 String ch = charKey.getStringValue();
336 String str = charMap.get(charKey).head().getStringValue();
337 UnicodeString chValue = UnicodeString.makeUnicodeString(ch);
338 if (chValue.uLength() != 1) {
339 throw new XPathException("In the serialization parameter for the character map, each character to be mapped " +
340 "must be a single Unicode character", "SEPM0016");
341 }
342 int code = chValue.uCharAt(0);
343 String prev = intHashMap.put(code, str);
344 if (prev != null) { // This should never happen in this case because keys in a HashTrieMap must be unique
345 throw new XPathException("In the serialization parameters, the character map contains two entries for the character \\u" +
346 Integer.toHexString(65536 + code).substring(1), "SEPM0018");
347 }
348 }
349 StructuredQName name = new StructuredQName("output", NamespaceConstant.OUTPUT, "serialization-parameters");
350 return new CharacterMap(name, intHashMap);
351 }
352
353 private SerializationProperties serializationParamsFromMap(
354 Map<String, Sequence<?>> map, XPathContext context) throws XPathException {
355 Sequence seqVal;
356 Properties props = new Properties();
357 CharacterMapIndex charMapIndex = new CharacterMapIndex();
358 if ((seqVal = map.get("allow-duplicate-names")) != null) {
359 props.setProperty("allow-duplicate-names", toYesNoTypeString(seqVal));
360 }
361 if ((seqVal = map.get("byte-order-mark")) != null) {
362 props.setProperty("byte-order-mark", toYesNoTypeString(seqVal));
363 }
364 if ((seqVal = map.get("cdata-section-elements")) != null) {
365 props.setProperty("cdata-section-elements", toQNamesTypeString(seqVal));
366 }
367 if ((seqVal = map.get("doctype-public")) != null) {
368 props.setProperty("doctype-public", seqVal.head().getStringValue());
369 }
370 if ((seqVal = map.get("doctype-system")) != null) {
371 props.setProperty("doctype-system", seqVal.head().getStringValue());
372 }
373 if ((seqVal = map.get("encoding")) != null) {
374 props.setProperty("encoding", seqVal.head().getStringValue());
375 }
376 if ((seqVal = map.get("escape-uri-attributes")) != null) {
377 props.setProperty("escape-uri-attributes", toYesNoTypeString(seqVal));
378 }
379 if ((seqVal = map.get("html-version")) != null) {
380 props.setProperty("html-version", seqVal.head().getStringValue());
381 }
382 if ((seqVal = map.get("include-content-type")) != null) {
383 props.setProperty("include-content-type", toYesNoTypeString(seqVal));
384 }
385 if ((seqVal = map.get("indent")) != null) {
386 props.setProperty("indent", toYesNoTypeString(seqVal));
387 }
388 if ((seqVal = map.get("item-separator")) != null) {
389 props.setProperty("item-separator", seqVal.head().getStringValue());
390 }
391 if ((seqVal = map.get("json-node-output-method")) != null) {
392 props.setProperty("json-node-output-method", toMethodTypeString(seqVal));
393 }
394 if ((seqVal = map.get("media-type")) != null) {
395 props.setProperty("media-type", seqVal.head().getStringValue());
396 }
397 if ((seqVal = map.get("method")) != null) {
398 props.setProperty(OutputKeys.METHOD, toMethodTypeString(seqVal));
399 }
400 if ((seqVal = map.get("normalization-form")) != null) {
401 props.setProperty("normalization-form", seqVal.head().getStringValue()); //NMTOKEN param type
402 }
403 if ((seqVal = map.get("omit-xml-declaration")) != null) {
404 props.setProperty("omit-xml-declaration", toYesNoTypeString(seqVal));
405 }
406 if ((seqVal = map.get("standalone")) != null) {
407 props.setProperty("standalone", toYesNoOmitTypeString(seqVal));
408 }
409 if ((seqVal = map.get("suppress-indentation")) != null) {
410 props.setProperty("suppress-indentation", toQNamesTypeString(seqVal));
411 }
412 if ((seqVal = map.get("undeclare-prefixes")) != null) {
413 props.setProperty("undeclare-prefixes", toYesNoTypeString(seqVal));
414 }
415 if ((seqVal = map.get("use-character-maps")) != null) {
416 CharacterMap characterMap = toCharacterMap(seqVal, context);
417 charMapIndex.putCharacterMap(new StructuredQName("", "", "charMap"), characterMap);
418 props.setProperty(SaxonOutputKeys.USE_CHARACTER_MAPS, "charMap");
419 }
420 if ((seqVal = map.get("version")) != null) {
421 props.setProperty("version", seqVal.head().getStringValue());
422 }
423 // Saxon extension serialization parameters
424 if ((seqVal = map.get(sx("attribute-order"))) != null) {
425 props.setProperty(SaxonOutputKeys.ATTRIBUTE_ORDER, toQNamesTypeString(seqVal));
426 }
427 if ((seqVal = map.get(sx("canonical"))) != null) {
428 props.setProperty(SaxonOutputKeys.CANONICAL, toYesNoTypeString(seqVal));
429 }
430 if ((seqVal = map.get(sx("character-representation"))) != null) {
431 props.setProperty(SaxonOutputKeys.CHARACTER_REPRESENTATION, seqVal.head().getStringValue());
432 }
433 if ((seqVal = map.get(sx("double-space"))) != null) {
434 props.setProperty(SaxonOutputKeys.DOUBLE_SPACE, toQNamesTypeString(seqVal));
435 }
436 if ((seqVal = map.get(sx("indent-spaces"))) != null) {
437 props.setProperty(SaxonOutputKeys.INDENT_SPACES, seqVal.head().getStringValue());
438 }
439 if ((seqVal = map.get(sx("line-length"))) != null) {
440 props.setProperty(SaxonOutputKeys.LINE_LENGTH, seqVal.head().getStringValue());
441 }
442 if ((seqVal = map.get(sx("property-order"))) != null) {
443 props.setProperty(SaxonOutputKeys.PROPERTY_ORDER, toSpaceSeparatedString(seqVal));
444 }
445 if ((seqVal = map.get(sx("recognize-binary"))) != null) {
446 props.setProperty(SaxonOutputKeys.RECOGNIZE_BINARY, toYesNoTypeString(seqVal));
447 }
448 if ((seqVal = map.get(sx("require-well-formed"))) != null) {
449 props.setProperty(SaxonOutputKeys.REQUIRE_WELL_FORMED, toYesNoTypeString(seqVal));
450 }
451 if ((seqVal = map.get(sx("single-quotes"))) != null) {
452 props.setProperty(SaxonOutputKeys.SINGLE_QUOTES, toYesNoTypeString(seqVal));
453 }
454 if ((seqVal = map.get(sx("supply-source-locator"))) != null) {
455 props.setProperty(SaxonOutputKeys.SUPPLY_SOURCE_LOCATOR, toYesNoTypeString(seqVal));
456 }
457 return new SerializationProperties(props, charMapIndex);
458 }
459
460
461 public StringValue call(XPathContext context, Sequence[] arguments) throws XPathException {
462 return evalSerialize(arguments[0].iterate(),
463 arguments.length == 1 ? null : arguments[1].head(), context);
464 }
465
466 private StringValue evalSerialize(SequenceIterator<?> iter, Item param, XPathContext context) throws XPathException {
467
468 SerializationProperties params = null;
469
470 // The default parameter values are implementation-defined when an output:serialization-parameters
471 // element is used (or when the argument is omitted), but are fixed by this specification in the
472 // case where a map (including an empty map) is supplied for the argument.
473 if (param != null) {
474 if (param instanceof NodeInfo) {
475 NodeInfo paramNode = (NodeInfo) param;
476 if (paramNode.getNodeKind() != Type.ELEMENT ||
477 !NamespaceConstant.OUTPUT.equals(paramNode.getURI()) ||
478 !"serialization-parameters".equals(paramNode.getLocalPart())) {
479 throw new XPathException("Second argument to fn:serialize() must be an element named {"
480 + NamespaceConstant.OUTPUT + "}serialization-parameters", "XPTY0004");
481 }
482 SerializationParamsHandler sph = new SerializationParamsHandler();
483 sph.setSerializationParams(paramNode);
484 params = sph.getSerializationProperties();
485
486 } else if (param instanceof MapItem) {
487 // If any parameters are supplied as QNames in the Saxon namespace, convert them to EQName strings
488 MapItem paramMap = (MapItem)param;
489 AtomicIterator keyIter = ((MapItem)param).keys();
490 AtomicValue k;
491 while ((k = keyIter.next()) != null) {
492 if (k instanceof QNameValue) {
493 String s = ((QNameValue) k).getStructuredQName().getEQName();
494 paramMap = paramMap.addEntry(new StringValue(s), paramMap.get(k));
495 }
496 }
497 Map<String, Sequence<?>> checkedOptions = getDetails().optionDetails.processSuppliedOptions(paramMap, context);
498 params = serializationParamsFromMap(checkedOptions, context);
499 } else {
500 throw new XPathException("Second argument to fn:serialize() must either be an element named {"
501 + NamespaceConstant.OUTPUT + "}serialization-parameters, or a map (if using XPath 3.1)", "XPTY0004");
502 }
503
504
505 } else {
506 params = new SerializationProperties(new Properties());
507 }
508
509 Properties props = params.getProperties();
510 if (props.getProperty(OutputKeys.METHOD) == null) {
511 props.setProperty(OutputKeys.METHOD, "xml");
512 }
513 if (props.getProperty(OutputKeys.OMIT_XML_DECLARATION) == null) {
514 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "true");
515 }
516
517 // TODO add more spec-defined defaults here (for both cases)
518 try {
519 StringWriter result = new StringWriter();
520
521 SerializerFactory sf = context.getConfiguration().getSerializerFactory();
522 PipelineConfiguration pipe = context.getConfiguration().makePipelineConfiguration();
523 Receiver out = sf.getReceiver(new StreamResult(result), params, pipe);
524 SequenceCopier.copySequence(iter, out);
525 return new StringValue(result.toString());
526 } catch (XPathException e) {
527 e.maybeSetErrorCode("SENR0001");
528 throw e;
529 }
530
531
532 }
533
534 }
535
536 // Copyright (c) 2011 Saxonica Limited.