Debian Codegraph @

net/sf/saxon/lib/SerializerFactory.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.lib;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.*;
12 import net.sf.saxon.om.NameChecker;
13 import net.sf.saxon.om.NamespaceResolver;
14 import net.sf.saxon.om.QNameException;
15 import net.sf.saxon.om.TreeInfo;
16 import net.sf.saxon.query.SequenceWrapper;
17 import net.sf.saxon.serialize.*;
18 import net.sf.saxon.stax.StAXResultHandlerImpl;
19 import net.sf.saxon.trans.Err;
20 import net.sf.saxon.trans.SaxonErrorCode;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.value.AtomicValue;
23 import net.sf.saxon.value.BigDecimalValue;
24
25 import javax.xml.transform.OutputKeys;
26 import javax.xml.transform.Result;
27 import javax.xml.transform.Source;
28 import javax.xml.transform.TransformerException;
29 import javax.xml.transform.sax.SAXResult;
30 import javax.xml.transform.stax.StAXResult;
31 import javax.xml.transform.stream.StreamResult;
32 import java.io.Writer;
33 import java.util.*;
34 import java.util.regex.Pattern;
35
36 /**
37 * Helper class to construct a serialization pipeline for a given result destination
38 * and a given set of output properties. The pipeline is represented by a Receiver object
39 * to which result tree events are sent.
40 * <p>Since Saxon 8.8 is is possible to write a subclass of SerializerFactory and register it
41 * with the Configuration, allowing customisation of the Serializer pipeline.</p>
42 * <p>The class includes methods for instantiating each of the components used on the Serialization
43 * pipeline. This allows a customized SerializerFactory to replace any or all of these components
44 * by subclasses that refine the behaviour.</p>
45 */
46
47 public class SerializerFactory {
48
49 Configuration config;
50 PipelineConfiguration pipe;
51
52 /**
53 * Create a SerializerFactory
54 *
55 * @param config the Saxon Configuration
56 */
57
58 public SerializerFactory(Configuration config) {
59 this.config = config;
60 }
61
62 public SerializerFactory(PipelineConfiguration pipe) {
63 this.pipe = pipe;
64 this.config = pipe.getConfiguration();
65 }
66
67 public Configuration getConfiguration() {
68 return config;
69 }
70 /**
71 * Create a serializer with given output properties, and return
72 * an XMLStreamWriter that can be used to feed events to the serializer.
73 *
74 * @param result the destination of the serialized output (wraps a Writer, an OutputStream, or a File)
75 * @param properties the serialization properties to be used
76 * @return a serializer in the form of an XMLStreamWriter
77 * @throws net.sf.saxon.trans.XPathException
78 * if any error occurs
79 */
80
81 public StreamWriterToReceiver getXMLStreamWriter(
82 StreamResult result,
83 Properties properties) throws XPathException {
84 Receiver r = getReceiver(result, new SerializationProperties(properties));
85 r = new NamespaceReducer(r);
86 return new StreamWriterToReceiver(r);
87 }
88
89 /**
90 * Get a Receiver that wraps a given Result object. Saxon calls this method to construct
91 * a serialization pipeline. The method can be overridden in a subclass; alternatively, the
92 * subclass can override the various methods used to instantiate components of the serialization
93 * pipeline.
94 * <p>Note that this method ignores the {@link SaxonOutputKeys#WRAP} output property. If
95 * wrapped output is required, the user must create a {@link net.sf.saxon.query.SequenceWrapper} directly.</p>
96 * <p>The effect of the method changes in Saxon 9.7 so that for serialization methods other than
97 * "json" and "adaptive", the returned Receiver performs the function of "sequence normalization" as
98 * defined in the Serialization specification. Previously the client code handled this by wrapping the
99 * result in a ComplexContentOutputter (usually as a side-effect of called XPathContext.changeOutputDestination()).
100 * Wrapping in a ComplexContentOutputter is no longer necessary, though it does no harm because the ComplexContentOutputter
101 * is idempotent.</p>
102 *
103 * <p>Changed in 9.9 so that no character maps are used. Previously the character maps from the Executable
104 * associated with the Controller referenced from the PipelineConfiguration were used.</p>
105 *
106 * @param result The final destination of the serialized output. Usually a StreamResult,
107 * but other kinds of Result are possible.
108 * @param pipe The PipelineConfiguration.
109 * @param props The serialization properties. If this includes the property {@link SaxonOutputKeys#USE_CHARACTER_MAPS}
110 * then the PipelineConfiguration must contain a non-null Controller, and the Executable associated with this Controller
111 * must have a CharacterMapIndex which is used to resolve the names of the character maps appearing in this property.
112 * @return the newly constructed Receiver that performs the required serialization
113 * @throws net.sf.saxon.trans.XPathException
114 * if any failure occurs
115 * @deprecated since Saxon 9.9: use one of the other {@code getReceiver} methods
116 */
117
118 public Receiver getReceiver(Result result,
119 PipelineConfiguration pipe,
120 Properties props)
121 throws XPathException {
122 return getReceiver(result, new SerializationProperties(props), pipe);
123 }
124
125 /**
126 * Get a Receiver that wraps a given Result object. Saxon calls this method to construct
127 * a serialization pipeline. The method can be overridden in a subclass; alternatively, the
128 * subclass can override the various methods used to instantiate components of the serialization
129 * pipeline.
130 * <p>This version of the method calls {@link #getReceiver(Result, SerializationProperties, PipelineConfiguration)}
131 * supplying default output properties, and a {@code PipelineConfiguration} newly constructed using
132 * {@link Configuration#makePipelineConfiguration()}.</p>
133 *
134 * @param result The final destination of the serialized output. Usually a StreamResult,
135 * but other kinds of Result are possible.
136 * @throws XPathException if a serializer cannot be created
137 */
138
139 public Receiver getReceiver(Result result) throws XPathException {
140 return getReceiver(result, new SerializationProperties(), config.makePipelineConfiguration());
141 }
142
143 /**
144 * Get a Receiver that wraps a given Result object. Saxon calls this method to construct
145 * a serialization pipeline. The method can be overridden in a subclass; alternatively, the
146 * subclass can override the various methods used to instantiate components of the serialization
147 * pipeline.
148 * <p>This version of the method calls {@link #getReceiver(Result, SerializationProperties, PipelineConfiguration)}
149 * supplying a {@code PipelineConfiguration} newly constructed using {@link Configuration#makePipelineConfiguration()}.</p>
150 *
151 * @param result The final destination of the serialized output. Usually a StreamResult,
152 * but other kinds of Result are possible.
153 * @param params The serialization properties, including character maps
154 * @return the newly constructed Receiver that performs the required serialization
155 * @throws XPathException if a serializer cannot be created
156 */
157
158 public Receiver getReceiver(Result result, SerializationProperties params) throws XPathException {
159 return getReceiver(result, params, config.makePipelineConfiguration());
160 }
161
162 /**
163 * Get a Receiver that wraps a given Result object. Saxon calls this method to construct
164 * a serialization pipeline. The method can be overridden in a subclass; alternatively, the
165 * subclass can override the various methods used to instantiate components of the serialization
166 * pipeline.
167 * <p>Note that this method ignores the {@link SaxonOutputKeys#WRAP} output property. If
168 * wrapped output is required, the user must create a {@link net.sf.saxon.query.SequenceWrapper} directly.</p>
169 * <p>The effect of the method changes in Saxon 9.7 so that for serialization methods other than
170 * "json" and "adaptive", the returned Receiver performs the function of "sequence normalization" as
171 * defined in the Serialization specification. Previously the client code handled this by wrapping the
172 * result in a ComplexContentOutputter (usually as a side-effect of called XPathContext.changeOutputDestination()).
173 * Wrapping in a ComplexContentOutputter is no longer necessary, though it does no harm because the ComplexContentOutputter
174 * is idempotent.</p>
175 *
176 * @param result The final destination of the serialized output. Usually a StreamResult,
177 * but other kinds of Result are possible.
178 * @param params The serialization properties, including character maps
179 * @param pipe The PipelineConfiguration.
180 * @return the newly constructed Receiver that performs the required serialization
181 * @throws XPathException if a serializer cannot be created
182 */
183
184 public Receiver getReceiver(Result result,
185 SerializationProperties params,
186 PipelineConfiguration pipe)
187 throws XPathException {
188
189 Objects.requireNonNull(result);
190 Objects.requireNonNull(params);
191 Objects.requireNonNull(pipe);
192
193 Properties props = params.getProperties();
194 CharacterMapIndex charMapIndex = params.getCharacterMapIndex();
195 if (charMapIndex == null) {
196 charMapIndex = new CharacterMapIndex();
197 }
198 String nextInChain = props.getProperty(SaxonOutputKeys.NEXT_IN_CHAIN);
199 if (nextInChain != null && !nextInChain.isEmpty()) {
200 String href = props.getProperty(SaxonOutputKeys.NEXT_IN_CHAIN);
201 String base = props.getProperty(SaxonOutputKeys.NEXT_IN_CHAIN_BASE_URI);
202 if (base == null) {
203 base = "";
204 }
205 Properties sansNext = new Properties(props);
206 sansNext.setProperty(SaxonOutputKeys.NEXT_IN_CHAIN, "");
207 return prepareNextStylesheet(pipe, href, base, result);
208 }
209 String paramDoc = props.getProperty(SaxonOutputKeys.PARAMETER_DOCUMENT);
210 if (paramDoc != null) {
211 String base = props.getProperty(SaxonOutputKeys.PARAMETER_DOCUMENT_BASE_URI);
212 if (base == null) {
213 base = result.getSystemId();
214 }
215 Properties props2 = new Properties(props);
216 Source source;
217 try {
218 source = config.getURIResolver().resolve(paramDoc, base);
219 } catch (TransformerException e) {
220 throw XPathException.makeXPathException(e);
221 }
222 ParseOptions options = new ParseOptions();
223 options.setSchemaValidationMode(Validation.LAX);
224 TreeInfo doc = config.buildDocumentTree(source);
225 SerializationParamsHandler ph = new SerializationParamsHandler();
226 ph.setSerializationParams(doc.getRootNode());
227 Properties paramDocProps = ph.getSerializationProperties().getProperties();
228 Enumeration<?> names = paramDocProps.propertyNames();
229 while (names.hasMoreElements()) {
230 String name = (String)names.nextElement();
231 String value = paramDocProps.getProperty(name);
232 props2.setProperty(name, value);
233 }
234 CharacterMap charMap = ph.getCharacterMap();
235 if (charMap != null) {
236 props2.setProperty(SaxonOutputKeys.USE_CHARACTER_MAPS, charMap.getName().getClarkName());
237 charMapIndex.putCharacterMap(charMap.getName(), charMap);
238 }
239 props = props2;
240 }
241 if (result instanceof StreamResult) {
242
243 // The "target" is the start of the output pipeline, the Receiver that
244 // instructions will actually write to (except that other things like a
245 // NamespaceReducer may get added in front of it). The "emitter" is the
246 // last thing in the output pipeline, the Receiver that actually generates
247 // characters or bytes that are written to the StreamResult.
248
249 SequenceReceiver target;
250 String method = props.getProperty(OutputKeys.METHOD);
251 if (method == null) {
252 return newUncommittedSerializer(result, new Sink(pipe), params);
253 }
254
255 Emitter emitter = null;
256
257 switch (method) {
258 case "html": {
259 emitter = newHTMLEmitter(props);
260 emitter.setPipelineConfiguration(pipe);
261 target = createHTMLSerializer(emitter, params, pipe);
262 break;
263 }
264 case "xml": {
265 emitter = newXMLEmitter(props);
266 emitter.setPipelineConfiguration(pipe);
267 target = createXMLSerializer((XMLEmitter) emitter, params);
268 break;
269 }
270 case "xhtml": {
271 emitter = newXHTMLEmitter(props);
272 emitter.setPipelineConfiguration(pipe);
273 target = createXHTMLSerializer(emitter, params, pipe);
274 break;
275 }
276 case "text": {
277 emitter = newTEXTEmitter();
278 emitter.setPipelineConfiguration(pipe);
279 target = createTextSerializer(emitter, params);
280 break;
281 }
282 case "json": {
283 StreamResult sr = (StreamResult) result;
284 props.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
285 JSONEmitter je = new JSONEmitter(pipe, sr, props);
286 JSONSerializer js = new JSONSerializer(pipe, je, props);
287 String sortOrder = props.getProperty(SaxonOutputKeys.PROPERTY_ORDER);
288 if (sortOrder != null) {
289 js.setPropertySorter(getPropertySorter(sortOrder));
290 }
291 CharacterMapExpander characterMapExpander = makeCharacterMapExpander(pipe, props, charMapIndex);
292 ProxyReceiver normalizer = makeUnicodeNormalizer(pipe, props);
293 return customizeJSONSerializer(js, props, characterMapExpander, normalizer);
294
295 }
296 case "adaptive": {
297 ExpandedStreamResult esr = new ExpandedStreamResult(pipe.getConfiguration(), (StreamResult)result, props);
298 Writer writer = esr.obtainWriter();
299 AdaptiveEmitter je = new AdaptiveEmitter(pipe, writer);
300 je.setOutputProperties(props);
301 CharacterMapExpander characterMapExpander = makeCharacterMapExpander(pipe, props, charMapIndex);
302 ProxyReceiver normalizer = makeUnicodeNormalizer(pipe, props);
303 return customizeAdaptiveSerializer(je, props, characterMapExpander, normalizer);
304 }
305 default: {
306 if (method.startsWith("{" + NamespaceConstant.SAXON + "}")) {
307 CharacterMapExpander characterMapExpander = makeCharacterMapExpander(pipe, props, charMapIndex);
308 ProxyReceiver normalizer = makeUnicodeNormalizer(pipe, props);
309 target = createSaxonSerializationMethod(
310 method, params, pipe, characterMapExpander, normalizer, (StreamResult)result);
311 if (target instanceof Emitter) {
312 emitter = (Emitter) target;
313 }
314 } else {
315 Receiver userReceiver;
316 if (pipe == null) {
317 throw new XPathException("Unsupported serialization method " + method);
318 } else {
319 userReceiver = createUserDefinedOutputMethod(method, props, pipe);
320 if (userReceiver instanceof Emitter) {
321 emitter = (Emitter) userReceiver;
322 target = params.makeSequenceNormalizer(emitter);
323 } else {
324 return params.makeSequenceNormalizer(userReceiver);
325 }
326 }
327 }
328 }
329 }
330 if (emitter != null) {
331 emitter.setOutputProperties(props);
332 StreamResult sr = (StreamResult) result;
333 emitter.setStreamResult(sr);
334 }
335 //target = new RegularSequenceChecker(target); // add this back in for diagnostics only
336 target.setSystemId(result.getSystemId());
337 return target;
338 } else {
339 // Handle results other than StreamResult: these generally do not involve serialization
340 return getReceiverForNonSerializedResult(result, props, pipe);
341
342 }
343 }
344
345 private ProxyReceiver makeUnicodeNormalizer(PipelineConfiguration pipe, Properties props) throws XPathException {
346 String normForm = props.getProperty(SaxonOutputKeys.NORMALIZATION_FORM);
347 if (normForm != null && !normForm.equals("none")) {
348 return newUnicodeNormalizer(new Sink(pipe), props);
349 }
350 return null;
351 }
352
353 private CharacterMapExpander makeCharacterMapExpander(PipelineConfiguration pipe, Properties props, CharacterMapIndex charMapIndex) throws XPathException {
354 String useMaps = props.getProperty(SaxonOutputKeys.USE_CHARACTER_MAPS);
355 if (useMaps != null) {
356 return charMapIndex.makeCharacterMapExpander(useMaps, new Sink(pipe), this);
357 }
358 return null;
359 }
360
361 /**
362 * Get a Receiver to handle a result other than a StreamResult. This will generally not involve
363 * serialization.
364 * @param result the destination
365 * @param props the serialization parameters (which in most cases will be ignored)
366 * @param pipe the pipeline configuration
367 * @return a suitable receiver to accept the raw query or transformation results
368 * @throws XPathException if any failure occurs
369 */
370
371 private Receiver getReceiverForNonSerializedResult(Result result, Properties props, PipelineConfiguration pipe) throws XPathException {
372 if (result instanceof Emitter) {
373 if (((Emitter) result).getOutputProperties() == null) {
374 ((Emitter) result).setOutputProperties(props);
375 }
376 return (Emitter) result;
377 } else if (result instanceof JSONSerializer) {
378 if (((JSONSerializer) result).getOutputProperties() == null) {
379 ((JSONSerializer) result).setOutputProperties(props);
380 }
381 return (JSONSerializer) result;
382 } else if (result instanceof AdaptiveEmitter) {
383 if (((AdaptiveEmitter) result).getOutputProperties() == null) {
384 ((AdaptiveEmitter) result).setOutputProperties(props);
385 }
386 return (AdaptiveEmitter) result;
387 } else if (result instanceof ComplexContentOutputter) {
388 return (ComplexContentOutputter)result;
389 } else if (result instanceof Receiver) {
390 Receiver receiver = (Receiver) result;
391 receiver.setSystemId(result.getSystemId());
392 receiver.setPipelineConfiguration(pipe);
393 if (((Receiver) result).handlesAppend() && "no".equals(props.getProperty(SaxonOutputKeys.BUILD_TREE))) {
394 return receiver;
395 // TODO: handle item-separator
396 } else {
397 return new ComplexContentOutputter(receiver);
398 }
399 } else if (result instanceof SAXResult) {
400 ContentHandlerProxy proxy = newContentHandlerProxy();
401 proxy.setUnderlyingContentHandler(((SAXResult) result).getHandler());
402 proxy.setPipelineConfiguration(pipe);
403 proxy.setOutputProperties(props);
404 if ("yes".equals(props.getProperty(SaxonOutputKeys.SUPPLY_SOURCE_LOCATOR))) {
405 if (config.isCompileWithTracing() && pipe.getController() != null) {
406 pipe.getController().addTraceListener(proxy.getTraceListener());
407 } else {
408 throw new XPathException(
409 "Cannot use saxon:supply-source-locator unless tracing was enabled at compile time", SaxonErrorCode.SXSE0002);
410 }
411 }
412 //proxy.open();
413 return makeSequenceNormalizer(proxy, props);
414 //#if DOTNET == false
415 } else if (result instanceof StAXResult) {
416 StAXResultHandler handler = new StAXResultHandlerImpl();
417 Receiver r = handler.getReceiver(result, props);
418 r.setPipelineConfiguration(pipe);
419 return makeSequenceNormalizer(r, props);
420 //#endif
421 } else {
422 if (pipe != null) {
423 // try to find an external object model that knows this kind of Result
424 List externalObjectModels = pipe.getConfiguration().getExternalObjectModels();
425 for (Object externalObjectModel : externalObjectModels) {
426 ExternalObjectModel model = (ExternalObjectModel) externalObjectModel;
427 Receiver builder = model.getDocumentBuilder(result);
428 if (builder != null) {
429 builder.setSystemId(result.getSystemId());
430 builder.setPipelineConfiguration(pipe);
431 return new TreeReceiver(builder);
432 }
433 }
434 }
435 }
436
437 throw new IllegalArgumentException("Unknown type of result: " + result.getClass());
438 }
439
440 public SequenceReceiver makeSequenceNormalizer(Receiver receiver, Properties properties) {
441 String method = properties.getProperty(OutputKeys.METHOD);
442 if ("json".equals(method) || "adaptive".equals(method)) {
443 return receiver instanceof SequenceReceiver ? (SequenceReceiver)receiver : new TreeReceiver(receiver);
444 } else {
445 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
446 SequenceReceiver result;
447 String separator = properties.getProperty(SaxonOutputKeys.ITEM_SEPARATOR);
448 if (separator == null || "#absent".equals(separator)) {
449 result = new SequenceNormalizerWithSpaceSeparator(receiver);
450 } else {
451 result = new SequenceNormalizerWithItemSeparator(receiver, separator);
452 }
453 result.setPipelineConfiguration(pipe);
454 return result;
455 }
456 }
457
458 /**
459 * Create a serialization pipeline to implement the HTML output method. This method is protected
460 * so that it can be customized in a user-written SerializerFactory
461 *
462 * @param emitter the emitter at the end of the pipeline (created using the method {@link #newHTMLEmitter}
463 * @param params the serialization properties
464 * @param pipe the pipeline configuration information
465 * @return a Receiver acting as the entry point to the serialization pipeline
466 * @throws XPathException if a failure occurs
467 */
468
469 protected SequenceReceiver createHTMLSerializer(
470 Emitter emitter, SerializationProperties params, PipelineConfiguration pipe) throws XPathException {
471 Receiver target;
472 target = emitter;
473 Properties props = params.getProperties();
474 if (!"no".equals(props.getProperty(OutputKeys.INDENT))) {
475 target = newHTMLIndenter(target, props);
476 }
477 target = injectUnicodeNormalizer(params, target);
478 target = injectCharacterMapExpander(params, target, true);
479 String cdataElements = props.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
480 if (cdataElements != null && !cdataElements.isEmpty()) {
481 target = newCDATAFilter(target, props);
482 }
483
484 if (SaxonOutputKeys.isHtmlVersion5(props)) {
485 target = addHtml5Component(target, props);
486 }
487
488 if (!"no".equals(props.getProperty(SaxonOutputKeys.ESCAPE_URI_ATTRIBUTES))) {
489 target = newHTMLURIEscaper(target, props);
490 }
491 if (!"no".equals(props.getProperty(SaxonOutputKeys.INCLUDE_CONTENT_TYPE))) {
492 target = newHTMLMetaTagAdjuster(target, props);
493 }
494 String attributeOrder = props.getProperty(SaxonOutputKeys.ATTRIBUTE_ORDER);
495 if (attributeOrder != null && !attributeOrder.isEmpty()) {
496 target = newAttributeSorter(target, props);
497 }
498 if (params.getValidationFactory() != null) {
499 target = params.getValidationFactory().makeFilter(target);
500 }
501 return makeSequenceNormalizer(target, props);
502 }
503
504 /**
505 * Create a serialization pipeline to implement the text output method. This method is protected
506 * so that it can be customized in a user-written SerializerFactory
507 *
508 * @param emitter the emitter at the end of the pipeline (created using the method {@link #newTEXTEmitter}
509 * @param params the serialization properties
510 * @return a Receiver acting as the entry point to the serialization pipeline
511 * @throws XPathException if a failure occurs
512 */
513
514 protected SequenceReceiver createTextSerializer(
515 Emitter emitter, SerializationProperties params) throws XPathException {
516 Properties props = params.getProperties();
517 Receiver target;
518 target = injectUnicodeNormalizer(params, emitter);
519 target = injectCharacterMapExpander(params, target, false);
520 target = addTextOutputFilter(target, props);
521 if (params.getValidationFactory() != null) {
522 target = params.getValidationFactory().makeFilter(target);
523 }
524 return makeSequenceNormalizer(target, props);
525 }
526
527 /**
528 * Create a serialization pipeline to implement the JSON output method. This method is protected
529 * so that it can be customized in a user-written SerializerFactory
530 *
531 * @param emitter the emitter at the end of the pipeline (created using the method {@link #newTEXTEmitter}
532 * @param props the serialization properties
533 * @param characterMapExpander the filter to be used for expanding character maps defined in the stylesheet
534 * @param normalizer the filter used for Unicode normalization
535 * @return a Receiver acting as the entry point to the serialization pipeline
536 */
537
538 protected SequenceReceiver customizeJSONSerializer(
539 JSONSerializer emitter, Properties props,
540 CharacterMapExpander characterMapExpander, ProxyReceiver normalizer) throws XPathException {
541 if (normalizer instanceof UnicodeNormalizer) {
542 emitter.setNormalizer(((UnicodeNormalizer)normalizer).getNormalizer());
543 }
544 if (characterMapExpander != null) {
545 emitter.setCharacterMap(characterMapExpander.getCharacterMap());
546 }
547 return emitter;
548 }
549
550 /**
551 * Create a serialization pipeline to implement the Adaptive output method. This method is protected
552 * so that it can be customized in a user-written SerializerFactory
553 *
554 * @param emitter the emitter at the end of the pipeline
555 * @param props the serialization properties
556 * @param characterMapExpander the filter to be used for expanding character maps defined in the stylesheet
557 * @param normalizer the filter used for Unicode normalization
558 * @return a Receiver acting as the entry point to the serialization pipeline
559 */
560
561 protected SequenceReceiver customizeAdaptiveSerializer(
562 AdaptiveEmitter emitter, Properties props,
563 CharacterMapExpander characterMapExpander, ProxyReceiver normalizer) {
564 if (normalizer instanceof UnicodeNormalizer) {
565 emitter.setNormalizer(((UnicodeNormalizer) normalizer).getNormalizer());
566 }
567 if (characterMapExpander != null) {
568 emitter.setCharacterMap(characterMapExpander.getCharacterMap());
569 }
570 return emitter;
571 }
572
573
574 /**
575 * Create a serialization pipeline to implement the XHTML output method. This method is protected
576 * so that it can be customized in a user-written SerializerFactory
577 *
578 * @param emitter the emitter at the end of the pipeline (created using the method {@link #newXHTMLEmitter}
579 * @param params the serialization properties
580 * @param pipe the pipeline configuration information
581 * @return a Receiver acting as the entry point to the serialization pipeline
582 * @throws XPathException if a failure occurs
583 */
584
585 protected SequenceReceiver createXHTMLSerializer(
586 Emitter emitter, SerializationProperties params, PipelineConfiguration pipe) throws XPathException {
587 Receiver target = emitter;
588 Properties props = params.getProperties();
589 if (!"no".equals(props.getProperty(OutputKeys.INDENT))) {
590 target = newXHTMLIndenter(target, props);
591 }
592 target = injectUnicodeNormalizer(params, target);
593 target = injectCharacterMapExpander(params, target, true);
594 String cdataElements = props.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
595 if (cdataElements != null && !cdataElements.isEmpty()) {
596 target = newCDATAFilter(target, props);
597 }
598
599 if (SaxonOutputKeys.isXhtmlHtmlVersion5(props)) {
600 target = addHtml5Component(target, props);
601 }
602 if (!"no".equals(props.getProperty(SaxonOutputKeys.ESCAPE_URI_ATTRIBUTES))) {
603 target = newXHTMLURIEscaper(target, props);
604 }
605 if (!"no".equals(props.getProperty(SaxonOutputKeys.INCLUDE_CONTENT_TYPE))) {
606 target = newXHTMLMetaTagAdjuster(target, props);
607 }
608 String attributeOrder = props.getProperty(SaxonOutputKeys.ATTRIBUTE_ORDER);
609 if (attributeOrder != null && !attributeOrder.isEmpty()) {
610 target = newAttributeSorter(target, props);
611 }
612 if (params.getValidationFactory() != null) {
613 target = params.getValidationFactory().makeFilter(target);
614 }
615 return makeSequenceNormalizer(target, props);
616 }
617
618 /**
619 * This method constructs a step in the output pipeline to perform namespace-related
620 * tasks for HTML5 serialization. The default implementation adds a NamespaceReducer
621 * and an XHTMLPrefixRemover
622 *
623 * @param target the Receiver that receives the output of this step
624 * @param outputProperties the serialization properties
625 * @return a new Receiver to perform HTML5-related namespace manipulation
626 */
627
628 public Receiver addHtml5Component(Receiver target, Properties outputProperties) {
629 target = new NamespaceReducer(target);
630 target = new XHTMLPrefixRemover(target);
631 return target;
632 }
633
634 /**
635 * Create a serialization pipeline to implement the XML output method. This method is protected
636 * so that it can be customized in a user-written SerializerFactory
637 *
638 * @param emitter the emitter at the end of the pipeline (created using the method {@link #newXHTMLEmitter}
639 * @param params the serialization properties
640 * @return a Receiver acting as the entry point to the serialization pipeline
641 * @throws XPathException if a failure occurs
642 */
643
644 protected SequenceReceiver createXMLSerializer(
645 XMLEmitter emitter, SerializationProperties params) throws XPathException {
646 Receiver target;
647 Properties props = params.getProperties();
648 boolean canonical = "yes".equals(props.getProperty(SaxonOutputKeys.CANONICAL));
649 if ("yes".equals(props.getProperty(OutputKeys.INDENT)) || canonical) {
650 target = newXMLIndenter(emitter, props);
651 } else {
652 target = emitter;
653 }
654 if ("1.0".equals(props.getProperty(OutputKeys.VERSION)) &&
655 config.getXMLVersion() == Configuration.XML11) {
656 // Check result meets XML 1.0 constraints if configuration allows XML 1.1 input but
657 // this result document must conform to 1.0
658 target = newXML10ContentChecker(target, props);
659 }
660 target = injectUnicodeNormalizer(params, target);
661 if (!canonical) {
662 target = injectCharacterMapExpander(params, target, true);
663 }
664 String cdataElements = props.getProperty(OutputKeys.CDATA_SECTION_ELEMENTS);
665 if (cdataElements != null && !cdataElements.isEmpty() && !canonical) {
666 target = newCDATAFilter(target, props);
667 }
668 if (canonical) {
669 target = newAttributeSorter(target, props);
670 target = newNamespaceSorter(target, props);
671 } else {
672 String attributeOrder = props.getProperty(SaxonOutputKeys.ATTRIBUTE_ORDER);
673 if (attributeOrder != null && !attributeOrder.isEmpty()) {
674 target = newAttributeSorter(target, props);
675 }
676 }
677 if (params.getValidationFactory() != null) {
678 target = params.getValidationFactory().makeFilter(target);
679 }
680 return makeSequenceNormalizer(target, props);
681 }
682
683 protected SequenceReceiver createSaxonSerializationMethod(
684 String method, SerializationProperties params,
685 PipelineConfiguration pipe, CharacterMapExpander characterMapExpander,
686 ProxyReceiver normalizer, StreamResult result) throws XPathException {
687 throw new XPathException("Saxon serialization methods require Saxon-PE to be enabled");
688 }
689
690 /**
691 * Create a serialization pipeline to implement a user-defined output method. This method is protected
692 * so that it can be customized in a user-written SerializerFactory
693 *
694 * @param method the name of the user-defined output method, as a QName in Clark format
695 * (that is "{uri}local").
696 * @param props the serialization properties
697 * @param pipe the pipeline configuration information
698 * @return a Receiver acting as the entry point to the serialization pipeline
699 * @throws XPathException if a failure occurs
700 */
701
702 protected SequenceReceiver createUserDefinedOutputMethod(String method, Properties props, PipelineConfiguration pipe) throws XPathException {
703 Receiver userReceiver;// See if this output method is recognized by the Configuration
704 userReceiver = pipe.getConfiguration().makeEmitter(method, props);
705 userReceiver.setPipelineConfiguration(pipe);
706 if (userReceiver instanceof ContentHandlerProxy &&
707 "yes".equals(props.getProperty(SaxonOutputKeys.SUPPLY_SOURCE_LOCATOR))) {
708 if (pipe.getConfiguration().isCompileWithTracing() && pipe.getController() != null) {
709 pipe.getController().addTraceListener(
710 ((ContentHandlerProxy) userReceiver).getTraceListener());
711 } else {
712 throw new XPathException(
713 "Cannot use saxon:supply-source-locator unless tracing was enabled at compile time", SaxonErrorCode.SXSE0002);
714 }
715 }
716 return userReceiver instanceof SequenceReceiver ? (SequenceReceiver)userReceiver : new TreeReceiver(userReceiver);
717 }
718
719 protected Receiver injectCharacterMapExpander(SerializationProperties params, Receiver out, boolean useNullMarkers) throws XPathException {
720 CharacterMapIndex charMapIndex = params.getCharacterMapIndex();
721 if (charMapIndex != null) {
722 String useMaps = params.getProperties().getProperty(SaxonOutputKeys.USE_CHARACTER_MAPS);
723 if (useMaps != null) {
724 CharacterMapExpander expander = charMapIndex.makeCharacterMapExpander(useMaps, out, this);
725 expander.setUseNullMarkers(useNullMarkers);
726 return expander;
727 }
728 }
729 return out;
730 }
731
732 protected Receiver injectUnicodeNormalizer(SerializationProperties params, Receiver out) throws XPathException {
733 Properties props = params.getProperties();
734 String normForm = props.getProperty(SaxonOutputKeys.NORMALIZATION_FORM);
735 if (normForm != null && !normForm.equals("none")) {
736 return newUnicodeNormalizer(out, props);
737 }
738 return out;
739 }
740
741 /**
742 * Create a ContentHandlerProxy. This method exists so that it can be overridden in a subclass.
743 *
744 * @return the newly created ContentHandlerProxy.
745 */
746
747 protected ContentHandlerProxy newContentHandlerProxy() {
748 return new ContentHandlerProxy();
749 }
750
751 /**
752 * Create an UncommittedSerializer. This method exists so that it can be overridden in a subclass.
753 *
754 * @param result the result destination
755 * @param next the next receiver in the pipeline
756 * @param params the serialization parameters
757 * @return the newly created UncommittedSerializer.
758 */
759
760 protected UncommittedSerializer newUncommittedSerializer(Result result, Receiver next, SerializationProperties params) {
761 return new UncommittedSerializer(result, next, params);
762 }
763
764 /**
765 * Create a new XML Emitter. This method exists so that it can be overridden in a subclass.
766 *
767 * @param properties the output properties
768 * @return the newly created XML emitter.
769 */
770
771 protected Emitter newXMLEmitter(Properties properties) {
772 return new XMLEmitter();
773 }
774
775 /**
776 * Create a new HTML Emitter. This method exists so that it can be overridden in a subclass.
777 *
778 * @param properties the output properties
779 * @return the newly created HTML emitter.
780 */
781
782 protected Emitter newHTMLEmitter(Properties properties) {
783 HTMLEmitter emitter;
784 // Note, we recognize html-version even when running XSLT 2.0.
785 if (SaxonOutputKeys.isHtmlVersion5(properties)) {
786 emitter = new HTML50Emitter();
787 } else {
788 emitter = new HTML40Emitter();
789 }
790 return emitter;
791 }
792
793 /**
794 * Create a new XHTML Emitter. This method exists so that it can be overridden in a subclass.
795 *
796 * @param properties the output properties
797 * @return the newly created XHTML emitter.
798 */
799
800 protected Emitter newXHTMLEmitter(Properties properties) {
801 boolean is5 = SaxonOutputKeys.isXhtmlHtmlVersion5(properties);
802 return is5 ? new XHTML5Emitter() : new XHTML1Emitter();
803 }
804
805 /**
806 * Add a filter to the text output method pipeline. This does nothing unless overridden
807 * in a subclass
808 *
809 * @param next the next receiver (typically the TextEmitter)
810 * @param properties the output properties
811 * @return the receiver to be used in place of the "next" receiver
812 * @throws XPathException if the operation fails
813 */
814
815 public Receiver addTextOutputFilter(Receiver next, Properties properties) throws XPathException {
816 return next;
817 }
818
819 /**
820 * Create a new Text Emitter. This method exists so that it can be overridden in a subclass.
821 *
822 * @return the newly created text emitter.
823 */
824
825 protected Emitter newTEXTEmitter() {
826 return new TEXTEmitter();
827 }
828
829 /**
830 * Create a new XML Indenter. This method exists so that it can be overridden in a subclass.
831 *
832 * @param next the next receiver in the pipeline
833 * @param outputProperties the serialization parameters
834 * @return the newly created XML indenter.
835 */
836
837 protected ProxyReceiver newXMLIndenter(XMLEmitter next, Properties outputProperties) {
838 XMLIndenter r = new XMLIndenter(next);
839 r.setOutputProperties(outputProperties);
840 return r;
841 }
842
843 /**
844 * Create a new HTML Indenter. This method exists so that it can be overridden in a subclass.
845 *
846 * @param next the next receiver in the pipeline
847 * @param outputProperties the serialization parameters
848 * @return the newly created HTML indenter.
849 */
850
851 protected ProxyReceiver newHTMLIndenter(Receiver next, Properties outputProperties) {
852 HTMLIndenter r = new HTMLIndenter(next, "html");
853 r.setOutputProperties(outputProperties);
854 return r;
855 }
856
857 /**
858 * Create a new XHTML Indenter. This method exists so that it can be overridden in a subclass.
859 *
860 * @param next the next receiver in the pipeline
861 * @param outputProperties the serialization parameters
862 * @return the newly created XHTML indenter.
863 */
864
865 protected ProxyReceiver newXHTMLIndenter(Receiver next, Properties outputProperties) {
866 String method = "xhtml";
867 String htmlVersion = outputProperties.getProperty("html-version");
868 if (htmlVersion != null && htmlVersion.startsWith("5")) {
869 method="xhtml5";
870 }
871 HTMLIndenter r = new HTMLIndenter(next, method);
872 r.setOutputProperties(outputProperties);
873 return r;
874 }
875
876 /**
877 * Create a new XHTML MetaTagAdjuster, responsible for insertion, removal, or replacement of meta
878 * elements. This method exists so that it can be overridden in a subclass.
879 *
880 * @param next the next receiver in the pipeline
881 * @param outputProperties the serialization parameters
882 * @return the newly created XHTML MetaTagAdjuster.
883 */
884
885 protected MetaTagAdjuster newXHTMLMetaTagAdjuster(Receiver next, Properties outputProperties) {
886 MetaTagAdjuster r = new MetaTagAdjuster(next);
887 r.setIsXHTML(true);
888 r.setOutputProperties(outputProperties);
889 return r;
890 }
891
892 /**
893 * Create a new XHTML MetaTagAdjuster, responsible for insertion, removal, or replacement of meta
894 * elements. This method exists so that it can be overridden in a subclass.
895 *
896 * @param next the next receiver in the pipeline
897 * @param outputProperties the serialization parameters
898 * @return the newly created HTML MetaTagAdjuster.
899 */
900
901 protected MetaTagAdjuster newHTMLMetaTagAdjuster(Receiver next, Properties outputProperties) {
902 MetaTagAdjuster r = new MetaTagAdjuster(next);
903 r.setIsXHTML(false);
904 r.setOutputProperties(outputProperties);
905 return r;
906 }
907
908 /**
909 * Create a new HTML URI Escaper, responsible for percent-encoding of URIs in
910 * HTML output documents. This method exists so that it can be overridden in a subclass.
911 *
912 * @param next the next receiver in the pipeline
913 * @param outputProperties the serialization parameters
914 * @return the newly created HTML URI escaper.
915 */
916
917 protected ProxyReceiver newHTMLURIEscaper(Receiver next, Properties outputProperties) {
918 return new HTMLURIEscaper(next);
919 }
920
921 /**
922 * Create a new XHTML URI Escaper, responsible for percent-encoding of URIs in
923 * HTML output documents. This method exists so that it can be overridden in a subclass.
924 *
925 * @param next the next receiver in the pipeline
926 * @param outputProperties the serialization parameters
927 * @return the newly created HTML URI escaper.
928 */
929
930 protected ProxyReceiver newXHTMLURIEscaper(Receiver next, Properties outputProperties) {
931 return new XHTMLURIEscaper(next);
932 }
933
934 /**
935 * Create a new CDATA Filter, responsible for insertion of CDATA sections where required.
936 * This method exists so that it can be overridden in a subclass.
937 *
938 * @param next the next receiver in the pipeline
939 * @param outputProperties the serialization parameters
940 * @return the newly created CDATA filter.
941 * @throws net.sf.saxon.trans.XPathException
942 * if an error occurs
943 */
944
945 protected ProxyReceiver newCDATAFilter(Receiver next, Properties outputProperties) throws XPathException {
946 CDATAFilter r = new CDATAFilter(next);
947 r.setOutputProperties(outputProperties);
948 return r;
949 }
950
951 /**
952 * Create a new AttributeSorter, responsible for sorting of attributes into a specified order.
953 * This method exists so that it can be overridden in a subclass. The Saxon-HE version of
954 * this method returns the supplied receiver unchanged (attribute sorting is not supported
955 * in Saxon-HE). The AttributeSorter handles both sorting of attributes into a user-specified
956 * order (saxon:attribute-order) and sorting into C14N order (saxon:canonical).
957 *
958 * @param next the next receiver in the pipeline
959 * @param outputProperties the serialization parameters
960 * @return the newly created filter.
961 */
962
963 protected Receiver newAttributeSorter(Receiver next, Properties outputProperties) throws XPathException {
964 return next;
965 }
966
967 /**
968 * Create a new NamespaceSorter, responsible for sorting of namespaces into a specified order.
969 *
970 * @param next the next receiver in the pipeline
971 * @param outputProperties the serialization parameters
972 * @return the newly created filter.
973 */
974
975 protected Receiver newNamespaceSorter(Receiver next, Properties outputProperties) throws XPathException {
976 return next;
977 }
978
979 /**
980 * Create a new XML 1.0 content checker, responsible for checking that the output conforms to
981 * XML 1.0 rules (this is used only if the Configuration supports XML 1.1 but the specific output
982 * file requires XML 1.0). This method exists so that it can be overridden in a subclass.
983 *
984 * @param next the next receiver in the pipeline
985 * @param outputProperties the serialization parameters
986 * @return the newly created XML 1.0 content checker.
987 */
988
989 protected ProxyReceiver newXML10ContentChecker(Receiver next, Properties outputProperties) {
990 return new XML10ContentChecker(next);
991 }
992
993 /**
994 * Create a Unicode Normalizer. This method exists so that it can be overridden in a subclass.
995 *
996 * @param next the next receiver in the pipeline
997 * @param outputProperties the serialization parameters
998 * @return the newly created Unicode normalizer.
999 * @throws net.sf.saxon.trans.XPathException
1000 * if an error occurs
1001 */
1002
1003 protected ProxyReceiver newUnicodeNormalizer(Receiver next, Properties outputProperties) throws XPathException {
1004 String normForm = outputProperties.getProperty(SaxonOutputKeys.NORMALIZATION_FORM);
1005 return new UnicodeNormalizer(normForm, next);
1006 }
1007
1008 /**
1009 * Create a new CharacterMapExpander. This method exists so that it can be overridden in a subclass.
1010 *
1011 * @param next the next receiver in the pipeline
1012 * @return the newly created CharacterMapExpander.
1013 */
1014
1015 public CharacterMapExpander newCharacterMapExpander(Receiver next) {
1016 return new CharacterMapExpander(next);
1017 }
1018
1019 /**
1020 * Prepare another stylesheet to handle the output of this one.
1021 * <p>This method is intended for internal use, to support the
1022 * <code>saxon:next-in-chain</code> extension.</p>
1023 *
1024 * @param pipe the current transformation
1025 * @param href URI of the next stylesheet to be applied
1026 * @param baseURI base URI for resolving href if it's a relative
1027 * URI
1028 * @param result the output destination of the current stylesheet
1029 * @return a replacement destination for the current stylesheet
1030 * @throws XPathException if any dynamic error occurs
1031 */
1032
1033 public SequenceReceiver prepareNextStylesheet(PipelineConfiguration pipe, String href, String baseURI, Result result)
1034 throws XPathException {
1035 pipe.getConfiguration().checkLicensedFeature(Configuration.LicenseFeature.PROFESSIONAL_EDITION, "saxon:next-in-chain", -1);
1036 return null;
1037 }
1038
1039 /**
1040 * Get a SequenceWrapper, a class that serializes an XDM sequence with full annotation of item types, node kinds,
1041 * etc. There are variants for Saxon-HE and Saxon-PE
1042 * @param destination the place where the wrapped sequence will be sent
1043 * @return the new SequenceWrapper
1044 */
1045
1046 public SequenceWrapper newSequenceWrapper(Receiver destination) {
1047 return new SequenceWrapper(destination);
1048 }
1049
1050 /**
1051 * Check that a supplied output property is valid, and normalize the value (specifically in the case of boolean
1052 * values where yes|true|1 are normalized to "yes", and no|false|0 are normalized to "no").
1053 *
1054 * @param key the name of the property, in Clark format
1055 * @param value the value of the property. This may be set to null, in which case no validation takes place.
1056 * The value must be in JAXP format, that is, with lexical QNames expanded to Clark names
1057 * @return normalized value of the property, or null if the supplied value is null
1058 * @throws XPathException if the property name or value is invalid
1059 */
1060
1061 public String checkOutputProperty(String key, String value) throws XPathException {
1062 if (!key.startsWith("{")) {
1063 switch (key) {
1064 case SaxonOutputKeys.ALLOW_DUPLICATE_NAMES:
1065 if (value != null) {
1066 value = checkYesOrNo(key, value);
1067 }
1068 break;
1069 case SaxonOutputKeys.BUILD_TREE:
1070 if (value != null) {
1071 value = checkYesOrNo(key, value);
1072 }
1073 break;
1074 case SaxonOutputKeys.BYTE_ORDER_MARK:
1075 if (value != null) {
1076 value = checkYesOrNo(key, value);
1077 }
1078 break;
1079 case OutputKeys.CDATA_SECTION_ELEMENTS:
1080 if (value != null) {
1081 checkListOfClarkNames(key, value);
1082 }
1083 break;
1084 case OutputKeys.DOCTYPE_PUBLIC:
1085 if (value != null) {
1086 checkPublicIdentifier(value);
1087 }
1088 break;
1089 case OutputKeys.DOCTYPE_SYSTEM:
1090 if (value != null) {
1091 checkSystemIdentifier(value);
1092 }
1093 break;
1094 case OutputKeys.ENCODING:
1095 // no constraints
1096 break;
1097 case SaxonOutputKeys.ESCAPE_URI_ATTRIBUTES:
1098 if (value != null) {
1099 value = checkYesOrNo(key, value);
1100 }
1101 break;
1102 case SaxonOutputKeys.HTML_VERSION:
1103 if (value != null) {
1104 checkDecimal(key, value);
1105 }
1106 break;
1107 case SaxonOutputKeys.INCLUDE_CONTENT_TYPE:
1108 if (value != null) {
1109 value = checkYesOrNo(key, value);
1110 }
1111 break;
1112 case OutputKeys.INDENT:
1113 if (value != null) {
1114 value = checkYesOrNo(key, value);
1115 }
1116 break;
1117 case SaxonOutputKeys.ITEM_SEPARATOR:
1118 // no checking needed
1119
1120 break;
1121 case OutputKeys.METHOD:
1122 case SaxonOutputKeys.JSON_NODE_OUTPUT_METHOD:
1123 if (value != null) {
1124 checkMethod(key, value);
1125 }
1126 break;
1127 case OutputKeys.MEDIA_TYPE:
1128 // no constraints
1129 break;
1130 case SaxonOutputKeys.NORMALIZATION_FORM:
1131 if (value != null) {
1132 checkNormalizationForm(value);
1133 }
1134 break;
1135 case OutputKeys.OMIT_XML_DECLARATION:
1136 if (value != null) {
1137 value = checkYesOrNo(key, value);
1138 }
1139 break;
1140 case OutputKeys.STANDALONE:
1141 if (value != null && !value.equals("omit")) {
1142 value = checkYesOrNo(key, value);
1143 }
1144 break;
1145 case SaxonOutputKeys.SUPPRESS_INDENTATION:
1146 if (value != null) {
1147 checkListOfClarkNames(key, value);
1148 }
1149 break;
1150 case SaxonOutputKeys.UNDECLARE_PREFIXES:
1151 if (value != null) {
1152 value = checkYesOrNo(key, value);
1153 }
1154 break;
1155 case SaxonOutputKeys.USE_CHARACTER_MAPS:
1156 if (value != null) {
1157 checkListOfClarkNames(key, value);
1158 }
1159 break;
1160 case OutputKeys.VERSION:
1161 // no constraints
1162
1163 break;
1164 case SaxonOutputKeys.PARAMETER_DOCUMENT:
1165 // no checking
1166 break;
1167 default:
1168 throw new XPathException("Unknown serialization parameter " + Err.wrap(key), "XQST0109");
1169 }
1170 } else if (key.startsWith("{http://saxon.sf.net/}")) {
1171 // Some Saxon serialization parameters are recognized in HE if they are used for internal purposes
1172 switch (key) {
1173 case SaxonOutputKeys.STYLESHEET_VERSION:
1174 // return
1175 break;
1176 case SaxonOutputKeys.PARAMETER_DOCUMENT_BASE_URI:
1177 // return
1178 break;
1179 case SaxonOutputKeys.SUPPLY_SOURCE_LOCATOR:
1180 if (value != null) {
1181 value = checkYesOrNo(key, value);
1182 }
1183 break;
1184 case SaxonOutputKeys.UNFAILING:
1185 if (value != null) {
1186 value = checkYesOrNo(key, value);
1187 }
1188 break;
1189 default:
1190 throw new XPathException("Serialization parameter " + Err.wrap(key) + " not available in Saxon-HE", "XQST0109");
1191 }
1192 } else {
1193 //return;
1194 }
1195 return value;
1196 }
1197
1198 protected static String checkYesOrNo(String key, String value) throws XPathException {
1199 if ("yes".equals(value) || "true".equals(value) || "1".equals(value)) {
1200 return "yes";
1201 } else if ("no".equals(value) || "false".equals(value) || "0".equals(value)) {
1202 return "no";
1203 } else {
1204 throw new XPathException("Serialization parameter " + Err.wrap(key) + " must have the value yes|no, true|false, or 1|0", "SEPM0016");
1205 }
1206 }
1207
1208 private void checkMethod(String key, String value) throws XPathException {
1209 if (!"xml".equals(value) && !"html".equals(value) && !"xhtml".equals(value) && !"text".equals(value)) {
1210 if (!SaxonOutputKeys.JSON_NODE_OUTPUT_METHOD.equals(key) && ("json".equals(value) || "adaptive".equals(value))) {
1211 return;
1212 }
1213 if (isValidClarkName(value)) {
1214 checkExtensions(value);
1215 } else {
1216 throw new XPathException("Invalid value (" + value + ") for serialization method: " +
1217 "must be xml|html|xhtml|text|json|adaptive, or a QName in '{uri}local' form", "SEPM0016");
1218 }
1219 }
1220
1221 }
1222
1223 private static void checkNormalizationForm(String value) throws XPathException {
1224 if (!NameChecker.isValidNmtoken(value)) {
1225 throw new XPathException("Invalid value for normalization-form: " +
1226 "must be NFC, NFD, NFKC, NFKD, fully-normalized, or none", "SEPM0016");
1227 }
1228 }
1229
1230 private static boolean isValidClarkName(/*@NotNull*/ String value) {
1231 if (value.isEmpty() || value.charAt(0) != '{') {
1232 return false;
1233 }
1234 int closer = value.indexOf('}');
1235 return closer >= 1 &&
1236 closer != value.length() - 1 &&
1237 NameChecker.isValidNCName(value.substring(closer + 1));
1238 }
1239
1240 protected static void checkNonNegativeInteger(String key, String value) throws XPathException {
1241 try {
1242 int n = Integer.parseInt(value);
1243 if (n < 0) {
1244 throw new XPathException("Value of " + Err.wrap(key) + " must be a non-negative integer", "SEPM0016");
1245 }
1246 } catch (NumberFormatException err) {
1247 throw new XPathException("Value of " + Err.wrap(key) + " must be a non-negative integer", "SEPM0016");
1248 }
1249 }
1250
1251 private static void checkDecimal(String key, String value) throws XPathException {
1252 if (!BigDecimalValue.castableAsDecimal(value)) {
1253 throw new XPathException("Value of " + Err.wrap(key) +
1254 " must be a decimal number", "SEPM0016");
1255 }
1256 }
1257
1258 protected static void checkListOfClarkNames(String key, String value) throws XPathException {
1259 StringTokenizer tok = new StringTokenizer(value, " \t\n\r", false);
1260 while (tok.hasMoreTokens()) {
1261 String s = tok.nextToken();
1262 if (isValidClarkName(s) || NameChecker.isValidNCName(s)) {
1263 // ok
1264 } else {
1265 throw new XPathException("Value of " + Err.wrap(key) +
1266 " must be a list of QNames in '{uri}local' notation", "SEPM0016");
1267 }
1268 }
1269 }
1270
1271 protected static void checkListOfClarkNamesAllowingStar(String key, String value) throws XPathException {
1272 StringTokenizer tok = new StringTokenizer(value, " \t\n\r", false);
1273 while (tok.hasMoreTokens()) {
1274 String s = tok.nextToken();
1275 if ("*".equals(s) || isValidClarkName(s) || NameChecker.isValidNCName(s)) {
1276 // ok
1277 } else {
1278 throw new XPathException("Value of " + Err.wrap(key) +
1279 " must be a list of QNames in '{uri}local' notation", "SEPM0016");
1280 }
1281 }
1282 }
1283
1284 private static Pattern publicIdPattern = Pattern.compile("^[\\s\\r\\na-zA-Z0-9\\-'()+,./:=?;!*#@$_%]*$");
1285
1286 private static void checkPublicIdentifier(String value) throws XPathException {
1287 if (!publicIdPattern.matcher(value).matches()) {
1288 throw new XPathException("Invalid character in doctype-public parameter", "SEPM0016");
1289 }
1290 }
1291
1292 private static void checkSystemIdentifier(/*@NotNull*/ String value) throws XPathException {
1293 if (value.contains("'") && value.contains("\"")) {
1294 throw new XPathException("The doctype-system parameter must not contain both an apostrophe and a quotation mark", "SEPM0016");
1295 }
1296 }
1297
1298 /**
1299 * Process a serialization property whose value is a list of element names, for example cdata-section-elements
1300 *
1301 * @param value The value of the property as written
1302 * @param nsResolver The namespace resolver to use; may be null if prevalidated is set or if names are supplied
1303 * in Clark format
1304 * @param useDefaultNS True if the namespace resolver should be used for unprefixed names; false if
1305 * unprefixed names should be considered to be in no namespace
1306 * @param prevalidated true if the property has already been validated
1307 * @param errorCode The error code to return in the event of problems
1308 * @return The list of element names with lexical QNames replaced by Clark names, starting with a single space
1309 * @throws XPathException if any error is found in the list of element names, for example, an undeclared namespace prefix
1310 */
1311
1312 /*@NotNull*/
1313 public static String parseListOfNodeNames(
1314 String value, NamespaceResolver nsResolver, boolean useDefaultNS, boolean prevalidated, /*@NotNull*/ String errorCode)
1315 throws XPathException {
1316 StringBuilder s = new StringBuilder();
1317 StringTokenizer st = new StringTokenizer(value, " \t\n\r", false);
1318 while (st.hasMoreTokens()) {
1319 String displayname = st.nextToken();
1320 if (prevalidated || (nsResolver == null)) {
1321 s.append(' ').append(displayname);
1322 } else if (displayname.startsWith("Q{")) {
1323 s.append(' ').append(displayname.substring(1));
1324 } else {
1325 try {
1326 String[] parts = NameChecker.getQNameParts(displayname);
1327 String muri = nsResolver.getURIForPrefix(parts[0], useDefaultNS);
1328 if (muri == null) {
1329 throw new XPathException("Namespace prefix '" + parts[0] + "' has not been declared", errorCode);
1330 }
1331 s.append(" {").append(muri).append('}').append(parts[1]);
1332 } catch (QNameException err) {
1333 throw new XPathException("Invalid element name. " + err.getMessage(), errorCode);
1334 }
1335 }
1336 }
1337 return s.toString();
1338 }
1339
1340 protected void checkExtensions(String key /*@Nullable*/) throws XPathException {
1341 throw new XPathException("Serialization property " + Err.wrap(key) + " is not available in Saxon-HE");
1342 }
1343
1344 protected Comparator<AtomicValue> getPropertySorter(String sortSpecification) throws XPathException {
1345 throw new XPathException("Serialization property saxon:property-order is not available in Saxon-HE");
1346 }
1347
1348
1349 }
1350