Debian Codegraph @

net/sf/saxon/event/ContentHandlerProxy.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.event;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.expr.XPathContext;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.expr.parser.Location;
15 import net.sf.saxon.lib.Logger;
16 import net.sf.saxon.lib.SaxonOutputKeys;
17 import net.sf.saxon.lib.TraceListener;
18 import net.sf.saxon.om.Item;
19 import net.sf.saxon.om.NamespaceBinding;
20 import net.sf.saxon.om.NamespaceBindingSet;
21 import net.sf.saxon.om.NodeName;
22 import net.sf.saxon.trace.InstructionInfo;
23 import net.sf.saxon.trans.SaxonErrorCode;
24 import net.sf.saxon.trans.XPathException;
25 import net.sf.saxon.tree.util.AttributeCollectionImpl;
26 import net.sf.saxon.type.SchemaException;
27 import net.sf.saxon.type.SchemaType;
28 import net.sf.saxon.type.SimpleType;
29 import net.sf.saxon.value.Whitespace;
30 import org.xml.sax.ContentHandler;
31 import org.xml.sax.Locator;
32 import org.xml.sax.SAXException;
33 import org.xml.sax.ext.LexicalHandler;
34
35 import javax.xml.transform.Result;
36 import javax.xml.transform.sax.TransformerHandler;
37 import java.util.Properties;
38 import java.util.Stack;
39
40 /**
41 * A ContentHandlerProxy is a Receiver that converts events into the form expected by an
42 * underlying SAX2 ContentHandler. Relevant events (notably comments) can also be
43 * fed to a LexicalHandler.
44 * <p>Note that in general the output passed to a Receiver
45 * corresponds to an External General Parsed Entity. A SAX2 ContentHandler only expects
46 * to deal with well-formed XML documents, so we only pass it the contents of the first
47 * element encountered, unless the saxon:require-well-formed output property is set to "no".</p>
48 * <p>This ContentHandlerProxy provides no access to type information. For a ContentHandler that
49 * makes type information available, see {@link com.saxonica.ee.jaxp.TypedContentHandler}</p>
50 * <p>The ContentHandlerProxy can also be nominated as a TraceListener, to receive notification
51 * of trace events.</p>
52 */
53
54 public class ContentHandlerProxy implements Receiver {
55 private PipelineConfiguration pipe;
56 private String systemId;
57 protected ContentHandler handler;
58 protected LexicalHandler lexicalHandler;
59 private int depth = 0;
60 private boolean requireWellFormed = false;
61 private boolean undeclareNamespaces = false;
62 private Stack<String> elementStack = new Stack<>();
63 private Stack<String> namespaceStack = new Stack<>();
64 private ContentHandlerProxyTraceListener traceListener;
65 protected AttributeCollectionImpl pendingAttributes;
66 private NodeName pendingElement = null;
67 private Location currentLocation = ExplicitLocation.UNKNOWN_LOCATION;
68
69 // MARKER is a value added to the namespace stack at the start of an element, so that we know how
70 // far to unwind the stack on an end-element event.
71
72 private static final String MARKER = "##";
73
74 /**
75 * Set the underlying content handler. This call is mandatory before using this Receiver.
76 * If the content handler is an instance of {@link LexicalHandler}, then it will also receive
77 * notification of lexical events such as comments.
78 *
79 * @param handler the SAX content handler to which all events will be directed
80 */
81
82 public void setUnderlyingContentHandler(ContentHandler handler) {
83 this.handler = handler;
84 if (handler instanceof LexicalHandler) {
85 lexicalHandler = (LexicalHandler) handler;
86 }
87 }
88
89 /**
90 * Get the underlying content handler
91 *
92 * @return the SAX content handler to which all events are being directed
93 */
94
95 public ContentHandler getUnderlyingContentHandler() {
96 return handler;
97 }
98
99 /**
100 * Set the Lexical Handler to be used. If called, this must be called AFTER
101 * setUnderlyingContentHandler()
102 *
103 * @param handler the SAX lexical handler to which lexical events (such as comments) will
104 * be notified.
105 */
106
107 public void setLexicalHandler(LexicalHandler handler) {
108 lexicalHandler = handler;
109 }
110
111 /**
112 * Set the pipeline configuration
113 *
114 * @param pipe the pipeline configuration
115 */
116
117 public void setPipelineConfiguration(/*@NotNull*/ PipelineConfiguration pipe) {
118 this.pipe = pipe;
119 }
120
121 /**
122 * Get the pipeline configuration
123 */
124
125 /*@NotNull*/
126 public PipelineConfiguration getPipelineConfiguration() {
127 return pipe;
128 }
129
130 /**
131 * Get the Saxon configuration
132 *
133 * @return the Saxon configuration
134 */
135
136 public Configuration getConfiguration() {
137 return pipe.getConfiguration();
138 }
139
140 /**
141 * Set the System ID of the destination tree
142 *
143 * @param systemId the system ID (effectively the base URI)
144 */
145
146 public void setSystemId(String systemId) {
147 this.systemId = systemId;
148 }
149
150 /**
151 * Get the System ID of the destination tree
152 *
153 * @return the system ID (effectively the base URI)
154 */
155
156 public String getSystemId() {
157 return systemId;
158 }
159
160 /**
161 * Get the associated TraceListener that receives notification of trace events
162 *
163 * @return the trace listener. If there is no existing trace listener, then a new one
164 * will be created.
165 */
166
167 public ContentHandlerProxyTraceListener getTraceListener() {
168 if (traceListener == null) {
169 traceListener = new ContentHandlerProxyTraceListener();
170 }
171 return traceListener;
172 }
173
174 /**
175 * Get the current location identifier
176 *
177 * @return the location identifier of the most recent event.
178 */
179
180 public Location getCurrentLocation() {
181 return currentLocation;
182 }
183
184 /**
185 * Notify an unparsed entity URI.
186 *
187 * @param name The name of the unparsed entity
188 * @param systemID The system identifier of the unparsed entity
189 * @param publicID The public identifier of the unparsed entity
190 */
191
192 public void setUnparsedEntity(String name, String systemID, String publicID) throws XPathException {
193 // Avoid passing unparsed entities to a general-purpose DTDHandler because it's probably
194 // expecting them in the context of the rest of the DTD, which we don't make available.
195 if (handler instanceof TransformerHandler) {
196 try {
197 ((TransformerHandler)handler).unparsedEntityDecl(name, publicID, systemID, "unknown");
198 } catch (SAXException e) {
199 throw new XPathException(e);
200 }
201 }
202 }
203
204 /**
205 * Set the output details.
206 *
207 * @param details the serialization properties. The only values used by this implementation are
208 * {@link SaxonOutputKeys#REQUIRE_WELL_FORMED} and {@link net.sf.saxon.lib.SaxonOutputKeys#UNDECLARE_PREFIXES}.
209 */
210
211 public void setOutputProperties(Properties details) {
212 String prop = details.getProperty(SaxonOutputKeys.REQUIRE_WELL_FORMED);
213 if (prop != null) {
214 requireWellFormed = prop.equals("yes");
215 }
216 prop = details.getProperty(SaxonOutputKeys.UNDECLARE_PREFIXES);
217 if (prop != null) {
218 undeclareNamespaces = prop.equals("yes");
219 }
220 }
221
222 /**
223 * Ask whether the content handler can handle a stream of events that is merely
224 * well-balanced, or whether it can only handle a well-formed sequence.
225 *
226 * @return true if the content handler requires the event stream to represent a well-formed
227 * XML document (containing exactly one top-level element node and no top-level text nodes)
228 */
229
230 public boolean isRequireWellFormed() {
231 return requireWellFormed;
232 }
233
234 /**
235 * Set whether the content handler can handle a stream of events that is merely
236 * well-balanced, or whether it can only handle a well-formed sequence. The default is false.
237 *
238 * @param wellFormed set to true if the content handler requires the event stream to represent a well-formed
239 * XML document (containing exactly one top-level element node and no top-level text nodes). Otherwise,
240 * multiple top-level elements and text nodes are allowed, as in the XDM model.
241 */
242
243 public void setRequireWellFormed(boolean wellFormed) {
244 requireWellFormed = wellFormed;
245 }
246
247 /**
248 * Ask whether namespace undeclaration events (for a non-null prefix) should be notified.
249 * The default is no, because some ContentHandlers (e.g. JDOM) can't cope with them.
250 *
251 * @return true if namespace undeclarations (xmlns:p="") are to be output
252 */
253
254 public boolean isUndeclareNamespaces() {
255 return undeclareNamespaces;
256 }
257
258 /**
259 * Set whether namespace undeclaration events (for a non-null prefix) should be notified.
260 * The default is no, because some ContentHandlers (e.g. JDOM) can't cope with them.
261 *
262 * @param undeclareNamespaces true if namespace undeclarations (xmlns:p="") are to be output
263 */
264
265 public void setUndeclareNamespaces(boolean undeclareNamespaces) {
266 this.undeclareNamespaces = undeclareNamespaces;
267 }
268
269 /**
270 * Notify the start of the event stream
271 */
272
273 public void open() throws XPathException {
274 pendingAttributes = new AttributeCollectionImpl(getPipelineConfiguration().getConfiguration());
275 if (handler == null) {
276 throw new IllegalStateException("ContentHandlerProxy.open(): no underlying handler provided");
277 }
278 try {
279 Locator locator = new ContentHandlerProxyLocator(this);
280 handler.setDocumentLocator(locator);
281 handler.startDocument();
282 } catch (SAXException err) {
283 handleSAXException(err);
284 }
285 depth = 0;
286 }
287
288 /**
289 * Notify the end of the event stream
290 */
291
292 public void close() throws XPathException {
293 if (depth >= 0) {
294 try {
295 handler.endDocument();
296 } catch (SAXException err) {
297 handleSAXException(err);
298 }
299 }
300 depth = -1;
301 }
302
303 /**
304 * Notify the start of the document.
305 */
306
307 public void startDocument(int properties) throws XPathException {
308 }
309
310 /**
311 * Notify the end of the document
312 */
313
314 public void endDocument() throws XPathException {
315 }
316
317 /**
318 * Notify the start of an element
319 */
320
321 public void startElement(NodeName nameCode, SchemaType typeCode, Location location, int properties) throws XPathException {
322 depth++;
323 if (depth <= 0 && requireWellFormed) {
324 notifyNotWellFormed();
325 }
326 pendingElement = nameCode;
327 currentLocation = location.saveLocation();
328 namespaceStack.push(MARKER);
329 }
330
331 /**
332 * Notify a namespace. Namespaces are notified <b>after</b> the startElement event, and before
333 * any children for the element.
334 */
335
336 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
337 for (NamespaceBinding ns : namespaceBindings) {
338 String prefix = ns.getPrefix();
339 if (prefix.equals("xml")) {
340 return;
341 }
342 String uri = ns.getURI();
343 if (!undeclareNamespaces && uri.isEmpty() && !prefix.isEmpty()) {
344 // This is a namespace undeclaration, but the ContentHandler doesn't want to know about undeclarations
345 return;
346 }
347 try {
348 handler.startPrefixMapping(prefix, uri);
349 namespaceStack.push(prefix);
350 } catch (SAXException err) {
351 handleSAXException(err);
352 }
353 }
354 }
355
356 /**
357 * Notify an attribute. Attributes are notified after the startElement event, and before any
358 * children.
359 */
360
361 public void attribute(NodeName nameCode, SimpleType typeCode, CharSequence value, Location locationId, int properties)
362 throws XPathException {
363 int index = pendingAttributes.findByNodeName(nameCode);
364 if (index < 0) {
365 pendingAttributes.addAttribute(nameCode, typeCode, value.toString(), locationId, properties);
366 } else {
367 pendingAttributes.setAttribute(index, nameCode, typeCode, value.toString(), locationId, properties);
368 }
369 }
370
371 /**
372 * Notify the start of the content, that is, the completion of all attributes and namespaces.
373 * Note that the initial receiver of output from XSLT instructions will not receive this event,
374 * it has to detect it itself. Note that this event is reported for every element even if it has
375 * no attributes, no namespaces, and no content.
376 */
377
378 public void startContent() throws XPathException {
379 try {
380 if (depth > 0 || !requireWellFormed) {
381 String uri = pendingElement.getURI();
382 String localName = pendingElement.getLocalPart();
383 String qname = pendingElement.getDisplayName();
384
385 handler.startElement(uri, localName, qname, pendingAttributes);
386
387 elementStack.push(uri);
388 elementStack.push(localName);
389 elementStack.push(qname);
390
391 pendingAttributes.clear();
392 pendingElement = null;
393 }
394 } catch (SAXException err) {
395 handleSAXException(err);
396
397 }
398 }
399
400
401 /**
402 * End of element
403 */
404
405 public void endElement() throws XPathException {
406 if (depth > 0) {
407 try {
408 assert !elementStack.isEmpty();
409 String qname = elementStack.pop();
410 String localName = elementStack.pop();
411 String uri = elementStack.pop();
412 handler.endElement(uri, localName, qname);
413 } catch (SAXException err) {
414 handleSAXException(err);
415 }
416 }
417
418 while (true) {
419 String prefix = namespaceStack.pop();
420 if (prefix.equals(MARKER)) {
421 break;
422 }
423 try {
424 handler.endPrefixMapping(prefix);
425 } catch (SAXException err) {
426 handleSAXException(err);
427 }
428 }
429 depth--;
430 // if this was the outermost element, and well formed output is required
431 // then no further elements will be processed
432 if (requireWellFormed && depth <= 0) {
433 depth = Integer.MIN_VALUE; // crude but effective
434 }
435
436 }
437
438 /**
439 * Character data
440 */
441
442 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
443 currentLocation = locationId;
444 boolean disable = (properties & ReceiverOptions.DISABLE_ESCAPING) != 0;
445 if (disable) {
446 setEscaping(false);
447 }
448 try {
449 if (depth <= 0 && requireWellFormed) {
450 if (Whitespace.isWhite(chars)) {
451 // ignore top-level white space
452 } else {
453 notifyNotWellFormed();
454 }
455 } else {
456 handler.characters(chars.toString().toCharArray(), 0, chars.length());
457 }
458 } catch (SAXException err) {
459 handleSAXException(err);
460 }
461 if (disable) {
462 setEscaping(true);
463 }
464 }
465
466 /**
467 * The following function is called when it is found that the output is not a well-formed document.
468 * Unless the ContentHandler accepts "balanced content", this is a fatal error.
469 */
470
471 protected void notifyNotWellFormed() throws XPathException {
472 XPathException err = new XPathException("The result tree cannot be supplied to the ContentHandler because it is not well-formed XML");
473 err.setErrorCode(SaxonErrorCode.SXCH0002);
474 throw err;
475 }
476
477
478 /**
479 * Processing Instruction
480 */
481
482 public void processingInstruction(String target, CharSequence data, Location locationId, int properties)
483 throws XPathException {
484 currentLocation = locationId;
485 try {
486 handler.processingInstruction(target, data.toString());
487 } catch (SAXException err) {
488 handleSAXException(err);
489 }
490 }
491
492 /**
493 * Output a comment. Passes it on to the ContentHandler provided that the ContentHandler
494 * is also a SAX2 LexicalHandler.
495 */
496
497 public void comment(CharSequence chars, Location locationId, int properties)
498 throws XPathException {
499 currentLocation = locationId;
500 try {
501 if (lexicalHandler != null) {
502 lexicalHandler.comment(chars.toString().toCharArray(), 0, chars.length());
503 }
504 } catch (SAXException err) {
505 handleSAXException(err);
506 }
507 }
508
509 /**
510 * Ask whether this Receiver (or the downstream pipeline) makes any use of the type annotations
511 * supplied on element and attribute events
512 *
513 * @return true if the Receiver makes any use of this information. If false, the caller
514 * may supply untyped nodes instead of supplying the type annotation
515 */
516
517 public boolean usesTypeAnnotations() {
518 return false;
519 }
520
521 /**
522 * Switch escaping on or off. This is called when the XSLT disable-output-escaping attribute
523 * is used to switch escaping on or off. It is not called for other sections of output (e.g.
524 * element names) where escaping is inappropriate. The action, as defined in JAXP 1.1, is
525 * to notify the request to the Content Handler using a processing instruction.
526 *
527 * @param escaping true if escaping is to be switched on, false to switch it off
528 */
529
530 private void setEscaping(boolean escaping) {
531 try {
532 handler.processingInstruction(escaping ? Result.PI_ENABLE_OUTPUT_ESCAPING : PI_DISABLE_OUTPUT_ESCAPING, "");
533 } catch (SAXException err) {
534 throw new AssertionError(err);
535 }
536 }
537
538
539 /**
540 * Handle a SAXException thrown by the ContentHandler
541 *
542 * @param err the exception to be handler
543 * @throws XPathException always
544 */
545
546 private void handleSAXException(SAXException err) throws XPathException {
547 Exception nested = err.getException();
548 if (nested instanceof XPathException) {
549 throw (XPathException) nested;
550 } else if (nested instanceof SchemaException) {
551 throw new XPathException(nested);
552 } else {
553 XPathException de = new XPathException(err);
554 de.setErrorCode(SaxonErrorCode.SXCH0003);
555 throw de;
556 }
557 }
558
559 /**
560 * Create a TraceListener that will collect information about the current
561 * location in the source document. This is used to provide information
562 * to the receiving application for diagnostic purposes.
563 */
564
565 public static class ContentHandlerProxyTraceListener implements TraceListener {
566
567 private Stack<Item> contextItemStack;
568
569 public void setOutputDestination(Logger stream) {
570 // no action
571 }
572
573 /**
574 * Get the context item stack
575 *
576 * @return the context item stack
577 */
578
579 /*@Nullable*/
580 public Stack getContextItemStack() {
581 return contextItemStack;
582 }
583
584 /**
585 * Method called at the start of execution, that is, when the run-time transformation starts
586 */
587
588 public void open(Controller controller) {
589 contextItemStack = new Stack<>();
590 }
591
592 /**
593 * Method called at the end of execution, that is, when the run-time execution ends
594 */
595
596 public void close() {
597 contextItemStack = null;
598 }
599
600 /**
601 * Method that is called when an instruction in the stylesheet gets processed.
602 *
603 * @param instruction gives information about the instruction being
604 * executed, and about the context in which it is executed. This object is mutable,
605 * so if information from the InstructionInfo is to be retained, it must be copied.
606 */
607
608 public void enter(InstructionInfo instruction, XPathContext context) {
609 // do nothing
610 }
611
612 /**
613 * Method that is called after processing an instruction of the stylesheet,
614 * that is, after any child instructions have been processed.
615 *
616 * @param instruction gives the same information that was supplied to the
617 * enter method, though it is not necessarily the same object. Note that the
618 * line number of the instruction is that of the start tag in the source stylesheet,
619 * not the line number of the end tag.
620 */
621
622 public void leave(InstructionInfo instruction) {
623 // do nothing
624 }
625
626 /**
627 * Method that is called by an instruction that changes the current item
628 * in the source document: that is, xsl:for-each, xsl:apply-templates, xsl:for-each-group.
629 * The method is called after the enter method for the relevant instruction, and is called
630 * once for each item processed.
631 *
632 * @param currentItem the new current item. Item objects are not mutable; it is safe to retain
633 * a reference to the Item for later use.
634 */
635
636 public void startCurrentItem(Item currentItem) {
637 if (contextItemStack == null) {
638 contextItemStack = new Stack<>();
639 }
640 contextItemStack.push(currentItem);
641 }
642
643 /**
644 * Method that is called when an instruction has finished processing a new current item
645 * and is ready to select a new current item or revert to the previous current item.
646 * The method will be called before the leave() method for the instruction that made this
647 * item current.
648 *
649 * @param currentItem the item that was current, whose processing is now complete. This will represent
650 * the same underlying item as the corresponding startCurrentItem() call, though it will
651 * not necessarily be the same actual object.
652 */
653
654 public void endCurrentItem(Item currentItem) {
655 contextItemStack.pop();
656 }
657
658 }
659
660 }
661