-
Notifications
You must be signed in to change notification settings - Fork 389
/
XmlPullParser.java
715 lines (618 loc) · 17.8 KB
/
XmlPullParser.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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wicket.markup.parser;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.ParseException;
import org.apache.wicket.markup.parser.XmlTag.TagType;
import org.apache.wicket.markup.parser.XmlTag.TextSegment;
import org.apache.wicket.util.io.FullyBufferedReader;
import org.apache.wicket.util.io.IOUtils;
import org.apache.wicket.util.io.XmlReader;
import org.apache.wicket.util.lang.Args;
import org.apache.wicket.util.parse.metapattern.parsers.TagNameParser;
import org.apache.wicket.util.parse.metapattern.parsers.VariableAssignmentParser;
import org.apache.wicket.util.string.Strings;
/**
* A fairly shallow markup pull parser which parses a markup string of a given type of markup (for
* example, html, xml, vxml or wml) into ComponentTag and RawMarkup tokens.
*
* @author Jonathan Locke
* @author Juergen Donnerstag
*/
public final class XmlPullParser implements IXmlPullParser
{
/** */
public static final String STYLE = "style";
/** */
public static final String SCRIPT = "script";
/**
* The encoding of the XML.
*/
private String encoding;
/**
* A XML independent reader which loads the whole source data into memory and which provides
* convenience methods to access the data.
*/
private FullyBufferedReader input;
/** temporary variable which will hold the name of the closing tag. */
private String skipUntilText;
/** The last substring selected from the input */
private CharSequence lastText;
/** Everything in between <!DOCTYPE ... > */
private CharSequence doctype;
/** The type of what is in lastText */
private HttpTagType lastType = HttpTagType.NOT_INITIALIZED;
/** The last tag found */
private XmlTag lastTag;
/**
* Construct.
*/
public XmlPullParser()
{
}
@Override
public final String getEncoding()
{
return encoding;
}
@Override
public final CharSequence getDoctype()
{
return doctype;
}
@Override
public final CharSequence getInputFromPositionMarker(final int toPos)
{
return input.getSubstring(toPos);
}
@Override
public final CharSequence getInput(final int fromPos, final int toPos)
{
return input.getSubstring(fromPos, toPos);
}
/**
* Whatever will be in between the current index and the closing tag, will be ignored (and thus
* treated as raw markup (text). This is useful for tags like 'script'.
*
* @throws ParseException
*/
private void skipUntil() throws ParseException
{
// this is a tag with non-XHTML text as body - skip this until the
// skipUntilText is found.
final int startIndex = input.getPosition();
final int tagNameLen = skipUntilText.length();
int pos = input.getPosition() - 1;
String endTagText = null;
int lastPos = 0;
while (!skipUntilText.equalsIgnoreCase(endTagText))
{
pos = input.find("</", pos + 1);
if ((pos == -1) || ((pos + (tagNameLen + 2)) >= input.size()))
{
throw new ParseException(
skipUntilText + " tag not closed" + getLineAndColumnText(), startIndex);
}
lastPos = pos + 2;
endTagText = input.getSubstring(lastPos, lastPos + tagNameLen).toString();
}
input.setPosition(pos);
lastText = input.getSubstring(startIndex, pos);
lastType = HttpTagType.BODY;
// Check that the tag is properly closed
lastPos = input.find('>', lastPos + tagNameLen);
if (lastPos == -1)
{
throw new ParseException(skipUntilText + " tag not closed" + getLineAndColumnText(),
startIndex);
}
// Reset the state variable
skipUntilText = null;
}
/**
*
* @return line and column number
*/
private String getLineAndColumnText()
{
return " (line " + input.getLineNumber() + ", column " + input.getColumnNumber() + ")";
}
/**
* @return XXX
* @throws ParseException
*/
@Override
public final HttpTagType next() throws ParseException
{
// Reached end of markup file?
if (input.getPosition() >= input.size())
{
return HttpTagType.NOT_INITIALIZED;
}
if (skipUntilText != null)
{
skipUntil();
return lastType;
}
// Any more tags in the markup?
final int openBracketIndex = input.find('<');
// Tag or Body?
if (input.charAt(input.getPosition()) != '<')
{
// It's a BODY
if (openBracketIndex == -1)
{
// There is no next matching tag.
lastText = input.getSubstring(-1);
input.setPosition(input.size());
lastType = HttpTagType.BODY;
return lastType;
}
lastText = input.getSubstring(openBracketIndex);
input.setPosition(openBracketIndex);
lastType = HttpTagType.BODY;
return lastType;
}
// Determine the line number
input.countLinesTo(openBracketIndex);
// Get index of closing tag and advance past the tag
int closeBracketIndex = -1;
if (openBracketIndex != -1 && openBracketIndex < input.size() - 1)
{
char nextChar = input.charAt(openBracketIndex + 1);
if ((nextChar == '!') || (nextChar == '?'))
closeBracketIndex = input.find('>', openBracketIndex);
else
closeBracketIndex = input.findOutOfQuotes('>', openBracketIndex);
}
if (closeBracketIndex == -1)
{
throw new ParseException("No matching close bracket at" + getLineAndColumnText(),
input.getPosition());
}
// Get the complete tag text
lastText = input.getSubstring(openBracketIndex, closeBracketIndex + 1);
// Get the tagtext between open and close brackets
String tagText = lastText.subSequence(1, lastText.length() - 1).toString();
if (tagText.length() == 0)
{
throw new ParseException("Found empty tag: '<>' at" + getLineAndColumnText(),
input.getPosition());
}
// Type of the tag, to be determined next
final TagType type;
// If the tag ends in '/', it's a "simple" tag like <foo/>
if (tagText.endsWith("/"))
{
type = TagType.OPEN_CLOSE;
tagText = tagText.substring(0, tagText.length() - 1);
}
else if (tagText.startsWith("/"))
{
// The tag text starts with a '/', it's a simple close tag
type = TagType.CLOSE;
tagText = tagText.substring(1);
}
else
{
// It must be an open tag
type = TagType.OPEN;
// If open tag and starts with "s" like "script" or "style", than ...
if ((tagText.length() > STYLE.length()) &&
((tagText.charAt(0) == 's') || (tagText.charAt(0) == 'S')))
{
final String lowerCase = tagText.toLowerCase();
if (lowerCase.startsWith(SCRIPT))
{
String typeAttr = "type=";
int idxOfType = lowerCase.indexOf(typeAttr);
if (idxOfType > 0)
{
// +1 to remove the ' or "
String typePrefix = lowerCase.substring(idxOfType + typeAttr.length() + 1);
if (typePrefix.startsWith("text/javascript"))
{
// prepare to skip everything between the open and close tag
skipUntilText = SCRIPT;
}
// any other type is assumed to be a template so it can contain child nodes.
// See WICKET-5288
}
else
{
// no type attribute so it is 'text/javascript'
// prepare to skip everything between the open and close tag
skipUntilText = SCRIPT;
}
}
else if (lowerCase.startsWith(STYLE))
{
// prepare to skip everything between the open and close tag
skipUntilText = STYLE;
}
}
}
// Handle special tags like <!-- and <![CDATA ...
final char firstChar = tagText.charAt(0);
if ((firstChar == '!') || (firstChar == '?'))
{
specialTagHandling(tagText, openBracketIndex, closeBracketIndex);
input.countLinesTo(openBracketIndex);
TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(),
input.getColumnNumber());
lastTag = new XmlTag(text, type);
return lastType;
}
TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(),
input.getColumnNumber());
XmlTag tag = new XmlTag(text, type);
lastTag = tag;
// Parse the tag text and populate tag attributes
if (parseTagText(tag, tagText))
{
// Move to position after the tag
input.setPosition(closeBracketIndex + 1);
lastType = HttpTagType.TAG;
return lastType;
}
else
{
throw new ParseException("Malformed tag" + getLineAndColumnText(), openBracketIndex);
}
}
/**
* Handle special tags like <!-- --> or <![CDATA[..]]> or <?xml>
*
* @param tagText
* @param openBracketIndex
* @param closeBracketIndex
* @throws ParseException
*/
protected void specialTagHandling(String tagText, final int openBracketIndex,
int closeBracketIndex) throws ParseException
{
// Handle comments
if (tagText.startsWith("!--"))
{
// downlevel-revealed conditional comments e.g.: <!--[if (gt IE9)|!(IE)]><!-->
if (tagText.contains("![endif]--"))
{
lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF;
// Move to position after the tag
input.setPosition(closeBracketIndex + 1);
return;
}
// Conditional comment? E.g.
// "<!--[if IE]><a href='test.html'>my link</a><![endif]-->"
if (tagText.startsWith("!--[if ") && tagText.endsWith("]"))
{
int pos = input.find("]-->", openBracketIndex + 1);
if (pos == -1)
{
throw new ParseException("Unclosed conditional comment beginning at" +
getLineAndColumnText(), openBracketIndex);
}
pos += 4;
lastText = input.getSubstring(openBracketIndex, pos);
// Actually it is no longer a comment. It is now
// up to the browser to select the section appropriate.
input.setPosition(closeBracketIndex + 1);
lastType = HttpTagType.CONDITIONAL_COMMENT;
}
else
{
// Normal comment section.
// Skip ahead to "-->". Note that you can not simply test for
// tagText.endsWith("--") as the comment might contain a '>'
// inside.
int pos = input.find("-->", openBracketIndex + 1);
if (pos == -1)
{
throw new ParseException("Unclosed comment beginning at" +
getLineAndColumnText(), openBracketIndex);
}
pos += 3;
lastText = input.getSubstring(openBracketIndex, pos);
lastType = HttpTagType.COMMENT;
input.setPosition(pos);
}
return;
}
// The closing tag of a conditional comment, e.g.
// "<!--[if IE]><a href='test.html'>my link</a><![endif]-->
// and also <!--<![endif]-->"
if (tagText.equals("![endif]--"))
{
lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF;
input.setPosition(closeBracketIndex + 1);
return;
}
// CDATA sections might contain "<" which is not part of an XML tag.
// Make sure escaped "<" are treated right
if (tagText.startsWith("!["))
{
final String startText = (tagText.length() <= 8 ? tagText : tagText.substring(0, 8));
if (startText.toUpperCase().equals("![CDATA["))
{
int pos1 = openBracketIndex;
do
{
// Get index of closing tag and advance past the tag
closeBracketIndex = findChar('>', pos1);
if (closeBracketIndex == -1)
{
throw new ParseException("No matching close bracket at" +
getLineAndColumnText(), input.getPosition());
}
// Get the tagtext between open and close brackets
tagText = input.getSubstring(openBracketIndex + 1, closeBracketIndex)
.toString();
pos1 = closeBracketIndex + 1;
}
while (tagText.endsWith("]]") == false);
// Move to position after the tag
input.setPosition(closeBracketIndex + 1);
lastText = tagText;
lastType = HttpTagType.CDATA;
return;
}
}
if (tagText.charAt(0) == '?')
{
lastType = HttpTagType.PROCESSING_INSTRUCTION;
// Move to position after the tag
input.setPosition(closeBracketIndex + 1);
return;
}
if (tagText.startsWith("!DOCTYPE"))
{
lastType = HttpTagType.DOCTYPE;
// Get the tagtext between open and close brackets
doctype = input.getSubstring(openBracketIndex + 1, closeBracketIndex);
// Move to position after the tag
input.setPosition(closeBracketIndex + 1);
return;
}
// Move to position after the tag
lastType = HttpTagType.SPECIAL_TAG;
input.setPosition(closeBracketIndex + 1);
}
/**
* @return MarkupElement
*/
@Override
public final XmlTag getElement()
{
return lastTag;
}
/**
* @return The xml string from the last element
*/
@Override
public final CharSequence getString()
{
return lastText;
}
/**
* @return The next XML tag
* @throws ParseException
*/
public final XmlTag nextTag() throws ParseException
{
while (next() != HttpTagType.NOT_INITIALIZED)
{
switch (lastType)
{
case TAG :
return lastTag;
case BODY :
break;
case COMMENT :
break;
case CONDITIONAL_COMMENT :
break;
case CDATA :
break;
case PROCESSING_INSTRUCTION :
break;
case SPECIAL_TAG :
break;
}
}
return null;
}
/**
* Find the char but ignore any text within ".." and '..'
*
* @param ch
* The character to search
* @param startIndex
* Start index
* @return -1 if not found, else the index
*/
private int findChar(final char ch, int startIndex)
{
char quote = 0;
for (; startIndex < input.size(); startIndex++)
{
final char charAt = input.charAt(startIndex);
if (quote != 0)
{
if (quote == charAt)
{
quote = 0;
}
}
else if ((charAt == '"') || (charAt == '\''))
{
quote = charAt;
}
else if (charAt == ch)
{
return startIndex;
}
}
return -1;
}
/**
* Parse the given string.
* <p>
* Note: xml character encoding is NOT applied. It is assumed the input provided does have the
* correct encoding already.
*
* @param string
* The input string
* @throws IOException
* Error while reading the resource
*/
@Override
public void parse(final CharSequence string) throws IOException
{
Args.notNull(string, "string");
this.input = new FullyBufferedReader(new StringReader(string.toString()));
this.encoding = null;
}
/**
* Reads and parses markup from an input stream, using UTF-8 encoding by default when not
* specified in XML declaration.
*
* @param in
* The input stream to read and parse
* @throws IOException
*
* @see {@link #parse(InputStream, String)}
*/
@Override
public void parse(final InputStream in) throws IOException
{
// When XML declaration does not specify encoding, it defaults to UTF-8
parse(in, "UTF-8");
}
/**
* Reads and parses markup from an input stream.
* <p>
* Note: The input is closed after parsing.
*
* @param inputStream
* The input stream to read and parse
* @param encoding
* The default character encoding of the input
* @throws IOException
*/
@Override
public void parse(final InputStream inputStream, final String encoding) throws IOException
{
Args.notNull(inputStream, "inputStream");
try
{
XmlReader xmlReader = new XmlReader(new BufferedInputStream(inputStream, 4000),
encoding);
this.input = new FullyBufferedReader(xmlReader);
this.encoding = xmlReader.getEncoding();
}
finally
{
IOUtils.closeQuietly(inputStream);
}
}
@Override
public final void setPositionMarker()
{
input.setPositionMarker(input.getPosition());
}
@Override
public final void setPositionMarker(final int pos)
{
input.setPositionMarker(pos);
}
@Override
public String toString()
{
return input.toString();
}
/**
* Parses the text between tags. For example, "a href=foo.html".
*
* @param tag
* @param tagText
* The text between tags
* @return false in case of an error
* @throws ParseException
*/
private boolean parseTagText(final XmlTag tag, final String tagText) throws ParseException
{
// Get the length of the tagtext
final int tagTextLength = tagText.length();
// If we match tagname pattern
final TagNameParser tagnameParser = new TagNameParser(tagText);
if (tagnameParser.matcher().lookingAt())
{
// Extract the tag from the pattern matcher
tag.name = tagnameParser.getName();
tag.namespace = tagnameParser.getNamespace();
// Are we at the end? Then there are no attributes, so we just
// return the tag
int pos = tagnameParser.matcher().end(0);
if (pos == tagTextLength)
{
return true;
}
// Extract attributes
final VariableAssignmentParser attributeParser = new VariableAssignmentParser(tagText);
while (attributeParser.matcher().find(pos))
{
// Get key and value using attribute pattern
String value = attributeParser.getValue();
// In case like <html xmlns:wicket> will the value be null
if (value == null)
{
value = "";
}
// Set new position to end of attribute
pos = attributeParser.matcher().end(0);
// Chop off double quotes or single quotes
if (value.startsWith("\"") || value.startsWith("\'"))
{
value = value.substring(1, value.length() - 1);
}
// Trim trailing whitespace
value = value.trim();
// Unescape
value = Strings.unescapeMarkup(value).toString();
// Get key
final String key = attributeParser.getKey();
// Put the attribute in the attributes hash
if (null != tag.getAttributes().put(key, value))
{
throw new ParseException("Same attribute found twice: " + key +
getLineAndColumnText(), input.getPosition());
}
// The input has to match exactly (no left over junk after
// attributes)
if (pos == tagTextLength)
{
return true;
}
}
return true;
}
return false;
}
}