Debian Codegraph @

net/sf/saxon/serialize/XMLEmitter.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.serialize;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.ReceiverOptions;
12 import net.sf.saxon.expr.parser.Location;
13 import net.sf.saxon.lib.SaxonOutputKeys;
14 import net.sf.saxon.om.NamespaceBinding;
15 import net.sf.saxon.om.NamespaceBindingSet;
16 import net.sf.saxon.om.NodeName;
17 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
18 import net.sf.saxon.serialize.charcode.UTF8CharacterSet;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.tiny.CharSlice;
21 import net.sf.saxon.tree.tiny.CompressedWhitespace;
22 import net.sf.saxon.tree.util.FastStringBuffer;
23 import net.sf.saxon.type.SchemaType;
24 import net.sf.saxon.type.SimpleType;
25 import net.sf.saxon.value.Whitespace;
26
27 import javax.xml.transform.OutputKeys;
28 import java.util.Arrays;
29 import java.util.Properties;
30 import java.util.Stack;
31
32 /**
33 * XMLEmitter is an Emitter that generates XML output
34 * to a specified destination.
35 */
36
37 public class XMLEmitter extends Emitter {
38
39 // NOTE: we experimented with XMLUTF8Emitter which combines XML escaping and UTF8 encoding
40 // into a single loop. Scrapped it because we couldn't measure any benefits - but there
41 // ought to be, in theory. Perhaps we weren't buffering the writes carefully enough.
42
43 protected boolean canonical = false;
44 protected boolean started = false;
45 protected boolean startedElement = false;
46 protected boolean openStartTag = false;
47 protected boolean declarationIsWritten = false;
48 protected NodeName elementCode;
49 protected int indentForNextAttribute = -1;
50 protected boolean undeclareNamespaces = false;
51 protected boolean unfailing = false;
52 protected char delimiter = '"';
53 protected boolean[] attSpecials = specialInAtt;
54
55 // The element stack holds the display names (lexical QNames) of elements that
56 // have been started but not finished. It is used to obtain the element name
57 // for the end tag.
58
59 protected Stack<String> elementStack = new Stack<>();
60
61 // For other names we use a hashtable. It
62
63 private boolean indenting = false;
64 private String indentChars = "\n ";
65 private boolean requireWellFormed = false;
66 protected CharacterReferenceGenerator characterReferenceGenerator = HexCharacterReferenceGenerator.THE_INSTANCE;
67
68
69 static boolean[] specialInText; // lookup table for special characters in text
70 static boolean[] specialInAtt; // lookup table for special characters in attributes
71 static boolean[] specialInAttSingle; // lookup table for special characters in attributes with single-quote delimiter
72 // create look-up table for ASCII characters that need special treatment
73
74 static {
75 specialInText = new boolean[128];
76 for (int i = 0; i <= 31; i++) {
77 specialInText[i] = true; // allowed in XML 1.1 as character references
78 }
79 for (int i = 32; i <= 127; i++) {
80 specialInText[i] = false;
81 }
82 // note, 0 is used to switch escaping on and off for mapped characters
83 specialInText['\n'] = false;
84 specialInText['\t'] = false;
85 specialInText['\r'] = true;
86 specialInText['<'] = true;
87 specialInText['>'] = true;
88 specialInText['&'] = true;
89
90 specialInAtt = new boolean[128];
91 for (int i = 0; i <= 31; i++) {
92 specialInAtt[i] = true; // allowed in XML 1.1 as character references
93 }
94 for (int i = 32; i <= 127; i++) {
95 specialInAtt[i] = false;
96 }
97 specialInAtt[(char) 0] = true;
98 // used to switch escaping on and off for mapped characters
99 specialInAtt['\r'] = true;
100 specialInAtt['\n'] = true;
101 specialInAtt['\t'] = true;
102 specialInAtt['<'] = true;
103 specialInAtt['>'] = true;
104 specialInAtt['&'] = true;
105 specialInAtt['\"'] = true;
106
107 specialInAttSingle = Arrays.copyOf(specialInAtt, 128);
108 specialInAttSingle['\"'] = false;
109 specialInAttSingle['\''] = true;
110 }
111
112 /**
113 * Set the character reference generator to be used for generating hexadecimal or decimal
114 * character references
115 *
116 * @param generator the character reference generator to be used
117 */
118
119 public void setCharacterReferenceGenerator(CharacterReferenceGenerator generator) {
120 this.characterReferenceGenerator = generator;
121 }
122
123 /**
124 * Say that all non-ASCII characters should be escaped, regardless of the character encoding
125 *
126 * @param escape true if all non ASCII characters should be escaped
127 */
128
129 public void setEscapeNonAscii(Boolean escape) {
130 // no action (not currently supported for this output method
131 }
132
133 /**
134 * Start of the event stream. Nothing is done at this stage: the opening of the output
135 * file is deferred until some content is written to it.
136 */
137
138 public void open() throws XPathException {
139 }
140
141 /**
142 * Start of a document node. Nothing is done at this stage: the opening of the output
143 * file is deferred until some content is written to it.
144 */
145
146 public void startDocument(int properties) throws XPathException {
147 }
148
149 /**
150 * Notify the end of a document node
151 */
152
153 public void endDocument() throws XPathException {
154 // Following code removed as a result of bug 2323. If a failure occurs during xsl:result-document processing,
155 // and the output is being written to a SAXResult, then the ContentHandler.endDocument() method is called in order
156 // to close any open files; and this calls Emitter.endDocument() at a point where the output is incomplete.
157 // if (!elementStack.isEmpty()) {
158 // throw new IllegalStateException("Attempt to end document in serializer when elements are unclosed");
159 // }
160 }
161
162 /**
163 * Do the real work of starting the document. This happens when the first
164 * content is written.
165 *
166 * @throws XPathException f an error occurs opening the output file
167 */
168
169 protected void openDocument() throws XPathException {
170 if (writer == null) {
171 makeWriter();
172 }
173 if (characterSet == null) {
174 characterSet = UTF8CharacterSet.getInstance();
175 }
176 if (outputProperties == null) {
177 outputProperties = new Properties();
178 }
179
180 undeclareNamespaces = "yes".equals(outputProperties.getProperty(SaxonOutputKeys.UNDECLARE_PREFIXES));
181 canonical = "yes".equals(outputProperties.getProperty(SaxonOutputKeys.CANONICAL));
182 unfailing = "yes".equals(outputProperties.getProperty(SaxonOutputKeys.UNFAILING));
183
184 if ("yes".equals(outputProperties.getProperty(SaxonOutputKeys.SINGLE_QUOTES))) {
185 delimiter = '\'';
186 attSpecials = specialInAttSingle;
187 }
188 writeDeclaration();
189 }
190
191 /**
192 * Output the XML declaration
193 */
194
195 public void writeDeclaration() throws XPathException {
196 if (declarationIsWritten) {
197 return;
198 }
199 declarationIsWritten = true;
200 try {
201 indenting = "yes".equals(outputProperties.getProperty(OutputKeys.INDENT));
202
203 String byteOrderMark = outputProperties.getProperty(SaxonOutputKeys.BYTE_ORDER_MARK);
204 String encoding = outputProperties.getProperty(OutputKeys.ENCODING);
205 if (encoding == null || encoding.equalsIgnoreCase("utf8") || canonical) {
206 encoding = "UTF-8";
207 }
208
209 if ("yes".equals(byteOrderMark) && !canonical && (
210 "UTF-8".equalsIgnoreCase(encoding) ||
211 "UTF-16LE".equalsIgnoreCase(encoding) ||
212 "UTF-16BE".equalsIgnoreCase(encoding))) {
213 writer.write('\uFEFF');
214 }
215
216 String omitXMLDeclaration = outputProperties.getProperty(OutputKeys.OMIT_XML_DECLARATION);
217 if (omitXMLDeclaration == null) {
218 omitXMLDeclaration = "no";
219 }
220
221 if (canonical) {
222 omitXMLDeclaration = "yes";
223 }
224
225 String version = outputProperties.getProperty(OutputKeys.VERSION);
226 if (version == null) {
227 version = getConfiguration().getXMLVersion() == Configuration.XML10 ? "1.0" : "1.1";
228 } else {
229 if (!version.equals("1.0") && !version.equals("1.1")) {
230 if (unfailing) {
231 version = "1.0";
232 } else {
233 XPathException err = new XPathException("XML version must be 1.0 or 1.1");
234 err.setErrorCode("SESU0013");
235 throw err;
236 }
237 }
238 if (!version.equals("1.0") && omitXMLDeclaration.equals("yes") &&
239 outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM) != null) {
240 if (!unfailing) {
241 XPathException err = new XPathException("Values of 'version', 'omit-xml-declaration', and 'doctype-system' conflict");
242 err.setErrorCode("SEPM0009");
243 throw err;
244 }
245 }
246 }
247
248 String undeclare = outputProperties.getProperty(SaxonOutputKeys.UNDECLARE_PREFIXES);
249 if ("yes".equals(undeclare)) {
250 undeclareNamespaces = true;
251 }
252
253 if (version.equals("1.0") && undeclareNamespaces) {
254 if (unfailing) {
255 undeclareNamespaces = false;
256 } else {
257 XPathException err = new XPathException("Cannot undeclare namespaces with XML version 1.0");
258 err.setErrorCode("SEPM0010");
259 throw err;
260 }
261 }
262
263 String standalone = outputProperties.getProperty(OutputKeys.STANDALONE);
264 if ("omit".equals(standalone)) {
265 standalone = null;
266 }
267
268 if (standalone != null) {
269 requireWellFormed = true;
270 if (omitXMLDeclaration.equals("yes") && !unfailing) {
271 XPathException err = new XPathException("Values of 'standalone' and 'omit-xml-declaration' conflict");
272 err.setErrorCode("SEPM0009");
273 throw err;
274 }
275 }
276
277 String systemId = outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM);
278 if (systemId != null && !"".equals(systemId)) {
279 requireWellFormed = true;
280 }
281
282 if (omitXMLDeclaration.equals("no")) {
283 writer.write("<?xml version=\"" + version + "\" " + "encoding=\"" + encoding + '\"' +
284 (standalone != null ? " standalone=\"" + standalone + '\"' : "") + "?>");
285 // don't write a newline character: it's wrong if the output is an
286 // external general parsed entity
287 }
288 } catch (java.io.IOException err) {
289 throw new XPathException("Failure writing to " + getSystemId(), err);
290 }
291 }
292
293 /**
294 * Output the document type declaration
295 *
296 * @param name the qualified name of the element
297 * @param displayName The element name as displayed
298 * @param systemId The DOCTYPE system identifier
299 * @param publicId The DOCTYPE public identifier
300 * @throws net.sf.saxon.trans.XPathException if an error occurs writing to the output
301 */
302
303 protected void writeDocType(NodeName name, String displayName, String systemId, String publicId) throws XPathException {
304 try {
305 if (!canonical) {
306 if (declarationIsWritten && !indenting) {
307 // don't add a newline if indenting, because the indenter will already have done so
308 writer.write("\n");
309 }
310 writer.write("<!DOCTYPE " + displayName + '\n');
311 String quotedSystemId = null;
312 if (systemId != null) {
313 if (systemId.contains("\"")) {
314 quotedSystemId = "'" + systemId + "'";
315 } else {
316 quotedSystemId = '"' + systemId + '"';
317 }
318 }
319 if (systemId != null && publicId == null) {
320 writer.write(" SYSTEM " + quotedSystemId + ">\n");
321 } else if (systemId == null && publicId != null) { // handles the HTML case
322 writer.write(" PUBLIC \"" + publicId + "\">\n");
323 } else {
324 writer.write(" PUBLIC \"" + publicId + "\" " + quotedSystemId + ">\n");
325 }
326 }
327 } catch (java.io.IOException err) {
328 throw new XPathException("Failure writing to " + getSystemId(), err);
329 }
330 }
331
332 /**
333 * End of the document.
334 */
335
336 public void close() throws XPathException {
337 // if nothing has been written, we should still create the file and write an XML declaration
338 if (!started) {
339 openDocument();
340 }
341 try {
342 if (writer != null) {
343 writer.flush();
344 }
345 } catch (java.io.IOException err) {
346 throw new XPathException("Failure writing to " + getSystemId(), err);
347 }
348 super.close();
349 }
350
351 /**
352 * Start of an element. Output the start tag, escaping special characters.
353 */
354
355 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
356 try {
357 previousAtomic = false;
358 if (!started) {
359 openDocument();
360 } else if (requireWellFormed && elementStack.isEmpty() && startedElement && !unfailing) {
361 XPathException err = new XPathException("When 'standalone' or 'doctype-system' is specified, " +
362 "the document must be well-formed; but this document contains more than one top-level element");
363 err.setErrorCode("SEPM0004");
364 throw err;
365 }
366 startedElement = true;
367
368 String displayName = elemName.getDisplayName();
369 if (!allCharactersEncodable) {
370 int badchar = testCharacters(displayName);
371 if (badchar != 0) {
372 XPathException err = new XPathException("Element name contains a character (decimal + " +
373 badchar + ") not available in the selected encoding");
374 err.setErrorCode("SERE0008");
375 throw err;
376 }
377 }
378
379 elementStack.push(displayName);
380 elementCode = elemName;
381
382 try {
383 if (!started) {
384 String systemId = outputProperties.getProperty(OutputKeys.DOCTYPE_SYSTEM);
385 String publicId = outputProperties.getProperty(OutputKeys.DOCTYPE_PUBLIC);
386 // Treat "" as equivalent to absent. This goes beyond what the spec strictly allows.
387 if ("".equals(systemId)) {
388 systemId = null;
389 }
390 if ("".equals(publicId)) {
391 publicId = null;
392 }
393 if (systemId != null) {
394 requireWellFormed = true;
395 writeDocType(elemName, displayName, systemId, publicId);
396 } else if (writeDocTypeWithNullSystemId()) {
397 writeDocType(elemName, displayName, null, publicId);
398 }
399 started = true;
400 }
401 if (openStartTag) {
402 closeStartTag();
403 }
404 writer.write('<');
405 writer.write(displayName);
406 openStartTag = true;
407 indentForNextAttribute = -1;
408
409 } catch (java.io.IOException err) {
410 throw new XPathException("Failure writing to " + getSystemId(), err);
411 }
412 } catch (XPathException e) {
413 e.maybeSetLocation(location);
414 throw e;
415 }
416 }
417
418 protected boolean writeDocTypeWithNullSystemId() {
419 return false;
420 }
421
422
423 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
424 try {
425 for (NamespaceBinding ns : namespaceBindings) {
426 String nsprefix = ns.getPrefix();
427 String nsuri = ns.getURI();
428
429 String sep = getAttributeIndentString();
430
431 if (nsprefix.isEmpty()) {
432 writer.write(sep);
433 writeAttribute(elementCode, "xmlns", nsuri, 0);
434 } else if (nsprefix.equals("xml")) {
435 //return;
436 } else {
437 int badchar = testCharacters(nsprefix);
438 if (badchar != 0) {
439 XPathException err = new XPathException("Namespace prefix contains a character (decimal + " +
440 badchar + ") not available in the selected encoding");
441 err.setErrorCode("SERE0008");
442 throw err;
443 }
444 if (undeclareNamespaces || !nsuri.isEmpty()) {
445 writer.write(sep);
446 writeAttribute(elementCode, "xmlns:" + nsprefix, nsuri, 0);
447 }
448 }
449 }
450 } catch (java.io.IOException err) {
451 throw new XPathException("Failure writing to " + getSystemId(), err);
452 }
453 }
454
455 public void setIndentForNextAttribute(int indent) {
456 indentForNextAttribute = indent;
457 }
458
459 public void attribute(NodeName nameCode, SimpleType typeCode, CharSequence value, Location locationId, int properties)
460 throws XPathException {
461
462 String displayName = nameCode.getDisplayName();
463 if (!allCharactersEncodable) {
464 int badchar = testCharacters(displayName);
465 if (badchar != 0) {
466 if (unfailing) {
467 displayName = convertToAscii(displayName);
468 } else {
469 XPathException err = new XPathException("Attribute name contains a character (decimal + " +
470 badchar + ") not available in the selected encoding");
471 err.setErrorCode("SERE0008");
472 throw err;
473 }
474 }
475 }
476
477 try {
478 writer.write(getAttributeIndentString());
479 } catch (java.io.IOException err) {
480 throw new XPathException("Failure writing to " + getSystemId(), err);
481 }
482
483
484 writeAttribute(
485 elementCode,
486 displayName,
487 value,
488 properties);
489
490
491 }
492
493 protected String getAttributeIndentString() {
494 if (indentForNextAttribute < 0) {
495 return " ";
496 } else {
497 int indent = indentForNextAttribute;
498 while (indent >= indentChars.length()) {
499 //noinspection StringConcatenationInLoop
500 indentChars += " ";
501 }
502 return indentChars.substring(0, indent);
503 }
504 }
505
506
507 public void startContent() throws XPathException {
508 // don't add ">" to the start tag until we know whether the element has content
509 }
510
511 /**
512 * Mark the end of the start tag
513 *
514 * @throws XPathException if an IO exception occurs
515 */
516
517 public void closeStartTag() throws XPathException {
518 try {
519 if (openStartTag) {
520 writer.write('>');
521 openStartTag = false;
522 }
523 } catch (java.io.IOException err) {
524 throw new XPathException("Failure writing to " + getSystemId(), err);
525 }
526 }
527
528 /**
529 * Close an empty element tag. (This is overridden in XHTMLEmitter).
530 *
531 * @param displayName the name of the empty element
532 * @param nameCode the fingerprint of the name of the empty element
533 * @return the string used to close an empty element tag.
534 */
535
536 protected String emptyElementTagCloser(String displayName, NodeName nameCode) {
537 return canonical ? "></" + displayName + ">" : "/>";
538 }
539
540 /**
541 * Write attribute name=value pair.
542 *
543 * @param elCode The element name is not used in this version of the
544 * method, but is used in the HTML subclass.
545 * @param attname The attribute name, which has already been validated to ensure
546 * it can be written in this encoding
547 * @param value The value of the attribute
548 * @param properties Any special properties of the attribute
549 * @throws net.sf.saxon.trans.XPathException if an error occurs
550 */
551
552 protected void writeAttribute(NodeName elCode, String attname, CharSequence value, int properties) throws XPathException {
553 try {
554 String val = value.toString();
555 writer.write(attname);
556 if ((properties & ReceiverOptions.NO_SPECIAL_CHARS) != 0) {
557 writer.write('=');
558 writer.write(delimiter);
559 writer.write(val);
560 writer.write(delimiter);
561 } else if ((properties & ReceiverOptions.USE_NULL_MARKERS) != 0) {
562 // null (0) characters will be used before and after any section of
563 // the value generated from a character map
564 writer.write('=');
565 char delim = val.indexOf('"') >= 0 && val.indexOf('\'') < 0 ? '\'' : delimiter;
566 writer.write(delim);
567 writeEscape(value, true);
568 writer.write(delim);
569 } else {
570 writer.write("=");
571 writer.write(delimiter);
572 writeEscape(value, true);
573 writer.write(delimiter);
574 }
575 } catch (java.io.IOException err) {
576 throw new XPathException("Failure writing to " + getSystemId(), err);
577 }
578 }
579
580
581 /**
582 * Test that all characters in a name (for example) are supported in the target encoding.
583 *
584 * @param chars the characters to be tested
585 * @return zero if all the characters are available, or the value of the
586 * first offending character if not
587 */
588
589 protected int testCharacters(CharSequence chars) {
590 for (int i = 0; i < chars.length(); i++) {
591 char c = chars.charAt(i);
592 if (c > 127) {
593 if (UTF16CharacterSet.isHighSurrogate(c)) {
594 int cc = UTF16CharacterSet.combinePair(c, chars.charAt(++i));
595 if (!characterSet.inCharset(cc)) {
596 return cc;
597 }
598 } else if (!characterSet.inCharset(c)) {
599 return c;
600 }
601 }
602 }
603 return 0;
604 }
605
606 /**
607 * Where characters are not available in the selected encoding, substitute them
608 */
609
610 protected String convertToAscii(CharSequence chars) {
611 FastStringBuffer buff = new FastStringBuffer(chars.length());
612 for (int i = 0; i < chars.length(); i++) {
613 char c = chars.charAt(i);
614 if (c >= 20 && c < 127) {
615 buff.append(c);
616 } else {
617 buff.append("_" + (int) c + "_");
618 }
619 }
620 return buff.toString();
621 }
622
623 /**
624 * End of an element.
625 */
626
627 public void endElement() throws XPathException {
628 String displayName = elementStack.pop();
629 try {
630 if (openStartTag) {
631 writer.write(emptyElementTagCloser(displayName, elementCode));
632 openStartTag = false;
633 } else {
634 writer.write("</");
635 writer.write(displayName);
636 writer.write('>');
637 }
638 } catch (java.io.IOException err) {
639 throw new XPathException("Failure writing to " + getSystemId(), err);
640 }
641 }
642
643 /**
644 * Character data.
645 */
646
647 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
648 if (!started) {
649 openDocument();
650 }
651
652 if (requireWellFormed && elementStack.isEmpty() && !Whitespace.isWhite(chars) && !unfailing) {
653 XPathException err = new XPathException("When 'standalone' or 'doctype-system' is specified, " +
654 "the document must be well-formed; but this document contains a top-level text node");
655 err.setErrorCode("SEPM0004");
656 throw err;
657 }
658
659 try {
660 if (openStartTag) {
661 closeStartTag();
662 }
663
664 if ((properties & ReceiverOptions.NO_SPECIAL_CHARS) != 0) {
665 writeCharSequence(chars);
666 } else if ((properties & ReceiverOptions.DISABLE_ESCAPING) == 0) {
667 writeEscape(chars, false);
668 } else {
669 // disable-output-escaping="yes"
670 if (testCharacters(chars) == 0) {
671 if ((properties & ReceiverOptions.USE_NULL_MARKERS) == 0) {
672 // null (0) characters will be used before and after any section of
673 // the value generated from a character map
674 writeCharSequence(chars);
675 } else {
676 // Need to strip out any null markers. See test output-html109
677 final int len = chars.length();
678 for (int i = 0; i < len; i++) {
679 char c = chars.charAt(i);
680 if (c != 0) {
681 writer.write(c);
682 }
683 }
684 }
685 } else {
686 // Using disable output escaping with characters
687 // that are not available in the target encoding
688 // The required action is to ignore d-o-e in respect of those characters that are
689 // not available in the encoding. This is slow...
690 final int len = chars.length();
691 for (int i = 0; i < len; i++) {
692 char c = chars.charAt(i);
693 if (c != 0) {
694 if (c > 127 && UTF16CharacterSet.isHighSurrogate(c)) {
695 char[] pair = new char[2];
696 pair[0] = c;
697 pair[1] = chars.charAt(++i);
698 int cc = UTF16CharacterSet.combinePair(c, pair[1]);
699 if (!characterSet.inCharset(cc)) {
700 writeEscape(new CharSlice(pair), false);
701 } else {
702 writeCharSequence(new CharSlice(pair));
703 }
704 } else {
705 char[] ca = {c};
706 if (!characterSet.inCharset(c)) {
707 writeEscape(new CharSlice(ca), false);
708 } else {
709 writeCharSequence(new CharSlice(ca));
710 }
711 }
712 }
713 }
714 }
715 }
716 } catch (java.io.IOException err) {
717 throw new XPathException("Failure writing to " + getSystemId(), err);
718 }
719 }
720
721 /**
722 * Write a CharSequence (without any escaping of special characters): various implementations
723 *
724 * @param s the character sequence to be written
725 * @throws java.io.IOException in the event of a failure to write to the output file
726 */
727
728 public void writeCharSequence(CharSequence s) throws java.io.IOException {
729 if (s instanceof String) {
730 writer.write((String) s);
731 } else if (s instanceof CharSlice) {
732 ((CharSlice) s).write(writer);
733 } else if (s instanceof FastStringBuffer) {
734 ((FastStringBuffer) s).write(writer);
735 } else if (s instanceof CompressedWhitespace) {
736 ((CompressedWhitespace) s).write(writer);
737 } else {
738 writer.write(s.toString());
739 }
740 }
741
742
743 /**
744 * Handle a processing instruction.
745 */
746
747 public void processingInstruction(String target, CharSequence data, Location locationId, int properties)
748 throws XPathException {
749 if (!started) {
750 openDocument();
751 }
752 int x = testCharacters(target);
753 if (x != 0) {
754 if (unfailing) {
755 target = convertToAscii(target);
756 } else {
757 XPathException err = new XPathException("Character in processing instruction name cannot be represented " +
758 "in the selected encoding (code " + x + ')');
759 err.setErrorCode("SERE0008");
760 throw err;
761 }
762 }
763 x = testCharacters(data);
764 if (x != 0) {
765 if (unfailing) {
766 data = convertToAscii(data);
767 } else {
768 XPathException err = new XPathException("Character in processing instruction data cannot be represented " +
769 "in the selected encoding (code " + x + ')');
770 err.setErrorCode("SERE0008");
771 throw err;
772 }
773 }
774 try {
775 if (openStartTag) {
776 closeStartTag();
777 }
778 writer.write("<?" + target + (data.length() > 0 ? ' ' + data.toString() : "") + "?>");
779 } catch (java.io.IOException err) {
780 throw new XPathException("Failure writing to " + getSystemId(), err);
781 }
782 }
783
784 /**
785 * Write contents of array to current writer, after escaping special characters.
786 * This method converts the XML special characters (such as &lt; and &amp;) into their
787 * predefined entities.
788 *
789 * @param chars The character sequence containing the string
790 * @param inAttribute Set to true if the text is in an attribute value
791 */
792
793 protected void writeEscape(final CharSequence chars, final boolean inAttribute)
794 throws java.io.IOException, XPathException {
795 int segstart = 0;
796 boolean disabled = false;
797 final boolean[] specialChars = inAttribute ? attSpecials : specialInText;
798
799 if (chars instanceof CompressedWhitespace) {
800 ((CompressedWhitespace) chars).writeEscape(specialChars, writer);
801 return;
802 }
803
804 final int clength = chars.length();
805 while (segstart < clength) {
806 int i = segstart;
807 // find a maximal sequence of "ordinary" characters
808 while (i < clength) {
809 final char c = chars.charAt(i);
810 if (c < 127) {
811 if (specialChars[c]) {
812 break;
813 } else {
814 i++;
815 }
816 } else if (c < 160) {
817 break;
818 } else if (c == 0x2028) {
819 break;
820 } else if (UTF16CharacterSet.isHighSurrogate(c)) {
821 break;
822 } else if (!characterSet.inCharset(c)) {
823 break;
824 } else {
825 i++;
826 }
827 }
828
829 // if this was the whole string write it out and exit
830 if (i >= clength) {
831 if (segstart == 0) {
832 writeCharSequence(chars);
833 } else {
834 writeCharSequence(chars.subSequence(segstart, i));
835 }
836 return;
837 }
838
839 // otherwise write out this sequence
840 if (i > segstart) {
841 writeCharSequence(chars.subSequence(segstart, i));
842 }
843
844 // examine the special character that interrupted the scan
845 final char c = chars.charAt(i);
846 if (c == 0) {
847 // used to switch escaping on and off
848 disabled = !disabled;
849 } else if (disabled) {
850 if (c > 127) {
851 if (UTF16CharacterSet.isHighSurrogate(c)) {
852 int cc = UTF16CharacterSet.combinePair(c, chars.charAt(i + 1));
853 if (!characterSet.inCharset(cc)) {
854 XPathException de = new XPathException("Character x" + Integer.toHexString(cc) +
855 " is not available in the chosen encoding");
856 de.setErrorCode("SERE0008");
857 throw de;
858 }
859 } else if (!characterSet.inCharset(c)) {
860 XPathException de = new XPathException("Character " + c + " (x" + Integer.toHexString((int) c) +
861 ") is not available in the chosen encoding");
862 de.setErrorCode("SERE0008");
863 throw de;
864 }
865 }
866 writer.write(c);
867 } else if (c < 127) {
868 // process special ASCII characters
869 switch (c) {
870 case '<':
871 writer.write("&lt;");
872 break;
873 case '>':
874 writer.write("&gt;");
875 break;
876 case '&':
877 writer.write("&amp;");
878 break;
879 case '\"':
880 writer.write("&#34;");
881 break;
882 case '\'':
883 writer.write("&#39;");
884 break;
885 case '\n':
886 writer.write("&#xA;");
887 break;
888 case '\r':
889 writer.write("&#xD;");
890 break;
891 case '\t':
892 writer.write("&#x9;");
893 break;
894 default:
895 // C0 control characters
896 characterReferenceGenerator.outputCharacterReference(c, writer);
897 break;
898 }
899 } else if (c < 160 || c == 0x2028) {
900 // XML 1.1 requires these characters to be written as character references
901 characterReferenceGenerator.outputCharacterReference(c, writer);
902 } else if (UTF16CharacterSet.isHighSurrogate(c)) {
903 char d = chars.charAt(++i);
904 int charval = UTF16CharacterSet.combinePair(c, d);
905 if (characterSet.inCharset(charval)) {
906 writer.write(c);
907 writer.write(d);
908 } else {
909 characterReferenceGenerator.outputCharacterReference(charval, writer);
910 }
911 } else {
912 // process characters not available in the current encoding
913 characterReferenceGenerator.outputCharacterReference(c, writer);
914 }
915 segstart = ++i;
916 }
917 }
918
919
920 /**
921 * Handle a comment.
922 */
923
924 public void comment(CharSequence chars, Location locationId, int properties) throws XPathException {
925 if (!started) {
926 openDocument();
927 }
928 int x = testCharacters(chars);
929 if (x != 0) {
930 if (unfailing) {
931 chars = convertToAscii(chars);
932 } else {
933 XPathException err = new XPathException("Character in comment cannot be represented " +
934 "in the selected encoding (code " + x + ')');
935 err.setErrorCode("SERE0008");
936 throw err;
937 }
938 }
939 try {
940 if (openStartTag) {
941 closeStartTag();
942 }
943 writer.write("<!--");
944 writer.write(chars.toString());
945 writer.write("-->");
946 } catch (java.io.IOException err) {
947 throw new XPathException("Failure writing to " + getSystemId(), err);
948 }
949 }
950
951 /**
952 * Ask whether this Receiver (or the downstream pipeline) makes any use of the type annotations
953 * supplied on element and attribute events
954 *
955 * @return true if the Receiver makes any use of this information. If false, the caller
956 * may supply untyped nodes instead of supplying the type annotation
957 */
958
959 public boolean usesTypeAnnotations() {
960 return false;
961 }
962
963 /**
964 * Ask whether anything has yet been written
965 *
966 * @return true if content has been output
967 */
968
969 public boolean isStarted() {
970 return started;
971 }
972
973
974 }
975