Debian Codegraph @

net/sf/saxon/event/ReceivingContentHandler.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.expr.parser.ExplicitLocation;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.lib.Feature;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.QuitParsingException;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.tiny.CharSlice;
18 import net.sf.saxon.tree.tiny.CompressedWhitespace;
19 import net.sf.saxon.type.*;
20 import net.sf.saxon.value.Whitespace;
21 import org.xml.sax.*;
22 import org.xml.sax.ext.Attributes2;
23 import org.xml.sax.ext.LexicalHandler;
24
25 import javax.xml.transform.Result;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.util.Arrays;
29 import java.util.HashMap;
30 import java.util.Stack;
31
32 /**
33 * ReceivingContentHandler is a glue class that provides a standard SAX ContentHandler
34 * interface to a Saxon Receiver. To achieve this it needs to map names supplied
35 * as strings to numeric name codes, for which purpose it needs access to a name
36 * pool. The class also performs the function of assembling adjacent text nodes.
37 * <p>If the input stream contains the processing instructions assigned by JAXP to switch
38 * disable-output-escaping on or off, these will be reflected in properties set in the corresponding
39 * characters events. In this case adjacent text nodes will not be combined.</p>
40 * <p>The {@code ReceivingContentHandler} is written on the assumption that it is receiving events
41 * from a parser configured with {@code http://xml.org/sax/features/namespaces} set to true
42 * and {@code http://xml.org/sax/features/namespace-prefixes} set to false.</p>
43 * <p>When running as a {@code TransformerHandler}, we have no control over the feature settings
44 * of the sender of the events, and if the events do not follow this pattern then the class may
45 * fail in unpredictable ways.</p>
46 *
47 */
48
49 public class ReceivingContentHandler
50 implements ContentHandler, LexicalHandler, DTDHandler
51 {
52 private PipelineConfiguration pipe;
53 private Receiver receiver;
54 private boolean inDTD = false; // true while processing the DTD
55 private LocalLocator localLocator = new LocalLocator(ExplicitLocation.UNKNOWN_LOCATION);
56 private boolean lineNumbering;
57 private Location lastTextNodeLocator;
58
59 // buffer for accumulating character data, until the next markup event is received
60
61 private char[] buffer = new char[512];
62 private int charsUsed = 0;
63 private CharSlice slice = new CharSlice(buffer, 0, 0);
64
65 // array for accumulating namespace information
66
67 private NamespaceBinding[] namespaces = new NamespaceBinding[20];
68 private int namespacesUsed = 0;
69
70 // determine whether ignorable whitespace is ignored
71
72 private boolean ignoreIgnorable = false;
73
74 // determine whether DTD attribute types are retained
75
76 private boolean retainDTDAttributeTypes = false;
77
78 // determine whether DTD attribute value defaults should be suppressed
79
80 //private boolean suppressDTDAttributeDefaults = false;
81
82 // indicate that escaping is allowed to be disabled using the JAXP-defined processing instructions
83
84 private boolean allowDisableOutputEscaping = false;
85
86 // indicate that escaping is disabled
87
88 private boolean escapingDisabled = false;
89
90 // flag to indicate whether the last tag was a start tag or an end tag
91
92 private boolean afterStartTag = true;
93
94 /**
95 * A local cache is used to avoid allocating namecodes for the same name more than once.
96 * This reduces contention on the NamePool. This is a two-level hashmap: the first level
97 * has the namespace URI as its key, and returns a HashMap which maps lexical QNames to integer
98 * namecodes.
99 */
100
101 private HashMap<String, HashMap<String, NodeName>> nameCache = new HashMap<>(10);
102 private HashMap<String, NodeName> noNamespaceNameCache = new HashMap<>(10);
103
104 // Action to be taken with defaulted attributes. 0=process normally, -1=suppress, +1=mark as defaulted
105 private int defaultedAttributesAction = 0;
106
107 // Stack holding depth of nesting of elements within external entities; created on first use
108 private Stack<Integer> elementDepthWithinEntity;
109
110
111 /**
112 * Create a ReceivingContentHandler and initialise variables
113 */
114
115 public ReceivingContentHandler() {
116 }
117
118 /**
119 * Set the ReceivingContentHandler to its initial state, except for the local name cache,
120 * which is retained
121 */
122
123 public void reset() {
124 pipe = null;
125 receiver = null;
126 ignoreIgnorable = false;
127 retainDTDAttributeTypes = false;
128 charsUsed = 0;
129 slice.setLength(0);
130 namespacesUsed = 0;
131 localLocator = new LocalLocator(ExplicitLocation.UNKNOWN_LOCATION);
132 allowDisableOutputEscaping = false;
133 escapingDisabled = false;
134 lineNumbering = false;
135 }
136
137 /**
138 * Set the receiver to which events are passed. ReceivingContentHandler is essentially a translator
139 * that takes SAX events as input and produces Saxon Receiver events as output; these Receiver events
140 * are passed to the supplied Receiver
141 *
142 * @param receiver the Receiver of events
143 */
144
145 public void setReceiver(Receiver receiver) {
146 this.receiver = receiver;
147 //receiver = new TracingFilter(receiver);
148 }
149
150 /**
151 * Get the receiver to which events are passed.
152 *
153 * @return the underlying Receiver
154 */
155
156 public Receiver getReceiver() {
157 return receiver;
158 }
159
160 /**
161 * Set the pipeline configuration
162 *
163 * @param pipe the pipeline configuration. This holds a reference to the Saxon configuration, as well as
164 * information that can vary from one pipeline to another
165 */
166
167 public void setPipelineConfiguration(PipelineConfiguration pipe) {
168 this.pipe = pipe;
169 Configuration config = pipe.getConfiguration();
170 ignoreIgnorable = pipe.getParseOptions().getSpaceStrippingRule() != NoElementsSpaceStrippingRule.getInstance();
171 retainDTDAttributeTypes = config.getBooleanProperty(Feature.RETAIN_DTD_ATTRIBUTE_TYPES);
172 if (!pipe.getParseOptions().isExpandAttributeDefaults()) {
173 defaultedAttributesAction = -1;
174 } else if (config.getBooleanProperty(Feature.MARK_DEFAULTED_ATTRIBUTES)) {
175 defaultedAttributesAction = +1;
176 }
177 allowDisableOutputEscaping = config.getConfigurationProperty(Feature.USE_PI_DISABLE_OUTPUT_ESCAPING);
178 lineNumbering = pipe.getParseOptions().isLineNumbering();
179 }
180
181 /**
182 * Get the pipeline configuration
183 *
184 * @return the pipeline configuration as supplied to
185 * {@link #setPipelineConfiguration(PipelineConfiguration)}
186 */
187
188 public PipelineConfiguration getPipelineConfiguration() {
189 return pipe;
190 }
191
192 /**
193 * Get the Configuration object
194 *
195 * @return the Saxon configuration
196 */
197
198 public Configuration getConfiguration() {
199 return pipe.getConfiguration();
200 }
201
202 /**
203 * Set whether "ignorable whitespace" should be ignored. This method is effective only
204 * if called after setPipelineConfiguration, since the default value is taken from the
205 * configuration.
206 *
207 * @param ignore true if ignorable whitespace (whitespace in element content that is notified
208 * via the {@link #ignorableWhitespace(char[], int, int)} method) should be ignored, false if
209 * it should be treated as ordinary text.
210 */
211
212 public void setIgnoreIgnorableWhitespace(boolean ignore) {
213 ignoreIgnorable = ignore;
214 }
215
216 /**
217 * Determine whether "ignorable whitespace" is ignored. This returns the value that was set
218 * using {@link #setIgnoreIgnorableWhitespace} if that has been called; otherwise the value
219 * from the configuration.
220 *
221 * @return true if ignorable whitespace is being ignored
222 */
223
224 public boolean isIgnoringIgnorableWhitespace() {
225 return ignoreIgnorable;
226 }
227
228 /**
229 * Receive notification of the beginning of a document.
230 */
231
232 public void startDocument() throws SAXException {
233 // System.err.println("ReceivingContentHandler#startDocument");
234 try {
235 charsUsed = 0;
236 namespacesUsed = 0;
237 receiver.setPipelineConfiguration(pipe);
238 String systemId = localLocator.getSystemId();
239 if (systemId != null) {
240 receiver.setSystemId(localLocator.getSystemId());
241 }
242 receiver.open();
243 receiver.startDocument(0);
244 } catch (QuitParsingException quit) {
245 getPipelineConfiguration().getErrorListener().warning(quit);
246 throw new SAXException(quit);
247 } catch (XPathException err) {
248 throw new SAXException(err);
249 }
250 }
251
252 /**
253 * Receive notification of the end of a document
254 */
255
256 public void endDocument() throws SAXException {
257 // System.err.println("RCH: end document");
258 try {
259 flush(true);
260 receiver.endDocument();
261 receiver.close();
262 } catch (ValidationException err) {
263 err.setLocator(localLocator);
264 throw new SAXException(err);
265 } catch (QuitParsingException err) {
266 // no action: not worth bothering at this stage of the game
267 } catch (XPathException err) {
268 err.maybeSetLocation(localLocator);
269 throw new SAXException(err);
270 }
271 }
272
273 /**
274 * Supply a locator that can be called to give information about location in the source document
275 * being parsed.
276 */
277
278 public void setDocumentLocator(Locator locator) {
279 localLocator = new LocalLocator(locator);
280 if (!lineNumbering) {
281 lastTextNodeLocator = localLocator;
282 }
283 }
284
285 /**
286 * Notify a namespace prefix to URI binding
287 */
288
289 public void startPrefixMapping(String prefix, String uri) {
290 //System.err.println("StartPrefixMapping " + prefix + "=" + uri);
291 if (prefix.equals("xmlns")) {
292 // the binding xmlns:xmlns="http://www.w3.org/2000/xmlns/"
293 // should never be reported, but it's been known to happen
294 return;
295 }
296 if (namespacesUsed >= namespaces.length) {
297 namespaces = Arrays.copyOf(namespaces, namespacesUsed * 2);
298 }
299 namespaces[namespacesUsed++] = new NamespaceBinding(prefix, uri);
300 }
301
302 /**
303 * Notify that a namespace binding is going out of scope
304 */
305
306 public void endPrefixMapping(String prefix) {
307 }
308
309 /**
310 * Receive notification of the beginning of an element.
311 *
312 * <p>The Parser will invoke this method at the beginning of every
313 * element in the XML document; there will be a corresponding
314 * {@link #endElement endElement} event for every startElement event
315 * (even when the element is empty). All of the element's content will be
316 * reported, in order, before the corresponding endElement
317 * event.</p>
318 *
319 * <p>This event allows up to three name components for each
320 * element:</p>
321 *
322 * <ol>
323 * <li>the Namespace URI;</li>
324 * <li>the local name; and</li>
325 * <li>the qualified (prefixed) name.</li>
326 * </ol>
327 *
328 * <p>Saxon expects all three of these to be provided.
329 *
330 * <p>The attribute list provided should contain only
331 * attributes with explicit values (specified or defaulted):
332 * #IMPLIED attributes should be omitted. The attribute list
333 * should not contain attributes used for Namespace declarations
334 * (xmlns* attributes); if it does, Saxon will ignore them,
335 * which may lead to unresolved namespace prefixes.</p>
336 *
337 * @param uri the Namespace URI, or the empty string if the
338 * element has no Namespace URI or if Namespace
339 * processing is not being performed
340 * @param localname the local name (without prefix), or the
341 * empty string if Namespace processing is not being
342 * performed
343 * @param rawname the qualified name (with prefix), or the
344 * empty string if qualified names are not available
345 * @param atts the attributes attached to the element. If
346 * there are no attributes, it shall be an empty
347 * Attributes object. The value of this object after
348 * startElement returns is undefined
349 * @throws org.xml.sax.SAXException any SAX exception, possibly
350 * wrapping another exception
351 * @see #endElement
352 * @see org.xml.sax.Attributes
353 * @see org.xml.sax.helpers.AttributesImpl
354 */
355 public void startElement(String uri, String localname, String rawname, Attributes atts)
356 throws SAXException {
357 // System.err.println("ReceivingContentHandler#startElement " +
358 // uri + "," + localname + "," + rawname +
359 // " at line " + locator.getLineNumber() + " of " + locator.getSystemId());
360 //for (int a=0; a<atts.getLength(); a++) {
361 // System.err.println(" Attribute " + atts.getURI(a) + "/" + atts.getLocalName(a) + "/" + atts.getQName(a));
362 //}
363 try {
364 flush(true);
365
366 NodeName elementName = getNodeName(uri, localname, rawname);
367 receiver.startElement(elementName, Untyped.getInstance(), localLocator, ReceiverOptions.NAMESPACE_OK);
368
369 localLocator.levelInEntity++;
370 for (int n = 0; n < namespacesUsed; n++) {
371 receiver.namespace(namespaces[n], 0);
372 }
373
374 for (int a = 0; a < atts.getLength(); a++) {
375 int properties = ReceiverOptions.NAMESPACE_OK;
376 String qname = atts.getQName(a);
377 if (qname.startsWith("xmlns") && (qname.length()==5 || qname.charAt(5)==':')) {
378 // We normally configure the parser so that it doesn't notify namespaces as attributes.
379 // But when running as a TransformerHandler, we have no control over the feature settings
380 // of the sender of the events. So we filter them out, just in case. There might be cases
381 // where we ought not just to ignore them, but to handle them as namespace events, but
382 // we'll cross that bridge when we come to it.
383 continue;
384 }
385
386 if (defaultedAttributesAction != 0
387 && atts instanceof Attributes2
388 && !((Attributes2) atts).isSpecified(qname)) {
389 if (defaultedAttributesAction == -1) {
390 // suppress defaulted attributes
391 continue;
392 } else {
393 // mark defaulted attributes
394 properties |= ReceiverOptions.DEFAULTED_ATTRIBUTE;
395 }
396 }
397
398 NodeName attCode = getNodeName(atts.getURI(a), atts.getLocalName(a), atts.getQName(a));
399 String type = atts.getType(a);
400 SimpleType typeCode = BuiltInAtomicType.UNTYPED_ATOMIC;
401 if (retainDTDAttributeTypes) {
402 switch (type) {
403 case "CDATA":
404 // common case, no action
405 break;
406 case "ID":
407 typeCode = BuiltInAtomicType.ID;
408 break;
409 case "IDREF":
410 typeCode = BuiltInAtomicType.IDREF;
411 break;
412 case "IDREFS":
413 typeCode = BuiltInListType.IDREFS;
414 break;
415 case "NMTOKEN":
416 typeCode = BuiltInAtomicType.NMTOKEN;
417 break;
418 case "NMTOKENS":
419 typeCode = BuiltInListType.NMTOKENS;
420 break;
421 case "ENTITY":
422 typeCode = BuiltInAtomicType.ENTITY;
423 break;
424 case "ENTITIES":
425 typeCode = BuiltInListType.ENTITIES;
426 break;
427 }
428 } else {
429 switch (type) {
430 case "ID":
431 properties |= ReceiverOptions.IS_ID;
432 break;
433 case "IDREF":
434 properties |= ReceiverOptions.IS_IDREF;
435 break;
436 case "IDREFS":
437 properties |= ReceiverOptions.IS_IDREF;
438 break;
439 }
440 }
441
442 receiver.attribute(attCode, typeCode, atts.getValue(a), localLocator, properties);
443 }
444
445 afterStartTag = true;
446 receiver.startContent();
447
448 namespacesUsed = 0;
449 } catch (XPathException err) {
450 err.maybeSetLocation(localLocator);
451 throw new SAXException(err);
452 }
453 }
454
455 /**
456 * Get the NodeName object associated with a name appearing in the document. Note that no
457 * NamePool name code is allocated at this stage, but the returned NodeName object contains
458 * room for one to be added later, to speed up name comparisons.
459 *
460 * @param uri the namespace URI
461 * @param localname the local part of the name
462 * @param rawname the lexical QName
463 * @return the NamePool name code, newly allocated if necessary
464 * @throws SAXException if the information supplied by the SAX parser is insufficient
465 */
466
467 private NodeName getNodeName(String uri, String localname, String rawname) throws SAXException {
468 // System.err.println("URI=" + uri + " local=" + " raw=" + rawname);
469 // The XML parser isn't required to report the rawname (qname), though all known parsers do.
470 // If none is provided, we give up
471 if (rawname.isEmpty()) {
472 throw new SAXException("Saxon requires an XML parser that reports the QName of each element");
473 }
474 // It's also possible (especially when using a TransformerHandler) that the parser
475 // has been configured to report the QName rather than the localname+URI
476 if (localname.isEmpty()) {
477 throw new SAXException("Parser configuration problem: namespace reporting is not enabled");
478 }
479
480 // Following code maintains a local cache to remember all the element names that have been
481 // allocated, which reduces contention on the NamePool. It also avoids parsing the lexical QName
482 // when the same name is used repeatedly. We also get a tiny improvement by avoiding the first hash
483 // table lookup for names in the null namespace.
484
485 HashMap<String, NodeName> map2 = uri.isEmpty() ? noNamespaceNameCache : nameCache.get(uri);
486 if (map2 == null) {
487 map2 = new HashMap<>(50);
488 nameCache.put(uri, map2);
489 if (uri.isEmpty()) {
490 noNamespaceNameCache = map2;
491 }
492 }
493
494 NodeName n = map2.get(rawname);
495 // we use the rawname (qname) rather than the local name because we want to retain the prefix
496 // Note that the NodeName objects generated do not contain a namecode or fingerprint; it will be generated
497 // later if we are building a TinyTree, but not necessarily on other paths (e.g. an identity transformation).
498 // The NodeName object is shared by all elements with the same name, so when the namecode is allocated to one
499 // of them, it is there for all of them.
500 if (n == null) {
501 if (uri.isEmpty()) {
502 NoNamespaceName qn = new NoNamespaceName(localname);
503 map2.put(rawname, qn);
504 return qn;
505 } else {
506 String prefix = NameChecker.getPrefix(rawname);
507 FingerprintedQName qn = new FingerprintedQName(prefix, uri, localname);
508 map2.put(rawname, qn);
509 return qn;
510 }
511 } else {
512 return n;
513 }
514
515 }
516
517
518 /**
519 * Report the end of an element (the close tag)
520 */
521
522 public void endElement(String uri, String localname, String rawname) throws SAXException {
523 //System.err.println("ReceivingContentHandler#End element " + rawname);
524 try {
525 // don't attempt whitespace compression if this end tag follows a start tag
526 flush(!afterStartTag);
527 localLocator.levelInEntity--;
528 receiver.endElement();
529 } catch (ValidationException err) {
530 err.maybeSetLocation(localLocator);
531 if (!err.hasBeenReported()) {
532 pipe.getErrorListener().fatalError(err);
533 }
534 err.setHasBeenReported(true);
535 throw new SAXException(err);
536 } catch (XPathException err) {
537 err.maybeSetLocation(localLocator);
538 throw new SAXException(err);
539 }
540 afterStartTag = false;
541 }
542
543 /**
544 * Report character data. Note that contiguous character data may be reported as a sequence of
545 * calls on this method, with arbitrary boundaries
546 */
547
548 public void characters(char ch[], int start, int length) {
549 // System.err.println("characters (" + length + ")");
550 // need to concatenate chunks of text before we can decide whether a node is all-white
551
552 while (charsUsed + length > buffer.length) {
553 buffer = Arrays.copyOf(buffer, buffer.length*2);
554 slice = new CharSlice(buffer, 0, 0);
555 }
556 System.arraycopy(ch, start, buffer, charsUsed, length);
557 charsUsed += length;
558 if (lineNumbering) {
559 lastTextNodeLocator = localLocator.saveLocation();
560 }
561 }
562
563 /**
564 * Report character data classified as "Ignorable whitespace", that is, whitespace text nodes
565 * appearing as children of elements with an element-only content model
566 */
567
568 public void ignorableWhitespace(char ch[], int start, int length) {
569 if (!ignoreIgnorable) {
570 characters(ch, start, length);
571 }
572 }
573
574 /**
575 * Notify the existence of a processing instruction
576 */
577
578 public void processingInstruction(String name, String remainder) throws SAXException {
579 try {
580 flush(true);
581 if (!inDTD) {
582 if (name == null) {
583 // trick used by the old James Clark xp parser to notify a comment
584 comment(remainder.toCharArray(), 0, remainder.length());
585 } else {
586 // some parsers allow through PI names containing colons
587 if (!NameChecker.isValidNCName(name)) {
588 throw new SAXException("Invalid processing instruction name (" + name + ')');
589 }
590 if (allowDisableOutputEscaping) {
591 if (name.equals(Result.PI_DISABLE_OUTPUT_ESCAPING)) {
592 //flush();
593 escapingDisabled = true;
594 return;
595 } else if (name.equals(Result.PI_ENABLE_OUTPUT_ESCAPING)) {
596 //flush();
597 escapingDisabled = false;
598 return;
599 }
600 }
601 CharSequence data;
602 if (remainder == null) {
603 // allowed by the spec but rarely seen: see Saxon bug 2491
604 data = "";
605 } else {
606 // not strictly necessary (the parser should have done this) but needed in practice
607 data = Whitespace.removeLeadingWhitespace(remainder);
608 }
609 receiver.processingInstruction(name, data, localLocator, 0);
610 }
611 }
612 } catch (XPathException err) {
613 throw new SAXException(err);
614 }
615 }
616
617 /**
618 * Notify the existence of a comment. Note that in SAX this is part of LexicalHandler interface
619 * rather than the ContentHandler interface.
620 */
621
622 public void comment(char ch[], int start, int length) throws SAXException {
623 try {
624 flush(true);
625 if (!inDTD) {
626 receiver.comment(new CharSlice(ch, start, length), localLocator, 0);
627 }
628 } catch (XPathException err) {
629 throw new SAXException(err);
630 }
631 }
632
633 /**
634 * Flush buffer for accumulated character data
635 *
636 * @param compress true if compression of whitespace should be attempted. This is an expensive
637 * operation, so we avoid doing it when we hit an end tag that follows after a start tag, as
638 * it's not likely to succeed in that situation.
639 * @throws XPathException if flushing the character data fails
640 */
641
642 private void flush(boolean compress) throws XPathException {
643 if (charsUsed > 0) {
644 slice.setLength(charsUsed);
645 CharSequence cs = compress ? CompressedWhitespace.compress(slice) : slice;
646 receiver.characters(cs, lastTextNodeLocator,
647 escapingDisabled ? ReceiverOptions.DISABLE_ESCAPING : ReceiverOptions.WHOLE_TEXT_NODE);
648 charsUsed = 0;
649 escapingDisabled = false;
650 }
651 }
652
653 /**
654 * Notify a skipped entity. Saxon ignores this event
655 */
656
657 public void skippedEntity(String name) {
658 }
659
660 // No-op methods to satisfy lexical handler interface
661
662 /**
663 * Register the start of the DTD. Saxon ignores the DTD; however, it needs to know when the DTD starts and
664 * ends so that it can ignore comments in the DTD, which are reported like any other comment, but which
665 * are skipped because they are not part of the XPath data model
666 */
667
668 public void startDTD(String name, String publicId, String systemId) {
669 inDTD = true;
670 }
671
672 /**
673 * Register the end of the DTD. Comments in the DTD are skipped because they
674 * are not part of the XPath data model
675 */
676
677 public void endDTD() {
678 inDTD = false;
679 }
680
681 public void startEntity(String name) {
682 if (elementDepthWithinEntity == null) {
683 elementDepthWithinEntity = new Stack<>();
684 }
685 elementDepthWithinEntity.push(localLocator.levelInEntity);
686 localLocator.levelInEntity = 0;
687 }
688
689 public void endEntity(String name) {
690 localLocator.levelInEntity = elementDepthWithinEntity.pop();
691 }
692
693 public void startCDATA() {
694 }
695
696 public void endCDATA() {
697 }
698
699 //////////////////////////////////////////////////////////////////////////////
700 // Implement DTDHandler interface
701 //////////////////////////////////////////////////////////////////////////////
702
703
704 public void notationDecl(String name,
705 String publicId,
706 String systemId) {
707 }
708
709
710 public void unparsedEntityDecl(String name,
711 String publicId,
712 String systemId,
713 String notationName) throws SAXException {
714 // Some (non-conformant) SAX parsers report the systemId as written.
715 // We need to turn it into an absolute URL.
716
717 String uri = systemId;
718 if (localLocator != null) {
719 try {
720 URI suppliedURI = new URI(systemId);
721 if (!suppliedURI.isAbsolute()) {
722 String baseURI = localLocator.getSystemId();
723 if (baseURI != null) { // See bug 21679
724 URI absoluteURI = new URI(baseURI).resolve(systemId);
725 uri = absoluteURI.toString();
726 }
727 }
728 } catch (URISyntaxException err) {
729 // fallback - no action
730 }
731 }
732 try {
733 receiver.setUnparsedEntity(name, uri, publicId);
734 } catch (XPathException err) {
735 throw new SAXException(err);
736 }
737 }
738
739 /**
740 * An implementation of the Saxon {@link Location} interface that wraps the SAX Locator
741 * information. Note that this object is mutable and changes continually as parsing proceeds;
742 * it is therefore necessary to call its {@link #saveLocation()} method to obtain an
743 * immutable location that still has meaning once parsing is finished.
744 */
745
746 public static class LocalLocator implements Location {
747
748 private Locator saxLocator;
749 public int levelInEntity;
750
751 public LocalLocator(Locator saxLocator) {
752 this.saxLocator = saxLocator;
753 this.levelInEntity = 0;
754 }
755
756 /**
757 * Return the system identifier for the current document event.
758 *
759 * @return A string containing the system identifier, or
760 * null if none is available.
761 */
762
763 public String getSystemId() {
764 return saxLocator.getSystemId();
765 }
766
767 /**
768 * Return the public identifier for the current document event.
769 *
770 * @return A string containing the public identifier, or
771 * null if none is available.
772 */
773
774 public String getPublicId() {
775 return saxLocator.getPublicId();
776 }
777
778 /**
779 * Return the line number where the current document event ends.
780 *
781 * @return The line number, or -1 if none is available.
782 */
783
784 public int getLineNumber() {
785 return saxLocator.getLineNumber();
786 }
787
788 /**
789 * Return the character position where the current document event ends.
790 *
791 * @return The column number, or -1 if none is available.
792 */
793
794 public int getColumnNumber() {
795 return saxLocator.getColumnNumber();
796 }
797
798 /**
799 * Get an immutable copy of this Location object. By default Location objects may be mutable, so they
800 * should not be saved for later use. The result of this operation holds the same location information,
801 * but in an immutable form.
802 */
803
804 public Location saveLocation() {
805 return new ExplicitLocation(getSystemId(), getLineNumber(), getColumnNumber());
806 }
807 }
808
809 }
810