-
-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathFullDTDReader.java
3516 lines (3214 loc) · 126 KB
/
FullDTDReader.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
/* Woodstox XML processor
*
* Copyright (c) 2004- Tatu Saloranta, tatu.saloranta@iki.fi
*
* Licensed under the License specified in file LICENSE, included with
* the source code.
* You may not use this file except in compliance with the License.
*
* 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.
*/
package com.ctc.wstx.dtd;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;
import javax.xml.stream.Location;
import javax.xml.stream.XMLReporter;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.NotationDeclaration;
import org.codehaus.stax2.validation.XMLValidationProblem;
import org.codehaus.stax2.validation.XMLValidator;
import com.ctc.wstx.api.ReaderConfig;
import com.ctc.wstx.cfg.ErrorConsts;
import com.ctc.wstx.cfg.XmlConsts;
import com.ctc.wstx.ent.*;
import com.ctc.wstx.evt.WNotationDeclaration;
import com.ctc.wstx.exc.WstxIOException;
import com.ctc.wstx.io.WstxInputData;
import com.ctc.wstx.io.WstxInputSource;
import com.ctc.wstx.util.*;
/**
* Reader that reads in DTD information from internal or external subset.
*<p>
* There are 2 main modes for DTDReader, depending on whether it is parsing
* internal or external subset. Parsing of internal subset is somewhat
* simpler, since no dependency checking is needed. For external subset,
* handling of parameter entities is bit more complicated, as care has to
* be taken to distinguish between using PEs defined in int. subset, and
* ones defined in ext. subset itself. This determines cachability of
* external subsets.
*<p>
* Reader also implements simple stand-alone functionality for flattening
* DTD files (expanding all references to their eventual textual form);
* this is sometimes useful when optimizing modularized DTDs
* (which are more maintainable) into single monolithic DTDs (which in
* general can be more performant).
*
* @author Tatu Saloranta
*/
public class FullDTDReader
extends MinimalDTDReader
{
/**
* Flag that can be changed to enable or disable interning of shared
* names; shared names are used for enumerated values to reduce
* memory usage.
*/
final static boolean INTERN_SHARED_NAMES = false;
// // // Entity expansion types:
final static Boolean ENTITY_EXP_GE = Boolean.FALSE;
final static Boolean ENTITY_EXP_PE = Boolean.TRUE;
/*
///////////////////////////////////////////////////////////
// Configuration
///////////////////////////////////////////////////////////
*/
final int mConfigFlags;
// Extracted wstx-specific settings:
final boolean mCfgSupportDTDPP;
/**
* This flag indicates whether we should build a validating 'real'
* validator (true, the usual case),
* or a simpler pseudo-validator that can do all non-validation tasks
* that are based on DTD info (entity expansion, notation references,
* default attribute values). Latter is used in non-validating mode.
*<p>
*/
final boolean mCfgFullyValidating;
/*
///////////////////////////////////////////////////////////
// Entity handling, parameter entities (PEs)
///////////////////////////////////////////////////////////
*/
/**
* Set of parameter entities defined so far in the currently parsed
* subset. Note: the first definition sticks, entities can not be
* redefined.
*<p>
* Keys are entity name Strings; values are instances of EntityDecl
*/
HashMap<String,EntityDecl> mParamEntities;
/**
* Set of parameter entities already defined for the subset being
* parsed; namely, PEs defined in the internal subset passed when
* parsing matching external subset. Null when parsing internal
* subset.
*/
final HashMap<String,EntityDecl> mPredefdPEs;
/**
* Set of parameter entities (ids) that have been referenced by this
* DTD; only maintained for external subsets, and only as long as
* no pre-defined PE has been referenced.
*/
Set<String> mRefdPEs;
/*
///////////////////////////////////////////////////////////
// Entity handling, general entities (GEs)
///////////////////////////////////////////////////////////
*/
/**
* Set of generic entities defined so far in this subset.
* As with parameter entities, the first definition sticks.
*<p>
* Keys are entity name Strings; values are instances of EntityDecl
*<p>
* Note: this Map only contains entities declared and defined in the
* subset being parsed; no previously defined values are passed.
*/
HashMap<String,EntityDecl> mGeneralEntities;
/**
* Set of general entities already defined for the subset being
* parsed; namely, PEs defined in the internal subset passed when
* parsing matching external subset. Null when parsing internal
* subset. Such entities are only needed directly for one purpose;
* to be expanded when reading attribute default value definitions.
*/
final HashMap<String,EntityDecl> mPredefdGEs;
/**
* Set of general entities (ids) that have been referenced by this
* DTD; only maintained for external subsets, and only as long as
* no pre-defined GEs have been referenced.
*/
Set<String> mRefdGEs;
/*
///////////////////////////////////////////////////////////
// Entity handling, both PEs and GEs
///////////////////////////////////////////////////////////
*/
/**
* Flag used to keep track of whether current (external) subset
* has referenced at least one PE that was pre-defined.
*/
boolean mUsesPredefdEntities = false;
/*
///////////////////////////////////////////////////////////
// Notation settings
///////////////////////////////////////////////////////////
*/
/**
* Set of notations defined so far. Since it's illegal to (try to)
* redefine notations, there's no specific precedence.
*<p>
* Keys are entity name Strings; values are instances of
* NotationDecl objects
*/
HashMap<String,NotationDeclaration> mNotations;
/**
* Notations already parsed before current subset; that is,
* notations from the internal subset if we are currently
* parsing matching external subset.
*/
final HashMap<String,NotationDeclaration> mPredefdNotations;
/**
* Flag used to keep track of whether current (external) subset
* has referenced at least one notation that was defined in internal
* subset. If so, can not cache the external subset
*/
boolean mUsesPredefdNotations = false;
/**
* Finally, we need to keep track of Notation references that were
* made prior to declaration. This is needed to ensure that all
* references can be properly resolved.
*/
HashMap<String,Location> mNotationForwardRefs;
/*
///////////////////////////////////////////////////////////
// Element specifications
///////////////////////////////////////////////////////////
*/
/**
* Map used to shared PrefixedName instances, to reduce memory usage
* of (qualified) element and attribute names
*/
HashMap<PrefixedName,PrefixedName> mSharedNames = null;
/**
* Contains definition of elements and matching content specifications.
* Also contains temporary placeholders for elements that are indirectly
* "created" by ATTLIST declarations that precede actual declaration
* for the ELEMENT referred to.
*/
LinkedHashMap<PrefixedName,DTDElement> mElements;
/**
* Map used for sharing legal enumeration values; used since oftentimes
* same enumeration values are used with multiple attributes
*/
HashMap<String,String> mSharedEnumValues = null;
/*
///////////////////////////////////////////////////////////
// Entity expansion state
///////////////////////////////////////////////////////////
*/
/**
* This is the attribute default value that is currently being parsed.
* Needs to be a global member due to the way entity expansion failures
* are reported: problems need to be attached to this object, even
* thought the default value itself will not be passed through.
*/
DefaultAttrValue mCurrAttrDefault = null;
/**
* Flag that indicates if the currently expanding (or last expanded)
* entity is a Parameter Entity or General Entity.
*/
boolean mExpandingPE = false;
/**
* Text buffer used for constructing expansion value of the internal
* entities, and for default attribute values.
* Lazily constructed when needed, reused.
*/
TextBuffer mValueBuffer = null;
/*
///////////////////////////////////////////////////////////
// Reader state
///////////////////////////////////////////////////////////
*/
/**
* Nesting count for conditionally included sections; 0 means that
* we are not inside such a section. Note that condition ignore is
* handled separately.
*/
int mIncludeCount = 0;
/**
* This flag is used to catch uses of PEs in the internal subset
* within declarations (full declarations are ok, but not other types)
*/
boolean mCheckForbiddenPEs = false;
/**
* Keyword of the declaration being currently parsed (if any). Can be
* used for error reporting purposes.
*/
String mCurrDeclaration;
/*
///////////////////////////////////////////////////////////
// DTD++ support information
///////////////////////////////////////////////////////////
*/
/**
* Flag that indicates if any DTD++ features have been encountered
* (in DTD++-supporting mode).
*/
boolean mAnyDTDppFeatures = false;
/**
* Currently active default namespace URI.
*/
String mDefaultNsURI = "";
/**
* Prefix-to-NsURI mappings for this DTD, if any: lazily
* constructed when needed
*/
HashMap<String,String> mNamespaces = null;
/*
///////////////////////////////////////////////////////////
// Additional support for creating expanded output
// of processed DTD.
///////////////////////////////////////////////////////////
*/
DTDWriter mFlattenWriter = null;
/*
///////////////////////////////////////////////////////////
// Support for SAX API impl:
///////////////////////////////////////////////////////////
*/
final DTDEventListener mEventListener;
transient TextBuffer mTextBuffer = null;
/*
///////////////////////////////////////////////////////////
// Life-cycle
///////////////////////////////////////////////////////////
*/
/**
* Constructor used for reading/skipping internal subset.
*/
private FullDTDReader(WstxInputSource input, ReaderConfig cfg,
boolean constructFully, int xmlVersion)
{
this(input, cfg, false, null, constructFully, xmlVersion);
}
/**
* Constructor used for reading external subset.
*/
private FullDTDReader(WstxInputSource input, ReaderConfig cfg,
DTDSubset intSubset,
boolean constructFully, int xmlVersion)
{
this(input, cfg, true, intSubset, constructFully, xmlVersion);
// Let's make sure line/col offsets are correct...
input.initInputLocation(this, mCurrDepth, 0);
}
/**
* Common initialization part of int/ext subset constructors.
*/
private FullDTDReader(WstxInputSource input, ReaderConfig cfg,
boolean isExt, DTDSubset intSubset,
boolean constructFully, int xmlVersion)
{
super(input, cfg, isExt);
/* What matters here is what the main xml doc had; that determines
* xml conformance level to use.
*/
mDocXmlVersion = xmlVersion;
mXml11 = cfg.isXml11();
int cfgFlags = cfg.getConfigFlags();
mConfigFlags = cfgFlags;
mCfgSupportDTDPP = (cfgFlags & CFG_SUPPORT_DTDPP) != 0;
mCfgFullyValidating = constructFully;
mUsesPredefdEntities = false;
mParamEntities = null;
mRefdPEs = null;
mRefdGEs = null;
mGeneralEntities = null;
// Did we get any existing parameter entities?
HashMap<String,EntityDecl> pes = (intSubset == null) ?
null : intSubset.getParameterEntityMap();
if (pes == null || pes.isEmpty()) {
mPredefdPEs = null;
} else {
mPredefdPEs = pes;
}
// How about general entities (needed only for attr. def. values)
HashMap<String,EntityDecl> ges = (intSubset == null) ?
null : intSubset.getGeneralEntityMap();
if (ges == null || ges.isEmpty()) {
mPredefdGEs = null;
} else {
mPredefdGEs = ges;
}
// And finally, notations
HashMap<String,NotationDeclaration> not = (intSubset == null) ?
null : intSubset.getNotationMap();
if (not == null || not.isEmpty()) {
mPredefdNotations = null;
} else {
mPredefdNotations = not;
}
mEventListener = mConfig.getDTDEventListener();
}
/**
* Method called to read in the internal subset definition.
*/
public static DTDSubset readInternalSubset(WstxInputData srcData,
WstxInputSource input,
ReaderConfig cfg,
boolean constructFully,
int xmlVersion)
throws XMLStreamException
{
FullDTDReader r = new FullDTDReader(input, cfg, constructFully, xmlVersion);
// Need to read using the same low-level reader interface:
r.copyBufferStateFrom(srcData);
DTDSubset ss;
try {
ss = r.parseDTD();
} finally {
/* And then need to restore changes back to owner (line nrs etc);
* effectively means that we'll stop reading external DTD subset,
* if so.
*/
srcData.copyBufferStateFrom(r);
}
return ss;
}
/**
* Method called to read in the external subset definition.
*/
public static DTDSubset readExternalSubset
(WstxInputSource src, ReaderConfig cfg, DTDSubset intSubset,
boolean constructFully, int xmlVersion)
throws XMLStreamException
{
FullDTDReader r = new FullDTDReader(src, cfg, intSubset, constructFully, xmlVersion);
return r.parseDTD();
}
/**
* Method that will parse, process and output contents of an external
* DTD subset. It will do processing similar to
* {@link #readExternalSubset}, but additionally will copy its processed
* ("flattened") input to specified writer.
*
* @param src Input source used to read the main external subset
* @param flattenWriter Writer to output processed DTD content to
* @param inclComments If true, will pass comments to the writer; if false,
* will strip comments out
* @param inclConditionals If true, will include conditional block markers,
* as well as intervening content; if false, will strip out both markers
* and ignorable sections.
* @param inclPEs If true, will output parameter entity declarations; if
* false will parse and use them, but not output.
*/
public static DTDSubset flattenExternalSubset(WstxInputSource src, Writer flattenWriter,
boolean inclComments, boolean inclConditionals,
boolean inclPEs)
throws IOException, XMLStreamException
{
ReaderConfig cfg = ReaderConfig.createFullDefaults();
// Need to create a non-shared copy to populate symbol table field
cfg = cfg.createNonShared(new SymbolTable());
/* Let's assume xml 1.0... can be taken as an arg later on, if we
* truly care.
*/
FullDTDReader r = new FullDTDReader(src, cfg, null, true, XmlConsts.XML_V_UNKNOWN);
r.setFlattenWriter(flattenWriter, inclComments, inclConditionals,
inclPEs);
DTDSubset ss = r.parseDTD();
r.flushFlattenWriter();
flattenWriter.flush();
return ss;
}
private TextBuffer getTextBuffer()
{
if (mTextBuffer == null) {
mTextBuffer = TextBuffer.createTemporaryBuffer();
mTextBuffer.resetInitialized();
} else {
mTextBuffer.resetWithEmpty();
}
return mTextBuffer;
}
/*
///////////////////////////////////////////////////////////
// Configuration
///////////////////////////////////////////////////////////
*/
/**
* Method that will set specified Writer as the 'flattening writer';
* writer used to output flattened version of DTD read in. This is
* similar to running a C-preprocessor on C-sources, except that
* defining writer will not prevent normal parsing of DTD itself.
*/
public void setFlattenWriter(Writer w, boolean inclComments,
boolean inclConditionals, boolean inclPEs)
{
mFlattenWriter = new DTDWriter(w, inclComments, inclConditionals,
inclPEs);
}
private void flushFlattenWriter() throws XMLStreamException {
mFlattenWriter.flush(mInputBuffer, mInputPtr);
}
/*
///////////////////////////////////////////////////////////
// Internal API
///////////////////////////////////////////////////////////
*/
/**
* Method that may need to be called by attribute default value
* validation code, during parsing....
*<p>
* Note: see base class for some additional remarks about this
* method.
*/
@Override
public EntityDecl findEntity(String entName)
{
if (mPredefdGEs != null) {
EntityDecl decl = mPredefdGEs.get(entName);
if (decl != null) {
return decl;
}
}
return mGeneralEntities.get(entName);
}
/*
///////////////////////////////////////////////////////////
// Main-level parsing methods
///////////////////////////////////////////////////////////
*/
protected DTDSubset parseDTD()
throws XMLStreamException
{
while (true) {
mCheckForbiddenPEs = false; // PEs are ok at this point
int i = getNextAfterWS();
if (i < 0) {
if (mIsExternal) { // ok for external DTDs
break;
}
// Error for internal subset
throwUnexpectedEOF(SUFFIX_IN_DTD_INTERNAL);
}
if (i == '%') { // parameter entity
expandPE();
continue;
}
/* First, let's keep track of start of the directive; needed for
* entity and notation declaration events.
*/
mTokenInputTotal = mCurrInputProcessed + mInputPtr;
mTokenInputRow = mCurrInputRow;
mTokenInputCol = mInputPtr - mCurrInputRowStart;
if (i == '<') {
// PEs not allowed within declarations, in the internal subset proper
mCheckForbiddenPEs = !mIsExternal && (mInput == mRootInput);
if (mFlattenWriter == null) {
parseDirective();
} else {
parseDirectiveFlattened();
}
continue;
}
if (i == ']') {
if (mIncludeCount == 0 && !mIsExternal) { // End of internal subset
break;
}
if (mIncludeCount > 0) { // active INCLUDE block(s) open?
boolean suppress = (mFlattenWriter != null) && !mFlattenWriter.includeConditionals();
if (suppress) {
mFlattenWriter.flush(mInputBuffer, mInputPtr-1);
mFlattenWriter.disableOutput();
}
try {
// ]]> needs to be a token, can not come from PE:
char c = dtdNextFromCurr();
if (c == ']') {
c = dtdNextFromCurr();
if (c == '>') {
// Ok, fine, conditional include section ended.
--mIncludeCount;
continue;
}
}
throwDTDUnexpectedChar(c, "; expected ']]>' to close conditional include section");
} finally {
if (suppress) {
mFlattenWriter.enableOutput(mInputPtr);
}
}
}
// otherwise will fall through, and give an error
}
if (mIsExternal) {
throwDTDUnexpectedChar(i, "; expected a '<' to start a directive");
}
throwDTDUnexpectedChar(i, "; expected a '<' to start a directive, or \"]>\" to end internal subset");
}
/* 05-Feb-2006, TSa: Not allowed to have unclosed INCLUDE/IGNORE
* blocks...
*/
if (mIncludeCount > 0) { // active INCLUDE block(s) open?
String suffix = (mIncludeCount == 1) ? "an INCLUDE block" : (""+mIncludeCount+" INCLUDE blocks");
throwUnexpectedEOF(getErrorMsg()+"; expected closing marker for "+suffix);
}
/* First check: have all notation references been resolved?
* (related to [WSTX-121])
*/
if (mNotationForwardRefs != null && mNotationForwardRefs.size() > 0) {
_reportUndefinedNotationRefs();
}
// Ok; time to construct and return DTD data object.
DTDSubset ss;
// There are more settings for ext. subsets:
if (mIsExternal) {
/* External subsets are cachable if they did not refer to any
* PEs or GEs defined in internal subset passed in (if any),
* nor to any notations.
* We don't care about PEs it defined itself, but need to pass
* in Set of PEs it refers to, to check if cached copy can be
* used with different int. subsets.
* We need not worry about notations referred, since they are
* not allowed to be re-defined.
*/
boolean cachable = !mUsesPredefdEntities && !mUsesPredefdNotations;
ss = DTDSubsetImpl.constructInstance(cachable,
mGeneralEntities, mRefdGEs,
null, mRefdPEs,
mNotations, mElements,
mCfgFullyValidating);
} else {
/* Internal subsets are not cachable (no unique way to refer
* to unique internal subsets), and there can be no references
* to pre-defined PEs, as none were passed.
*/
ss = DTDSubsetImpl.constructInstance(false, mGeneralEntities, null,
mParamEntities, null,
mNotations, mElements,
mCfgFullyValidating);
}
return ss;
}
protected void parseDirective()
throws XMLStreamException
{
/* Hmmh. Don't think PEs are allowed to contain starting
* '!' (or '?')... and it has to come from the same
* input source too (no splits)
*/
char c = dtdNextFromCurr();
if (c == '?') { // xml decl?
readPI();
return;
}
if (c != '!') { // nothing valid
throwDTDUnexpectedChar(c, "; expected '!' to start a directive");
}
/* ignore/include, comment, or directive; we are still getting
* token from same section though
*/
c = dtdNextFromCurr();
if (c == '-') { // plain comment
c = dtdNextFromCurr();
if (c != '-') {
throwDTDUnexpectedChar(c, "; expected '-' for a comment");
}
if (mEventListener != null && mEventListener.dtdReportComments()) {
readComment(mEventListener);
} else {
skipComment();
}
} else if (c == '[') {
checkInclusion();
} else if (c >= 'A' && c <= 'Z') {
handleDeclaration(c);
} else {
throwDTDUnexpectedChar(c, ErrorConsts.ERR_DTD_MAINLEVEL_KEYWORD);
}
}
/**
* Method similar to {@link #parseDirective}, but one that takes care
* to properly output dtd contents using {@code com.ctc.wstx.dtd.DTDWriter}
* as necessary.
* Separated to simplify both methods; otherwise would end up with
* 'if (... flatten...) ... else ...' spaghetti code.
*/
protected void parseDirectiveFlattened()
throws XMLStreamException
{
/* First, need to flush any flattened output there may be, at
* this point (except for opening lt char): and then need to
* temporarily disable more output until we know the type and
* whether it should be output or not:
*/
mFlattenWriter.flush(mInputBuffer, mInputPtr-1);
mFlattenWriter.disableOutput();
/* Let's determine type here, and call appropriate skip/parse
* methods.
*/
char c = dtdNextFromCurr();
if (c == '?') { // xml decl?
mFlattenWriter.enableOutput(mInputPtr);
mFlattenWriter.output("<?");
readPI();
//throwDTDUnexpectedChar(c, " expected '!' to start a directive");
return;
}
if (c != '!') { // nothing valid
throwDTDUnexpectedChar(c, ErrorConsts.ERR_DTD_MAINLEVEL_KEYWORD);
}
// ignore/include, comment, or directive
c = dtdNextFromCurr();
if (c == '-') { // plain comment
c = dtdNextFromCurr();
if (c != '-') {
throwDTDUnexpectedChar(c, "; expected '-' for a comment");
}
boolean comm = mFlattenWriter.includeComments();
if (comm) {
mFlattenWriter.enableOutput(mInputPtr);
mFlattenWriter.output("<!--");
}
try {
skipComment();
} finally {
if (!comm) {
mFlattenWriter.enableOutput(mInputPtr);
}
}
} else {
if (c == '[') {
boolean cond = mFlattenWriter.includeConditionals();
if (cond) {
mFlattenWriter.enableOutput(mInputPtr);
mFlattenWriter.output("<![");
}
try {
checkInclusion();
} finally {
if (!cond) {
mFlattenWriter.enableOutput(mInputPtr);
}
}
} else {
/* 12-Jul-2004, TSa: Do we need to see if we have to suppress
* a PE declaration?
*/
boolean filterPEs = (c == 'E') && !mFlattenWriter.includeParamEntities();
if (filterPEs) {
handleSuppressedDeclaration();
} else if (c >= 'A' && c <= 'Z') {
mFlattenWriter.enableOutput(mInputPtr);
mFlattenWriter.output("<!");
mFlattenWriter.output(c);
handleDeclaration(c);
} else {
throwDTDUnexpectedChar(c, ErrorConsts.ERR_DTD_MAINLEVEL_KEYWORD);
}
}
}
}
/*
///////////////////////////////////////////////////////////
// Overridden input handling
///////////////////////////////////////////////////////////
*/
@Override
protected void initInputSource(WstxInputSource newInput, boolean isExt, String entityId)
throws XMLStreamException
{
if (mFlattenWriter != null) {
// Anything to flush from previous buffer contents?
mFlattenWriter.flush(mInputBuffer, mInputPtr);
mFlattenWriter.disableOutput();
try {
/* Then let's let base class do the 'real' input source setup;
* this includes skipping of optional XML declaration that we
* do NOT want to output
*/
super.initInputSource(newInput, isExt, entityId);
} finally {
// This will effectively skip declaration
mFlattenWriter.enableOutput(mInputPtr);
}
} else {
super.initInputSource(newInput, isExt, entityId);
}
}
/**
* Need to override this method, to check couple of things: first,
* that nested input sources are balanced, when expanding parameter
* entities inside entity value definitions (as per XML specs), and
* secondly, to handle (optional) flattening output.
*/
@Override
protected boolean loadMore() throws XMLStreamException
{
WstxInputSource input = mInput;
// Any flattened not-yet-output input to flush?
if (mFlattenWriter != null) {
/* Note: can not trust mInputPtr; may not be correct. End of
* input should be, though.
*/
mFlattenWriter.flush(mInputBuffer, mInputEnd);
}
do {
/* Need to make sure offsets are properly updated for error
* reporting purposes, and do this now while previous amounts
* are still known.
*/
mCurrInputProcessed += mInputEnd;
mCurrInputRowStart -= mInputEnd;
try {
int count = input.readInto(this);
if (count > 0) {
if (mFlattenWriter != null) {
mFlattenWriter.setFlattenStart(mInputPtr);
}
return true;
}
input.close();
} catch (IOException ioe) {
throw constructFromIOE(ioe);
}
if (input == mRootInput) {
return false;
}
WstxInputSource parent = input.getParent();
if (parent == null) { // sanity check!
throwNullParent(input);
}
/* 13-Feb-2006, TSa: Ok, do we violate a proper nesting constraints
* with this input block closure?
*/
if (mCurrDepth != input.getScopeId()) {
handleIncompleteEntityProblem(input);
}
mInput = input = parent;
input.restoreContext(this);
if (mFlattenWriter != null) {
mFlattenWriter.setFlattenStart(mInputPtr);
}
mInputTopDepth = input.getScopeId();
/* 21-Feb-2006, TSa: Since linefeed normalization needs to be
* suppressed for internal entity expansion, we may need to
* change the state...
*/
if (!mNormalizeLFs) {
mNormalizeLFs = !input.fromInternalEntity();
}
// Maybe there are leftovers from that input in buffer now?
} while (mInputPtr >= mInputEnd);
return true;
}
@Override
protected boolean loadMoreFromCurrent() throws XMLStreamException
{
// Any flattened not-yet-output input to flush?
if (mFlattenWriter != null) {
mFlattenWriter.flush(mInputBuffer, mInputEnd);
}
// Need to update offsets properly
mCurrInputProcessed += mInputEnd;
mCurrInputRowStart -= mInputEnd;
try {
int count = mInput.readInto(this);
if (count > 0) {
if (mFlattenWriter != null) {
mFlattenWriter.setFlattenStart(mInputPtr);
}
return true;
}
} catch (IOException ie) {
throwFromIOE(ie);
}
return false;
}
@Override
protected boolean ensureInput(int minAmount) throws XMLStreamException
{
int currAmount = mInputEnd - mInputPtr;
if (currAmount >= minAmount) {
return true;
}
// Any flattened not-yet-output input to flush?
if (mFlattenWriter != null) {
mFlattenWriter.flush(mInputBuffer, mInputEnd);
}
try {
if (mInput.readMore(this, minAmount)) {
if (mFlattenWriter != null) {
//mFlattenWriter.setFlattenStart(mInputPtr);
mFlattenWriter.setFlattenStart(currAmount);
}
return true;
}
} catch (IOException ie) {
throwFromIOE(ie);
}
return false;
}
/*
///////////////////////////////////////////////////////////
// Internal methods, input access:
///////////////////////////////////////////////////////////
*/
private void loadMoreScoped(WstxInputSource currScope,
String entityName, Location loc)
throws XMLStreamException
{
boolean check = (mInput == currScope);
loadMore(getErrorMsg());
// Did we get out of the scope?
if (check && (mInput != currScope)) {
_reportWFCViolation("Unterminated entity value for entity '"
+entityName+"' (definition started at "
+loc+")");
}
}
/**
* @return Next character from the current input block, if any left;
* NULL if end of block (entity expansion)
*/
private char dtdNextIfAvailable()
throws XMLStreamException
{
char c;
if (mInputPtr < mInputEnd) {
c = mInputBuffer[mInputPtr++];
} else {
int i = peekNext();
if (i < 0) {
return CHAR_NULL;
}
++mInputPtr;
c = (char) i;
}
if (c == CHAR_NULL) {
throwNullChar();
}
return c;
}
/**
* Method that will get next character, and either return it as is (for
* normal chars), or expand parameter entity that starts with next
* character (which has to be '%').
*/
private char getNextExpanded()