/
ToStream.java
3609 lines (3277 loc) · 123 KB
/
ToStream.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id$
*/
package org.apache.xml.serializer;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.EmptyStackException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.xml.transform.ErrorListener;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import org.apache.xml.serializer.utils.MsgKey;
import org.apache.xml.serializer.utils.Utils;
import org.apache.xml.serializer.utils.WrappedRuntimeException;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
/**
* This abstract class is a base class for other stream
* serializers (xml, html, text ...) that write output to a stream.
*
* @xsl.usage internal
*/
abstract public class ToStream extends SerializerBase
{
private static final String COMMENT_BEGIN = "<!--";
private static final String COMMENT_END = "-->";
/** Stack to keep track of disabling output escaping. */
protected BoolStack m_disableOutputEscapingStates = new BoolStack();
/**
* The encoding information associated with this serializer.
* Although initially there is no encoding,
* there is a dummy EncodingInfo object that will say
* that every character is in the encoding. This is useful
* for a serializer that is in temporary output state and has
* no associated encoding. A serializer in final output state
* will have an encoding, and will worry about whether
* single chars or surrogate pairs of high/low chars form
* characters in the output encoding.
*/
EncodingInfo m_encodingInfo = new EncodingInfo(null,null, '\u0000');
/**
* Stack to keep track of whether or not we need to
* preserve whitespace.
*
* Used to push/pop values used for the field m_ispreserve, but
* m_ispreserve is only relevant if m_doIndent is true.
* If m_doIndent is false this field has no impact.
*
*/
protected BoolStack m_preserves = new BoolStack();
/**
* State flag to tell if preservation of whitespace
* is important.
*
* Used only in shouldIndent() but only if m_doIndent is true.
* If m_doIndent is false this flag has no impact.
*
*/
protected boolean m_ispreserve = false;
/**
* State flag that tells if the previous node processed
* was text, so we can tell if we should preserve whitespace.
*
* Used in endDocument() and shouldIndent() but
* only if m_doIndent is true.
* If m_doIndent is false this flag has no impact.
*/
protected boolean m_isprevtext = false;
private static final char[] s_systemLineSep;
static {
s_systemLineSep = SecuritySupport.getSystemProperty("line.separator").toCharArray();
}
/**
* The system line separator for writing out line breaks.
* The default value is from the system property,
* but this value can be set through the xsl:output
* extension attribute xalan:line-separator.
*/
protected char[] m_lineSep = s_systemLineSep;
/**
* True if the the system line separator is to be used.
*/
protected boolean m_lineSepUse = true;
/**
* The length of the line seperator, since the write is done
* one character at a time.
*/
protected int m_lineSepLen = m_lineSep.length;
/**
* Map that tells which characters should have special treatment, and it
* provides character to entity name lookup.
*/
protected CharInfo m_charInfo;
/** True if we control the buffer, and we should flush the output on endDocument. */
boolean m_shouldFlush = true;
/**
* Add space before self-closing '/>' syntax for XHTML.
*/
protected boolean m_spaceBeforeClose = false;
/**
* Flag to signal that a newline should be added.
*
* Used only in indent() which is called only if m_doIndent is true.
* If m_doIndent is false this flag has no impact.
*/
boolean m_startNewLine;
/**
* Tells if we're in an internal document type subset.
*/
protected boolean m_inDoctype = false;
/**
* Flag to quickly tell if the encoding is UTF8.
*/
boolean m_isUTF8 = false;
/**
* remembers if we are in between the startCDATA() and endCDATA() callbacks
*/
protected boolean m_cdataStartCalled = false;
/**
* If this flag is true DTD entity references are not left as-is,
* which is exiting older behavior.
*/
private boolean m_expandDTDEntities = true;
/**
* Default constructor
*/
public ToStream()
{
}
/**
* This helper method writes the syntax for closing a CDATA section.
*
* @throws org.xml.sax.SAXException if write fails
*/
protected void closeCDATA() throws org.xml.sax.SAXException
{
try
{
m_writer.write(CDATA_DELIMITER_CLOSE);
// write out a CDATA section closing "]]>"
m_cdataTagOpen = false; // Remember that we have done so.
}
catch (IOException e)
{
throw new SAXException(e);
}
}
/**
* Serializes the DOM node. Throws an exception only if an I/O
* exception occured while serializing.
*
* @param node Node to serialize.
* @throws IOException An I/O exception occured while serializing
*/
public void serialize(Node node) throws IOException
{
try
{
TreeWalker walker =
new TreeWalker(this);
walker.traverse(node);
}
catch (org.xml.sax.SAXException se)
{
throw new WrappedRuntimeException(se);
}
}
/**
* Taken from XSLTC
*/
protected boolean m_escaping = true;
/**
* Flush the formatter's result stream.
*
* @throws org.xml.sax.SAXException if write fails
*/
protected final void flushWriter() throws org.xml.sax.SAXException
{
final java.io.Writer writer = m_writer;
if (null != writer)
{
try
{
if (writer instanceof WriterToUTF8Buffered)
{
if (m_shouldFlush)
((WriterToUTF8Buffered) writer).flush();
else
((WriterToUTF8Buffered) writer).flushBuffer();
}
if (writer instanceof WriterToASCI)
{
if (m_shouldFlush)
writer.flush();
}
else
{
// Flush always.
// Not a great thing if the writer was created
// by this class, but don't have a choice.
writer.flush();
}
}
catch (IOException ioe)
{
throw new org.xml.sax.SAXException(ioe);
}
}
}
OutputStream m_outputStream;
/**
* Get the output stream where the events will be serialized to.
*
* @return reference to the result stream, or null of only a writer was
* set.
*/
public OutputStream getOutputStream()
{
return m_outputStream;
}
// Implement DeclHandler
/**
* Report an element type declaration.
*
* <p>The content model will consist of the string "EMPTY", the
* string "ANY", or a parenthesised group, optionally followed
* by an occurrence indicator. The model will be normalized so
* that all whitespace is removed,and will include the enclosing
* parentheses.</p>
*
* @param name The element type name.
* @param model The content model as a normalized string.
* @exception SAXException The application may raise an exception.
*/
public void elementDecl(String name, String model) throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
final java.io.Writer writer = m_writer;
DTDprolog();
writer.write("<!ELEMENT ");
writer.write(name);
writer.write(' ');
writer.write(model);
writer.write('>');
writer.write(m_lineSep, 0, m_lineSepLen);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
/**
* Report an internal entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param value The replacement text of the entity.
* @exception SAXException The application may raise an exception.
* @see #externalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void internalEntityDecl(String name, String value)
throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
DTDprolog();
outputEntityDecl(name, value);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
/**
* Output the doc type declaration.
*
* @param name non-null reference to document type name.
* NEEDSDOC @param value
*
* @throws IOException if an error occurs during writing.
*/
void outputEntityDecl(String name, String value) throws IOException
{
final java.io.Writer writer = m_writer;
writer.write("<!ENTITY ");
writer.write(name);
writer.write(" \"");
writer.write(value);
writer.write("\">");
writer.write(m_lineSep, 0, m_lineSepLen);
}
/**
* Output a system-dependent line break.
*
* @throws IOException if an error occurs during writing.
*/
protected final void outputLineSep() throws IOException
{
m_writer.write(m_lineSep, 0, m_lineSepLen);
}
void setProp(String name, String val, boolean defaultVal) {
if (val != null) {
char first = getFirstCharLocName(name);
switch (first) {
case 'c':
if (OutputKeys.CDATA_SECTION_ELEMENTS.equals(name)) {
String cdataSectionNames = val;
addCdataSectionElements(cdataSectionNames);
}
break;
case 'd':
if (OutputKeys.DOCTYPE_SYSTEM.equals(name)) {
this.m_doctypeSystem = val;
} else if (OutputKeys.DOCTYPE_PUBLIC.equals(name)) {
this.m_doctypePublic = val;
if (val.startsWith("-//W3C//DTD XHTML"))
m_spaceBeforeClose = true;
}
break;
case 'e':
String newEncoding = val;
if (OutputKeys.ENCODING.equals(name)) {
String possible_encoding = Encodings.getMimeEncoding(val);
if (possible_encoding != null) {
// if the encoding is being set, try to get the
// preferred
// mime-name and set it too.
super.setProp("mime-name", possible_encoding,
defaultVal);
}
final String oldExplicitEncoding = getOutputPropertyNonDefault(OutputKeys.ENCODING);
final String oldDefaultEncoding = getOutputPropertyDefault(OutputKeys.ENCODING);
if ( (defaultVal && ( oldDefaultEncoding == null || !oldDefaultEncoding.equalsIgnoreCase(newEncoding)))
|| ( !defaultVal && (oldExplicitEncoding == null || !oldExplicitEncoding.equalsIgnoreCase(newEncoding) ))) {
// We are trying to change the default or the non-default setting of the encoding to a different value
// from what it was
EncodingInfo encodingInfo = Encodings.getEncodingInfo(newEncoding);
if (newEncoding != null && encodingInfo.name == null) {
// We tried to get an EncodingInfo for Object for the given
// encoding, but it came back with an internall null name
// so the encoding is not supported by the JDK, issue a message.
final String msg = Utils.messages.createMessage(
MsgKey.ER_ENCODING_NOT_SUPPORTED,new Object[]{ newEncoding });
final String msg2 =
"Warning: encoding \"" + newEncoding + "\" not supported, using "
+ Encodings.DEFAULT_MIME_ENCODING;
try {
// Prepare to issue the warning message
final Transformer tran = super.getTransformer();
if (tran != null) {
final ErrorListener errHandler = tran
.getErrorListener();
// Issue the warning message
if (null != errHandler
&& m_sourceLocator != null) {
errHandler
.warning(new TransformerException(
msg, m_sourceLocator));
errHandler
.warning(new TransformerException(
msg2, m_sourceLocator));
} else {
System.out.println(msg);
System.out.println(msg2);
}
} else {
System.out.println(msg);
System.out.println(msg2);
}
} catch (Exception e) {
}
// We said we are using UTF-8, so use it
newEncoding = Encodings.DEFAULT_MIME_ENCODING;
val = Encodings.DEFAULT_MIME_ENCODING; // to store the modified value into the properties a little later
encodingInfo = Encodings.getEncodingInfo(newEncoding);
}
// The encoding was good, or was forced to UTF-8 above
// If there is already a non-default set encoding and we
// are trying to set the default encoding, skip the this block
// as the non-default value is already the one to use.
if (defaultVal == false || oldExplicitEncoding == null) {
m_encodingInfo = encodingInfo;
if (newEncoding != null)
m_isUTF8 = newEncoding.equals(Encodings.DEFAULT_MIME_ENCODING);
// if there was a previously set OutputStream
OutputStream os = getOutputStream();
if (os != null) {
Writer w = getWriter();
// If the writer was previously set, but
// set by the user, or if the new encoding is the same
// as the old encoding, skip this block
String oldEncoding = getOutputProperty(OutputKeys.ENCODING);
if ((w == null || !m_writer_set_by_user)
&& !newEncoding.equalsIgnoreCase(oldEncoding)) {
// Make the change of encoding in our internal
// table, then call setOutputStreamInternal
// which will stomp on the old Writer (if any)
// with a new Writer with the new encoding.
super.setProp(name, val, defaultVal);
setOutputStreamInternal(os,false);
}
}
}
}
}
break;
case 'i':
if (OutputPropertiesFactory.S_KEY_INDENT_AMOUNT.equals(name)) {
setIndentAmount(Integer.parseInt(val));
} else if (OutputKeys.INDENT.equals(name)) {
boolean b = "yes".equals(val) ? true : false;
m_doIndent = b;
}
break;
case 'l':
if (OutputPropertiesFactory.S_KEY_LINE_SEPARATOR.equals(name)) {
m_lineSep = val.toCharArray();
m_lineSepLen = m_lineSep.length;
}
break;
case 'm':
if (OutputKeys.MEDIA_TYPE.equals(name)) {
m_mediatype = val;
}
break;
case 'o':
if (OutputKeys.OMIT_XML_DECLARATION.equals(name)) {
boolean b = "yes".equals(val) ? true : false;
this.m_shouldNotWriteXMLHeader = b;
}
break;
case 's':
// if standalone was explicitly specified
if (OutputKeys.STANDALONE.equals(name)) {
if (defaultVal) {
setStandaloneInternal(val);
} else {
m_standaloneWasSpecified = true;
setStandaloneInternal(val);
}
}
break;
case 'v':
if (OutputKeys.VERSION.equals(name)) {
m_version = val;
}
break;
default:
break;
}
super.setProp(name, val, defaultVal);
}
}
/**
* Specifies an output format for this serializer. It the
* serializer has already been associated with an output format,
* it will switch to the new format. This method should not be
* called while the serializer is in the process of serializing
* a document.
*
* @param format The output format to use
*/
public void setOutputFormat(Properties format)
{
boolean shouldFlush = m_shouldFlush;
if (format != null)
{
// Set the default values first,
// and the non-default values after that,
// just in case there is some unexpected
// residual values left over from over-ridden default values
Enumeration propNames;
propNames = format.propertyNames();
while (propNames.hasMoreElements())
{
String key = (String) propNames.nextElement();
// Get the value, possibly a default value
String value = format.getProperty(key);
// Get the non-default value (if any).
String explicitValue = (String) format.get(key);
if (explicitValue == null && value != null) {
// This is a default value
this.setOutputPropertyDefault(key,value);
}
if (explicitValue != null) {
// This is an explicit non-default value
this.setOutputProperty(key,explicitValue);
}
}
}
// Access this only from the Hashtable level... we don't want to
// get default properties.
String entitiesFileName =
(String) format.get(OutputPropertiesFactory.S_KEY_ENTITIES);
if (null != entitiesFileName)
{
String method =
(String) format.get(OutputKeys.METHOD);
m_charInfo = CharInfo.getCharInfo(entitiesFileName, method);
}
m_shouldFlush = shouldFlush;
}
/**
* Returns the output format for this serializer.
*
* @return The output format in use
*/
public Properties getOutputFormat() {
Properties def = new Properties();
{
Set s = getOutputPropDefaultKeys();
Iterator i = s.iterator();
while (i.hasNext()) {
String key = (String) i.next();
String val = getOutputPropertyDefault(key);
def.put(key, val);
}
}
Properties props = new Properties(def);
{
Set s = getOutputPropKeys();
Iterator i = s.iterator();
while (i.hasNext()) {
String key = (String) i.next();
String val = getOutputPropertyNonDefault(key);
if (val != null)
props.put(key, val);
}
}
return props;
}
/**
* Specifies a writer to which the document should be serialized.
* This method should not be called while the serializer is in
* the process of serializing a document.
*
* @param writer The output writer stream
*/
public void setWriter(Writer writer)
{
setWriterInternal(writer, true);
}
private boolean m_writer_set_by_user;
private void setWriterInternal(Writer writer, boolean setByUser) {
m_writer_set_by_user = setByUser;
m_writer = writer;
// if we are tracing events we need to trace what
// characters are written to the output writer.
if (m_tracer != null) {
boolean noTracerYet = true;
Writer w2 = m_writer;
while (w2 instanceof WriterChain) {
if (w2 instanceof SerializerTraceWriter) {
noTracerYet = false;
break;
}
w2 = ((WriterChain)w2).getWriter();
}
if (noTracerYet)
m_writer = new SerializerTraceWriter(m_writer, m_tracer);
}
}
/**
* Set if the operating systems end-of-line line separator should
* be used when serializing. If set false NL character
* (decimal 10) is left alone, otherwise the new-line will be replaced on
* output with the systems line separator. For example on UNIX this is
* NL, while on Windows it is two characters, CR NL, where CR is the
* carriage-return (decimal 13).
*
* @param use_sytem_line_break True if an input NL is replaced with the
* operating systems end-of-line separator.
* @return The previously set value of the serializer.
*/
public boolean setLineSepUse(boolean use_sytem_line_break)
{
boolean oldValue = m_lineSepUse;
m_lineSepUse = use_sytem_line_break;
return oldValue;
}
/**
* Specifies an output stream to which the document should be
* serialized. This method should not be called while the
* serializer is in the process of serializing a document.
* <p>
* The encoding specified in the output properties is used, or
* if no encoding was specified, the default for the selected
* output method.
*
* @param output The output stream
*/
public void setOutputStream(OutputStream output)
{
setOutputStreamInternal(output, true);
}
private void setOutputStreamInternal(OutputStream output, boolean setByUser)
{
m_outputStream = output;
String encoding = getOutputProperty(OutputKeys.ENCODING);
if (Encodings.DEFAULT_MIME_ENCODING.equalsIgnoreCase(encoding))
{
// We wrap the OutputStream with a writer, but
// not one set by the user
setWriterInternal(new WriterToUTF8Buffered(output), false);
} else if (
"WINDOWS-1250".equals(encoding)
|| "US-ASCII".equals(encoding)
|| "ASCII".equals(encoding))
{
setWriterInternal(new WriterToASCI(output), false);
} else if (encoding != null) {
Writer osw = null;
try
{
osw = Encodings.getWriter(output, encoding);
}
catch (UnsupportedEncodingException uee)
{
osw = null;
}
if (osw == null) {
System.out.println(
"Warning: encoding \""
+ encoding
+ "\" not supported"
+ ", using "
+ Encodings.DEFAULT_MIME_ENCODING);
encoding = Encodings.DEFAULT_MIME_ENCODING;
setEncoding(encoding);
try {
osw = Encodings.getWriter(output, encoding);
} catch (UnsupportedEncodingException e) {
// We can't really get here, UTF-8 is always supported
// This try-catch exists to make the compiler happy
e.printStackTrace();
}
}
setWriterInternal(osw,false);
}
else {
// don't have any encoding, but we have an OutputStream
Writer osw = new OutputStreamWriter(output);
setWriterInternal(osw,false);
}
}
/**
* @see SerializationHandler#setEscaping(boolean)
*/
public boolean setEscaping(boolean escape)
{
final boolean temp = m_escaping;
m_escaping = escape;
return temp;
}
/**
* Might print a newline character and the indentation amount
* of the given depth.
*
* @param depth the indentation depth (element nesting depth)
*
* @throws IOException if an error occurs during writing.
*/
protected void indent(int depth) throws IOException
{
if (m_startNewLine)
outputLineSep();
/* For m_indentAmount > 0 this extra test might be slower
* but Xalan's default value is 0, so this extra test
* will run faster in that situation.
*/
if (m_indentAmount > 0)
printSpace(depth * m_indentAmount);
}
/**
* Indent at the current element nesting depth.
* @throws IOException if an error occurs while writing
*/
protected void indent() throws IOException
{
indent(m_elemContext.m_currentElemDepth);
}
/**
* Prints <var>n</var> spaces.
* @param n Number of spaces to print.
*
* @throws IOException if an error occurs while writing
*/
private void printSpace(int n) throws IOException
{
final java.io.Writer writer = m_writer;
for (int i = 0; i < n; i++)
{
writer.write(' ');
}
}
/**
* Report an attribute type declaration.
*
* <p>Only the effective (first) declaration for an attribute will
* be reported. The type will be one of the strings "CDATA",
* "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY",
* "ENTITIES", or "NOTATION", or a parenthesized token group with
* the separator "|" and all whitespace removed.</p>
*
* @param eName The name of the associated element.
* @param aName The name of the attribute.
* @param type A string representing the attribute type.
* @param valueDefault A string representing the attribute default
* ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if
* none of these applies.
* @param value A string representing the attribute's default value,
* or null if there is none.
* @exception SAXException The application may raise an exception.
*/
public void attributeDecl(
String eName,
String aName,
String type,
String valueDefault,
String value)
throws SAXException
{
// Do not inline external DTD
if (m_inExternalDTD)
return;
try
{
final java.io.Writer writer = m_writer;
DTDprolog();
writer.write("<!ATTLIST ");
writer.write(eName);
writer.write(' ');
writer.write(aName);
writer.write(' ');
writer.write(type);
if (valueDefault != null)
{
writer.write(' ');
writer.write(valueDefault);
}
//writer.write(" ");
//writer.write(value);
writer.write('>');
writer.write(m_lineSep, 0, m_lineSepLen);
}
catch (IOException e)
{
throw new SAXException(e);
}
}
/**
* Get the character stream where the events will be serialized to.
*
* @return Reference to the result Writer, or null.
*/
public Writer getWriter()
{
return m_writer;
}
/**
* Report a parsed external entity declaration.
*
* <p>Only the effective (first) declaration for each entity
* will be reported.</p>
*
* @param name The name of the entity. If it is a parameter
* entity, the name will begin with '%'.
* @param publicId The declared public identifier of the entity, or
* null if none was declared.
* @param systemId The declared system identifier of the entity.
* @exception SAXException The application may raise an exception.
* @see #internalEntityDecl
* @see org.xml.sax.DTDHandler#unparsedEntityDecl
*/
public void externalEntityDecl(
String name,
String publicId,
String systemId)
throws SAXException
{
try {
DTDprolog();
m_writer.write("<!ENTITY ");
m_writer.write(name);
if (publicId != null) {
m_writer.write(" PUBLIC \"");
m_writer.write(publicId);
}
else {
m_writer.write(" SYSTEM \"");
m_writer.write(systemId);
}
m_writer.write("\" >");
m_writer.write(m_lineSep, 0, m_lineSepLen);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @return true iff this character can be written without escaping.
* @param ch character to be tested
*/
protected boolean escapingNotNeeded(char ch)
{
final boolean ret;
if (ch < 127)
{
// This is the old/fast code here, but is this
// correct for all encodings?
if (ch >= CharInfo.S_SPACE || (CharInfo.S_LINEFEED == ch ||
CharInfo.S_CARRIAGERETURN == ch || CharInfo.S_HORIZONAL_TAB == ch))
ret= true;
else
ret = false;
}
else {
ret = m_encodingInfo.isInEncoding(ch);
}
return ret;
}
/**
* Once a surrogate has been detected, write out the pair of
* characters if it is in the encoding, or if there is no
* encoding, otherwise write out an entity reference
* of the value of the unicode code point of the character
* represented by the high/low surrogate pair.
* <p>
* An exception is thrown if there is no low surrogate in the pair,
* because the array ends unexpectely, or if the low char is there
* but its value is such that it is not a low surrogate.
*
* @param c the first (high) part of the surrogate, which
* must be confirmed before calling this method.
* @param ch Character array.
* @param i position Where the surrogate was detected.
* @param end The end index of the significant characters.
* @return 0 if the pair of characters was written out as-is,
* the unicode code point of the character represented by
* the surrogate pair if an entity reference with that value
* was written out.
*
* @throws IOException if invalid UTF-16 surrogate detected.
*/
protected int writeUTF16Surrogate(char c, char ch[], int i, int end)
throws IOException
{
int codePoint = 0;
if (i + 1 >= end)
{
throw new IOException(
Utils.messages.createMessage(
MsgKey.ER_INVALID_UTF16_SURROGATE,
new Object[] { Integer.toHexString((int) c)}));
}
final char high = c;
final char low = ch[i+1];
if (!Encodings.isLowUTF16Surrogate(low)) {
throw new IOException(
Utils.messages.createMessage(
MsgKey.ER_INVALID_UTF16_SURROGATE,
new Object[] {