-
Notifications
You must be signed in to change notification settings - Fork 7
/
DTDParser.java
2410 lines (2076 loc) · 77.7 KB
/
DTDParser.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
/*
* Copyright (c) 1998, 2023 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.dtdparser;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This implements parsing of XML 1.0 DTDs.
* <p>
* This conforms to the portion of the XML 1.0 specification related to the
* external DTD subset.
* <p>
* For multi-language applications (such as web servers using XML processing to
* create dynamic content), a method supports choosing a locale for parser
* diagnostics which is both understood by the message recipient and supported
* by the parser.
* <p>
* This parser produces a stream of parse events. It supports some features
* (exposing comments, CDATA sections, and entity references) which are not
* required to be reported by conformant XML processors.
*
* @author David Brownell
* @author Janet Koenig
* @author Kohsuke KAWAGUCHI
*/
public class DTDParser {
public static final String TYPE_CDATA = "CDATA";
public static final String TYPE_ID = "ID";
public static final String TYPE_IDREF = "IDREF";
public static final String TYPE_IDREFS = "IDREFS";
public static final String TYPE_ENTITY = "ENTITY";
public static final String TYPE_ENTITIES = "ENTITIES";
public static final String TYPE_NMTOKEN = "NMTOKEN";
public static final String TYPE_NMTOKENS = "NMTOKENS";
public static final String TYPE_NOTATION = "NOTATION";
public static final String TYPE_ENUMERATION = "ENUMERATION";
// stack of input entities being merged
private InputEntity in;
// temporaries reused during parsing
private StringBuffer strTmp;
private char[] nameTmp;
private NameCache nameCache;
private final char[] charTmp = new char[2];
// temporary DTD parsing state
private boolean doLexicalPE;
// DTD state, used during parsing
// private SimpleHashtable elements = new SimpleHashtable (47);
protected final Set<String> declaredElements = new HashSet<>();
private final SimpleHashtable<String, EntityDecl> params = new SimpleHashtable<>(7);
// exposed to package-private subclass
Map<String, Object> notations = new HashMap<>(7);
SimpleHashtable<String, EntityDecl> entities = new SimpleHashtable<>(17);
private final SimpleHashtable<String, Boolean> ids = new SimpleHashtable<>();
// listeners for DTD parsing events
private DTDEventListener dtdHandler;
private EntityResolver resolver;
private Locale locale;
// string constants -- use these copies so "==" works
// package private
static final String strANY = "ANY";
static final String strEMPTY = "EMPTY";
private static final Logger LOGGER = Logger.getLogger(DTDParser.class.getName());
/**
* Constructs a DTDParser.
*/
public DTDParser() {}
/**
* Used by applications to request locale for diagnostics.
*
* @param l The locale to use, or null to use system defaults (which may
* include only message IDs).
* @throws SAXException for errors
*/
public void setLocale(Locale l) throws SAXException {
if (l != null && !messages.isLocaleSupported(l.toString())) {
throw new SAXException(messages.getMessage(locale,
"P-078", new Object[]{l}));
}
locale = l;
}
/**
* Returns the diagnostic locale.
* @return the diagnostic locale
*/
public Locale getLocale() {
return locale;
}
/**
* Chooses a client locale to use for diagnostics, using the first language
* specified in the list that is supported by this parser. That locale is
* then set using <a href="#setLocale(java.util.Locale)"> setLocale()</a>.
* Such a list could be provided by a variety of user preference mechanisms,
* including the HTTP <em>Accept-Language</em> header field.
*
* @param languages Array of language specifiers, ordered with the most
* preferable one at the front. For example, "en-ca" then "fr-ca", followed
* by "zh_CN". Both RFC 1766 and Java styles are supported.
* @return The chosen locale, or null.
* @throws SAXException for errors
* @see MessageCatalog
*/
public Locale chooseLocale(String[] languages)
throws SAXException {
Locale l = messages.chooseLocale(languages);
if (l != null) {
setLocale(l);
}
return l;
}
/**
* Lets applications control entity resolution.
* @param r EntityResolver
*/
public void setEntityResolver(EntityResolver r) {
resolver = r;
}
/**
* Returns the object used to resolve entities
* @return the object used to resolve entities
*/
public EntityResolver getEntityResolver() {
return resolver;
}
/**
* Used by applications to set handling of DTD parsing events.
*/
public void setDtdHandler(DTDEventListener handler) {
dtdHandler = handler;
if (handler != null) {
handler.setDocumentLocator(new Locator() {
@Override
public String getPublicId() {
return DTDParser.this.getPublicId();
}
@Override
public String getSystemId() {
return DTDParser.this.getSystemId();
}
@Override
public int getLineNumber() {
return DTDParser.this.getLineNumber();
}
@Override
public int getColumnNumber() {
return DTDParser.this.getColumnNumber();
}
});
}
}
/**
* Returns the handler used to for DTD parsing events.
* @return the handler
*/
public DTDEventListener getDtdHandler() {
return dtdHandler;
}
/**
* Parse a DTD.
* @throws IOException for errors
* @throws SAXException for errors
*/
public void parse(InputSource in)
throws IOException, SAXException {
init();
parseInternal(in);
}
/**
* Parse a DTD.
* @throws IOException for errors
* @throws SAXException for errors
*/
public void parse(String uri)
throws IOException, SAXException {
InputSource inSource;
init();
// System.out.println ("parse (\"" + uri + "\")");
inSource = resolver.resolveEntity(null, uri);
// If custom resolver punts resolution to parser, handle it ...
if (inSource == null) {
inSource = Resolver.createInputSource(new java.net.URL(uri), false);
// ... or if custom resolver doesn't correctly construct the
// input entity, patch it up enough so relative URIs work, and
// issue a warning to minimize later confusion.
} else if (inSource.getSystemId() == null) {
warning("P-065", null);
inSource.setSystemId(uri);
}
parseInternal(inSource);
}
// makes sure the parser is reset to "before a document"
private void init() {
in = null;
// alloc temporary data used in parsing
strTmp = new StringBuffer();
nameTmp = new char[20];
nameCache = new NameCache();
// reset doc info
// isInAttribute = false;
doLexicalPE = false;
entities.clear();
notations.clear();
params.clear();
// elements.clear ();
declaredElements.clear();
// initialize predefined references ... re-interpreted later
builtin("amp", "&");
builtin("lt", "<");
builtin("gt", ">");
builtin("quot", "\"");
builtin("apos", "'");
if (locale == null) {
locale = Locale.getDefault();
}
if (resolver == null) {
resolver = new Resolver();
}
if (dtdHandler == null) {
dtdHandler = new DTDHandlerBase();
}
}
private void builtin(String entityName, String entityValue) {
InternalEntity entity;
entity = new InternalEntity(entityName, entityValue.toCharArray());
entities.put(entityName, entity);
}
////////////////////////////////////////////////////////////////
//
// parsing is by recursive descent, code roughly
// following the BNF rules except tweaked for simple
// lookahead. rules are more or less in numeric order,
// except where code sharing suggests other structures.
//
// a classic benefit of recursive descent parsers: it's
// relatively easy to get diagnostics that make sense.
//
////////////////////////////////////////////////////////////////
private void parseInternal(InputSource input)
throws IOException, SAXException {
if (input == null) {
fatal("P-000");
}
try {
in = InputEntity.getInputEntity(dtdHandler, locale);
in.init(input, null, null, false);
dtdHandler.startDTD(in);
// [30] extSubset ::= TextDecl? extSubsetDecl
// [31] extSubsetDecl ::= ( markupdecl | conditionalSect
// | PEReference | S )*
// ... same as [79] extPE, which is where the code is
ExternalEntity externalSubset = new ExternalEntity(in);
externalParameterEntity(externalSubset);
if (!in.isEOF()) {
fatal("P-001", new Object[]{Integer.toHexString(getc())});
}
afterRoot();
dtdHandler.endDTD();
} catch (EndOfInputException e) {
if (!in.isDocument()) {
String name = in.getName();
do { // force a relevant URI and line number
in = in.pop();
} while (in.isInternal());
fatal("P-002", new Object[]{name});
} else {
fatal("P-003", null);
}
} catch (RuntimeException e) {
LOGGER.log(Level.SEVERE, "Internal DTD parser error.", e);
throw new SAXParseException(e.getMessage() != null
? e.getMessage() : e.getClass().getName(),
getPublicId(), getSystemId(),
getLineNumber(), getColumnNumber());
} finally {
// recycle temporary data used during parsing
strTmp = null;
nameTmp = null;
nameCache = null;
// ditto input sources etc
if (in != null) {
in.close();
in = null;
}
// get rid of all DTD info ... some of it would be
// useful for editors etc., investigate later.
params.clear();
entities.clear();
notations.clear();
declaredElements.clear();
// elements.clear();
ids.clear();
}
}
void afterRoot() throws SAXException {
// Make sure all IDREFs match declared ID attributes. We scan
// after the document element is parsed, since XML allows forward
// references, and only now can we know if they're all resolved.
for (Enumeration<String> e = ids.keys();
e.hasMoreElements();) {
String id = e.nextElement();
Boolean value = ids.get(id);
if (Boolean.FALSE.equals(value)) {
error("V-024", new Object[]{id});
}
}
}
// role is for diagnostics
private void whitespace(String roleId)
throws IOException, SAXException {
// [3] S ::= (#x20 | #x9 | #xd | #xa)+
if (!maybeWhitespace()) {
fatal("P-004", new Object[]{messages.getMessage(locale, roleId)});
}
}
// S?
private boolean maybeWhitespace()
throws IOException, SAXException {
if (!doLexicalPE) {
return in.maybeWhitespace();
}
// see getc() for the PE logic -- this lets us splice
// expansions of PEs in "anywhere". getc() has smarts,
// so for external PEs we don't bypass it.
// XXX we can marginally speed PE handling, and certainly
// be cleaner (hence potentially more correct), by using
// the observations that expanded PEs only start and stop
// where whitespace is allowed. getc wouldn't need any
// "lexical" PE expansion logic, and no other method needs
// to handle termination of PEs. (parsing of literals would
// still need to pop entities, but not parsing of references
// in content.)
char c = getc();
boolean saw = false;
while (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
saw = true;
// this gracefully ends things when we stop playing
// with internal parameters. caller should have a
// grammar rule allowing whitespace at end of entity.
if (in.isEOF() && !in.isInternal()) {
return saw;
}
c = getc();
}
ungetc();
return saw;
}
private String maybeGetName()
throws IOException, SAXException {
NameCacheEntry entry = maybeGetNameCacheEntry();
return (entry == null) ? null : entry.name;
}
private NameCacheEntry maybeGetNameCacheEntry()
throws IOException, SAXException {
// [5] Name ::= (Letter|'_'|':') (Namechar)*
char c = getc();
if (!XmlChars.isLetter(c) && c != ':' && c != '_') {
ungetc();
return null;
}
return nameCharString(c);
}
// Used when parsing enumerations
private String getNmtoken()
throws IOException, SAXException {
// [7] Nmtoken ::= (Namechar)+
char c = getc();
if (!XmlChars.isNameChar(c)) {
fatal("P-006", new Object[]{c});
}
return nameCharString(c).name;
}
// n.b. this gets used when parsing attribute values (for
// internal references) so we can't use strTmp; it's also
// a hotspot for CPU and memory in the parser (called at least
// once for each element) so this has been optimized a bit.
private NameCacheEntry nameCharString(char c)
throws IOException, SAXException {
int i = 1;
nameTmp[0] = c;
for (;;) {
if ((c = in.getNameChar()) == 0) {
break;
}
if (i >= nameTmp.length) {
char[] tmp = new char[nameTmp.length + 10];
System.arraycopy(nameTmp, 0, tmp, 0, nameTmp.length);
nameTmp = tmp;
}
nameTmp[i++] = c;
}
return nameCache.lookupEntry(nameTmp, i);
}
//
// much similarity between parsing entity values in DTD
// and attribute values (in DTD or content) ... both follow
// literal parsing rules, newline canonicalization, etc.
//
// leaves value in 'strTmp' ... either a "replacement text" (4.5),
// or else partially normalized attribute value (the first bit
// of 3.3.3's spec, without the "if not CDATA" bits).
//
private void parseLiteral(boolean isEntityValue)
throws IOException, SAXException {
// [9] EntityValue ::=
// '"' ([^"&%] | Reference | PEReference)* '"'
// | "'" ([^'&%] | Reference | PEReference)* "'"
// [10] AttValue ::=
// '"' ([^"&] | Reference )* '"'
// | "'" ([^'&] | Reference )* "'"
char quote = getc();
char c;
InputEntity source = in;
if (quote != '\'' && quote != '"') {
fatal("P-007");
}
// don't report entity expansions within attributes,
// they're reported "fully expanded" via SAX
// isInAttribute = !isEntityValue;
// get value into strTmp
strTmp = new StringBuffer();
// scan, allowing entity push/pop wherever ...
// expanded entities can't terminate the literal!
for (;;) {
if (in != source && in.isEOF()) {
// we don't report end of parsed entities
// within attributes (no SAX hooks)
in = in.pop();
continue;
}
if ((c = getc()) == quote && in == source) {
break;
}
//
// Basically the "reference in attribute value"
// row of the chart in section 4.4 of the spec
//
if (c == '&') {
String entityName = maybeGetName();
if (entityName != null) {
nextChar(';', "F-020", entityName);
// 4.4 says: bypass these here ... we'll catch
// forbidden refs to unparsed entities on use
if (isEntityValue) {
strTmp.append('&');
strTmp.append(entityName);
strTmp.append(';');
continue;
}
expandEntityInLiteral(entityName, entities, isEntityValue);
// character references are always included immediately
} else if ((getc()) == '#') {
int tmp = parseCharNumber();
if (tmp > 0xffff) {
tmp = surrogatesToCharTmp(tmp);
strTmp.append(charTmp[0]);
if (tmp == 2) {
strTmp.append(charTmp[1]);
}
} else {
strTmp.append((char) tmp);
}
} else {
fatal("P-009");
}
continue;
}
// expand parameter entities only within entity value literals
if (c == '%' && isEntityValue) {
String entityName = maybeGetName();
if (entityName != null) {
nextChar(';', "F-021", entityName);
expandEntityInLiteral(entityName, params, isEntityValue);
continue;
} else {
fatal("P-011");
}
}
// For attribute values ...
if (!isEntityValue) {
// 3.3.3 says whitespace normalizes to space...
if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
strTmp.append(' ');
continue;
}
// "<" not legal in parsed literals ...
if (c == '<') {
fatal("P-012");
}
}
strTmp.append(c);
}
// isInAttribute = false;
}
// does a SINGLE expansion of the entity (often reparsed later)
private void expandEntityInLiteral(String name, SimpleHashtable<String, EntityDecl> table,
boolean isEntityValue)
throws IOException, SAXException {
EntityDecl entity = table.get(name);
if (entity instanceof InternalEntity) {
InternalEntity value = (InternalEntity) entity;
pushReader(value.buf, name, !value.isPE);
} else if (entity instanceof ExternalEntity) {
if (!isEntityValue) // must be a PE ...
{
fatal("P-013", new Object[]{name});
}
// XXX if this returns false ...
pushReader((ExternalEntity) entity);
} else if (entity == null) {
//
// Note: much confusion about whether spec requires such
// errors to be fatal in many cases, but none about whether
// it allows "normal" errors to be unrecoverable!
//
fatal((table == params) ? "V-022" : "P-014",
new Object[]{name});
}
}
// [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
// for PUBLIC and SYSTEM literals, also "<?xml ...type='literal'?>'
// NOTE: XML spec should explicitly say that PE ref syntax is
// ignored in PIs, comments, SystemLiterals, and Pubid Literal
// values ... can't process the XML spec's own DTD without doing
// that for comments.
private String getQuotedString(String type, String extra)
throws IOException, SAXException {
// use in.getc to bypass PE processing
char quote = in.getc();
if (quote != '\'' && quote != '"') {
fatal("P-015", new Object[]{
messages.getMessage(locale, type, new Object[]{extra})
});
}
char c;
strTmp = new StringBuffer();
while ((c = in.getc()) != quote) {
strTmp.append(c);
}
return strTmp.toString();
}
private String parsePublicId() throws IOException, SAXException {
// [12] PubidLiteral ::= ('"' PubidChar* '"') | ("'" PubidChar* "'")
// [13] PubidChar ::= #x20|#xd|#xa|[a-zA-Z0-9]|[-'()+,./:=?;!*#@$_%]
String retval = getQuotedString("F-033", null);
for (int i = 0; i < retval.length(); i++) {
char c = retval.charAt(i);
if (" \r\n-'()+,./:=?;!*#@$_%0123456789".indexOf(c) == -1
&& !(c >= 'A' && c <= 'Z')
&& !(c >= 'a' && c <= 'z')) {
fatal("P-016", new Object[]{c});
}
}
strTmp = new StringBuffer();
strTmp.append(retval);
return normalize(false);
}
// [14] CharData ::= [^<&]* - ([^<&]* ']]>' [^<&]*)
// handled by: InputEntity.parsedContent()
private boolean maybeComment(boolean skipStart)
throws IOException, SAXException {
// [15] Comment ::= '<!--'
// ( (Char - '-') | ('-' (Char - '-'))*
// '-->'
if (!in.peek(skipStart ? "!--" : "<!--", null)) {
return false;
}
boolean savedLexicalPE = doLexicalPE;
boolean saveCommentText;
doLexicalPE = false;
saveCommentText = false;
if (saveCommentText) {
strTmp = new StringBuffer();
}
oneComment:
for (;;) {
try {
// bypass PE expansion, but permit PEs
// to complete ... valid docs won't care.
for (;;) {
int c = getc();
if (c == '-') {
c = getc();
if (c != '-') {
if (saveCommentText) {
strTmp.append('-');
}
ungetc();
continue;
}
nextChar('>', "F-022", null);
break oneComment;
}
if (saveCommentText) {
strTmp.append((char) c);
}
}
} catch (EndOfInputException e) {
//
// This is fatal EXCEPT when we're processing a PE...
// in which case a validating processor reports an error.
// External PEs are easy to detect; internal ones we
// infer by being an internal entity outside an element.
//
if (in.isInternal()) {
error("V-021", null);
}
fatal("P-017");
}
}
doLexicalPE = savedLexicalPE;
if (saveCommentText) {
dtdHandler.comment(strTmp.toString());
}
return true;
}
private boolean maybePI(boolean skipStart)
throws IOException, SAXException {
// [16] PI ::= '<?' PITarget
// (S (Char* - (Char* '?>' Char*)))?
// '?>'
// [17] PITarget ::= Name - (('X'|'x')('M'|'m')('L'|'l')
boolean savedLexicalPE = doLexicalPE;
if (!in.peek(skipStart ? "?" : "<?", null)) {
return false;
}
doLexicalPE = false;
String target = maybeGetName();
if (target == null) {
fatal("P-018");
}
if ("xml".equals(target)) {
fatal("P-019");
}
if ("xml".equalsIgnoreCase(target)) {
fatal("P-020", new Object[]{target});
}
if (maybeWhitespace()) {
strTmp = new StringBuffer();
try {
for (;;) {
// use in.getc to bypass PE processing
char c = in.getc();
//Reached the end of PI.
if (c == '?' && in.peekc('>')) {
break;
}
strTmp.append(c);
}
} catch (EndOfInputException e) {
fatal("P-021");
}
dtdHandler.processingInstruction(target, strTmp.toString());
} else {
if (!in.peek("?>", null)) {
fatal("P-022");
}
dtdHandler.processingInstruction(target, "");
}
doLexicalPE = savedLexicalPE;
return true;
}
// [18] CDSect ::= CDStart CData CDEnd
// [19] CDStart ::= '<![CDATA['
// [20] CData ::= (Char* - (Char* ']]>' Char*))
// [21] CDEnd ::= ']]>'
//
// ... handled by InputEntity.unparsedContent()
// collapsing several rules together ...
// simpler than attribute literals -- no reference parsing!
private String maybeReadAttribute(String name, boolean must)
throws IOException, SAXException {
// [24] VersionInfo ::= S 'version' Eq \'|\" versionNum \'|\"
// [80] EncodingDecl ::= S 'encoding' Eq \'|\" EncName \'|\"
// [32] SDDecl ::= S 'standalone' Eq \'|\" ... \'|\"
if (!maybeWhitespace()) {
if (!must) {
return null;
}
fatal("P-024", new Object[]{name});
// NOTREACHED
}
if (!peek(name)) {
if (must) {
fatal("P-024", new Object[]{name});
} else {
// To ensure that the whitespace is there so that when we
// check for the next attribute we assure that the
// whitespace still exists.
ungetc();
return null;
}
}
// [25] Eq ::= S? '=' S?
maybeWhitespace();
nextChar('=', "F-023", null);
maybeWhitespace();
return getQuotedString("F-035", name);
}
private void readVersion(boolean must, String versionNum)
throws IOException, SAXException {
String value = maybeReadAttribute("version", must);
// [26] versionNum ::= ([a-zA-Z0-9_.:]| '-')+
if (must && value == null) {
fatal("P-025", new Object[]{versionNum});
}
if (value != null) {
int length = value.length();
for (int i = 0; i < length; i++) {
char c = value.charAt(i);
if (!((c >= '0' && c <= '9')
|| c == '_' || c == '.'
|| (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| c == ':' || c == '-')) {
fatal("P-026", new Object[]{value});
}
}
}
if (value != null && !value.equals(versionNum)) {
error("P-027", new Object[]{versionNum, value});
}
}
// common code used by most markup declarations
// ... S (Q)Name ...
private String getMarkupDeclname(String roleId, boolean qname)
throws IOException, SAXException {
String name;
whitespace(roleId);
name = maybeGetName();
if (name == null) {
fatal("P-005", new Object[]{messages.getMessage(locale, roleId)});
}
return name;
}
private boolean maybeMarkupDecl()
throws IOException, SAXException {
// [29] markupdecl ::= elementdecl | Attlistdecl
// | EntityDecl | NotationDecl | PI | Comment
return maybeElementDecl()
|| maybeAttlistDecl()
|| maybeEntityDecl()
|| maybeNotationDecl()
|| maybePI(false)
|| maybeComment(false);
}
private static final String XML_LANG = "xml:lang";
private boolean isXmlLang(String value) {
// [33] LanguageId ::= Langcode ('-' Subcode)*
// [34] Langcode ::= ISO639Code | IanaCode | UserCode
// [35] ISO639Code ::= [a-zA-Z] [a-zA-Z]
// [36] IanaCode ::= [iI] '-' SubCode
// [37] UserCode ::= [xX] '-' SubCode
// [38] SubCode ::= [a-zA-Z]+
// the ISO and IANA codes (and subcodes) are registered,
// but that's neither a WF nor a validity constraint.
int nextSuffix;
char c;
if (value.length() < 2) {
return false;
}
c = value.charAt(1);
if (c == '-') { // IANA, or user, code
c = value.charAt(0);
if (!(c == 'i' || c == 'I' || c == 'x' || c == 'X')) {
return false;
}
nextSuffix = 1;
} else if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
// 2-letter ISO code, or error
c = value.charAt(0);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
return false;
}
nextSuffix = 2;
} else {
return false;
}
// here "suffix" ::= '-' [a-zA-Z]+ suffix*
while (nextSuffix < value.length()) {
c = value.charAt(nextSuffix);
if (c != '-') {
break;
}
while (++nextSuffix < value.length()) {
c = value.charAt(nextSuffix);
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
break;
}
}
}
return value.length() == nextSuffix && c != '-';
}
//
// CHAPTER 3: Logical Structures
//
/*
* To validate, subclasses should at this time make sure that values are of
* the declared types:<UL> <LI> ID and IDREF(S) values are Names <LI>
* NMTOKEN(S) are Nmtokens <LI> ENUMERATION values match one of the tokens
* <LI> NOTATION values match a notation name <LI> ENTITIY(IES) values match
* an unparsed external entity </UL>
*
* <P> Separately, make sure IDREF values match some ID provided in the
* document (in the afterRoot method).
*/
/* void validateAttributeSyntax (Attribute attr, String value)
throws DTDParseException {
// ID, IDREF(S) ... values are Names
if (Attribute.ID == attr.type()) {
if (!XmlNames.isName (value))
error ("V-025", new Object [] { value });
Boolean b = (Boolean) ids.getNonInterned (value);
if (b == null || b.equals (Boolean.FALSE))
ids.put (value.intern (), Boolean.TRUE);
else
error ("V-026", new Object [] { value });
} else if (Attribute.IDREF == attr.type()) {
if (!XmlNames.isName (value))
error ("V-027", new Object [] { value });
Boolean b = (Boolean) ids.getNonInterned (value);
if (b == null)
ids.put (value.intern (), Boolean.FALSE);
} else if (Attribute.IDREFS == attr.type()) {
StringTokenizer tokenizer = new StringTokenizer (value);
Boolean b;
boolean sawValue = false;
while (tokenizer.hasMoreTokens ()) {
value = tokenizer.nextToken ();
if (!XmlNames.isName (value))
error ("V-027", new Object [] { value });
b = (Boolean) ids.getNonInterned (value);
if (b == null)
ids.put (value.intern (), Boolean.FALSE);
sawValue = true;
}
if (!sawValue)
error ("V-039", null);
// NMTOKEN(S) ... values are Nmtoken(s)
} else if (Attribute.NMTOKEN == attr.type()) {
if (!XmlNames.isNmtoken (value))
error ("V-028", new Object [] { value });