Debian Codegraph @

net/sf/saxon/pull/StaxBridge.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.pull;
9
10
11 import net.sf.saxon.event.PipelineConfiguration;
12 import net.sf.saxon.event.ReceiverOptions;
13 import net.sf.saxon.expr.parser.ExplicitLocation;
14 import net.sf.saxon.om.*;
15 import net.sf.saxon.trans.SaxonErrorCode;
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.tree.util.FastStringBuffer;
20 import net.sf.saxon.type.BuiltInAtomicType;
21 import net.sf.saxon.type.SchemaType;
22 import net.sf.saxon.type.SimpleType;
23 import net.sf.saxon.type.Untyped;
24 import net.sf.saxon.value.AtomicValue;
25 import net.sf.saxon.value.Whitespace;
26
27 import javax.xml.stream.*;
28 import javax.xml.stream.events.EntityDeclaration;
29 import java.io.InputStream;
30 import java.lang.reflect.InvocationTargetException;
31 import java.lang.reflect.Method;
32 import java.net.URI;
33 import java.net.URISyntaxException;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.List;
37
38 /**
39 * This class implements the Saxon PullProvider API on top of a standard StAX parser
40 * (or any other StAX XMLStreamReader implementation)
41 */
42
43 public class StaxBridge implements PullProvider {
44
45 private XMLStreamReader reader;
46 private StaxAttributes attributes = new StaxAttributes();
47 private PipelineConfiguration pipe;
48 private NamePool namePool;
49 private HashMap<String, NodeName> nameCache = new HashMap<>();
50 private List unparsedEntities = null;
51 int currentEvent = START_OF_INPUT;
52 int depth = 0;
53 boolean ignoreIgnorable = false;
54
55 /**
56 * Create a new instance of the class
57 */
58
59 public StaxBridge() {
60
61 }
62
63 /**
64 * Supply an input stream containing XML to be parsed. A StAX parser is created using
65 * the JAXP XMLInputFactory.
66 *
67 * @param systemId The Base URI of the input document
68 * @param inputStream the stream containing the XML to be parsed
69 * @throws XPathException if an error occurs creating the StAX parser
70 */
71
72 public void setInputStream(String systemId, InputStream inputStream) throws XPathException {
73 try {
74 XMLInputFactory factory = XMLInputFactory.newInstance();
75 //XMLInputFactory factory = new WstxInputFactory();
76 factory.setXMLReporter(new StaxErrorReporter());
77 reader = factory.createXMLStreamReader(systemId, inputStream);
78 } catch (XMLStreamException e) {
79 throw new XPathException(e);
80 }
81 }
82
83 /**
84 * Supply an XMLStreamReader: the events reported by this XMLStreamReader will be translated
85 * into PullProvider events
86 *
87 * @param reader the supplier of XML events, typically an XML parser
88 */
89
90 public void setXMLStreamReader(XMLStreamReader reader) {
91 this.reader = reader;
92 }
93
94 /**
95 * Set configuration information. This must only be called before any events
96 * have been read.
97 */
98
99 public void setPipelineConfiguration(PipelineConfiguration pipe) {
100 this.pipe = new PipelineConfiguration(pipe);
101 this.namePool = pipe.getConfiguration().getNamePool();
102 ignoreIgnorable = pipe.getConfiguration().getParseOptions().getSpaceStrippingRule() != NoElementsSpaceStrippingRule.getInstance();
103 }
104
105 /**
106 * Get configuration information.
107 */
108
109 public PipelineConfiguration getPipelineConfiguration() {
110 return pipe;
111 }
112
113 /**
114 * Get the XMLStreamReader used by this StaxBridge. This is available only after
115 * setInputStream() or setXMLStreamReader() has been called
116 *
117 * @return the instance of XMLStreamReader allocated when setInputStream() was called,
118 * or the instance supplied directly to setXMLStreamReader()
119 */
120
121 public XMLStreamReader getXMLStreamReader() {
122 return reader;
123 }
124
125 /**
126 * Get the name pool
127 *
128 * @return the name pool
129 */
130
131 public NamePool getNamePool() {
132 return pipe.getConfiguration().getNamePool();
133 }
134
135 /**
136 * Get the next event
137 *
138 * @return an integer code indicating the type of event. The code
139 * {@link #END_OF_INPUT} is returned at the end of the sequence.
140 */
141
142 public int next() throws XPathException {
143 if (currentEvent == START_OF_INPUT) {
144 // StAX isn't reporting START_DOCUMENT so we supply it ourselves
145 currentEvent = START_DOCUMENT;
146 return currentEvent;
147 }
148 if (currentEvent == END_OF_INPUT || currentEvent == END_DOCUMENT) {
149 try {
150 reader.close();
151 } catch (XMLStreamException e) {
152 throw new XPathException(e);
153 }
154 return END_OF_INPUT;
155 }
156 try {
157 if (reader.hasNext()) {
158 int event = reader.next();
159 //System.err.println("Read event " + event);
160 currentEvent = translate(event);
161 } else {
162 currentEvent = END_OF_INPUT;
163 }
164 } catch (XMLStreamException e) {
165 String message = e.getMessage();
166 // Following code recognizes the messages produced by the Sun Zephyr parser
167 if (message.startsWith("ParseError at")) {
168 int c = message.indexOf("\nMessage: ");
169 if (c > 0) {
170 message = message.substring(c + 10);
171 }
172 }
173 XPathException err = new XPathException("Error reported by XML parser: " + message, e);
174 err.setErrorCode(SaxonErrorCode.SXXP0003);
175 err.setLocator(translateLocation(e.getLocation()));
176 throw err;
177 }
178 return currentEvent;
179 }
180
181
182 private int translate(int event) throws XPathException {
183 //System.err.println("EVENT " + event);
184 switch (event) {
185 case XMLStreamConstants.ATTRIBUTE:
186 return ATTRIBUTE;
187 case XMLStreamConstants.CDATA:
188 return TEXT;
189 case XMLStreamConstants.CHARACTERS:
190 if (depth == 0 && reader.isWhiteSpace()) {
191 return next();
192 // } else if (reader.isWhiteSpace()) {
193 // return next();
194 } else {
195 // System.err.println("TEXT[" + new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()) + "]");
196 // System.err.println(" ARRAY length " + reader.getTextCharacters().length + "[" + new String(reader.getTextCharacters(), 0, reader.getTextStart() + reader.getTextLength()) + "]");
197 // System.err.println(" START: " + reader.getTextStart() + " LENGTH " + reader.getTextLength());
198 return TEXT;
199 }
200 case XMLStreamConstants.COMMENT:
201 return COMMENT;
202 case XMLStreamConstants.DTD:
203 unparsedEntities = (List) reader.getProperty("javax.xml.stream.entities");
204 return next();
205 case XMLStreamConstants.END_DOCUMENT:
206 return END_DOCUMENT;
207 case XMLStreamConstants.END_ELEMENT:
208 depth--;
209 return END_ELEMENT;
210 case XMLStreamConstants.ENTITY_DECLARATION:
211 return next();
212 case XMLStreamConstants.ENTITY_REFERENCE:
213 return next();
214 case XMLStreamConstants.NAMESPACE:
215 return NAMESPACE;
216 case XMLStreamConstants.NOTATION_DECLARATION:
217 return next();
218 case XMLStreamConstants.PROCESSING_INSTRUCTION:
219 return PROCESSING_INSTRUCTION;
220 case XMLStreamConstants.SPACE:
221 if (depth == 0) {
222 return next();
223 } else if (ignoreIgnorable) {
224 // (Brave attempt, but Woodstox doesn't seem to report ignorable whitespace)
225 return next();
226 } else {
227 return TEXT;
228 }
229 case XMLStreamConstants.START_DOCUMENT:
230 return next(); // we supplied the START_DOCUMENT ourselves
231 //return START_DOCUMENT;
232 case XMLStreamConstants.START_ELEMENT:
233 depth++;
234 return START_ELEMENT;
235 default:
236 throw new IllegalStateException("Unknown StAX event " + event);
237
238
239 }
240 }
241
242 /**
243 * Get the event most recently returned by next(), or by other calls that change
244 * the position, for example getStringValue() and skipToMatchingEnd(). This
245 * method does not change the position of the PullProvider.
246 *
247 * @return the current event
248 */
249
250 public int current() {
251 return currentEvent;
252 }
253
254 /**
255 * Get the attributes associated with the current element. This method must
256 * be called only after a START_ELEMENT event has been notified. The contents
257 * of the returned AttributeCollection are guaranteed to remain unchanged
258 * until the next START_ELEMENT event, but may be modified thereafter. The object
259 * should not be modified by the client.
260 * <p>Attributes may be read before or after reading the namespaces of an element,
261 * but must not be read after the first child node has been read, or after calling
262 * one of the methods skipToEnd(), getStringValue(), or getTypedValue().</p>
263 *
264 * @return an AttributeCollection representing the attributes of the element
265 * that has just been notified.
266 */
267
268 public AttributeCollection getAttributes() {
269 return attributes;
270 }
271
272 /**
273 * Get the namespace declarations associated with the current element. This method must
274 * be called only after a START_ELEMENT event has been notified. In the case of a top-level
275 * START_ELEMENT event (that is, an element that either has no parent node, or whose parent
276 * is not included in the sequence being read), the NamespaceDeclarations object returned
277 * will contain a namespace declaration for each namespace that is in-scope for this element
278 * node. In the case of a non-top-level element, the NamespaceDeclarations will contain
279 * a set of namespace declarations and undeclarations, representing the differences between
280 * this element and its parent.
281 * <p>It is permissible for this method to return namespace declarations that are redundant.</p>
282 * <p>The NamespaceDeclarations object is guaranteed to remain unchanged until the next START_ELEMENT
283 * event, but may then be overwritten. The object should not be modified by the client.</p>
284 * <p>Namespaces may be read before or after reading the attributes of an element,
285 * but must not be read after the first child node has been read, or after calling
286 * one of the methods skipToEnd(), getStringValue(), or getTypedValue().</p>
287 */
288
289 public NamespaceBinding[] getNamespaceDeclarations() {
290 int n = reader.getNamespaceCount();
291 if (n == 0) {
292 return NamespaceBinding.EMPTY_ARRAY;
293 } else {
294 NamespaceBinding[] bindings = new NamespaceBinding[n];
295 for (int i = 0; i < n; i++) {
296 String prefix = reader.getNamespacePrefix(i);
297 if (prefix == null) {
298 prefix = "";
299 }
300 String uri = reader.getNamespaceURI(i);
301 if (uri == null) {
302 uri = "";
303 }
304 bindings[i] = new NamespaceBinding(prefix, uri);
305 }
306 return bindings;
307 }
308 }
309
310 /**
311 * Skip the current subtree. This method may be called only immediately after
312 * a START_DOCUMENT or START_ELEMENT event. This call returns the matching
313 * END_DOCUMENT or END_ELEMENT event; the next call on next() will return
314 * the event following the END_DOCUMENT or END_ELEMENT.
315 */
316
317 public int skipToMatchingEnd() throws XPathException {
318 switch (currentEvent) {
319 case START_DOCUMENT:
320 currentEvent = END_DOCUMENT;
321 return currentEvent;
322 case START_ELEMENT:
323 try {
324 int skipDepth = 0;
325 while (reader.hasNext()) {
326 int event = reader.next();
327 if (event == XMLStreamConstants.START_ELEMENT) {
328 skipDepth++;
329 } else if (event == XMLStreamConstants.END_ELEMENT) {
330 if (skipDepth-- == 0) {
331 currentEvent = END_ELEMENT;
332 return currentEvent;
333 }
334 }
335 }
336 } catch (XMLStreamException e) {
337 throw new XPathException(e);
338 }
339 throw new IllegalStateException(
340 "Element start has no matching element end");
341 default:
342 throw new IllegalStateException(
343 "Cannot call skipToMatchingEnd() except when at start of element or document");
344
345 }
346 }
347
348 /**
349 * Close the event reader. This indicates that no further events are required.
350 * It is not necessary to close an event reader after {@link #END_OF_INPUT} has
351 * been reported, but it is recommended to close it if reading terminates
352 * prematurely. Once an event reader has been closed, the effect of further
353 * calls on next() is undefined.
354 */
355
356 public void close() {
357 try {
358 reader.close();
359 } catch (XMLStreamException e) {
360 //
361 }
362 }
363
364 /**
365 * Get the NodeName identifying the name of the current node. This method
366 * can be used after the {@link #START_ELEMENT}, {@link #PROCESSING_INSTRUCTION},
367 * {@link #ATTRIBUTE}, or {@link #NAMESPACE} events. With some PullProvider implementations,
368 * it can also be used after {@link #END_ELEMENT}, but this is not guaranteed: a client who
369 * requires the information at that point (for example, to do serialization) should insert an
370 * {@link com.saxonica.xqj.pull.ElementNameTracker} into the pipeline.
371 * If called at other times, the result is undefined and may result in an IllegalStateException.
372 * If called when the current node is an unnamed namespace node (a node representing the default namespace)
373 * the returned value is null.
374 *
375 * @return the NodeName. The NodeName can be used to obtain the prefix, local name,
376 * and namespace URI.
377 */
378 public NodeName getNodeName() {
379 if (currentEvent == START_ELEMENT || currentEvent == END_ELEMENT) {
380 String local = reader.getLocalName();
381 String uri = reader.getNamespaceURI();
382 // We keep a cache indexed by local name, on the assumption that most of the time, a given
383 // local name will only ever be used with the same prefix and URI
384 NodeName cached = nameCache.get(local);
385 if (cached != null && cached.hasURI(uri == null ? "": uri) && cached.getPrefix().equals(reader.getPrefix())) {
386 return cached;
387 } else {
388 int fp = namePool.allocateFingerprint(uri, local);
389 if (uri == null) {
390 cached = new NoNamespaceName(local, fp);
391 } else {
392 cached = new FingerprintedQName(reader.getPrefix(), uri, local, fp);
393 }
394 nameCache.put(local, cached);
395 return cached;
396 }
397 } else if (currentEvent == PROCESSING_INSTRUCTION) {
398 String local = reader.getPITarget();
399 return new NoNamespaceName(local);
400 } else {
401 throw new IllegalStateException();
402 }
403 }
404
405 /**
406 * Get the string value of the current element, text node, processing-instruction,
407 * or top-level attribute or namespace node, or atomic value.
408 * <p>In other situations the result is undefined and may result in an IllegalStateException.</p>
409 * <p>If the most recent event was a {@link #START_ELEMENT}, this method causes the content
410 * of the element to be read. The current event on completion of this method will be the
411 * corresponding {@link #END_ELEMENT}. The next call of next() will return the event following
412 * the END_ELEMENT event.</p>
413 *
414 * @return the String Value of the node in question, defined according to the rules in the
415 * XPath data model.
416 */
417
418 public CharSequence getStringValue() throws XPathException {
419 switch (currentEvent) {
420 case TEXT:
421 CharSlice cs = new CharSlice(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
422 return CompressedWhitespace.compress(cs);
423
424 case COMMENT:
425 return new CharSlice(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
426
427 case PROCESSING_INSTRUCTION:
428 String s = reader.getPIData();
429 // The BEA parser includes the separator space in the value,
430 // which isn't part of the XPath data model
431 return Whitespace.removeLeadingWhitespace(s);
432
433 case START_ELEMENT:
434 FastStringBuffer combinedText = null;
435 try {
436 int depth = 0;
437 while (reader.hasNext()) {
438 int event = reader.next();
439 if (event == XMLStreamConstants.CHARACTERS) {
440 if (combinedText == null) {
441 combinedText = new FastStringBuffer(FastStringBuffer.C64);
442 }
443 combinedText.append(
444 reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength());
445 } else if (event == XMLStreamConstants.START_ELEMENT) {
446 depth++;
447 } else if (event == XMLStreamConstants.END_ELEMENT) {
448 if (depth-- == 0) {
449 currentEvent = END_ELEMENT;
450 if (combinedText != null) {
451 return combinedText.condense();
452 } else {
453 return "";
454 }
455 }
456 }
457 }
458 } catch (XMLStreamException e) {
459 throw new XPathException(e);
460 }
461 default:
462 throw new IllegalStateException("getStringValue() called when current event is " + currentEvent);
463
464 }
465 }
466
467 /**
468 * Get an atomic value. This call may be used only when the last event reported was
469 * ATOMIC_VALUE. This indicates that the PullProvider is reading a sequence that contains
470 * a free-standing atomic value; it is never used when reading the content of a node.
471 */
472
473 public AtomicValue getAtomicValue() {
474 throw new IllegalStateException();
475 }
476
477 /**
478 * Get the type annotation of the current attribute or element node, or atomic value.
479 * The result of this method is undefined unless the most recent event was START_ELEMENT,
480 * ATTRIBUTE, or ATOMIC_VALUE.
481 *
482 * @return the type annotation.
483 */
484
485 public SchemaType getSchemaType() {
486 if (currentEvent == START_ELEMENT) {
487 return Untyped.getInstance();
488 } else if (currentEvent == ATTRIBUTE) {
489 return BuiltInAtomicType.UNTYPED_ATOMIC;
490 } else {
491 return null;
492 }
493 }
494
495 /**
496 * Get the location of the current event.
497 * For an event stream representing a real document, the location information
498 * should identify the location in the lexical XML source. For a constructed document, it should
499 * identify the location in the query or stylesheet that caused the node to be created.
500 * A value of null can be returned if no location information is available.
501 */
502
503 public net.sf.saxon.expr.parser.Location getSourceLocator() {
504 return translateLocation(reader.getLocation());
505 }
506
507 /**
508 * Translate a StAX Location object to a Saxon Locator
509 *
510 * @param location the StAX Location object
511 * @return a Saxon/SAX SourceLocator object
512 */
513
514 private ExplicitLocation translateLocation(Location location) {
515 if (location == null) {
516 return ExplicitLocation.UNKNOWN_LOCATION;
517 } else {
518 return new ExplicitLocation(location.getSystemId(), location.getLineNumber(), location.getColumnNumber());
519 }
520 }
521
522 /**
523 * Implement the Saxon AttributeCollection interface over the StAX interface.
524 */
525
526 private class StaxAttributes implements AttributeCollection {
527
528 /**
529 * Return the number of attributes in the list.
530 *
531 * @return The number of attributes in the list.
532 */
533
534 public int getLength() {
535 return reader.getAttributeCount();
536 }
537
538 public int getFingerprint(int index) {
539 String local = reader.getAttributeLocalName(index);
540 String uri = reader.getAttributeNamespace(index);
541 if (uri == null) {
542 uri = "";
543 }
544 return getNamePool().allocateFingerprint(uri, local);
545 }
546
547 /**
548 * Get the node name of an attribute (by position)
549 *
550 * @param index The position of the attribute in the list
551 * @return The node name of the attribute, or null if there is no attribute in that position
552 */
553 public NodeName getNodeName(int index) {
554 String local = reader.getAttributeLocalName(index);
555 String uri = reader.getAttributeNamespace(index);
556 String prefix = reader.getAttributePrefix(index);
557 if (prefix == null) {
558 prefix = "";
559 }
560 if (uri == null) {
561 uri = "";
562 }
563 return new FingerprintedQName(prefix, uri, local);
564 }
565
566 /**
567 * Get the type annotation of an attribute (by position).
568 *
569 * @param index The position of the attribute in the list.
570 * @return The type annotation
571 */
572
573 public SimpleType getTypeAnnotation(int index) {
574 String type = reader.getAttributeType(index);
575 if ("ID".equals(type)) {
576 return BuiltInAtomicType.ID;
577 }
578 return BuiltInAtomicType.UNTYPED_ATOMIC;
579 }
580
581 /**
582 * Get the locationID of an attribute (by position)
583 *
584 * @param index The position of the attribute in the list.
585 * @return The location of the attribute. This can be used to obtain the
586 * actual system identifier and line number of the relevant location
587 */
588
589 public net.sf.saxon.expr.parser.Location getLocation(int index) {
590 return ExplicitLocation.UNKNOWN_LOCATION;
591 }
592
593 /**
594 * Get the systemId part of the location of an attribute, at a given index.
595 * <p>Attribute location information is not available from a SAX parser, so this method
596 * is not useful for getting the location of an attribute in a source document. However,
597 * in a Saxon result document, the location information represents the location in the
598 * stylesheet of the instruction used to generate this attribute, which is useful for
599 * debugging.</p>
600 *
601 * @param index the required attribute
602 * @return the systemId of the location of the attribute
603 */
604
605 public String getSystemId(int index) {
606 return reader.getLocation().getSystemId();
607 }
608
609 /**
610 * Get the line number part of the location of an attribute, at a given index.
611 * <p>Attribute location information is not available from a SAX parser, so this method
612 * is not useful for getting the location of an attribute in a source document. However,
613 * in a Saxon result document, the location information represents the location in the
614 * stylesheet of the instruction used to generate this attribute, which is useful for
615 * debugging.</p>
616 *
617 * @param index the required attribute
618 * @return the line number of the location of the attribute
619 */
620
621 public int getLineNumber(int index) {
622 return reader.getLocation().getLineNumber();
623 }
624
625 /**
626 * Get the properties of an attribute (by position)
627 *
628 * @param index The position of the attribute in the list.
629 * @return The properties of the attribute. This is a set
630 * of bit-settings defined in class {@link net.sf.saxon.event.ReceiverOptions}. The
631 * most interesting of these is {{@link net.sf.saxon.event.ReceiverOptions#DEFAULTED_ATTRIBUTE},
632 * which indicates an attribute that was added to an element as a result of schema validation.
633 */
634
635 public int getProperties(int index) {
636 int properties = 0;
637 if (!reader.isAttributeSpecified(index)) {
638 properties |= ReceiverOptions.DEFAULTED_ATTRIBUTE;
639 }
640 if (isIdref(index)) {
641 properties |= ReceiverOptions.IS_IDREF | ReceiverOptions.ID_IDREF_CHECKED;
642 }
643 return properties;
644 }
645
646 /**
647 * Get the prefix of the name of an attribute (by position).
648 *
649 * @param index The position of the attribute in the list.
650 * @return The prefix of the attribute name as a string, or null if there
651 * is no attribute at that position. Returns "" for an attribute that
652 * has no prefix.
653 */
654
655 public String getPrefix(int index) {
656 return getNodeName(index).getPrefix();
657 }
658
659 /**
660 * Get the lexical QName of an attribute (by position).
661 *
662 * @param index The position of the attribute in the list.
663 * @return The lexical QName of the attribute as a string, or null if there
664 * is no attribute at that position.
665 */
666
667 public String getQName(int index) {
668 return getNodeName(index).getDisplayName();
669 }
670
671 /**
672 * Get the local name of an attribute (by position).
673 *
674 * @param index The position of the attribute in the list.
675 * @return The local name of the attribute as a string, or null if there
676 * is no attribute at that position.
677 */
678
679 public String getLocalName(int index) {
680 return reader.getAttributeLocalName(index);
681 }
682
683 /**
684 * Get the namespace URI of an attribute (by position).
685 *
686 * @param index The position of the attribute in the list.
687 * @return The local name of the attribute as a string, or null if there
688 * is no attribute at that position.
689 */
690
691 public String getURI(int index) {
692 return reader.getAttributeNamespace(index);
693 }
694
695 /**
696 * Get the index of an attribute (by name).
697 *
698 * @param uri The namespace uri of the attribute.
699 * @param localname The local name of the attribute.
700 * @return The index position of the attribute
701 */
702
703 public int getIndex(String uri, String localname) {
704 for (int i = 0; i < getLength(); i++) {
705 if (getLocalName(i).equals(localname) && getURI(i).equals(uri)) {
706 return i;
707 }
708 }
709 return -1;
710 }
711
712 /**
713 * Get the index, given the fingerprint
714 */
715
716 public int getIndexByFingerprint(int fingerprint) {
717 return getIndex(getNamePool().getURI(fingerprint), getNamePool().getLocalName(fingerprint));
718 }
719
720 /**
721 * Get the attribute value using its fingerprint
722 */
723
724 public String getValueByFingerprint(int fingerprint) {
725 return getValue(getIndexByFingerprint(fingerprint));
726 }
727
728 /**
729 * Get the value of an attribute (by name).
730 *
731 * @param uri The namespace uri of the attribute.
732 * @param localname The local name of the attribute.
733 * @return The index position of the attribute
734 */
735
736 public String getValue(String uri, String localname) {
737 return reader.getAttributeValue(uri, localname);
738 }
739
740 /**
741 * Get the value of an attribute (by position).
742 *
743 * @param index The position of the attribute in the list.
744 * @return The attribute value as a string, or null if
745 * there is no attribute at that position.
746 */
747
748 public String getValue(int index) {
749 return reader.getAttributeValue(index);
750 }
751
752 /**
753 * Determine whether a given attribute has the is-ID property set
754 */
755
756 public boolean isId(int index) {
757 return "ID".equals(reader.getAttributeType(index));
758 }
759
760 /**
761 * Determine whether a given attribute has the is-idref property set
762 */
763
764 public boolean isIdref(int index) {
765 String attributeType = reader.getAttributeType(index);
766 return "IDREF".equals(attributeType) || "IDREFS".equals(attributeType);
767 }
768 }
769
770 /**
771 * Get a list of unparsed entities.
772 *
773 * @return a list of unparsed entities, or null if the information is not available, or
774 * an empty list if there are no unparsed entities. Each item in the list will
775 * be an instance of {@link net.sf.saxon.pull.UnparsedEntity}
776 */
777
778 public List<UnparsedEntity> getUnparsedEntities() {
779 if (unparsedEntities == null) {
780 return null;
781 }
782 List<UnparsedEntity> list = new ArrayList<>(unparsedEntities.size());
783 for (Object ent : unparsedEntities) {
784 String name = null;
785 String systemId = null;
786 String publicId = null;
787 String baseURI = null;
788 if (ent instanceof EntityDeclaration) {
789 // This is what we would expect from the StAX API spec
790 EntityDeclaration ed = (EntityDeclaration) ent;
791 name = ed.getName();
792 systemId = ed.getSystemId();
793 publicId = ed.getPublicId();
794 baseURI = ed.getBaseURI();
795 } else if (ent.getClass().getName().equals("com.ctc.wstx.ent.UnparsedExtEntity")) {
796 // Woodstox 3.0.0 returns this: use introspection to get the data we need
797 try {
798 Class<?> woodstoxClass = ent.getClass();
799 Class<?>[] noArgClasses = new Class<?>[0];
800 Object[] noArgs = new Object[0];
801 Method method = woodstoxClass.getMethod("getName", noArgClasses);
802 name = (String) method.invoke(ent, noArgs);
803 method = woodstoxClass.getMethod("getSystemId", noArgClasses);
804 systemId = (String) method.invoke(ent, noArgs);
805 method = woodstoxClass.getMethod("getPublicId", noArgClasses);
806 publicId = (String) method.invoke(ent, noArgs);
807 method = woodstoxClass.getMethod("getBaseURI", noArgClasses);
808 baseURI = (String) method.invoke(ent, noArgs);
809 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
810 //
811 }
812 }
813 if (name != null) {
814 if (baseURI != null && systemId != null) {
815 try {
816 systemId = new URI(baseURI).resolve(systemId).toString();
817 } catch (URISyntaxException err) {
818 //
819 }
820 }
821 UnparsedEntity ue = new UnparsedEntity();
822 ue.setName(name);
823 ue.setSystemId(systemId);
824 ue.setPublicId(publicId);
825 ue.setBaseURI(baseURI);
826 list.add(ue);
827 }
828 }
829 return list;
830 }
831
832 /**
833 * Error reporting class for StAX parser errors
834 */
835
836 private class StaxErrorReporter implements XMLReporter {
837
838 public void report(String message, String errorType,
839 Object relatedInformation, Location location) {
840 ExplicitLocation loc = translateLocation(location);
841 XPathException err = new XPathException("Error reported by XML parser: " + message + " (" + errorType + ')');
842 err.setLocator(loc);
843 pipe.getErrorListener().error(err);
844 }
845
846 }
847
848 }
849