Debian Codegraph @

net/sf/saxon/event/StreamWriterToReceiver.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.expr.parser.ExplicitLocation;
11 import net.sf.saxon.lib.StandardURIChecker;
12 import net.sf.saxon.om.*;
13 import net.sf.saxon.pull.NamespaceContextImpl;
14 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
15 import net.sf.saxon.trans.Err;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.type.BuiltInAtomicType;
18 import net.sf.saxon.type.Untyped;
19
20 import javax.xml.namespace.NamespaceContext;
21 import javax.xml.stream.XMLStreamException;
22 import javax.xml.stream.XMLStreamWriter;
23 import java.util.*;
24 import java.util.function.IntPredicate;
25
26 /**
27 * This class implements the XmlStreamWriter interface, translating the events into Saxon
28 * Receiver events. The Receiver can be anything: a serializer, a schema validator, a tree builder.
29 *
30 * <p>This class does not itself perform "namespace repairing" as defined in the interface Javadoc
31 * (also referred to as "prefix defaulting" in the StaX JSR specification). In normal use, however,
32 * the events emitted by this class are piped into a {@link NamespaceReducer} which performs a function
33 * very similar to namespace repairing; specifically, it ensures that when elements and attribute are
34 * generated with a given namespace URI and local name, then namespace declarations are generated
35 * automatically without any explicit need to call the {@link #writeNamespace(String, String)} method.</p>
36 *
37 * <p>The class will check all names, URIs, and character content for conformance against XML well-formedness
38 * rules unless the <code>checkValues</code> option is set to false.</p>
39 *
40 * <p>The implementation of this class is influenced not only by the Javadoc documentation of the
41 * <code>XMLStreamWriter</code> interface (which is woefully inadequate), but also by the helpful
42 * but unofficial interpretation of the spec to be found at
43 * http://veithen.github.io/2009/11/01/understanding-stax.html</p>
44 *
45 * <p>Provided that the sequence of events sent to this class is legitimate, the events
46 * sent to the supplied {@code Receiver} should constitute a <b>regular sequence</b>
47 * as defined in the documentation of class {@link RegularSequenceChecker}.</p>
48 *
49 * @since 9.3. Rewritten May 2015 to fix bug 2357. Further modified in 9.7.0.2 in light of the discussion
50 * of bug 2398, and the interpretation of the spec cited above.
51 */
52 public class StreamWriterToReceiver implements XMLStreamWriter {
53
54 private static boolean DEBUG = false;
55
56 private static class Triple {
57 public String prefix;
58 public String uri;
59 public String local;
60 public String value;
61 }
62
63 private static class StartTag {
64 public Triple elementName;
65 public List<Triple> attributes;
66 public List<Triple> namespaces;
67
68 public StartTag() {
69 elementName = new Triple();
70 attributes = new ArrayList<>();
71 namespaces = new ArrayList<>();
72 }
73 }
74
75 private StartTag pendingTag = null;
76
77 /**
78 * The receiver to which events will be passed
79 */
80
81 private Receiver receiver;
82
83 /**
84 * The Checker used for testing valid characters
85 */
86
87 private IntPredicate charChecker;
88
89 /**
90 * Flag to indicate whether names etc are to be checked for well-formedness
91 */
92
93 private boolean isChecking = false;
94
95 /**
96 * The current depth of element nesting. -1 indicates outside startDocument/endDocument; non-negative
97 * values indicate the number of open start element tags
98 */
99
100 private int depth = -1;
101
102 /**
103 * Flag indicating that an empty element has been requested.
104 */
105 private boolean isEmptyElement;
106
107 /**
108 * inScopeNamespaces represents namespaces that have been declared in the XML stream
109 */
110 private NamespaceReducer inScopeNamespaces;
111
112 /**
113 * setPrefixes represents the namespace bindings that have been set, at each level of the stack,
114 * using {@link #setPrefix}. There is one entry for each level of element nesting, and the entry is a list
115 * of NamespaceBinding objects, that is, prefix/uri pairs
116 */
117
118 private Stack<List<NamespaceBinding>> setPrefixes = new Stack<>();
119
120 /**
121 * rootNamespaceContext is the namespace context supplied at the start, is the final fallback
122 * for allocating a prefix to a URI
123 */
124
125 private javax.xml.namespace.NamespaceContext rootNamespaceContext = null;
126
127 /**
128 * Constructor. Creates a StreamWriter as a front-end to a given Receiver.
129 *
130 * @param receiver the Receiver that is to receive the events generated
131 * by this StreamWriter.
132 */
133 public StreamWriterToReceiver(Receiver receiver) {
134 // Events are passed through a NamespaceReducer which maintains the namespace context
135 // It also eliminates duplicate namespace declarations, and creates extra namespace declarations
136 // where needed to support prefix-uri mappings used on elements and attributes
137 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
138 this.inScopeNamespaces = new NamespaceReducer(receiver);
139 this.receiver = inScopeNamespaces;
140 //this.receiver = new TracingFilter(this.receiver);
141 this.charChecker = pipe.getConfiguration().getValidCharacterChecker();
142 this.setPrefixes.push(new ArrayList<>());
143 this.rootNamespaceContext = new NamespaceContextImpl(new NamespaceResolver() {
144 // See bug 2902; initialise rootNamespaceContext to an empty set of namespaces
145 @Override
146 public String getURIForPrefix(String prefix, boolean useDefault) {
147 return null;
148 }
149
150 @Override
151 public Iterator<String> iteratePrefixes() {
152 List<String> e = Collections.emptyList();
153 return e.iterator();
154 }
155 });
156 }
157
158
159 /**
160 * Get the Receiver to which this StreamWriterToReceiver is writing events
161 *
162 * @return the destination Receiver
163 */
164
165 public Receiver getReceiver() {
166 return receiver;
167 }
168
169 /**
170 * Say whether prefixes are to be invented when none is specified by the user.
171 * This method has no effect, and is deprecated
172 *
173 * @param invent true if prefixes are to be invented.
174 * @deprecated since 9.7.0.2. In normal use this class feeds its output into a {@link NamespaceReducer}
175 * which performs the equivalent of "namespace repairing" or "prefix invention": that is, it ensures
176 * that when elements or attributes are written in a specific namespace, there is no need for an
177 * explicit {@link #writeNamespace(String, String)} call to create the namespace declaration.
178 */
179
180 public void setInventPrefixes(boolean invent) {
181 // no action
182 }
183
184 /**
185 * Ask whether prefixes are to be invented when none is specified by the user.
186 * This method is deprecated.
187 *
188 * @return true if the next receiver in the pipeline is a {@link NamespaceReducer}; this is an approximation
189 * of the result in earlier releases.
190 * @deprecated since 9.7.0.2
191 */
192
193 public boolean isInventPrefixes() {
194 return receiver instanceof NamespaceReducer;
195 }
196
197
198 /**
199 * Say whether names and values are to be checked for conformance with XML rules
200 *
201 * @param check true if names and values are to be checked. Default is false;
202 */
203
204 public void setCheckValues(boolean check) {
205 this.isChecking = check;
206 }
207
208 /**
209 * Ask whether names and values are to be checked for conformance with XML rules
210 *
211 * @return true if names and values are to be checked. Default is false;
212 */
213
214 public boolean isCheckValues() {
215 return this.isChecking;
216 }
217
218 public void flushStartTag() throws XMLStreamException {
219 if (depth == -1) {
220 writeStartDocument();
221 }
222 if (pendingTag != null) {
223 try {
224 completeTriple(pendingTag.elementName, false);
225 for (Triple t : pendingTag.attributes) {
226 completeTriple(t, true);
227 }
228 NodeName nc;
229 if (pendingTag.elementName.uri.isEmpty()) {
230 nc = new NoNamespaceName(pendingTag.elementName.local);
231 } else {
232 nc = new FingerprintedQName(pendingTag.elementName.prefix, pendingTag.elementName.uri, pendingTag.elementName.local);
233 }
234 receiver.startElement(nc, Untyped.getInstance(), ExplicitLocation.UNKNOWN_LOCATION, 0);
235 for (Triple t : pendingTag.namespaces) {
236 if (t.prefix == null) {
237 t.prefix = "";
238 }
239 if (t.uri == null) {
240 t.uri = "";
241 }
242 receiver.namespace(new NamespaceBinding(t.prefix, t.uri), 0);
243 }
244 for (Triple t : pendingTag.attributes) {
245 if (t.uri.isEmpty()) {
246 nc = new NoNamespaceName(t.local);
247 } else {
248 nc = new FingerprintedQName(t.prefix, t.uri, t.local);
249 }
250 receiver.attribute(nc, BuiltInAtomicType.UNTYPED_ATOMIC, t.value, ExplicitLocation.UNKNOWN_LOCATION, 0);
251 }
252 pendingTag = null;
253 receiver.startContent();
254 if (isEmptyElement) {
255 isEmptyElement = false;
256 depth--;
257 setPrefixes.pop();
258 receiver.endElement();
259 }
260 } catch (XPathException e) {
261 throw new XMLStreamException(e);
262 }
263 }
264 }
265
266 /**
267 * Fill in the unknown parts of a (prefix, uri, localname) triple by reference to the namespace
268 * context.
269 * <p>For details see the table in the <code>XMLStreamWriter</code> javadoc.</p>
270 * @param t the (prefix, uri, localname) triple. Note that the prefix will be null if not supplied
271 * in the call, and will be "" if an empty string or null was supplied in the call; these
272 * cases are handled differently.
273 * @param isAttribute true if this is an attribute name rather than an element name
274 * @throws XMLStreamException if the name is invalid or incomplete
275 */
276
277 private void completeTriple(Triple t, boolean isAttribute) throws XMLStreamException {
278 if (t.local == null) {
279 throw new XMLStreamException("Local name of " + (isAttribute ? "Attribute" : "Element") + " is missing");
280 }
281 if (isChecking && !isValidNCName(t.local)) {
282 throw new XMLStreamException("Local name of " + (isAttribute ? "Attribute" : "Element") +
283 Err.wrap(t.local) + " is invalid");
284 }
285 if (t.prefix == null) {
286 t.prefix = "";
287 }
288 if (t.uri == null) {
289 t.uri = "";
290 }
291 if (isChecking && !t.uri.isEmpty() && isInvalidURI(t.uri)) {
292 throw new XMLStreamException("Namespace URI " + Err.wrap(t.local) + " is invalid");
293 }
294 if (t.prefix.isEmpty() && !t.uri.isEmpty()) {
295 t.prefix = getPrefixForUri(t.uri);
296 }
297 }
298
299 private String getDefaultNamespace() {
300 for (Triple t : pendingTag.namespaces) {
301 if (t.prefix == null || t.prefix.isEmpty()) {
302 return t.uri;
303 }
304 }
305 return inScopeNamespaces.getURIForPrefix("", true);
306 }
307
308 private String getUriForPrefix(String prefix) {
309 for (Triple t : pendingTag.namespaces) {
310 if (prefix.equals(t.prefix)) {
311 return t.uri;
312 }
313 }
314 return inScopeNamespaces.getURIForPrefix(prefix, false);
315 }
316
317 private String getPrefixForUri(String uri) {
318 for (Triple t : pendingTag.namespaces) {
319 if (uri.equals(t.uri)) {
320 return t.prefix == null ? "" : t.prefix;
321 }
322 }
323 String setPrefix = getPrefix(uri);
324 if (setPrefix != null) {
325 return setPrefix;
326 }
327 Iterator<String> prefixes = inScopeNamespaces.iteratePrefixes();
328 while (prefixes.hasNext()) {
329 String p = prefixes.next();
330 if (inScopeNamespaces.getURIForPrefix(p, false).equals(uri)) {
331 return p;
332 }
333 }
334 return "";
335 }
336
337 /**
338 * Generate a start element event for an element in no namespace. Note: the element
339 * will be in no namespace, even if {@link #setDefaultNamespace(String)} has been called;
340 * this is Saxon's interpretation of the intended effect of the StAX specification.
341 *
342 * @param localName local name of the tag, may not be null
343 * @throws XMLStreamException if names are being checked and the name is invalid, or if an error occurs downstream
344 * @throws NullPointerException if the supplied local name is null
345 */
346
347 public void writeStartElement(String localName) throws XMLStreamException {
348 if (DEBUG) {
349 System.err.println("StartElement " + localName);
350 }
351 checkNonNull(localName);
352 setPrefixes.push(new ArrayList<>());
353 flushStartTag();
354 depth++;
355 pendingTag = new StartTag();
356 pendingTag.elementName.local = localName;
357 }
358
359 /**
360 * Generate a start element event. The name of the element is determined by the supplied
361 * namespace URI and local name. The prefix used for the element is determined by the in-scope
362 * prefixes established using {@link #setPrefix(String, String)} and/or {@link #setDefaultNamespace(String)}
363 * if these include the specified namespace URI; otherwise the namespace will become the default namespace
364 * and there will therefore be no prefix.
365 *
366 * @param namespaceURI the namespace URI of the element name. Must not be null. A zero-length
367 * string means the element is in no namespace.
368 * @param localName local part of the element name. Must not be null
369 * @throws XMLStreamException if names are being checked and are found to be invalid, or if an
370 * error occurs downstream in the pipeline.
371 * @throws NullPointerException if either argument is null
372 */
373
374 public void writeStartElement(String namespaceURI, String localName) throws XMLStreamException {
375 if (DEBUG) {
376 System.err.println("StartElement Q{" + namespaceURI + "}" + localName);
377 }
378 checkNonNull(namespaceURI);
379 checkNonNull(localName);
380 setPrefixes.push(new ArrayList<>());
381 flushStartTag();
382 depth++;
383 pendingTag = new StartTag();
384 pendingTag.elementName.local = localName;
385 pendingTag.elementName.uri = namespaceURI;
386
387 }
388
389 /**
390 * Generate a start element event. The name of the element is determined by the supplied
391 * namespace URI and local name, and the prefix will be as supplied in the call.
392 *
393 * @param prefix the prefix of the element, must not be null. If the prefix is supplied as a zero-length
394 * string, the element will nave no prefix (that is, the namespace URI will become the default
395 * namespace).
396 * @param localName local name of the element, must not be null
397 * @param namespaceURI the uri to bind the prefix to, must not be null. If the value is a zero-length string,
398 * the element will be in no namespace; in this case any prefix is ignored.
399 * @throws NullPointerException if any of the arguments is null.
400 * @throws XMLStreamException if names are being checked and are found to be invalid, or if an
401 * error occurs downstream in the pipeline.
402 */
403
404 public void writeStartElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
405 if (DEBUG) {
406 System.err.println("StartElement " + prefix + "=Q{" + namespaceURI + "}" + localName);
407 }
408 checkNonNull(prefix);
409 checkNonNull(localName);
410 checkNonNull(namespaceURI);
411 setPrefixes.push(new ArrayList<>());
412 flushStartTag();
413 depth++;
414 pendingTag = new StartTag();
415 pendingTag.elementName.local = localName;
416 pendingTag.elementName.uri = namespaceURI;
417 pendingTag.elementName.prefix = prefix;
418 }
419
420 public void writeEmptyElement(String namespaceURI, String localName) throws XMLStreamException {
421 checkNonNull(namespaceURI);
422 checkNonNull(localName);
423 flushStartTag();
424 writeStartElement(namespaceURI, localName);
425 isEmptyElement = true;
426 }
427
428 public void writeEmptyElement(String prefix, String localName, String namespaceURI) throws XMLStreamException {
429 checkNonNull(prefix);
430 checkNonNull(localName);
431 checkNonNull(namespaceURI);
432 flushStartTag();
433 writeStartElement(prefix, localName, namespaceURI);
434 isEmptyElement = true;
435 }
436
437 public void writeEmptyElement(String localName) throws XMLStreamException {
438 checkNonNull(localName);
439 flushStartTag();
440 writeStartElement(localName);
441 isEmptyElement = true;
442 }
443
444 public void writeEndElement() throws XMLStreamException {
445 if (DEBUG) {
446 System.err.println("EndElement" + depth);
447 }
448 if (depth <= 0) {
449 throw new IllegalStateException("writeEndElement with no matching writeStartElement");
450 }
451 // if (isEmptyElement) {
452 // throw new IllegalStateException("writeEndElement called for an empty element");
453 // }
454 try {
455 flushStartTag();
456 setPrefixes.pop();
457 receiver.endElement();
458 depth--;
459 } catch (XPathException err) {
460 throw new XMLStreamException(err);
461 }
462 }
463
464 public void writeEndDocument() throws XMLStreamException {
465 if (depth == -1) {
466 throw new IllegalStateException("writeEndDocument with no matching writeStartDocument");
467 }
468 try {
469 flushStartTag();
470 while (depth > 0) {
471 writeEndElement();
472 }
473 receiver.endDocument();
474 depth = -1;
475 } catch (XPathException err) {
476 throw new XMLStreamException(err);
477 }
478 }
479
480 public void close() throws XMLStreamException {
481 if (depth >= 0) {
482 writeEndDocument();
483 }
484 try {
485 receiver.close();
486 } catch (XPathException err) {
487 throw new XMLStreamException(err);
488 }
489 }
490
491 public void flush() {
492 // no action
493 }
494
495 public void writeAttribute(String localName, String value) {
496 checkNonNull(localName);
497 checkNonNull(value);
498 if (pendingTag == null) {
499 throw new IllegalStateException("Cannot write attribute when not in a start tag");
500 }
501 Triple t = new Triple();
502 t.local = localName;
503 t.value = value;
504 pendingTag.attributes.add(t);
505 }
506
507 public void writeAttribute(String prefix, String namespaceURI, String localName, String value) {
508 checkNonNull(prefix);
509 checkNonNull(namespaceURI);
510 checkNonNull(localName);
511 checkNonNull(value);
512 if (pendingTag == null) {
513 throw new IllegalStateException("Cannot write attribute when not in a start tag");
514 }
515 Triple t = new Triple();
516 t.prefix = prefix;
517 t.uri = namespaceURI;
518 t.local = localName;
519 t.value = value;
520 pendingTag.attributes.add(t);
521 }
522
523 public void writeAttribute(String namespaceURI, String localName, String value) {
524 checkNonNull(namespaceURI);
525 checkNonNull(localName);
526 checkNonNull(value);
527 Triple t = new Triple();
528 t.uri = namespaceURI;
529 t.local = localName;
530 t.value = value;
531 pendingTag.attributes.add(t);
532
533 }
534
535 /**
536 * Emits a namespace declaration event.
537 *
538 * <p>If the prefix argument to this method is the empty string,
539 * "xmlns", or null this method will delegate to writeDefaultNamespace.</p>
540 *
541 * <p>This method does not change the name of any element or attribute; its only use is to write
542 * additional or redundant namespace declarations. With this implementation of XMLStreamWriter,
543 * this method is needed only to generate namespace declarations for prefixes that do not appear
544 * in element or attribute names. If an attempt is made to generate a namespace declaration that
545 * conflicts with the prefix-uri bindings in scope for element and attribute names, an exception
546 * occurs.</p>
547 *
548 * @param prefix the prefix to bind this namespace to
549 * @param namespaceURI the uri to bind the prefix to
550 * @throws IllegalStateException if the current state does not allow Namespace writing
551 * @throws XMLStreamException if things go wrong
552 */
553
554 public void writeNamespace(String prefix, String namespaceURI) throws XMLStreamException {
555 if (prefix == null || prefix.equals("") || prefix.equals("xmlns")) {
556 writeDefaultNamespace(namespaceURI);
557 } else {
558 checkNonNull(namespaceURI);
559 if (pendingTag == null) {
560 throw new IllegalStateException("Cannot write namespace when not in a start tag");
561 }
562 Triple t = new Triple();
563 t.uri = namespaceURI;
564 t.prefix = prefix;
565 pendingTag.namespaces.add(t);
566 }
567
568 }
569
570 /**
571 * Emits a default namespace declaration
572 *
573 * <p>This method does not change the name of any element or attribute; its only use is to write
574 * additional or redundant namespace declarations. With this implementation of XMLStreamWriter,
575 * this method is needed only to generate namespace declarations for prefixes that do not appear
576 * in element or attribute names. If an attempt is made to generate a namespace declaration that
577 * conflicts with the prefix-uri bindings in scope for element and attribute names, an exception
578 * occurs.</p>
579 *
580 * @param namespaceURI the uri to bind the default namespace to
581 * @throws IllegalStateException if the current state does not allow Namespace writing
582 */
583
584 public void writeDefaultNamespace(String namespaceURI) {
585 checkNonNull(namespaceURI);
586 if (pendingTag == null) {
587 throw new IllegalStateException("Cannot write namespace when not in a start tag");
588 }
589 Triple t = new Triple();
590 t.uri = namespaceURI;
591 pendingTag.namespaces.add(t);
592
593 }
594
595 public void writeComment(String data) throws XMLStreamException {
596 flushStartTag();
597 if (data == null) {
598 data = "";
599 }
600 try {
601 if (!isValidChars(data)) {
602 throw new IllegalArgumentException("Invalid XML character in comment: " + data);
603 }
604 if (isChecking && data.contains("--")) {
605 throw new IllegalArgumentException("Comment contains '--'");
606 }
607 receiver.comment(data, ExplicitLocation.UNKNOWN_LOCATION, 0);
608 } catch (XPathException err) {
609 throw new XMLStreamException(err);
610 }
611 }
612
613 public void writeProcessingInstruction(String target) throws XMLStreamException {
614 writeProcessingInstruction(target, "");
615 }
616
617 public void writeProcessingInstruction(/*@NotNull*/ String target, /*@NotNull*/ String data) throws XMLStreamException {
618 checkNonNull(target);
619 checkNonNull(data);
620 flushStartTag();
621 try {
622 if (isChecking) {
623 if (!isValidNCName(target) || "xml".equalsIgnoreCase(target)) {
624 throw new IllegalArgumentException("Invalid PITarget: " + target);
625 }
626 if (!isValidChars(data)) {
627 throw new IllegalArgumentException("Invalid character in PI data: " + data);
628 }
629 }
630 receiver.processingInstruction(target, data, ExplicitLocation.UNKNOWN_LOCATION, 0);
631 } catch (XPathException err) {
632 throw new XMLStreamException(err);
633 }
634 }
635
636 public void writeCData(/*@NotNull*/ String data) throws XMLStreamException {
637 checkNonNull(data);
638 flushStartTag();
639 writeCharacters(data);
640 }
641
642 public void writeDTD(String dtd) throws XMLStreamException {
643 // no-op
644 }
645
646 public void writeEntityRef(String name) {
647 throw new UnsupportedOperationException("writeEntityRef");
648 }
649
650 public void writeStartDocument() throws XMLStreamException {
651 writeStartDocument("utf-8", "1.0");
652 }
653
654 public void writeStartDocument(/*@Nullable*/ String version) throws XMLStreamException {
655 writeStartDocument("utf-8", version);
656 }
657
658 public void writeStartDocument(/*@Nullable*/ String encoding, /*@Nullable*/ String version) throws XMLStreamException {
659 if (encoding == null) {
660 encoding = "utf-8";
661 }
662 if (version == null) {
663 version = "1.0";
664 }
665 if (depth != -1) {
666 throw new IllegalStateException("writeStartDocument must be the first call");
667 }
668 try {
669 receiver.open();
670 receiver.startDocument(0);
671 } catch (XPathException err) {
672 throw new XMLStreamException(err);
673 }
674 depth = 0;
675 }
676
677 public void writeCharacters(String text)
678 throws XMLStreamException {
679 checkNonNull(text);
680 flushStartTag();
681 if (!isValidChars(text)) {
682 throw new IllegalArgumentException("illegal XML character: " + text);
683 }
684 try {
685 receiver.characters(text, ExplicitLocation.UNKNOWN_LOCATION, 0);
686 } catch (XPathException err) {
687 throw new XMLStreamException(err);
688 }
689 }
690
691 public void writeCharacters(char[] text, int start, int len)
692 throws XMLStreamException {
693 checkNonNull(text);
694 writeCharacters(new String(text, start, len));
695 }
696
697 public String getPrefix(String uri) {
698 for (int i=setPrefixes.size()-1; i>=0; i--) {
699 List<NamespaceBinding> bindings = setPrefixes.get(i);
700 for (int j=bindings.size()-1; j>=0; j--) {
701 NamespaceBinding binding = bindings.get(j);
702 if (binding.getURI().equals(uri)) {
703 return binding.getPrefix();
704 }
705 }
706 }
707 if (rootNamespaceContext != null) {
708 return rootNamespaceContext.getPrefix(uri);
709 }
710 return null;
711 }
712
713 public void setPrefix(String prefix, String uri) {
714 // See Saxon bug 2398: this should have stack-like effect
715 checkNonNull(prefix);
716 if (uri == null) {
717 uri = "";
718 }
719 if (isInvalidURI(uri)) {
720 throw new IllegalArgumentException("Invalid namespace URI: " + uri);
721 }
722 if (!"".equals(prefix) && !isValidNCName(prefix)) {
723 throw new IllegalArgumentException("Invalid namespace prefix: " + prefix);
724 }
725 setPrefixes.peek().add(new NamespaceBinding(prefix, uri));
726 }
727
728 public void setDefaultNamespace(String uri) {
729 setPrefix("", uri);
730 }
731
732 public void setNamespaceContext(javax.xml.namespace.NamespaceContext context) {
733 // Note, we do not enforce the rule that this can only be called once, because the spec is self-contradictory
734 // on this point.
735 if (depth > 0) {
736 throw new IllegalStateException("setNamespaceContext may only be called at the start of the document");
737 }
738 // Unfortunately the JAXP NamespaceContext class does not allow us to discover all the namespaces
739 // that were declared, nor to declare new ones. So we have to retain it separately
740 rootNamespaceContext = context;
741 }
742
743 /**
744 * Return the current namespace context.
745 *
746 * <p>The specification of this method is hopelessly vague. This method returns a namespace context
747 * that contains the namespaces declared using {@link #setPrefix(String, String)} calls that are
748 * in-scope at the time, overlaid on the root namespace context that was defined using
749 * {@link #setNamespaceContext(NamespaceContext)}. The namespaces bound using {@link #setPrefix(String, String)}
750 * are copied, and are therefore unaffected by subsequent changes, but the root namespace context
751 * is not copied, because the NamespaceContext interface provides no way of doing so.</p>
752 * @return a copy of the current namespace context.
753 */
754 public javax.xml.namespace.NamespaceContext getNamespaceContext() {
755 return new NamespaceContext() {
756 final NamespaceContext rootNamespaceContext = StreamWriterToReceiver.this.rootNamespaceContext;
757 final Map<String, String> bindings = new HashMap<>();
758
759 {
760 for (List<NamespaceBinding> list : setPrefixes) {
761 for (NamespaceBinding binding : list) {
762 bindings.put(binding.getPrefix(), binding.getURI());
763 }
764 }
765 }
766
767 public String getNamespaceURI(String prefix) {
768 String uri = bindings.get(prefix);
769 if (uri != null) {
770 return uri;
771 }
772 return rootNamespaceContext.getNamespaceURI(prefix);
773 }
774
775 public String getPrefix(String namespaceURI) {
776 for (Map.Entry<String, String> entry : bindings.entrySet()) {
777 if (entry.getValue().equals(namespaceURI)) {
778 return entry.getKey();
779 }
780 }
781 return rootNamespaceContext.getPrefix(namespaceURI);
782 }
783
784 public Iterator<String> getPrefixes(String namespaceURI) {
785 List<String> prefixes = new ArrayList<>();
786 for (Map.Entry<String, String> entry : bindings.entrySet()) {
787 if (entry.getValue().equals(namespaceURI)) {
788 prefixes.add(entry.getKey());
789 }
790 }
791 Iterator root = rootNamespaceContext.getPrefixes(namespaceURI);
792 while (root.hasNext()) {
793 prefixes.add((String)root.next());
794 }
795 return prefixes.iterator();
796 }
797 };
798 }
799
800 public Object getProperty(String name) throws IllegalArgumentException {
801 if (name.equals("javax.xml.stream.isRepairingNamespaces")) {
802 return receiver instanceof NamespaceReducer;
803 } else {
804 throw new IllegalArgumentException(name);
805 }
806 }
807
808 /**
809 * Test whether a supplied name is a valid NCName
810 *
811 * @param name the name to be tested
812 * @return true if the name is valid or if checking is disabled
813 */
814
815 private boolean isValidNCName(String name) {
816 return !isChecking || NameChecker.isValidNCName(name);
817 }
818
819 /**
820 * Test whether a supplied character string is valid in XML
821 *
822 * @param text the string to be tested
823 * @return true if the string is valid or if checking is disabled
824 */
825
826 private boolean isValidChars(String text) {
827 return !isChecking || (UTF16CharacterSet.firstInvalidChar(text, charChecker) == -1);
828 }
829
830 /**
831 * Test whether a supplied namespace URI is a valid URI
832 *
833 * @param uri the namespace URI to be tested
834 * @return true if the name is invalid (unless checking is disabled)
835 */
836
837 private boolean isInvalidURI(String uri) {
838 return isChecking && !StandardURIChecker.getInstance().isValidURI(uri);
839 }
840
841 private void checkNonNull(Object value) {
842 if (value == null) {
843 throw new NullPointerException();
844 }
845 }
846
847 }
848