-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathHTMLScanner.java
More file actions
3696 lines (3323 loc) · 140 KB
/
HTMLScanner.java
File metadata and controls
3696 lines (3323 loc) · 140 KB
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) 2002-2009 Andy Clark, Marc Guillemot
* Copyright (c) 2017-2024 Ronald Brill
*
* Licensed 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
* https://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.
*/
package org.htmlunit.cyberneko;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Locale;
import org.htmlunit.cyberneko.HTMLElements.Element;
import org.htmlunit.cyberneko.io.PlaybackInputStream;
import org.htmlunit.cyberneko.util.MiniStack;
import org.htmlunit.cyberneko.xerces.util.EncodingMap;
import org.htmlunit.cyberneko.xerces.util.NamespaceSupport;
import org.htmlunit.cyberneko.xerces.util.URI;
import org.htmlunit.cyberneko.xerces.util.XMLAttributesImpl;
import org.htmlunit.cyberneko.xerces.xni.Augmentations;
import org.htmlunit.cyberneko.xerces.xni.NamespaceContext;
import org.htmlunit.cyberneko.xerces.xni.QName;
import org.htmlunit.cyberneko.xerces.xni.XMLAttributes;
import org.htmlunit.cyberneko.xerces.xni.XMLDocumentHandler;
import org.htmlunit.cyberneko.xerces.xni.XMLLocator;
import org.htmlunit.cyberneko.xerces.xni.XMLString;
import org.htmlunit.cyberneko.xerces.xni.XNIException;
import org.htmlunit.cyberneko.xerces.xni.parser.XMLComponentManager;
import org.htmlunit.cyberneko.xerces.xni.parser.XMLConfigurationException;
import org.htmlunit.cyberneko.xerces.xni.parser.XMLDocumentScanner;
import org.htmlunit.cyberneko.xerces.xni.parser.XMLInputSource;
/**
* A simple HTML scanner. This scanner makes no attempt to balance tags or fix
* other problems in the source document — it just scans what it can and
* generates XNI document "events", ignoring errors of all kinds.
* <p>
* This component recognizes the following features:
* <ul>
* <li>http://cyberneko.org/html/features/augmentations
* <li>http://cyberneko.org/html/features/report-errors
* <li>http://cyberneko.org/html/features/scanner/script/strip-cdata-delims
* <li>http://cyberneko.org/html/features/scanner/script/strip-comment-delims
* <li>http://cyberneko.org/html/features/scanner/style/strip-cdata-delims
* <li>http://cyberneko.org/html/features/scanner/style/strip-comment-delims
* <li>http://cyberneko.org/html/features/scanner/ignore-specified-charset
* <li>http://cyberneko.org/html/features/scanner/cdata-sections
* <li>http://cyberneko.org/html/features/scanner/cdata-early-closing
* <li>http://cyberneko.org/html/features/override-doctype
* <li>http://cyberneko.org/html/features/insert-doctype
* <li>http://cyberneko.org/html/features/parse-noscript-content
* <li>http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe
* <li>http://cyberneko.org/html/features/scanner/allow-selfclosing-tags
* </ul>
* <p>
* This component recognizes the following properties:
* <ul>
* <li>http://cyberneko.org/html/properties/names/elems
* <li>http://cyberneko.org/html/properties/names/attrs
* <li>http://cyberneko.org/html/properties/default-encoding
* <li>http://cyberneko.org/html/properties/error-reporter
* <li>http://cyberneko.org/html/properties/doctype/pubid
* <li>http://cyberneko.org/html/properties/doctype/sysid
* </ul>
*
* @see HTMLElements
*
* @author Andy Clark
* @author Marc Guillemot
* @author Ahmed Ashour
* @author Ronald Brill
* @author René Schwietzke
*/
public class HTMLScanner implements XMLDocumentScanner, XMLLocator, HTMLComponent {
// doctype info: HTML 4.01 strict
/** HTML 4.01 strict public identifier ("-//W3C//DTD HTML 4.01//EN"). */
public static final String HTML_4_01_STRICT_PUBID = "-//W3C//DTD HTML 4.01//EN";
/**
* HTML 4.01 strict system identifier ("http://www.w3.org/TR/html4/strict.dtd").
*/
public static final String HTML_4_01_STRICT_SYSID = "http://www.w3.org/TR/html4/strict.dtd";
// doctype info: HTML 4.01 loose
/**
* HTML 4.01 transitional public identifier ("-//W3C//DTD HTML 4.01
* Transitional//EN").
*/
public static final String HTML_4_01_TRANSITIONAL_PUBID = "-//W3C//DTD HTML 4.01 Transitional//EN";
/**
* HTML 4.01 transitional system identifier
* ("http://www.w3.org/TR/html4/loose.dtd").
*/
public static final String HTML_4_01_TRANSITIONAL_SYSID = "http://www.w3.org/TR/html4/loose.dtd";
// doctype info: HTML 4.01 frameset
/**
* HTML 4.01 frameset public identifier ("-//W3C//DTD HTML 4.01 Frameset//EN").
*/
public static final String HTML_4_01_FRAMESET_PUBID = "-//W3C//DTD HTML 4.01 Frameset//EN";
/**
* HTML 4.01 frameset system identifier
* ("http://www.w3.org/TR/html4/frameset.dtd").
*/
public static final String HTML_4_01_FRAMESET_SYSID = "http://www.w3.org/TR/html4/frameset.dtd";
// features
/** Include infoset augmentations. */
protected static final String AUGMENTATIONS = "http://cyberneko.org/html/features/augmentations";
/** Report errors. */
protected static final String REPORT_ERRORS = "http://cyberneko.org/html/features/report-errors";
/**
* Strip HTML comment delimiters ("<!−−" and
* "−−>") from SCRIPT tag contents.
*/
public static final String SCRIPT_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-comment-delims";
/**
* Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from SCRIPT tag
* contents.
*/
public static final String SCRIPT_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/script/strip-cdata-delims";
/**
* Strip HTML comment delimiters ("<!−−" and
* "−−>") from STYLE tag contents.
*/
public static final String STYLE_STRIP_COMMENT_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-comment-delims";
/**
* Strip XHTML CDATA delimiters ("<![CDATA[" and "]]>") from STYLE tag
* contents.
*/
public static final String STYLE_STRIP_CDATA_DELIMS = "http://cyberneko.org/html/features/scanner/style/strip-cdata-delims";
/**
* Ignore specified charset found in the <meta equiv='Content-Type'
* content='text/html;charset=…'> tag or in the <?xml …
* encoding='…'> processing instruction
*/
public static final String IGNORE_SPECIFIED_CHARSET = "http://cyberneko.org/html/features/scanner/ignore-specified-charset";
/** Scan CDATA sections. */
public static final String CDATA_SECTIONS = "http://cyberneko.org/html/features/scanner/cdata-sections";
/** '>' closes the cdata section (see html spec) */
public static final String CDATA_EARLY_CLOSING = "http://cyberneko.org/html/features/scanner/cdata-early-closing";
/** Override doctype declaration public and system identifiers. */
public static final String OVERRIDE_DOCTYPE = "http://cyberneko.org/html/features/override-doctype";
/** Insert document type declaration. */
public static final String INSERT_DOCTYPE = "http://cyberneko.org/html/features/insert-doctype";
/** Parse <noscript>...</noscript> content */
public static final String PARSE_NOSCRIPT_CONTENT = "http://cyberneko.org/html/features/parse-noscript-content";
/** Allows self closing <iframe/> tag */
public static final String ALLOW_SELFCLOSING_IFRAME = "http://cyberneko.org/html/features/scanner/allow-selfclosing-iframe";
/** Allows self closing tags e.g. <div/> (XHTML) */
public static final String ALLOW_SELFCLOSING_TAGS = "http://cyberneko.org/html/features/scanner/allow-selfclosing-tags";
/** Normalize attribute values. */
protected static final String NORMALIZE_ATTRIBUTES = "http://cyberneko.org/html/features/scanner/normalize-attrs";
/** Recognized features. */
private static final String[] RECOGNIZED_FEATURES = {
AUGMENTATIONS,
REPORT_ERRORS,
SCRIPT_STRIP_CDATA_DELIMS,
SCRIPT_STRIP_COMMENT_DELIMS,
STYLE_STRIP_CDATA_DELIMS,
STYLE_STRIP_COMMENT_DELIMS,
IGNORE_SPECIFIED_CHARSET,
CDATA_SECTIONS,
CDATA_EARLY_CLOSING,
OVERRIDE_DOCTYPE,
INSERT_DOCTYPE,
NORMALIZE_ATTRIBUTES,
PARSE_NOSCRIPT_CONTENT,
ALLOW_SELFCLOSING_IFRAME,
ALLOW_SELFCLOSING_TAGS, };
/** Recognized features defaults. */
private static final Boolean[] RECOGNIZED_FEATURES_DEFAULTS = {
null,
null,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.TRUE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.FALSE,
Boolean.TRUE,
Boolean.FALSE,
Boolean.FALSE, };
// properties
/** Modify HTML element names: { "upper", "lower", "default" }. */
protected static final String NAMES_ELEMS = "http://cyberneko.org/html/properties/names/elems";
/** Modify HTML attribute names: { "upper", "lower", "default" }. */
protected static final String NAMES_ATTRS = "http://cyberneko.org/html/properties/names/attrs";
/** Default encoding. */
protected static final String DEFAULT_ENCODING = "http://cyberneko.org/html/properties/default-encoding";
/** Error reporter. */
protected static final String ERROR_REPORTER = "http://cyberneko.org/html/properties/error-reporter";
/** Doctype declaration public identifier. */
protected static final String DOCTYPE_PUBID = "http://cyberneko.org/html/properties/doctype/pubid";
/** Doctype declaration system identifier. */
protected static final String DOCTYPE_SYSID = "http://cyberneko.org/html/properties/doctype/sysid";
/** Recognized properties. */
private static final String[] RECOGNIZED_PROPERTIES = {
NAMES_ELEMS,
NAMES_ATTRS,
DEFAULT_ENCODING,
ERROR_REPORTER,
DOCTYPE_PUBID,
DOCTYPE_SYSID};
/** Recognized properties defaults. */
private static final Object[] RECOGNIZED_PROPERTIES_DEFAULTS = {
null,
null,
"Windows-1252",
null,
HTML_4_01_TRANSITIONAL_PUBID,
HTML_4_01_TRANSITIONAL_SYSID};
// states
/** State: content. */
protected static final short STATE_CONTENT = 0;
/** State: markup bracket. */
protected static final short STATE_MARKUP_BRACKET = 1;
/** State: start document. */
protected static final short STATE_START_DOCUMENT = 10;
/** State: end document. */
protected static final short STATE_END_DOCUMENT = 11;
// modify HTML names
/** Don't modify HTML names. */
protected static final short NAMES_NO_CHANGE = 0;
/** Uppercase HTML names. */
protected static final short NAMES_UPPERCASE = 1;
/** Lowercase HTML names. */
protected static final short NAMES_LOWERCASE = 2;
// defaults
/* Default buffer size, 10 cache lines minus overhead
* A smaller buffer creates less cache misses compared
* to 2048 bytes or more.
*/
protected static final int DEFAULT_BUFFER_SIZE = (10 * 64) - 24;
// debugging
/** Set to true to debug changes in the scanner. */
private static final boolean DEBUG_SCANNER = false;
/** Set to true to debug changes in the scanner state. */
private static final boolean DEBUG_SCANNER_STATE = false;
/** Set to true to debug the buffer. */
private static final boolean DEBUG_BUFFER = false;
/** Set to true to debug character encoding handling. */
private static final boolean DEBUG_CHARSET = false;
/** Set to true to debug callbacks. */
protected static final boolean DEBUG_CALLBACKS = false;
// static vars
/** Synthesized event info item. */
protected static final HTMLEventInfo SYNTHESIZED_ITEM = new HTMLEventInfo.SynthesizedItem();
// features
/** Augmentations. */
private boolean fAugmentations_;
/** Report errors. */
boolean fReportErrors_;
/** Strip CDATA delimiters from SCRIPT tags. */
boolean fScriptStripCDATADelims_;
/** Strip comment delimiters from SCRIPT tags. */
boolean fScriptStripCommentDelims_;
/** Strip CDATA delimiters from STYLE tags. */
boolean fStyleStripCDATADelims_;
/** Strip comment delimiters from STYLE tags. */
boolean fStyleStripCommentDelims_;
/** Ignore specified character set. */
boolean fIgnoreSpecifiedCharset_;
/** CDATA sections. */
boolean fCDATASections_;
/** CDATA early closing. */
boolean fCDATAEarlyClosing_;
/** Override doctype declaration public and system identifiers. */
private boolean fOverrideDoctype_;
/** Insert document type declaration. */
boolean fInsertDoctype_;
/** Normalize attribute values. */
boolean fNormalizeAttributes_;
/** Parse noscript content. */
boolean fParseNoScriptContent_;
/** Allows self closing iframe tags. */
boolean fAllowSelfclosingIframe_;
/** Allows self closing tags. */
boolean fAllowSelfclosingTags_;
// properties
/** Modify HTML element names. */
protected short fNamesElems;
/** Modify HTML attribute names. */
protected short fNamesAttrs;
/** Default encoding. */
protected String fDefaultIANAEncoding;
/** Error reporter. */
protected HTMLErrorReporter fErrorReporter;
/** Doctype declaration public identifier. */
protected String fDoctypePubid;
/** Doctype declaration system identifier. */
protected String fDoctypeSysid;
// boundary locator information
/** Beginning line number. */
protected int fBeginLineNumber;
/** Beginning column number. */
protected int fBeginColumnNumber;
/** Beginning character offset in the file. */
protected int fBeginCharacterOffset;
/** Ending line number. */
protected int fEndLineNumber;
/** Ending column number. */
protected int fEndColumnNumber;
/** Ending character offset in the file. */
protected int fEndCharacterOffset;
// state
/** The playback byte stream. */
protected PlaybackInputStream fByteStream;
/** Current entity. */
CurrentEntity fCurrentEntity;
/** The current entity stack. */
protected final MiniStack<CurrentEntity> fCurrentEntityStack = new MiniStack<>();
/** The current scanner. */
protected Scanner fScanner;
/** The current scanner state. */
protected short fScannerState;
/** The document handler. */
protected XMLDocumentHandler fDocumentHandler;
/** Auto-detected IANA encoding. */
protected String fIANAEncoding;
/** Auto-detected Java encoding. */
protected String fJavaEncoding;
/** Element count. */
protected int fElementCount;
/** Element depth. */
protected int fElementDepth;
// scanners
/** Content scanner. */
protected Scanner fContentScanner = new ContentScanner();
/**
* Special scanner used for elements whose content needs to be scanned as plain
* text, ignoring markup such as elements and entity references. For example:
* <SCRIPT> and <COMMENT>.
*/
protected final SpecialScanner fSpecialScanner = new SpecialScanner();
// temp vars
/** String buffer. */
protected final XMLString fStringBuffer = new XMLString();
/** String buffer. */
final XMLString fStringBuffer2 = new XMLString();
/** String buffer, larger because scripts areas are larger */
final XMLString fScanScriptContent = new XMLString(128);
final XMLString fScanUntilEndTag = new XMLString();
final XMLString fScanComment = new XMLString();
private final XMLString fScanLiteral = new XMLString();
/** Single boolean array. */
final boolean[] fSingleBoolean = {false};
final HTMLConfiguration htmlConfiguration_;
/**
* Our location item, to be reused because {@link Augmentations}
* says so, so let's save on memory
*/
private final LocationItem fLocationItem = new LocationItem();
/**
* Creates a new HTMLScanner with the given configuration
*
* @param htmlConfiguration the configuration to use
*/
HTMLScanner(final HTMLConfiguration htmlConfiguration) {
this.htmlConfiguration_ = htmlConfiguration;
}
/**
* Pushes an input source onto the current entity stack. This enables the
* scanner to transparently scan new content (e.g. the output written by an
* embedded script). At the end of the current entity, the scanner returns where
* it left off at the time this entity source was pushed.
* <p>
* <strong>Note:</strong> This functionality is experimental at this time and is
* subject to change in future releases of NekoHTML.
*
* @param inputSource The new input source to start scanning.
* @see #evaluateInputSource(XMLInputSource)
*/
public void pushInputSource(final XMLInputSource inputSource) {
final Reader reader = getReader(inputSource);
fCurrentEntityStack.push(fCurrentEntity);
final String encoding = inputSource.getEncoding();
final String publicId = inputSource.getPublicId();
final String baseSystemId = inputSource.getBaseSystemId();
final String literalSystemId = inputSource.getSystemId();
final String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
fCurrentEntity = new CurrentEntity(reader, encoding, publicId, baseSystemId, literalSystemId, expandedSystemId);
}
private Reader getReader(final XMLInputSource inputSource) {
final Reader reader = inputSource.getCharacterStream();
if (reader == null) {
try {
return new InputStreamReader(inputSource.getByteStream(), fJavaEncoding);
}
catch (final UnsupportedEncodingException e) {
// should not happen as this encoding is already used to parse the "main" source
}
}
return reader;
}
/**
* Immediately evaluates an input source and add the new content (e.g. the
* output written by an embedded script).
*
* @param inputSource The new input source to start evaluating.
* @see #pushInputSource(XMLInputSource)
*/
public void evaluateInputSource(final XMLInputSource inputSource) {
final Scanner previousScanner = fScanner;
final short previousScannerState = fScannerState;
final CurrentEntity previousEntity = fCurrentEntity;
final Reader reader = getReader(inputSource);
final String encoding = inputSource.getEncoding();
final String publicId = inputSource.getPublicId();
final String baseSystemId = inputSource.getBaseSystemId();
final String literalSystemId = inputSource.getSystemId();
final String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
fCurrentEntity = new CurrentEntity(reader, encoding, publicId, baseSystemId, literalSystemId, expandedSystemId);
setScanner(fContentScanner);
setScannerState(STATE_CONTENT);
try {
do {
fScanner.scan(false);
}
while (fScannerState != STATE_END_DOCUMENT);
}
catch (final IOException e) {
// ignore
}
setScanner(previousScanner);
setScannerState(previousScannerState);
fCurrentEntity = previousEntity;
}
/**
* Cleans up used resources. For example, if scanning is terminated early, then
* this method ensures all remaining open streams are closed.
*
* @param closeall Close all streams, including the original. This is used in
* cases when the application has opened the original document
* stream and should be responsible for closing it.
*/
public void cleanup(final boolean closeall) {
final int size = fCurrentEntityStack.size();
if (size > 0) {
// current entity is not the original, so close it
if (fCurrentEntity != null) {
fCurrentEntity.closeQuietly();
}
// close remaining streams
for (int i = closeall ? 0 : 1; i < size; i++) {
fCurrentEntity = fCurrentEntityStack.pop();
fCurrentEntity.closeQuietly();
}
}
else if (closeall && fCurrentEntity != null) {
fCurrentEntity.closeQuietly();
}
}
/** Returns the encoding. */
@Override
public String getEncoding() {
return fCurrentEntity != null ? fCurrentEntity.encoding_ : null;
}
/** Returns the public identifier. */
@Override
public String getPublicId() {
return fCurrentEntity != null ? fCurrentEntity.publicId : null;
}
/** Returns the base system identifier. */
@Override
public String getBaseSystemId() {
return fCurrentEntity != null ? fCurrentEntity.baseSystemId : null;
}
/** Returns the literal system identifier. */
@Override
public String getLiteralSystemId() {
return fCurrentEntity != null ? fCurrentEntity.literalSystemId : null;
}
/** Returns the expanded system identifier. */
@Override
public String getExpandedSystemId() {
return fCurrentEntity != null ? fCurrentEntity.expandedSystemId : null;
}
/** Returns the current line number. */
@Override
public int getLineNumber() {
return fCurrentEntity != null ? fCurrentEntity.getLineNumber() : -1;
}
/** Returns the current column number. */
@Override
public int getColumnNumber() {
return fCurrentEntity != null ? fCurrentEntity.getColumnNumber() : -1;
}
/** Returns the XML version. */
@Override
public String getXMLVersion() {
return fCurrentEntity != null ? fCurrentEntity.version : null;
}
/** Returns the character offset. */
@Override
public int getCharacterOffset() {
return fCurrentEntity != null ? fCurrentEntity.getCharacterOffset() : -1;
}
/** Returns the default state for a feature. */
@Override
public Boolean getFeatureDefault(final String featureId) {
final int length = RECOGNIZED_FEATURES != null ? RECOGNIZED_FEATURES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_FEATURES[i].equals(featureId)) {
return RECOGNIZED_FEATURES_DEFAULTS[i];
}
}
return null;
}
/** Returns the default state for a property. */
@Override
public Object getPropertyDefault(final String propertyId) {
final int length = RECOGNIZED_PROPERTIES != null ? RECOGNIZED_PROPERTIES.length : 0;
for (int i = 0; i < length; i++) {
if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) {
return RECOGNIZED_PROPERTIES_DEFAULTS[i];
}
}
return null;
}
/** Returns recognized features. */
@Override
public String[] getRecognizedFeatures() {
return RECOGNIZED_FEATURES;
}
/** Returns recognized properties. */
@Override
public String[] getRecognizedProperties() {
return RECOGNIZED_PROPERTIES;
}
/** Resets the component. */
@Override
public void reset(final XMLComponentManager manager) throws XMLConfigurationException {
// get features
fAugmentations_ = manager.getFeature(AUGMENTATIONS);
fReportErrors_ = manager.getFeature(REPORT_ERRORS);
fScriptStripCDATADelims_ = manager.getFeature(SCRIPT_STRIP_CDATA_DELIMS);
fScriptStripCommentDelims_ = manager.getFeature(SCRIPT_STRIP_COMMENT_DELIMS);
fStyleStripCDATADelims_ = manager.getFeature(STYLE_STRIP_CDATA_DELIMS);
fStyleStripCommentDelims_ = manager.getFeature(STYLE_STRIP_COMMENT_DELIMS);
fIgnoreSpecifiedCharset_ = manager.getFeature(IGNORE_SPECIFIED_CHARSET);
fCDATASections_ = manager.getFeature(CDATA_SECTIONS);
fCDATAEarlyClosing_ = manager.getFeature(CDATA_EARLY_CLOSING);
fOverrideDoctype_ = manager.getFeature(OVERRIDE_DOCTYPE);
fInsertDoctype_ = manager.getFeature(INSERT_DOCTYPE);
fNormalizeAttributes_ = manager.getFeature(NORMALIZE_ATTRIBUTES);
fParseNoScriptContent_ = manager.getFeature(PARSE_NOSCRIPT_CONTENT);
fAllowSelfclosingIframe_ = manager.getFeature(ALLOW_SELFCLOSING_IFRAME);
fAllowSelfclosingTags_ = manager.getFeature(ALLOW_SELFCLOSING_TAGS);
// get properties
fNamesElems = getNamesValue(String.valueOf(manager.getProperty(NAMES_ELEMS)));
fNamesAttrs = getNamesValue(String.valueOf(manager.getProperty(NAMES_ATTRS)));
fDefaultIANAEncoding = String.valueOf(manager.getProperty(DEFAULT_ENCODING));
fErrorReporter = (HTMLErrorReporter) manager.getProperty(ERROR_REPORTER);
fDoctypePubid = String.valueOf(manager.getProperty(DOCTYPE_PUBID));
fDoctypeSysid = String.valueOf(manager.getProperty(DOCTYPE_SYSID));
}
/** Sets a feature. */
@Override
public void setFeature(final String featureId, final boolean state) {
if (featureId.equals(AUGMENTATIONS)) {
fAugmentations_ = state;
}
else if (featureId.equals(IGNORE_SPECIFIED_CHARSET)) {
fIgnoreSpecifiedCharset_ = state;
}
else if (featureId.equals(SCRIPT_STRIP_CDATA_DELIMS)) {
fScriptStripCDATADelims_ = state;
}
else if (featureId.equals(SCRIPT_STRIP_COMMENT_DELIMS)) {
fScriptStripCommentDelims_ = state;
}
else if (featureId.equals(STYLE_STRIP_CDATA_DELIMS)) {
fStyleStripCDATADelims_ = state;
}
else if (featureId.equals(STYLE_STRIP_COMMENT_DELIMS)) {
fStyleStripCommentDelims_ = state;
}
else if (featureId.equals(PARSE_NOSCRIPT_CONTENT)) {
fParseNoScriptContent_ = state;
}
else if (featureId.equals(ALLOW_SELFCLOSING_IFRAME)) {
fAllowSelfclosingIframe_ = state;
}
else if (featureId.equals(ALLOW_SELFCLOSING_TAGS)) {
fAllowSelfclosingTags_ = state;
}
}
/** Sets a property. */
@Override
public void setProperty(final String propertyId, final Object value) throws XMLConfigurationException {
if (propertyId.equals(NAMES_ELEMS)) {
fNamesElems = getNamesValue(String.valueOf(value));
return;
}
if (propertyId.equals(NAMES_ATTRS)) {
fNamesAttrs = getNamesValue(String.valueOf(value));
return;
}
if (propertyId.equals(DEFAULT_ENCODING)) {
fDefaultIANAEncoding = String.valueOf(value);
return;
}
}
/** Sets the input source. */
@Override
public void setInputSource(final XMLInputSource source) throws IOException {
// reset state
fElementCount = 0;
fElementDepth = -1;
fByteStream = null;
fCurrentEntityStack.clear();
fBeginLineNumber = 1;
fBeginColumnNumber = 1;
fBeginCharacterOffset = 0;
fEndLineNumber = fBeginLineNumber;
fEndColumnNumber = fBeginColumnNumber;
fEndCharacterOffset = fBeginCharacterOffset;
// reset encoding information
fIANAEncoding = fDefaultIANAEncoding;
fJavaEncoding = fIANAEncoding;
// get location information
String encoding = source.getEncoding();
final String publicId = source.getPublicId();
final String baseSystemId = source.getBaseSystemId();
final String literalSystemId = source.getSystemId();
final String expandedSystemId = expandSystemId(literalSystemId, baseSystemId);
// open stream
Reader reader = source.getCharacterStream();
if (reader == null) {
InputStream inputStream = source.getByteStream();
if (inputStream == null) {
final URL url = new URL(expandedSystemId);
inputStream = url.openStream();
}
fByteStream = new PlaybackInputStream(inputStream);
final String[] encodings = new String[2];
if (encoding == null) {
fByteStream.detectEncoding(encodings);
}
else {
encodings[0] = encoding;
}
if (encodings[0] == null) {
encodings[0] = fDefaultIANAEncoding;
if (fReportErrors_) {
fErrorReporter.reportWarning("HTML1000", null);
}
}
if (encodings[1] == null) {
encodings[1] = EncodingMap.getIANA2JavaMapping(encodings[0].toUpperCase(Locale.ROOT));
if (encodings[1] == null) {
encodings[1] = encodings[0];
if (fReportErrors_) {
fErrorReporter.reportWarning("HTML1001", new Object[] {encodings[0]});
}
}
}
fIANAEncoding = encodings[0];
fJavaEncoding = encodings[1];
encoding = fIANAEncoding;
reader = new BufferedReader(new InputStreamReader(fByteStream, fJavaEncoding));
}
fCurrentEntity = new CurrentEntity(reader, encoding, publicId, baseSystemId, literalSystemId, expandedSystemId);
// set scanner and state
setScanner(fContentScanner);
setScannerState(STATE_START_DOCUMENT);
}
/** Scans the document. */
@Override
public boolean scanDocument(final boolean complete) throws XNIException, IOException {
do {
if (!fScanner.scan(complete)) {
return false;
}
}
while (complete);
return true;
}
/** Sets the document handler. */
@Override
public void setDocumentHandler(final XMLDocumentHandler handler) {
fDocumentHandler = handler;
}
/** Returns the document handler. */
@Override
public XMLDocumentHandler getDocumentHandler() {
return fDocumentHandler;
}
// Returns the value of the specified attribute, ignoring case.
protected static String getValue(final XMLAttributes attrs, final String aname) {
if (attrs != null) {
final int length = attrs.getLength();
for (int i = 0; i < length; i++) {
if (attrs.getQName(i).equalsIgnoreCase(aname)) {
return attrs.getValue(i);
}
}
}
return null;
}
/**
* Expands a system id and returns the system id as a URI, if it can be
* expanded. A return value of null means that the identifier is already
* expanded. An exception thrown indicates a failure to expand the id.
*
* @param systemId The systemId to be expanded.
* @param baseSystemId baseSystemId
*
* @return Returns the URI string representing the expanded system identifier. A
* null value indicates that the given system identifier is already
* expanded.
*
*/
@SuppressWarnings("unused")
public static String expandSystemId(final String systemId, final String baseSystemId) {
// check for bad parameters id
if (systemId == null || systemId.length() == 0) {
return systemId;
}
// if id already expanded, return
try {
new URI(systemId);
return systemId;
}
catch (final URI.MalformedURIException e) {
// continue on...
}
// normalize id
final String id = fixURI(systemId);
// normalize base
URI base;
URI uri = null;
try {
if (baseSystemId == null || baseSystemId.length() == 0 || baseSystemId.equals(systemId)) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"))
// deal with blanks in paths; maybe we have to do better uri encoding here
.replaceAll(" ", "%20");
}
catch (final SecurityException se) {
dir = "";
}
if (!dir.endsWith("/")) {
dir = dir + "/";
}
base = new URI("file", "", dir, null, null);
}
else {
try {
base = new URI(fixURI(baseSystemId));
}
catch (final URI.MalformedURIException e) {
String dir;
try {
dir = fixURI(System.getProperty("user.dir"))
// deal with blanks in paths; maybe we have to do better uri encoding here
.replaceAll(" ", "%20");
}
catch (final SecurityException se) {
dir = "";
}
if (baseSystemId.indexOf(':') != -1) {
// for xml schemas we might have baseURI with
// a specified drive
base = new URI("file", "", fixURI(baseSystemId), null, null);
}
else {
if (!dir.endsWith("/")) {
dir = dir + "/";
}
dir = dir + fixURI(baseSystemId);
base = new URI("file", "", dir, null, null);
}
}
}
// expand id
uri = new URI(base, id);
}
catch (final URI.MalformedURIException e) {
// let it go through
}
if (uri == null) {
return systemId;
}
return uri.toString();
}
/**
* Fixes a platform dependent filename to standard URI form.
*
* @param str The string to fix.
*
* @return Returns the fixed URI string.
*/
protected static String fixURI(String str) {
// handle platform dependent strings
str = str.replace(java.io.File.separatorChar, '/');
// Windows fix
if (str.length() >= 2) {
final char ch1 = str.charAt(1);
// change "C:blah" to "/C:blah"
if (ch1 == ':') {
final char ch0 = String.valueOf(str.charAt(0)).toUpperCase(Locale.ROOT).charAt(0);
if (ch0 >= 'A' && ch0 <= 'Z') {
str = "/" + str;
}
}
// change "//blah" to "file://blah"
else if (ch1 == '/' && str.charAt(0) == '/') {
str = "file:" + str;
}
}
// done
return str;
}
// Modifies the given name based on the specified mode.
protected static String modifyName(final String name, final short mode) {
switch (mode) {
case NAMES_UPPERCASE:
return name.toUpperCase(Locale.ROOT);
case NAMES_LOWERCASE:
return name.toLowerCase(Locale.ROOT);