/
StreamScanner.java
2480 lines (2267 loc) · 85.9 KB
/
StreamScanner.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.sr;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.stream.Location;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLReporter;
import javax.xml.stream.XMLResolver;
import javax.xml.stream.XMLStreamException;
import org.codehaus.stax2.XMLReporter2;
import org.codehaus.stax2.XMLStreamLocation2;
import org.codehaus.stax2.validation.XMLValidationProblem;
import com.ctc.wstx.api.ReaderConfig;
import com.ctc.wstx.cfg.ErrorConsts;
import com.ctc.wstx.cfg.InputConfigFlags;
import com.ctc.wstx.cfg.ParsingErrorMsgs;
import com.ctc.wstx.cfg.XmlConsts;
import com.ctc.wstx.dtd.MinimalDTDReader;
import com.ctc.wstx.ent.EntityDecl;
import com.ctc.wstx.ent.IntEntity;
import com.ctc.wstx.exc.*;
import com.ctc.wstx.io.DefaultInputResolver;
import com.ctc.wstx.io.WstxInputData;
import com.ctc.wstx.io.WstxInputLocation;
import com.ctc.wstx.io.WstxInputSource;
import com.ctc.wstx.util.ExceptionUtil;
import com.ctc.wstx.util.SymbolTable;
import com.ctc.wstx.util.TextBuffer;
/**
* Abstract base class that defines some basic functionality that all
* Woodstox reader classes (main XML reader, DTD reader) extend from.
*/
public abstract class StreamScanner
extends WstxInputData
implements InputProblemReporter,
InputConfigFlags, ParsingErrorMsgs
{
// // // Some well-known chars:
/**
* Last (highest) char code of the three, LF, CR and NULL
*/
public final static char CHAR_CR_LF_OR_NULL = (char) 13;
public final static int INT_CR_LF_OR_NULL = 13;
/**
* Character that allows quick check of whether a char can potentially
* be some kind of markup, WRT input stream processing;
* has to contain linefeeds, {@code &}, {@code <} and {@code >} (note: {@code >} only matters when
* quoting text, as part of {@code ]]>})
*/
protected final static char CHAR_FIRST_PURE_TEXT = (char) ('>' + 1);
/**
* First character in Unicode (ie one with lowest id) that is legal
* as part of a local name (all valid name chars minus ':'). Used
* for doing quick check for local name end; usually name ends in
* a whitespace or equals sign.
*/
protected final static char CHAR_LOWEST_LEGAL_LOCALNAME_CHAR = '-';
/*
///////////////////////////////////////////////////////////////////////
// Character validity constants, structs
///////////////////////////////////////////////////////////////////////
*/
/**
* We will only use validity array for first 256 characters, mostly
* because after those characters it's easier to do fairly simple
* block checks.
*/
private final static int VALID_CHAR_COUNT = 0x100;
private final static byte NAME_CHAR_INVALID_B = (byte) 0;
private final static byte NAME_CHAR_ALL_VALID_B = (byte) 1;
private final static byte NAME_CHAR_VALID_NONFIRST_B = (byte) -1;
private final static byte[] sCharValidity = new byte[VALID_CHAR_COUNT];
static {
// First, since all valid-as-first chars are also valid-as-other chars,
// we'll initialize common chars:
sCharValidity['_'] = NAME_CHAR_ALL_VALID_B;
for (int i = 0, last = ('z' - 'a'); i <= last; ++i) {
sCharValidity['A' + i] = NAME_CHAR_ALL_VALID_B;
sCharValidity['a' + i] = NAME_CHAR_ALL_VALID_B;
}
for (int i = 0xC0; i < 0xF6; ++i) { // not all are fully valid, but
sCharValidity[i] = NAME_CHAR_ALL_VALID_B;
}
// ... now we can 'revert' ones not fully valid:
sCharValidity[0xD7] = NAME_CHAR_INVALID_B;
sCharValidity[0xF7] = NAME_CHAR_INVALID_B;
// And then we can proceed with ones only valid-as-other.
sCharValidity['-'] = NAME_CHAR_VALID_NONFIRST_B;
sCharValidity['.'] = NAME_CHAR_VALID_NONFIRST_B;
sCharValidity[0xB7] = NAME_CHAR_VALID_NONFIRST_B;
for (int i = '0'; i <= '9'; ++i) {
sCharValidity[i] = NAME_CHAR_VALID_NONFIRST_B;
}
}
/**
* Public identifiers only use 7-bit ascii range.
*/
private final static int VALID_PUBID_CHAR_COUNT = 0x80;
private final static byte[] sPubidValidity = new byte[VALID_PUBID_CHAR_COUNT];
// private final static byte PUBID_CHAR_INVALID_B = (byte) 0;
private final static byte PUBID_CHAR_VALID_B = (byte) 1;
static {
for (int i = 0, last = ('z' - 'a'); i <= last; ++i) {
sPubidValidity['A' + i] = PUBID_CHAR_VALID_B;
sPubidValidity['a' + i] = PUBID_CHAR_VALID_B;
}
for (int i = '0'; i <= '9'; ++i) {
sPubidValidity[i] = PUBID_CHAR_VALID_B;
}
// 3 main white space types are valid
sPubidValidity[0x0A] = PUBID_CHAR_VALID_B;
sPubidValidity[0x0D] = PUBID_CHAR_VALID_B;
sPubidValidity[0x20] = PUBID_CHAR_VALID_B;
// And many of punctuation/separator ascii chars too:
sPubidValidity['-'] = PUBID_CHAR_VALID_B;
sPubidValidity['\''] = PUBID_CHAR_VALID_B;
sPubidValidity['('] = PUBID_CHAR_VALID_B;
sPubidValidity[')'] = PUBID_CHAR_VALID_B;
sPubidValidity['+'] = PUBID_CHAR_VALID_B;
sPubidValidity[','] = PUBID_CHAR_VALID_B;
sPubidValidity['.'] = PUBID_CHAR_VALID_B;
sPubidValidity['/'] = PUBID_CHAR_VALID_B;
sPubidValidity[':'] = PUBID_CHAR_VALID_B;
sPubidValidity['='] = PUBID_CHAR_VALID_B;
sPubidValidity['?'] = PUBID_CHAR_VALID_B;
sPubidValidity[';'] = PUBID_CHAR_VALID_B;
sPubidValidity['!'] = PUBID_CHAR_VALID_B;
sPubidValidity['*'] = PUBID_CHAR_VALID_B;
sPubidValidity['#'] = PUBID_CHAR_VALID_B;
sPubidValidity['@'] = PUBID_CHAR_VALID_B;
sPubidValidity['$'] = PUBID_CHAR_VALID_B;
sPubidValidity['_'] = PUBID_CHAR_VALID_B;
sPubidValidity['%'] = PUBID_CHAR_VALID_B;
}
/*
///////////////////////////////////////////////////////////////////////
// Basic configuration
///////////////////////////////////////////////////////////////////////
*/
/**
* Copy of the configuration object passed by the factory.
* Contains immutable settings for this reader (or in case
* of DTD parsers, reader that uses it)
*/
protected final ReaderConfig mConfig;
// // // Various extracted settings:
/**
* If true, Reader is namespace aware, and should do basic checks
* (usually enforcing limitations on having colons in names)
*/
protected final boolean mCfgNsEnabled;
// Extracted standard on/off settings:
/**
* note: left non-final on purpose: sub-class may need to modify
* the default value after construction.
*/
protected boolean mCfgReplaceEntities;
/*
///////////////////////////////////////////////////////////////////////
// Symbol handling, if applicable
///////////////////////////////////////////////////////////////////////
*/
final SymbolTable mSymbols;
/**
* Local full name for the event, if it has one (note: element events
* do NOT use this variable; those names are stored in element stack):
* target for processing instructions.
*<p>
* Currently used for proc. instr. target, and entity name (at least
* when current entity reference is null).
*<p>
* Note: this variable is generally not cleared, since it comes from
* a symbol table, ie. this won't be the only reference.
*/
protected String mCurrName;
/*
///////////////////////////////////////////////////////////////////////
// Input handling
///////////////////////////////////////////////////////////////////////
*/
/**
* Currently active input source; contains link to parent (nesting) input
* sources, if any.
*/
protected WstxInputSource mInput;
/**
* Top-most input source this reader can use; due to input source
* chaining, this is not necessarily the root of all input; for example,
* external DTD subset reader's root input still has original document
* input as its parent.
*/
protected final WstxInputSource mRootInput;
/**
* Custom resolver used to handle external entities that are to be expanded
* by this reader (external param/general entity expander)
*/
protected XMLResolver mEntityResolver = null;
/**
* This is the current depth of the input stack (same as what input
* element stack would return as its depth).
* It is used to enforce input scope constraints for nesting of
* elements (for xml reader) and dtd declaration (for dtd reader)
* with regards to input block (entity expansion) boundaries.
*<p>
* Basically this value is compared to {@link #mInputTopDepth}, which
* indicates what was the depth at the point where the currently active
* input scope/block was started.
*/
protected int mCurrDepth;
protected int mInputTopDepth;
/**
* Number of times a parsed general entity has been expanded; used for
* (optionally) limiting number of expansion to guard against
* denial-of-service attacks like "Billion Laughs".
*
* @since 4.3
*/
protected int mEntityExpansionCount;
/**
* Flag that indicates whether linefeeds in the input data are to
* be normalized or not.
* Xml specs mandate that the line feeds are only normalized
* when they are from the external entities (main doc, external
* general/parsed entities), so normalization has to be
* suppressed when expanding internal general/parsed entities.
*/
protected boolean mNormalizeLFs;
/**
* Flag that indicates whether all escaped chars are accepted in XML 1.0.
*
* @since 5.2
*/
protected boolean mAllowXml11EscapedCharsInXml10;
/*
///////////////////////////////////////////////////////////////////////
// Buffer(s) for local name(s) and text content
///////////////////////////////////////////////////////////////////////
*/
/**
* Temporary buffer used if local name can not be just directly
* constructed from input buffer (name is on a boundary or such).
*/
protected char[] mNameBuffer = null;
/*
///////////////////////////////////////////////////////////////////////
// Information about starting location of event
// Reader is pointing to; updated on-demand
///////////////////////////////////////////////////////////////////////
*/
// // // Location info at point when current token was started
/**
* Total number of characters read before start of current token.
* For big (gigabyte-sized) sizes are possible, needs to be long,
* unlike pointers and sizes related to in-memory buffers.
*/
protected long mTokenInputTotal = 0;
/**
* Input row on which current token starts, 1-based
*/
protected int mTokenInputRow = 1;
/**
* Column on input row that current token starts; 0-based (although
* in the end it'll be converted to 1-based)
*/
protected int mTokenInputCol = 0;
/*
///////////////////////////////////////////////////////////////////////
// XML document information (from doc decl if one was found) common to
// all entities (main xml document, external DTD subset)
///////////////////////////////////////////////////////////////////////
*/
/**
* Input stream encoding, if known (passed in, or determined by
* auto-detection); null if not.
*/
protected String mDocInputEncoding = null;
/**
* Character encoding from xml declaration, if any; null if no
* declaration, or it didn't specify encoding.
*/
protected String mDocXmlEncoding = null;
/**
* XML version as declared by the document; one of constants
* from {@link XmlConsts} (like {@link XmlConsts#XML_V_10}).
*/
protected int mDocXmlVersion = XmlConsts.XML_V_UNKNOWN;
/**
* Cache of internal character entities;
*/
protected Map<String,IntEntity> mCachedEntities;
/**
* Flag for whether or not character references should be treated as entities
*/
protected boolean mCfgTreatCharRefsAsEntities;
/**
* Entity reference stream currently points to.
*/
protected EntityDecl mCurrEntity;
/*
///////////////////////////////////////////////////////////////////////
// Life-cycle
///////////////////////////////////////////////////////////////////////
*/
/**
* Constructor used when creating a complete new (main-level) reader that
* does not share its input buffers or state with another reader.
*/
protected StreamScanner(WstxInputSource input, ReaderConfig cfg,
XMLResolver res)
{
super();
mInput = input;
// 17-Jun-2004, TSa: Need to know root-level input source
mRootInput = input;
mConfig = cfg;
mSymbols = cfg.getSymbols();
int cf = cfg.getConfigFlags();
mCfgNsEnabled = (cf & CFG_NAMESPACE_AWARE) != 0;
mCfgReplaceEntities = (cf & CFG_REPLACE_ENTITY_REFS) != 0;
mAllowXml11EscapedCharsInXml10 = mConfig.willAllowXml11EscapedCharsInXml10();
mNormalizeLFs = mConfig.willNormalizeLFs();
mInputBuffer = null;
mInputPtr = mInputEnd = 0;
mEntityResolver = res;
mCfgTreatCharRefsAsEntities = mConfig.willTreatCharRefsAsEnts();
if (mCfgTreatCharRefsAsEntities) {
mCachedEntities = new HashMap<String,IntEntity>();
} else {
mCachedEntities = Collections.emptyMap();
}
}
/**
* @since 5.2
*/
public ReaderConfig getConfig() {
return mConfig;
}
/*
///////////////////////////////////////////////////////////////////////
// Package API
///////////////////////////////////////////////////////////////////////
*/
/**
* Method that returns location of the last character returned by this
* reader; that is, location "one less" than the currently pointed to
* location.
*/
protected WstxInputLocation getLastCharLocation()
{
return mInput.getLocation(mCurrInputProcessed + mInputPtr - 1,
mCurrInputRow, mInputPtr - mCurrInputRowStart);
}
protected URL getSource() throws IOException {
return mInput.getSource();
}
protected String getSystemId() {
return mInput.getSystemId();
}
/*
///////////////////////////////////////////////////////////////////////
// Partial `LocationInfo` implementation (not implemented
// by this base class, but is by some sub-classes)
///////////////////////////////////////////////////////////////////////
*/
/**
* Returns location of last properly parsed token; as per StAX specs,
* apparently needs to be the end of current event, which is the same
* as the start of the following event (or EOF if that's next).
*/
@Override
public abstract Location getLocation();
public XMLStreamLocation2 getStartLocation()
{
// note: +1 is used as columns are 1-based...
return mInput.getLocation(mTokenInputTotal,
mTokenInputRow, mTokenInputCol + 1);
}
public XMLStreamLocation2 getCurrentLocation()
{
return mInput.getLocation(mCurrInputProcessed + mInputPtr,
mCurrInputRow, mInputPtr - mCurrInputRowStart + 1);
}
/*
///////////////////////////////////////////////////////////////////////
// InputProblemReporter implementation
///////////////////////////////////////////////////////////////////////
*/
public WstxException throwWfcException(String msg, boolean deferErrors)
throws WstxException
{
WstxException ex = constructWfcException(msg);
if (!deferErrors) {
throw ex;
}
return ex;
}
@Override
public void throwParseError(String msg) throws XMLStreamException {
throwParseError(msg, null, null);
}
/**
* Throws generic parse error with specified message and current parsing
* location.
*<p>
* Note: public access only because core code in other packages needs
* to access it.
*/
@Override
public void throwParseError(String format, Object arg, Object arg2)
throws XMLStreamException
{
String msg = (arg == null && arg2 == null) ? format
: MessageFormat.format(format, new Object[] { arg, arg2 });
throw constructWfcException(msg);
}
public void reportProblem(String probType, String format, Object arg, Object arg2)
throws XMLStreamException
{
XMLReporter rep = mConfig.getXMLReporter();
if (rep != null) {
_reportProblem(rep, probType,
MessageFormat.format(format, new Object[] { arg, arg2 }), null);
}
}
@Override
public void reportProblem(Location loc, String probType,
String format, Object arg, Object arg2)
throws XMLStreamException
{
XMLReporter rep = mConfig.getXMLReporter();
if (rep != null) {
String msg = (arg != null || arg2 != null) ?
MessageFormat.format(format, new Object[] { arg, arg2 }) : format;
_reportProblem(rep, probType, msg, loc);
}
}
protected void _reportProblem(XMLReporter rep, String probType, String msg, Location loc)
throws XMLStreamException
{
if (loc == null) {
loc = getLastCharLocation();
}
_reportProblem(rep, new XMLValidationProblem(loc, msg, XMLValidationProblem.SEVERITY_ERROR, probType));
}
protected void _reportProblem(XMLReporter rep, XMLValidationProblem prob)
throws XMLStreamException
{
if (rep != null) {
Location loc = prob.getLocation();
if (loc == null) {
loc = getLastCharLocation();
prob.setLocation(loc);
}
// Backwards-compatibility fix: add non-null type, if missing:
if (prob.getType() == null) {
prob.setType(ErrorConsts.WT_VALIDATION);
}
// [WSTX-154]: was catching and dropping thrown exception: shouldn't.
// [WTSX-157]: need to support XMLReporter2
if (rep instanceof XMLReporter2) {
((XMLReporter2) rep).report(prob);
} else {
rep.report(prob.getMessage(), prob.getType(), prob, loc);
}
}
}
/**
*<p>
* Note: this is the base implementation used for implementing
* <code>ValidationContext</code>
*/
@Override
public void reportValidationProblem(XMLValidationProblem prob)
throws XMLStreamException
{
// !!! TBI: Fail-fast vs. deferred modes?
/* For now let's implement basic functionality: warnings get
* reported via XMLReporter, errors and fatal errors result in
* immediate exceptions.
*/
/* 27-May-2008, TSa: [WSTX-153] Above is incorrect: as per Stax
* javadocs for XMLReporter, both warnings and non-fatal errors
* (which includes all validation errors) should be reported via
* XMLReporter interface, and only fatals should cause an
* immediate stream exception (by-passing reporter)
*/
if (prob.getSeverity() > XMLValidationProblem.SEVERITY_ERROR) {
throw WstxValidationException.create(prob);
}
XMLReporter rep = mConfig.getXMLReporter();
if (rep != null) {
_reportProblem(rep, prob);
} else {
/* If no reporter, regular non-fatal errors are to be reported
* as exceptions as well, for backwards compatibility
*/
if (prob.getSeverity() >= XMLValidationProblem.SEVERITY_ERROR) {
throw WstxValidationException.create(prob);
}
}
}
public void reportValidationProblem(String msg, int severity)
throws XMLStreamException
{
reportValidationProblem(new XMLValidationProblem(getLastCharLocation(),
msg, severity));
}
@Override
public void reportValidationProblem(String msg)
throws XMLStreamException
{
reportValidationProblem(new XMLValidationProblem(getLastCharLocation(), msg,
XMLValidationProblem.SEVERITY_ERROR));
}
public void reportValidationProblem(Location loc, String msg)
throws XMLStreamException
{
reportValidationProblem(new XMLValidationProblem(loc, msg));
}
@Override
public void reportValidationProblem(String format, Object arg, Object arg2)
throws XMLStreamException
{
reportValidationProblem(MessageFormat.format(format, new Object[] { arg, arg2 }));
}
/*
///////////////////////////////////////////////////////////////////////
// Other error reporting methods
///////////////////////////////////////////////////////////////////////
*/
protected WstxException constructWfcException(String msg)
{
return new WstxParsingException(msg, getLastCharLocation());
}
/**
* Construct and return a {@link XMLStreamException} to throw
* as a result of a failed Typed Access operation (but one not
* caused by a Well-Formedness Constraint or Validation Constraint
* problem)
*/
/*
protected WstxException _constructTypeException(String msg)
{
// Hmmh. Should there be a distinct sub-type?
return new WstxParsingException(msg, getLastCharLocation());
}
*/
protected WstxException constructFromIOE(IOException ioe)
{
return new WstxIOException(ioe);
}
protected WstxException constructNullCharException()
{
return new WstxUnexpectedCharException("Illegal character (NULL, unicode 0) encountered: not valid in any content",
getLastCharLocation(), CHAR_NULL);
}
protected void throwUnexpectedChar(int i, String msg) throws WstxException
{
char c = (char) i;
String excMsg = "Unexpected character "+getCharDesc(c)+msg;
throw new WstxUnexpectedCharException(excMsg, getLastCharLocation(), c);
}
protected void throwNullChar() throws WstxException {
throw constructNullCharException();
}
protected void throwInvalidSpace(int i) throws WstxException {
throwInvalidSpace(i, false);
}
protected WstxException throwInvalidSpace(int i, boolean deferErrors)
throws WstxException
{
char c = (char) i;
WstxException ex;
if (c == CHAR_NULL) {
ex = constructNullCharException();
} else {
String msg = "Illegal character ("+getCharDesc(c)+")";
if (mXml11) {
msg += " [note: in XML 1.1, it could be included via entity expansion]";
}
ex = new WstxUnexpectedCharException(msg, getLastCharLocation(), c);
}
if (!deferErrors) {
throw ex;
}
return ex;
}
protected void throwUnexpectedEOF(String msg)
throws WstxException
{
throw new WstxEOFException("Unexpected EOF"+(msg == null ? "" : msg),
getLastCharLocation());
}
/**
* Similar to {@link #throwUnexpectedEOF}, but only indicates ending
* of an input block. Used when reading a token that can not span
* input block boundaries (ie. can not continue past end of an
* entity expansion).
*/
protected void throwUnexpectedEOB(String msg)
throws WstxException
{
throw new WstxEOFException("Unexpected end of input block"+(msg == null ? "" : msg),
getLastCharLocation());
}
protected void throwFromIOE(IOException ioe) throws WstxException {
throw new WstxIOException(ioe);
}
protected void throwFromStrE(XMLStreamException strex)
throws WstxException
{
if (strex instanceof WstxException) {
throw (WstxException) strex;
}
throw new WstxException(strex);
}
/**
* Method called to report an error, when caller's signature only
* allows runtime exceptions to be thrown.
*/
protected void throwLazyError(Exception e)
{
if (e instanceof XMLStreamException) {
WstxLazyException.throwLazily((XMLStreamException) e);
}
ExceptionUtil.throwRuntimeException(e);
}
protected String tokenTypeDesc(int type) {
return ErrorConsts.tokenTypeDesc(type);
}
/*
///////////////////////////////////////////////////////////////////////
// Input buffer handling
///////////////////////////////////////////////////////////////////////
*/
/**
* Returns current input source this source uses.
*<p>
* Note: public only because some implementations are on different
* package.
*/
public final WstxInputSource getCurrentInput() {
return mInput;
}
protected final int inputInBuffer() {
return mInputEnd - mInputPtr;
}
@SuppressWarnings("cast")
protected final int getNext() throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
if (!loadMore()) {
return -1;
}
}
return (int) mInputBuffer[mInputPtr++];
}
/**
* Similar to {@link #getNext}, but does not advance pointer
* in input buffer.
*<p>
* Note: this method only peeks within current input source;
* it does not close it and check nested input source (if any).
* This is necessary when checking keywords, since they can never
* cross input block boundary.
*/
@SuppressWarnings("cast")
protected final int peekNext()
throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
if (!loadMoreFromCurrent()) {
return -1;
}
}
return (int) mInputBuffer[mInputPtr];
}
protected final char getNextChar(String errorMsg)
throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
loadMore(errorMsg);
}
return mInputBuffer[mInputPtr++];
}
/**
* Similar to {@link #getNextChar}, but will not read more characters
* from parent input source(s) if the current input source doesn't
* have more content. This is often needed to prevent "runaway" content,
* such as comments that start in an entity but do not have matching
* close marker inside entity; XML specification specifically states
* such markup is not legal.
*/
protected final char getNextCharFromCurrent(String errorMsg)
throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
loadMoreFromCurrent(errorMsg);
}
return mInputBuffer[mInputPtr++];
}
/**
* Method that will skip through zero or more white space characters,
* and return either the character following white space, or -1 to
* indicate EOF (end of the outermost input source)/
*/
@SuppressWarnings("cast")
protected final int getNextAfterWS()
throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
if (!loadMore()) {
return -1;
}
}
char c = mInputBuffer[mInputPtr++];
while (c <= CHAR_SPACE) {
// Linefeed?
if (c == '\n' || c == '\r') {
skipCRLF(c);
} else if (c != CHAR_SPACE && c != '\t') {
throwInvalidSpace(c);
}
// Still a white space?
if (mInputPtr >= mInputEnd) {
if (!loadMore()) {
return -1;
}
}
c = mInputBuffer[mInputPtr++];
}
return (int) c;
}
protected final char getNextCharAfterWS(String errorMsg)
throws XMLStreamException
{
if (mInputPtr >= mInputEnd) {
loadMore(errorMsg);
}
char c = mInputBuffer[mInputPtr++];
while (c <= CHAR_SPACE) {
// Linefeed?
if (c == '\n' || c == '\r') {
skipCRLF(c);
} else if (c != CHAR_SPACE && c != '\t') {
throwInvalidSpace(c);
}
// Still a white space?
if (mInputPtr >= mInputEnd) {
loadMore(errorMsg);
}
c = mInputBuffer[mInputPtr++];
}
return c;
}
protected final char getNextInCurrAfterWS(String errorMsg)
throws XMLStreamException
{
return getNextInCurrAfterWS(errorMsg, getNextCharFromCurrent(errorMsg));
}
protected final char getNextInCurrAfterWS(String errorMsg, char c)
throws XMLStreamException
{
while (c <= CHAR_SPACE) {
// Linefeed?
if (c == '\n' || c == '\r') {
skipCRLF(c);
} else if (c != CHAR_SPACE && c != '\t') {
throwInvalidSpace(c);
}
// Still a white space?
if (mInputPtr >= mInputEnd) {
loadMoreFromCurrent(errorMsg);
}
c = mInputBuffer[mInputPtr++];
}
return c;
}
/**
* Method called when a CR has been spotted in input; checks if next
* char is LF, and if so, skips it. Note that next character has to
* come from the current input source, to qualify; it can never come
* from another (nested) input source.
*
* @return True, if passed in char is '\r' and next one is '\n'.
*/
protected final boolean skipCRLF(char c)
throws XMLStreamException
{
boolean result;
if (c == '\r' && peekNext() == '\n') {
++mInputPtr;
result = true;
} else {
result = false;
}
++mCurrInputRow;
mCurrInputRowStart = mInputPtr;
return result;
}
protected final void markLF() {
++mCurrInputRow;
mCurrInputRowStart = mInputPtr;
}
protected final void markLF(int inputPtr) {
++mCurrInputRow;
mCurrInputRowStart = inputPtr;
}
/**
* Method to push back last character read; can only be called once,
* that is, no more than one char can be guaranteed to be succesfully
* returned.
*/
protected final void pushback() { --mInputPtr; }
/*
///////////////////////////////////////////////////////////////////////
// Sub-class overridable input handling methods
///////////////////////////////////////////////////////////////////////
*/
/**
* Method called when an entity has been expanded (new input source
* has been created). Needs to initialize location information and change
* active input source.
*
* @param entityId Name of the entity being expanded
*/
protected void initInputSource(WstxInputSource newInput, boolean isExt,
String entityId)
throws XMLStreamException
{
// Let's make sure new input will be read next time input is needed:
mInputPtr = 0;
mInputEnd = 0;
/* Plus, reset the input location so that'll be accurate for
* error reporting etc.
*/
mInputTopDepth = mCurrDepth;
// [WSTX-296]: Check for entity expansion depth against configurable limit
int entityDepth = mInput.getEntityDepth() + 1;
verifyLimit("Maximum entity expansion depth", mConfig.getMaxEntityDepth(), entityDepth);
mInput = newInput;
mInput.initInputLocation(this, mCurrDepth, entityDepth);
/* 21-Feb-2006, TSa: Linefeeds are NOT normalized when expanding
* internal entities (XML, 2.11)
*/
if (isExt) {
mNormalizeLFs = true;
} else {
mNormalizeLFs = false;
}
}
/**
* Method that will try to read one or more characters from currently
* open input sources; closing input sources if necessary.
*
* @return true if reading succeeded (or may succeed), false if
* we reached EOF.
*/
protected boolean loadMore()
throws XMLStreamException
{
WstxInputSource input = mInput;