Debian Codegraph @

common/src/main/java/com/android/utils/PositionXmlParser.java

raw
1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.utils;
18
19 import static com.android.SdkConstants.UTF_8;
20
21 import com.android.annotations.NonNull;
22 import com.android.annotations.Nullable;
23 import com.android.ide.common.blame.SourcePosition;
24
25 import org.w3c.dom.Attr;
26 import org.w3c.dom.Comment;
27 import org.w3c.dom.Document;
28 import org.w3c.dom.Element;
29 import org.w3c.dom.NamedNodeMap;
30 import org.w3c.dom.Node;
31 import org.w3c.dom.NodeList;
32 import org.w3c.dom.Text;
33 import org.xml.sax.Attributes;
34 import org.xml.sax.InputSource;
35 import org.xml.sax.Locator;
36 import org.xml.sax.SAXException;
37 import org.xml.sax.XMLReader;
38 import org.xml.sax.ext.DefaultHandler2;
39
40 import java.io.ByteArrayOutputStream;
41 import java.io.IOException;
42 import java.io.InputStream;
43 import java.io.StringReader;
44 import java.io.UnsupportedEncodingException;
45 import java.util.ArrayList;
46 import java.util.List;
47 import java.util.regex.Matcher;
48 import java.util.regex.Pattern;
49
50 import javax.xml.parsers.DocumentBuilder;
51 import javax.xml.parsers.DocumentBuilderFactory;
52 import javax.xml.parsers.ParserConfigurationException;
53 import javax.xml.parsers.SAXParser;
54 import javax.xml.parsers.SAXParserFactory;
55
56 /**
57 * A simple DOM XML parser which can retrieve exact beginning and end offsets
58 * (and line and column numbers) for element nodes as well as attribute nodes.
59 */
60 public class PositionXmlParser {
61 private static final String UTF_16 = "UTF_16"; //$NON-NLS-1$
62 private static final String UTF_16LE = "UTF_16LE"; //$NON-NLS-1$
63 private static final String CONTENT_KEY = "contents"; //$NON-NLS-1$
64 private static final String POS_KEY = "offsets"; //$NON-NLS-1$
65 private static final String NAMESPACE_PREFIX_FEATURE =
66 "http://xml.org/sax/features/namespace-prefixes"; //$NON-NLS-1$
67 private static final String NAMESPACE_FEATURE =
68 "http://xml.org/sax/features/namespaces"; //$NON-NLS-1$
69 private static final String PROVIDE_XMLNS_URIS =
70 "http://xml.org/sax/features/xmlns-uris"; //$NON-NLS-1$
71 /** See http://www.w3.org/TR/REC-xml/#NT-EncodingDecl */
72 private static final Pattern ENCODING_PATTERN =
73 Pattern.compile("encoding=['\"](\\S*)['\"]"); //$NON-NLS-1$
74 private static final String LOAD_EXTERNAL_DTD =
75 "http://apache.org/xml/features/nonvalidating/load-external-dtd";; //$NON-NLS-1$
76
77 /**
78 * Parses the XML content from the given input stream.
79 *
80 * @param input the input stream containing the XML to be parsed
81 * @param checkDtd whether or not download the DTD and validate it
82 * @return the corresponding document
83 * @throws ParserConfigurationException if a SAX parser is not available
84 * @throws SAXException if the document contains a parsing error
85 * @throws IOException if something is seriously wrong. This should not
86 * happen since the input source is known to be constructed from
87 * a string.
88 */
89 @NonNull
90 public static Document parse(@NonNull InputStream input, boolean checkDtd)
91 throws ParserConfigurationException, SAXException, IOException {
92 // Read in all the data
93 ByteArrayOutputStream out = new ByteArrayOutputStream();
94 byte[] buf = new byte[1024];
95 while (true) {
96 int r = input.read(buf);
97 if (r == -1) {
98 break;
99 }
100 out.write(buf, 0, r);
101 }
102 input.close();
103 return parse(out.toByteArray(), checkDtd);
104 }
105
106 /**
107 * @see PositionXmlParser#parse(InputStream, boolean)
108 */
109 @NonNull
110 public static Document parse(@NonNull InputStream input)
111 throws IOException, SAXException, ParserConfigurationException {
112 return parse(input, true);
113 }
114
115 /**
116 * @see PositionXmlParser#parse(byte[], boolean)
117 */
118 @NonNull
119 public static Document parse(@NonNull byte[] data)
120 throws ParserConfigurationException, SAXException, IOException {
121 return parse(data, true);
122 }
123
124 /**
125 * Parses the XML content from the given byte array
126 *
127 * @param data the raw XML data (with unknown encoding)
128 * @param checkDtd whether or not download the DTD and validate it
129 * @return the corresponding document
130 * @throws ParserConfigurationException if a SAX parser is not available
131 * @throws SAXException if the document contains a parsing error
132 * @throws IOException if something is seriously wrong. This should not
133 * happen since the input source is known to be constructed from
134 * a string.
135 */
136 @NonNull
137 public static Document parse(@NonNull byte[] data, boolean checkDtd)
138 throws ParserConfigurationException, SAXException, IOException {
139 String xml = getXmlString(data);
140 xml = XmlUtils.stripBom(xml);
141 return parse(xml, new InputSource(new StringReader(xml)), true, checkDtd);
142 }
143
144 /**
145 * Parses the given XML content.
146 *
147 * @param xml the XML string to be parsed. This must be in the correct
148 * encoding already.
149 * @return the corresponding document
150 * @throws ParserConfigurationException if a SAX parser is not available
151 * @throws SAXException if the document contains a parsing error
152 * @throws IOException if something is seriously wrong. This should not
153 * happen since the input source is known to be constructed from
154 * a string.
155 */
156 @NonNull
157 public static Document parse(@NonNull String xml)
158 throws ParserConfigurationException, SAXException, IOException {
159 xml = XmlUtils.stripBom(xml);
160 return parse(xml, new InputSource(new StringReader(xml)), true, true);
161 }
162
163 @NonNull
164 private static Document parse(@NonNull String xml, @NonNull InputSource input, boolean checkBom,
165 boolean checkDtd)
166 throws ParserConfigurationException, SAXException, IOException {
167 try {
168 SAXParserFactory factory = SAXParserFactory.newInstance();
169 if (checkDtd) {
170 factory.setFeature(NAMESPACE_FEATURE, true);
171 factory.setFeature(NAMESPACE_PREFIX_FEATURE, true);
172 factory.setFeature(PROVIDE_XMLNS_URIS, true);
173 } else {
174 factory.setFeature(LOAD_EXTERNAL_DTD, false);
175 }
176 SAXParser parser = factory.newSAXParser();
177 DomBuilder handler = new DomBuilder(xml);
178 XMLReader xmlReader = parser.getXMLReader();
179 xmlReader.setProperty(
180 "http://xml.org/sax/properties/lexical-handler",
181 handler
182 );
183 parser.parse(input, handler);
184 return handler.getDocument();
185 } catch (SAXException e) {
186 if (checkBom && e.getMessage().contains("Content is not allowed in prolog")) {
187 // Byte order mark in the string? Skip it. There are many markers
188 // (see http://en.wikipedia.org/wiki/Byte_order_mark) so here we'll
189 // just skip those up to the XML prolog beginning character, <
190 xml = xml.replaceFirst("^([\\W]+)<","<"); //$NON-NLS-1$ //$NON-NLS-2$
191 return parse(xml, new InputSource(new StringReader(xml)), false, checkDtd);
192 }
193 throw e;
194 }
195 }
196
197 /**
198 * Returns the String corresponding to the given byte array of XML data
199 * (with unknown encoding). This method attempts to guess the encoding based
200 * on the XML prologue.
201 * @param data the XML data to be decoded into a string
202 * @return a string corresponding to the XML data
203 */
204 @NonNull
205 public static String getXmlString(@NonNull byte[] data) {
206 return getXmlString(data, UTF_8);
207 }
208
209 /**
210 * Returns the String corresponding to the given byte array of XML data
211 * (with unknown encoding). This method attempts to guess the encoding based
212 * on the XML prologue.
213 * @param data the XML data to be decoded into a string
214 * @param defaultCharset the default charset to use if not specified by an encoding prologue
215 * attribute or a byte order mark
216 * @return a string corresponding to the XML data
217 */
218 @NonNull
219 public static String getXmlString(@NonNull byte[] data, @NonNull String defaultCharset) {
220 int offset = 0;
221
222 String charset = null;
223 // Look for the byte order mark, to see if we need to remove bytes from
224 // the input stream (and to determine whether files are big endian or little endian) etc
225 // for files which do not specify the encoding.
226 // See http://unicode.org/faq/utf_bom.html#BOM for more.
227 if (data.length > 4) {
228 if (data[0] == (byte)0xef && data[1] == (byte)0xbb && data[2] == (byte)0xbf) {
229 // UTF-8
230 defaultCharset = charset = UTF_8;
231 offset += 3;
232 } else if (data[0] == (byte)0xfe && data[1] == (byte)0xff) {
233 // UTF-16, big-endian
234 defaultCharset = charset = UTF_16;
235 offset += 2;
236 } else if (data[0] == (byte)0x0 && data[1] == (byte)0x0
237 && data[2] == (byte)0xfe && data[3] == (byte)0xff) {
238 // UTF-32, big-endian
239 defaultCharset = charset = "UTF_32"; //$NON-NLS-1$
240 offset += 4;
241 } else if (data[0] == (byte)0xff && data[1] == (byte)0xfe
242 && data[2] == (byte)0x0 && data[3] == (byte)0x0) {
243 // UTF-32, little-endian. We must check for this *before* looking for
244 // UTF_16LE since UTF_32LE has the same prefix!
245 defaultCharset = charset = "UTF_32LE"; //$NON-NLS-1$
246 offset += 4;
247 } else if (data[0] == (byte)0xff && data[1] == (byte)0xfe) {
248 // UTF-16, little-endian
249 defaultCharset = charset = UTF_16LE;
250 offset += 2;
251 }
252 }
253 int length = data.length - offset;
254
255 // Guess encoding by searching for an encoding= entry in the first line.
256 // The prologue, and the encoding names, will always be in ASCII - which means
257 // we don't need to worry about strange character encodings for the prologue characters.
258 // However, one wrinkle is that the whole file may be encoded in something like UTF-16
259 // where there are two bytes per character, so we can't just look for
260 // ['e','n','c','o','d','i','n','g'] etc in the byte array since there could be
261 // multiple bytes for each character. However, since again the prologue is in ASCII,
262 // we can just drop the zeroes.
263 boolean seenOddZero = false;
264 boolean seenEvenZero = false;
265 int prologueStart = -1;
266 for (int lineEnd = offset; lineEnd < data.length; lineEnd++) {
267 if (data[lineEnd] == 0) {
268 if ((lineEnd - offset) % 2 == 0) {
269 seenEvenZero = true;
270 } else {
271 seenOddZero = true;
272 }
273 } else if (data[lineEnd] == '\n' || data[lineEnd] == '\r') {
274 break;
275 } else if (data[lineEnd] == '<') {
276 prologueStart = lineEnd;
277 } else if (data[lineEnd] == '>') {
278 // End of prologue. Quick check to see if this is a utf-8 file since that's
279 // common
280 for (int i = lineEnd - 4; i >= 0; i--) {
281 if ((data[i] == 'u' || data[i] == 'U')
282 && (data[i + 1] == 't' || data[i + 1] == 'T')
283 && (data[i + 2] == 'f' || data[i + 2] == 'F')
284 && (data[i + 3] == '-' || data[i + 3] == '_')
285 && (data[i + 4] == '8')
286 ) {
287 charset = UTF_8;
288 break;
289 }
290 }
291
292 if (charset == null) {
293 StringBuilder sb = new StringBuilder();
294 for (int i = prologueStart; i <= lineEnd; i++) {
295 if (data[i] != 0) {
296 sb.append((char) data[i]);
297 }
298 }
299 String prologue = sb.toString();
300 int encodingIndex = prologue.indexOf("encoding"); //$NON-NLS-1$
301 if (encodingIndex != -1) {
302 Matcher matcher = ENCODING_PATTERN.matcher(prologue);
303 if (matcher.find(encodingIndex)) {
304 charset = matcher.group(1);
305 }
306 }
307 }
308
309 break;
310 }
311 }
312
313 // No prologue on the first line, and no byte order mark: Assume UTF-8/16
314 if (charset == null) {
315 charset = seenOddZero ? UTF_16LE : seenEvenZero ? UTF_16 : defaultCharset;
316 }
317
318 String xml = null;
319 try {
320 xml = new String(data, offset, length, charset);
321 } catch (UnsupportedEncodingException e) {
322 try {
323 if (!charset.equals(defaultCharset)) {
324 xml = new String(data, offset, length, defaultCharset);
325 }
326 } catch (UnsupportedEncodingException u) {
327 // Just use the default encoding below
328 }
329 }
330 if (xml == null) {
331 xml = new String(data, offset, length);
332 }
333 return xml;
334 }
335
336 /**
337 * Returns the position for the given node. This is the start position. The
338 * end position can be obtained via {@link Position#getEnd()}.
339 *
340 * @param node the node to look up position for
341 * @return the position, or null if the node type is not supported for
342 * position info
343 */
344 @NonNull
345 public static SourcePosition getPosition(@NonNull Node node) {
346 return getPosition(node, -1, -1);
347 }
348
349 /**
350 * Returns the position for the given node. This is the start position. The
351 * end position can be obtained via {@link Position#getEnd()}. A specific
352 * range within the node can be specified with the {@code start} and
353 * {@code end} parameters.
354 *
355 * @param node the node to look up position for
356 * @param start the relative offset within the node range to use as the
357 * starting position, inclusive, or -1 to not limit the range
358 * @param end the relative offset within the node range to use as the ending
359 * position, or -1 to not limit the range
360 * @return the position, or null if the node type is not supported for
361 * position info
362 */
363
364 @NonNull
365 public static SourcePosition getPosition(@NonNull Node node, int start, int end) {
366 Position p = getPositionHelper(node, start, end);
367 return p == null ? SourcePosition.UNKNOWN : p.toSourcePosition();
368 }
369
370 /**
371 * Finds the leaf node at the given offset
372 *
373 * @param document root node
374 * @param offset offset to look for
375 * @return the leaf node at that offset, if any
376 */
377 @Nullable
378 public static Node findNodeAtOffset(@NonNull Document document, int offset) {
379 Element root = document.getDocumentElement();
380 if (root != null) {
381 return findNodeAtOffset(root, offset);
382 }
383
384 return null;
385 }
386
387 @Nullable
388 private static Node findNodeAtOffset(@NonNull Node node, int offset) {
389 Position p = getPositionHelper(node, -1, -1);
390 if (p != null) {
391 if (offset < p.getOffset()) {
392 return null;
393 }
394 Position end = p.getEnd();
395 if (end != null) {
396 if (offset >= end.getOffset()) {
397 return null;
398 }
399 }
400 } else {
401 return null;
402 }
403
404 NodeList children = node.getChildNodes();
405 for (int i = 0, n = children.getLength(); i < n; i++) {
406 Node item = children.item(i);
407 Node match = findNodeAtOffset(item, offset);
408 if (match != null) {
409 return match;
410 }
411 }
412
413 NamedNodeMap attributes = node.getAttributes();
414 if (attributes != null) {
415 for (int i = 0, n = attributes.getLength(); i < n; i++) {
416 Node item = attributes.item(i);
417 Node match = findNodeAtOffset(item, offset);
418 if (match != null) {
419 return match;
420 }
421 }
422 }
423
424 return node;
425 }
426
427 /**
428 * Finds the leaf node at the given offset
429 *
430 * @param document root node
431 * @param line the line
432 * @param column the column, or -1
433 * @return the leaf node at that offset, if any
434 */
435 @Nullable
436 public static Node findNodeAtLineAndCol(@NonNull Document document, int line, int column) {
437 Element root = document.getDocumentElement();
438 if (root != null) {
439 return findNodeAtLineAndCol(root, line, column);
440 }
441
442 return null;
443 }
444
445 @Nullable
446 private static Node findNodeAtLineAndCol(@NonNull Node node, int line, int column) {
447 Position p = getPositionHelper(node, -1, -1);
448 if (p != null) {
449 if (line < p.getLine() || line == p.getLine() && column != -1
450 && column < p.getColumn()) {
451 return null;
452 }
453 Position end = p.getEnd();
454 if (end != null) {
455 if (line > end.getLine() || line == end.getLine() && column != -1
456 && column >= end.getColumn()) {
457 return null;
458 }
459 }
460 } else {
461 return null;
462 }
463
464 NodeList children = node.getChildNodes();
465 for (int i = 0, n = children.getLength(); i < n; i++) {
466 Node item = children.item(i);
467 Node match = findNodeAtLineAndCol(item, line, column);
468 if (match != null) {
469 return match;
470 }
471 }
472
473 NamedNodeMap attributes = node.getAttributes();
474 if (attributes != null) {
475 for (int i = 0, n = attributes.getLength(); i < n; i++) {
476 Node item = attributes.item(i);
477 Node match = findNodeAtLineAndCol(item, line, column);
478 if (match != null) {
479 return match;
480 }
481 }
482 }
483
484 return node;
485 }
486
487 @Nullable
488 private static Position getPositionHelper(@NonNull Node node, int start, int end) {
489 // Look up the position information stored while parsing for the given node.
490 // Note however that we only store position information for elements (because
491 // there is no SAX callback for individual attributes).
492 // Therefore, this method special cases this:
493 // -- First, it looks at the owner element and uses its position
494 // information as a first approximation.
495 // -- Second, it uses that, as well as the original XML text, to search
496 // within the node range for an exact text match on the attribute name
497 // and if found uses that as the exact node offsets instead.
498 if (node instanceof Attr) {
499 Attr attr = (Attr) node;
500 Position pos = (Position) attr.getOwnerElement().getUserData(POS_KEY);
501 if (pos != null) {
502 int startOffset = pos.getOffset();
503 int endOffset = pos.getEnd().getOffset();
504 if (start != -1) {
505 startOffset += start;
506 if (end != -1) {
507 endOffset = startOffset + (end - start);
508 }
509 }
510
511 // Find attribute in the text
512 String contents = (String) node.getOwnerDocument().getUserData(CONTENT_KEY);
513 if (contents == null) {
514 return null;
515 }
516
517 // Locate the name=value attribute in the source text
518 // Fast string check first for the common occurrence
519 String name = attr.getName();
520 Pattern pattern = Pattern.compile(attr.getPrefix() != null
521 ? String.format("(%1$s\\s*=\\s*[\"'].*?[\"'])", name) //$NON-NLS-1$
522 : String.format("[^:](%1$s\\s*=\\s*[\"'].*?[\"'])", name));//$NON-NLS-1$
523 Matcher matcher = pattern.matcher(contents);
524 if (matcher.find(startOffset) && matcher.start(1) <= endOffset) {
525 int index = matcher.start(1);
526 // Adjust the line and column to this new offset
527 int line = pos.getLine();
528 int column = pos.getColumn();
529 for (int offset = pos.getOffset(); offset < index; offset++) {
530 char t = contents.charAt(offset);
531 if (t == '\n') {
532 line++;
533 column = 0;
534 } else {
535 column++;
536 }
537 }
538
539 Position attributePosition = new Position(line, column, index);
540 // Also set end range for retrieval in getLocation
541 attributePosition.setEnd(
542 new Position(line, column + matcher.end(1) - index, matcher.end(1)));
543 return attributePosition;
544 } else {
545 // No regexp match either: just fall back to element position
546 return pos;
547 }
548 }
549 } else if (node instanceof Text) {
550 // Position of parent element, if any
551 Position pos = null;
552 if (node.getPreviousSibling() != null) {
553 pos = (Position) node.getPreviousSibling().getUserData(POS_KEY);
554 }
555 if (pos == null) {
556 pos = (Position) node.getParentNode().getUserData(POS_KEY);
557 }
558 if (pos != null) {
559 // Attempt to point forward to the actual text node
560 int startOffset = pos.getOffset();
561 int endOffset = pos.getEnd().getOffset();
562 int line = pos.getLine();
563 int column = pos.getColumn();
564
565 // Find attribute in the text
566 String contents = (String) node.getOwnerDocument().getUserData(CONTENT_KEY);
567 if (contents == null || contents.length() < endOffset) {
568 return null;
569 }
570
571 boolean inAttribute = false;
572 for (int offset = startOffset; offset <= endOffset; offset++) {
573 char c = contents.charAt(offset);
574 if (c == '>' && !inAttribute) {
575 // Found the end of the element open tag: this is where the
576 // text begins.
577
578 // Skip >
579 offset++;
580 column++;
581
582 String text = node.getNodeValue();
583 int textIndex = 0;
584 int textLength = text.length();
585 int newLine = line;
586 int newColumn = column;
587 if (start != -1) {
588 textLength = Math.min(textLength, start);
589 for (; textIndex < textLength; textIndex++) {
590 char t = text.charAt(textIndex);
591 if (t == '\n') {
592 newLine++;
593 newColumn = 0;
594 } else {
595 newColumn++;
596 }
597 }
598 } else {
599 // Skip text whitespace prefix, if the text node contains
600 // non-whitespace characters
601 for (; textIndex < textLength; textIndex++) {
602 char t = text.charAt(textIndex);
603 if (t == '\n') {
604 newLine++;
605 newColumn = 0;
606 } else if (!Character.isWhitespace(t)) {
607 break;
608 } else {
609 newColumn++;
610 }
611 }
612 }
613 if (textIndex == text.length()) {
614 textIndex = 0; // Whitespace node
615 } else {
616 line = newLine;
617 column = newColumn;
618 }
619
620 Position attributePosition = new Position(line, column, offset + textIndex);
621 // Also set end range for retrieval in getLocation
622 if (end != -1) {
623 attributePosition.setEnd(new Position(line, column, offset + end));
624 } else {
625 attributePosition.setEnd(
626 new Position(line, column, offset + textLength));
627 }
628 return attributePosition;
629 } else if (c == '"') {
630 inAttribute = !inAttribute;
631 } else if (c == '\n') {
632 line++;
633 column = -1; // pre-subtract column added below
634 }
635 column++;
636 }
637
638 return pos;
639 }
640 }
641
642 return (Position) node.getUserData(POS_KEY);
643 }
644
645 /**
646 * SAX parser handler which incrementally builds up a DOM document as we go
647 * along, and updates position information along the way. Position
648 * information is attached to the DOM nodes by setting user data with the
649 * {@link #POS_KEY} key.
650 */
651 private static final class DomBuilder extends DefaultHandler2 {
652 private final String mXml;
653 private final Document mDocument;
654 private Locator mLocator;
655 private int mCurrentLine = 0;
656 private int mCurrentOffset;
657 private int mCurrentColumn;
658 private final List<Element> mStack = new ArrayList<Element>();
659 private final StringBuilder mPendingText = new StringBuilder();
660
661 private DomBuilder(String xml) throws ParserConfigurationException {
662 mXml = xml;
663
664 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
665 factory.setNamespaceAware(true);
666 factory.setValidating(false);
667 DocumentBuilder docBuilder = factory.newDocumentBuilder();
668 mDocument = docBuilder.newDocument();
669 mDocument.setUserData(CONTENT_KEY, xml, null);
670 }
671
672 /** Returns the document parsed by the handler */
673 @NonNull
674 Document getDocument() {
675 return mDocument;
676 }
677
678 @Override
679 public void setDocumentLocator(Locator locator) {
680 this.mLocator = locator;
681 }
682
683 @Override
684 public void startElement(String uri, String localName, String qName,
685 Attributes attributes) throws SAXException {
686 try {
687 flushText();
688 Element element = mDocument.createElementNS(uri, qName);
689 for (int i = 0; i < attributes.getLength(); i++) {
690 if (attributes.getURI(i) != null && !attributes.getURI(i).isEmpty()) {
691 Attr attr = mDocument.createAttributeNS(attributes.getURI(i),
692 attributes.getQName(i));
693 attr.setValue(attributes.getValue(i));
694 element.setAttributeNodeNS(attr);
695 assert attr.getOwnerElement() == element;
696 } else {
697 Attr attr = mDocument.createAttribute(attributes.getQName(i));
698 attr.setValue(attributes.getValue(i));
699 element.setAttributeNode(attr);
700 assert attr.getOwnerElement() == element;
701 }
702 }
703
704 Position pos = getCurrentPosition();
705
706 // The starting position reported to us by SAX is really the END of the
707 // open tag in an element, when all the attributes have been processed.
708 // We have to scan backwards to find the real beginning. We'll do that
709 // by scanning backwards.
710 // -1: Make sure that when we have <foo></foo> we don't consider </foo>
711 // the beginning since pos.offset will typically point to the first character
712 // AFTER the element open tag, which could be a closing tag or a child open
713 // tag
714 element.setUserData(POS_KEY, findOpeningTag(pos), null);
715 mStack.add(element);
716 } catch (Exception t) {
717 throw new SAXException(t);
718 }
719 }
720
721 @Override
722 public void endElement(String uri, String localName, String qName) {
723 flushText();
724 Element element = mStack.remove(mStack.size() - 1);
725
726 Position pos = (Position) element.getUserData(POS_KEY);
727 assert pos != null;
728 pos.setEnd(getCurrentPosition());
729
730 addNodeToParent(element);
731 }
732
733 @Override
734 public void comment(char[] chars, int start, int length) throws SAXException {
735
736 flushText();
737 String comment = new String(chars, start, length);
738 Comment domComment = mDocument.createComment(comment);
739
740 // current position is the closing comment tag.
741 Position currentPosition = getCurrentPosition();
742 Position startPosition = findOpeningTag(currentPosition);
743 startPosition.setEnd(currentPosition);
744
745 domComment.setUserData(POS_KEY, startPosition, null);
746 addNodeToParent(domComment);
747 }
748
749 /**
750 * Adds a node to the current parent element being visited, or to the document if there is
751 * no parent in context.
752 * @param nodeToAdd xml node to add.
753 */
754 private void addNodeToParent(Node nodeToAdd) {
755 if (mStack.isEmpty()){
756 mDocument.appendChild(nodeToAdd);
757 } else {
758 Element parent = mStack.get(mStack.size() - 1);
759 parent.appendChild(nodeToAdd);
760 }
761 }
762
763 /**
764 * Find opening tags from the current position.
765 * < cannot appear in attribute values or anywhere else within
766 * an element open tag, so we know the first occurrence is the real
767 * element start
768 * For comments, it is not legal to put < in a comment, however we are not
769 * validating so we will return an invalid column in that case.
770 * @param startingPosition the position to walk backwards until < is reached.
771 * @return the opening tag position or startPosition if cannot be found.
772 */
773 private Position findOpeningTag(Position startingPosition) {
774 for (int offset = startingPosition.getOffset() - 1; offset >= 0; offset--) {
775 char c = mXml.charAt(offset);
776
777 if (c == '<') {
778 // Adjust line position
779 int line = startingPosition.getLine();
780 for (int i = offset, n = startingPosition.getOffset(); i < n; i++) {
781 if (mXml.charAt(i) == '\n') {
782 line--;
783 }
784 }
785
786 // Compute new column position
787 int column = 0;
788 for (int i = offset - 1; i >= 0; i--, column++) {
789 if (mXml.charAt(i) == '\n') {
790 break;
791 }
792 }
793
794 return new Position(line, column, offset);
795 }
796 }
797 // we did not find it, approximate.
798 return startingPosition;
799 }
800
801 /**
802 * Returns a position holder for the current position. The most
803 * important part of this function is to incrementally compute the
804 * offset as well, by counting forwards until it reaches the new line
805 * number and column position of the XML parser, counting characters as
806 * it goes along.
807 */
808 private Position getCurrentPosition() {
809 int line = mLocator.getLineNumber() - 1;
810 int column = mLocator.getColumnNumber() - 1;
811
812 // Compute offset incrementally now that we have the new line and column
813 // numbers
814 int xmlLength = mXml.length();
815 while (mCurrentLine < line && mCurrentOffset < xmlLength) {
816 char c = mXml.charAt(mCurrentOffset);
817 if (c == '\r' && mCurrentOffset < xmlLength - 1) {
818 if (mXml.charAt(mCurrentOffset + 1) != '\n') {
819 mCurrentLine++;
820 mCurrentColumn = 0;
821 }
822 } else if (c == '\n') {
823 mCurrentLine++;
824 mCurrentColumn = 0;
825 } else {
826 mCurrentColumn++;
827 }
828 mCurrentOffset++;
829 }
830
831 mCurrentOffset += column - mCurrentColumn;
832 if (mCurrentOffset >= xmlLength) {
833 // The parser sometimes passes wrong column numbers at the
834 // end of the file: Ensure that the offset remains valid.
835 mCurrentOffset = xmlLength;
836 }
837 mCurrentColumn = column;
838
839 return new Position(mCurrentLine, mCurrentColumn, mCurrentOffset);
840 }
841
842 @Override
843 public void characters(char c[], int start, int length) throws SAXException {
844 mPendingText.append(c, start, length);
845 }
846
847 private void flushText() {
848 if (mPendingText.length() > 0 && !mStack.isEmpty()) {
849 Element element = mStack.get(mStack.size() - 1);
850 Node textNode = mDocument.createTextNode(mPendingText.toString());
851 element.appendChild(textNode);
852 mPendingText.setLength(0);
853 }
854 }
855 }
856
857 private static class Position {
858 /** The line number (0-based where the first line is line 0) */
859 private final int mLine;
860 private final int mColumn;
861 private final int mOffset;
862 private Position mEnd;
863
864 /**
865 * Creates a new {@link Position}
866 *
867 * @param line the 0-based line number, or -1 if unknown
868 * @param column the 0-based column number, or -1 if unknown
869 * @param offset the offset, or -1 if unknown
870 */
871 public Position(int line, int column, int offset) {
872 this.mLine = line;
873 this.mColumn = column;
874 this.mOffset = offset;
875 }
876
877 public int getLine() {
878 return mLine;
879 }
880
881 public int getOffset() {
882 return mOffset;
883 }
884
885 public int getColumn() {
886 return mColumn;
887 }
888
889 public Position getEnd() {
890 return mEnd;
891 }
892
893 public void setEnd(@NonNull Position end) {
894 mEnd = end;
895 }
896
897 public SourcePosition toSourcePosition() {
898 int endLine = mLine, endColumn = mColumn, endOffset = mOffset;
899
900 if (mEnd != null) {
901 endLine = mEnd.getLine();
902 endColumn = mEnd.getColumn();
903 endOffset = mEnd.getOffset();
904 }
905
906 return new SourcePosition(mLine, mColumn, mOffset, endLine, endColumn, endOffset);
907 }
908 }
909
910 private PositionXmlParser() { }
911 }