Debian Codegraph @

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

raw
1 /*
2 * Copyright (C) 2012 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 package com.android.utils;
17
18 import static com.android.SdkConstants.AMP_ENTITY;
19 import static com.android.SdkConstants.ANDROID_NS_NAME;
20 import static com.android.SdkConstants.ANDROID_URI;
21 import static com.android.SdkConstants.APOS_ENTITY;
22 import static com.android.SdkConstants.APP_PREFIX;
23 import static com.android.SdkConstants.GT_ENTITY;
24 import static com.android.SdkConstants.LT_ENTITY;
25 import static com.android.SdkConstants.QUOT_ENTITY;
26 import static com.android.SdkConstants.XMLNS;
27 import static com.android.SdkConstants.XMLNS_PREFIX;
28 import static com.android.SdkConstants.XMLNS_URI;
29 import static com.google.common.base.Charsets.UTF_16BE;
30 import static com.google.common.base.Charsets.UTF_16LE;
31 import static com.google.common.base.Charsets.UTF_8;
32
33 import com.android.SdkConstants;
34 import com.android.annotations.NonNull;
35 import com.android.annotations.Nullable;
36 import com.android.ide.common.blame.SourceFile;
37 import com.android.ide.common.blame.SourceFilePosition;
38 import com.android.ide.common.blame.SourcePosition;
39 import com.google.common.base.CharMatcher;
40 import com.google.common.io.Files;
41
42 import org.w3c.dom.Attr;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.NamedNodeMap;
46 import org.w3c.dom.Node;
47 import org.w3c.dom.NodeList;
48 import org.xml.sax.InputSource;
49 import org.xml.sax.SAXException;
50
51 import java.io.BufferedInputStream;
52 import java.io.ByteArrayInputStream;
53 import java.io.File;
54 import java.io.FileInputStream;
55 import java.io.IOException;
56 import java.io.InputStream;
57 import java.io.InputStreamReader;
58 import java.io.Reader;
59 import java.io.StringReader;
60 import java.util.HashSet;
61 import java.util.Locale;
62 import java.util.Map;
63
64 import javax.xml.parsers.DocumentBuilder;
65 import javax.xml.parsers.DocumentBuilderFactory;
66 import javax.xml.parsers.ParserConfigurationException;
67 import javax.xml.stream.XMLInputFactory;
68 import javax.xml.stream.XMLStreamException;
69 import javax.xml.stream.XMLStreamReader;
70
71 /** XML Utilities */
72 public class XmlUtils {
73 public static final String XML_COMMENT_BEGIN = "<!--"; //$NON-NLS-1$
74 public static final String XML_COMMENT_END = "-->"; //$NON-NLS-1$
75 public static final String XML_PROLOG =
76 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; //$NON-NLS-1$
77
78 /**
79 * Separator for xml namespace and localname
80 */
81 public static final char NS_SEPARATOR = ':'; //$NON-NLS-1$
82
83 private static final String SOURCE_FILE_USER_DATA_KEY = "sourcefile";
84
85 /**
86 * Returns the namespace prefix matching the requested namespace URI.
87 * If no such declaration is found, returns the default "android" prefix for
88 * the Android URI, and "app" for other URI's. By default the app namespace
89 * will be created. If this is not desirable, call
90 * {@link #lookupNamespacePrefix(Node, String, boolean)} instead.
91 *
92 * @param node The current node. Must not be null.
93 * @param nsUri The namespace URI of which the prefix is to be found,
94 * e.g. {@link SdkConstants#ANDROID_URI}
95 * @return The first prefix declared or the default "android" prefix
96 * (or "app" for non-Android URIs)
97 */
98 @NonNull
99 public static String lookupNamespacePrefix(@NonNull Node node, @NonNull String nsUri) {
100 String defaultPrefix = ANDROID_URI.equals(nsUri) ? ANDROID_NS_NAME : APP_PREFIX;
101 return lookupNamespacePrefix(node, nsUri, defaultPrefix, true /*create*/);
102 }
103
104 /**
105 * Returns the namespace prefix matching the requested namespace URI. If no
106 * such declaration is found, returns the default "android" prefix for the
107 * Android URI, and "app" for other URI's.
108 *
109 * @param node The current node. Must not be null.
110 * @param nsUri The namespace URI of which the prefix is to be found, e.g.
111 * {@link SdkConstants#ANDROID_URI}
112 * @param create whether the namespace declaration should be created, if
113 * necessary
114 * @return The first prefix declared or the default "android" prefix (or
115 * "app" for non-Android URIs)
116 */
117 @NonNull
118 public static String lookupNamespacePrefix(@NonNull Node node, @NonNull String nsUri,
119 boolean create) {
120 String defaultPrefix = ANDROID_URI.equals(nsUri) ? ANDROID_NS_NAME : APP_PREFIX;
121 return lookupNamespacePrefix(node, nsUri, defaultPrefix, create);
122 }
123
124 /**
125 * Returns the namespace prefix matching the requested namespace URI. If no
126 * such declaration is found, returns the default "android" prefix.
127 *
128 * @param node The current node. Must not be null.
129 * @param nsUri The namespace URI of which the prefix is to be found, e.g.
130 * {@link SdkConstants#ANDROID_URI}
131 * @param defaultPrefix The default prefix (root) to use if the namespace is
132 * not found. If null, do not create a new namespace if this URI
133 * is not defined for the document.
134 * @param create whether the namespace declaration should be created, if
135 * necessary
136 * @return The first prefix declared or the provided prefix (possibly with a
137 * number appended to avoid conflicts with existing prefixes.
138 */
139 public static String lookupNamespacePrefix(
140 @Nullable Node node, @Nullable String nsUri, @Nullable String defaultPrefix,
141 boolean create) {
142 // Note: Node.lookupPrefix is not implemented in wst/xml/core NodeImpl.java
143 // The following code emulates this simple call:
144 // String prefix = node.lookupPrefix(NS_RESOURCES);
145
146 // if the requested URI is null, it denotes an attribute with no namespace.
147 if (nsUri == null) {
148 return null;
149 }
150
151 // per XML specification, the "xmlns" URI is reserved
152 if (XMLNS_URI.equals(nsUri)) {
153 return XMLNS;
154 }
155
156 HashSet<String> visited = new HashSet<String>();
157 Document doc = node == null ? null : node.getOwnerDocument();
158
159 // Ask the document about it. This method may not be implemented by the Document.
160 String nsPrefix = null;
161 try {
162 nsPrefix = doc != null ? doc.lookupPrefix(nsUri) : null;
163 if (nsPrefix != null) {
164 return nsPrefix;
165 }
166 } catch (Throwable t) {
167 // ignore
168 }
169
170 // If that failed, try to look it up manually.
171 // This also gathers prefixed in use in the case we want to generate a new one below.
172 for (; node != null && node.getNodeType() == Node.ELEMENT_NODE;
173 node = node.getParentNode()) {
174 NamedNodeMap attrs = node.getAttributes();
175 for (int n = attrs.getLength() - 1; n >= 0; --n) {
176 Node attr = attrs.item(n);
177 if (XMLNS.equals(attr.getPrefix())) {
178 String uri = attr.getNodeValue();
179 nsPrefix = attr.getLocalName();
180 // Is this the URI we are looking for? If yes, we found its prefix.
181 if (nsUri.equals(uri)) {
182 return nsPrefix;
183 }
184 visited.add(nsPrefix);
185 }
186 }
187 }
188
189 // Failed the find a prefix. Generate a new sensible default prefix, unless
190 // defaultPrefix was null in which case the caller does not want the document
191 // modified.
192 if (defaultPrefix == null) {
193 return null;
194 }
195
196 //
197 // We need to make sure the prefix is not one that was declared in the scope
198 // visited above. Pick a unique prefix from the provided default prefix.
199 String prefix = defaultPrefix;
200 String base = prefix;
201 for (int i = 1; visited.contains(prefix); i++) {
202 prefix = base + Integer.toString(i);
203 }
204 // Also create and define this prefix/URI in the XML document as an attribute in the
205 // first element of the document.
206 if (doc != null) {
207 node = doc.getFirstChild();
208 while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
209 node = node.getNextSibling();
210 }
211 if (node != null && create) {
212 // This doesn't work:
213 //Attr attr = doc.createAttributeNS(XMLNS_URI, prefix);
214 //attr.setPrefix(XMLNS);
215 //
216 // Xerces throws
217 //org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create or
218 // change an object in a way which is incorrect with regard to namespaces.
219 //
220 // Instead pass in the concatenated prefix. (This is covered by
221 // the UiElementNodeTest#testCreateNameSpace() test.)
222 Attr attr = doc.createAttributeNS(XMLNS_URI, XMLNS_PREFIX + prefix);
223 attr.setValue(nsUri);
224 node.getAttributes().setNamedItemNS(attr);
225 }
226 }
227
228 return prefix;
229 }
230
231 /**
232 * Converts the given attribute value to an XML-attribute-safe value, meaning that
233 * single and double quotes are replaced with their corresponding XML entities.
234 *
235 * @param attrValue the value to be escaped
236 * @return the escaped value
237 */
238 @NonNull
239 public static String toXmlAttributeValue(@NonNull String attrValue) {
240 for (int i = 0, n = attrValue.length(); i < n; i++) {
241 char c = attrValue.charAt(i);
242 if (c == '"' || c == '\'' || c == '<' || c == '&') {
243 StringBuilder sb = new StringBuilder(2 * attrValue.length());
244 appendXmlAttributeValue(sb, attrValue);
245 return sb.toString();
246 }
247 }
248
249 return attrValue;
250 }
251
252 /**
253 * Converts the given XML-attribute-safe value to a java string
254 *
255 * @param escapedAttrValue the escaped value
256 * @return the unescaped value
257 */
258 @NonNull
259 public static String fromXmlAttributeValue(@NonNull String escapedAttrValue) {
260 String workingString = escapedAttrValue.replace(QUOT_ENTITY, "\"");
261 workingString = workingString.replace(LT_ENTITY, "<");
262 workingString = workingString.replace(APOS_ENTITY, "'");
263 workingString = workingString.replace(AMP_ENTITY, "&");
264 workingString = workingString.replace(GT_ENTITY, ">");
265
266 return workingString;
267 }
268
269 /**
270 * Converts the given attribute value to an XML-text-safe value, meaning that
271 * less than and ampersand characters are escaped.
272 *
273 * @param textValue the text value to be escaped
274 * @return the escaped value
275 */
276 @NonNull
277 public static String toXmlTextValue(@NonNull String textValue) {
278 for (int i = 0, n = textValue.length(); i < n; i++) {
279 char c = textValue.charAt(i);
280 if (c == '<' || c == '&') {
281 StringBuilder sb = new StringBuilder(2 * textValue.length());
282 appendXmlTextValue(sb, textValue);
283 return sb.toString();
284 }
285 }
286
287 return textValue;
288 }
289
290 /**
291 * Appends text to the given {@link StringBuilder} and escapes it as required for a
292 * DOM attribute node.
293 *
294 * @param sb the string builder
295 * @param attrValue the attribute value to be appended and escaped
296 */
297 public static void appendXmlAttributeValue(@NonNull StringBuilder sb,
298 @NonNull String attrValue) {
299 int n = attrValue.length();
300 // &, ", ' and < are illegal in attributes; see http://www.w3.org/TR/REC-xml/#NT-AttValue
301 // (' legal in a " string and " is legal in a ' string but here we'll stay on the safe
302 // side)
303 for (int i = 0; i < n; i++) {
304 char c = attrValue.charAt(i);
305 if (c == '"') {
306 sb.append(QUOT_ENTITY);
307 } else if (c == '<') {
308 sb.append(LT_ENTITY);
309 } else if (c == '\'') {
310 sb.append(APOS_ENTITY);
311 } else if (c == '&') {
312 sb.append(AMP_ENTITY);
313 } else {
314 sb.append(c);
315 }
316 }
317 }
318
319 /**
320 * Appends text to the given {@link StringBuilder} and escapes it as required for a
321 * DOM text node.
322 *
323 * @param sb the string builder
324 * @param textValue the text value to be appended and escaped
325 */
326 public static void appendXmlTextValue(@NonNull StringBuilder sb, @NonNull String textValue) {
327 appendXmlTextValue(sb, textValue, 0, textValue.length());
328 }
329
330 /**
331 * Appends text to the given {@link StringBuilder} and escapes it as required for a
332 * DOM text node.
333 *
334 * @param sb the string builder
335 * @param start the starting offset in the text string
336 * @param end the ending offset in the text string
337 * @param textValue the text value to be appended and escaped
338 */
339 public static void appendXmlTextValue(@NonNull StringBuilder sb, @NonNull String textValue, int start, int end) {
340 for (int i = start, n = Math.min(textValue.length(), end); i < n; i++) {
341 char c = textValue.charAt(i);
342 if (c == '<') {
343 sb.append(LT_ENTITY);
344 } else if (c == '&') {
345 sb.append(AMP_ENTITY);
346 } else {
347 sb.append(c);
348 }
349 }
350 }
351
352 /**
353 * Returns true if the given node has one or more element children
354 *
355 * @param node the node to test for element children
356 * @return true if the node has one or more element children
357 */
358 public static boolean hasElementChildren(@NonNull Node node) {
359 NodeList children = node.getChildNodes();
360 for (int i = 0, n = children.getLength(); i < n; i++) {
361 if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
362 return true;
363 }
364 }
365
366 return false;
367 }
368
369 /**
370 * Returns a character reader for the given file, which must be a UTF encoded file.
371 * <p>
372 * The reader does not need to be closed by the caller (because the file is read in
373 * full in one shot and the resulting array is then wrapped in a byte array input stream,
374 * which does not need to be closed.)
375 */
376 public static Reader getUtfReader(@NonNull File file) throws IOException {
377 byte[] bytes = Files.toByteArray(file);
378 int length = bytes.length;
379 if (length == 0) {
380 return new StringReader("");
381 }
382
383 switch (bytes[0]) {
384 case (byte)0xEF: {
385 if (length >= 3
386 && bytes[1] == (byte)0xBB
387 && bytes[2] == (byte)0xBF) {
388 // UTF-8 BOM: EF BB BF: Skip it
389 return new InputStreamReader(new ByteArrayInputStream(bytes, 3, length - 3),
390 UTF_8);
391 }
392 break;
393 }
394 case (byte)0xFE: {
395 if (length >= 2
396 && bytes[1] == (byte)0xFF) {
397 // UTF-16 Big Endian BOM: FE FF
398 return new InputStreamReader(new ByteArrayInputStream(bytes, 2, length - 2),
399 UTF_16BE);
400 }
401 break;
402 }
403 case (byte)0xFF: {
404 if (length >= 2
405 && bytes[1] == (byte)0xFE) {
406 if (length >= 4
407 && bytes[2] == (byte)0x00
408 && bytes[3] == (byte)0x00) {
409 // UTF-32 Little Endian BOM: FF FE 00 00
410 return new InputStreamReader(new ByteArrayInputStream(bytes, 4,
411 length - 4), "UTF-32LE");
412 }
413
414 // UTF-16 Little Endian BOM: FF FE
415 return new InputStreamReader(new ByteArrayInputStream(bytes, 2, length - 2),
416 UTF_16LE);
417 }
418 break;
419 }
420 case (byte)0x00: {
421 if (length >= 4
422 && bytes[0] == (byte)0x00
423 && bytes[1] == (byte)0x00
424 && bytes[2] == (byte)0xFE
425 && bytes[3] == (byte)0xFF) {
426 // UTF-32 Big Endian BOM: 00 00 FE FF
427 return new InputStreamReader(new ByteArrayInputStream(bytes, 4, length - 4),
428 "UTF-32BE");
429 }
430 break;
431 }
432 }
433
434 // No byte order mark: Assume UTF-8 (where the BOM is optional).
435 return new InputStreamReader(new ByteArrayInputStream(bytes), UTF_8);
436 }
437
438 /**
439 * Parses the given XML string as a DOM document, using the JDK parser. The parser does not
440 * validate, and is optionally namespace aware.
441 *
442 * @param xml the XML content to be parsed (must be well formed)
443 * @param namespaceAware whether the parser is namespace aware
444 * @return the DOM document
445 */
446 @NonNull
447 public static Document parseDocument(@NonNull String xml, boolean namespaceAware)
448 throws ParserConfigurationException, IOException, SAXException {
449 xml = stripBom(xml);
450 return parseDocument(new StringReader(xml), namespaceAware);
451 }
452
453 /**
454 * Parses the given {@link Reader} as a DOM document, using the JDK parser. The parser does not
455 * validate, and is optionally namespace aware.
456 *
457 * @param xml a reader for the XML content to be parsed (must be well formed)
458 * @param namespaceAware whether the parser is namespace aware
459 * @return the DOM document
460 */
461 @NonNull
462 public static Document parseDocument(@NonNull Reader xml, boolean namespaceAware)
463 throws ParserConfigurationException, IOException, SAXException {
464 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
465 InputSource is = new InputSource(xml);
466 factory.setNamespaceAware(namespaceAware);
467 factory.setValidating(false);
468 DocumentBuilder builder = factory.newDocumentBuilder();
469 return builder.parse(is);
470 }
471
472 /**
473 * Parses the given UTF file as a DOM document, using the JDK parser. The parser does not
474 * validate, and is optionally namespace aware.
475 *
476 * @param file the UTF encoded file to parse
477 * @param namespaceAware whether the parser is namespace aware
478 * @return the DOM document
479 */
480 @NonNull
481 public static Document parseUtfXmlFile(@NonNull File file, boolean namespaceAware)
482 throws ParserConfigurationException, IOException, SAXException {
483 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
484 Reader reader = getUtfReader(file);
485 try {
486 InputSource is = new InputSource(reader);
487 factory.setNamespaceAware(namespaceAware);
488 factory.setValidating(false);
489 DocumentBuilder builder = factory.newDocumentBuilder();
490 return builder.parse(is);
491 } finally {
492 reader.close();
493 }
494 }
495
496 /** Strips out a leading UTF byte order mark, if present */
497 @NonNull
498 public static String stripBom(@NonNull String xml) {
499 if (!xml.isEmpty() && xml.charAt(0) == '\uFEFF') {
500 return xml.substring(1);
501 }
502 return xml;
503 }
504
505 /**
506 * Parses the given XML string as a DOM document, using the JDK parser. The parser does not
507 * validate, and is optionally namespace aware. Any parsing errors are silently ignored.
508 *
509 * @param xml the XML content to be parsed (must be well formed)
510 * @param namespaceAware whether the parser is namespace aware
511 * @return the DOM document, or null
512 */
513 @Nullable
514 public static Document parseDocumentSilently(@NonNull String xml, boolean namespaceAware) {
515 try {
516 return parseDocument(xml, namespaceAware);
517 } catch (Exception e) {
518 // pass
519 // This method is deliberately silent; will return null
520 }
521
522 return null;
523 }
524
525 /**
526 * Dump an XML tree to string. This does not perform any pretty printing.
527 * To perform pretty printing, use {@code XmlPrettyPrinter.prettyPrint(node)} in
528 * {@code sdk-common}.
529 */
530 public static String toXml(@NonNull Node node) {
531 return toXml(node, null);
532 }
533 public static String toXml(
534 @NonNull Node node,
535 @Nullable Map<SourcePosition, SourceFilePosition> blame) {
536 PositionAwareStringBuilder sb = new PositionAwareStringBuilder(1000);
537 append(sb, node, blame);
538 return sb.toString();
539 }
540
541 /** Dump node to string without indentation adjustments */
542 private static void append(
543 @NonNull PositionAwareStringBuilder sb,
544 @NonNull Node node,
545 @Nullable Map<SourcePosition, SourceFilePosition> blame) {
546 short nodeType = node.getNodeType();
547 int currentLine = sb.line;
548 int currentColumn = sb.column;
549 int currentOffset = sb.getOffset();
550 switch (nodeType) {
551 case Node.DOCUMENT_NODE:
552 case Node.DOCUMENT_FRAGMENT_NODE: {
553 sb.append(XML_PROLOG);
554 NodeList children = node.getChildNodes();
555 for (int i = 0, n = children.getLength(); i < n; i++) {
556 append(sb, children.item(i), blame);
557 }
558 break;
559 }
560 case Node.COMMENT_NODE:
561 sb.append(XML_COMMENT_BEGIN);
562 sb.append(node.getNodeValue());
563 sb.append(XML_COMMENT_END);
564 break;
565 case Node.TEXT_NODE: {
566 sb.append(toXmlTextValue(node.getNodeValue()));
567 break;
568 }
569 case Node.CDATA_SECTION_NODE: {
570 sb.append("<![CDATA["); //$NON-NLS-1$
571 sb.append(node.getNodeValue());
572 sb.append("]]>"); //$NON-NLS-1$
573 break;
574 }
575 case Node.ELEMENT_NODE: {
576 sb.append('<');
577 Element element = (Element) node;
578 sb.append(element.getTagName());
579
580 NamedNodeMap attributes = element.getAttributes();
581 NodeList children = element.getChildNodes();
582 int childCount = children.getLength();
583 int attributeCount = attributes.getLength();
584
585 if (attributeCount > 0) {
586 for (int i = 0; i < attributeCount; i++) {
587 Node attribute = attributes.item(i);
588 sb.append(' ');
589 sb.append(attribute.getNodeName());
590 sb.append('=').append('"');
591 sb.append(toXmlAttributeValue(attribute.getNodeValue()));
592 sb.append('"');
593 }
594 }
595
596 if (childCount == 0) {
597 sb.append('/');
598 }
599 sb.append('>');
600 if (childCount > 0) {
601 for (int i = 0; i < childCount; i++) {
602 Node child = children.item(i);
603 append(sb, child, blame);
604 }
605 sb.append('<').append('/');
606 sb.append(element.getTagName());
607 sb.append('>');
608 }
609
610 if (blame != null) {
611 SourceFilePosition position = getSourceFilePosition(node);
612 if (!position.equals(SourceFilePosition.UNKNOWN)) {
613 blame.put(
614 new SourcePosition(
615 currentLine, currentColumn, currentOffset,
616 sb.line, sb.column, sb.getOffset()),
617 position);
618 }
619 }
620 break;
621 }
622
623 default:
624 throw new UnsupportedOperationException(
625 "Unsupported node type " + nodeType + ": not yet implemented");
626 }
627 }
628
629 /**
630 * Wraps a StringBuilder, but keeps track of the line and column of the end of the string.
631 *
632 * It implements append(String) and append(char) which as well as delegating to the underlying
633 * StringBuilder also keep track of any new lines, and set the line and column fields.
634 * The StringBuilder itself keeps track of the actual character offset.
635 */
636 private static class PositionAwareStringBuilder {
637 @SuppressWarnings("StringBufferField")
638 private final StringBuilder sb;
639 int line = 0;
640 int column = 0;
641
642 public PositionAwareStringBuilder(int size) {
643 sb = new StringBuilder(size);
644 }
645
646 public PositionAwareStringBuilder append(String text) {
647 sb.append(text);
648 // we find the last, as it might be useful later.
649 int lastNewLineIndex = text.lastIndexOf('\n');
650 if (lastNewLineIndex == -1) {
651 // If it does not contain a new line, we just increase the column number.
652 column += text.length();
653 } else {
654 // The string could contain multiple new lines.
655 line += CharMatcher.is('\n').countIn(text);
656 // But for column we only care about the number of characters after the last one.
657 column = text.length() - lastNewLineIndex - 1;
658 }
659 return this;
660 }
661
662 public PositionAwareStringBuilder append(char character) {
663 sb.append(character);
664 if (character == '\n') {
665 line += 1;
666 column = 0;
667 } else {
668 column++;
669 }
670 return this;
671 }
672
673 public int getOffset() {
674 return sb.length();
675 }
676
677 @Override
678 public String toString() {
679 return sb.toString();
680 }
681 }
682
683 public static void attachSourceFile(Node node, SourceFile sourceFile) {
684 node.setUserData(SOURCE_FILE_USER_DATA_KEY, sourceFile, null);
685 }
686
687 public static SourceFilePosition getSourceFilePosition(Node node) {
688 SourceFile sourceFile = (SourceFile) node.getUserData(SOURCE_FILE_USER_DATA_KEY);
689 if (sourceFile == null) {
690 sourceFile = SourceFile.UNKNOWN;
691 }
692 return new SourceFilePosition(sourceFile, PositionXmlParser.getPosition(node));
693 }
694
695 /**
696 * Format the given floating value into an XML string, omitting decimals if
697 * 0
698 *
699 * @param value the value to be formatted
700 * @return the corresponding XML string for the value
701 */
702 public static String formatFloatAttribute(double value) {
703 if (value != (int) value) {
704 // Run String.format without a locale, because we don't want locale-specific
705 // conversions here like separating the decimal part with a comma instead of a dot!
706 return String.format((Locale) null, "%.2f", value); //$NON-NLS-1$
707 } else {
708 return Integer.toString((int) value);
709 }
710 }
711
712 /**
713 * Returns the name of the root element tag stored in the given file, or null if it can't be
714 * determined.
715 */
716 @Nullable
717 public static String getRootTagName(@NonNull File xmlFile) {
718 try (InputStream stream = new BufferedInputStream(new FileInputStream(xmlFile))) {
719 XMLInputFactory factory = XMLInputFactory.newFactory();
720 XMLStreamReader xmlStreamReader =
721 factory.createXMLStreamReader(stream);
722
723 while (xmlStreamReader.hasNext()) {
724 int event = xmlStreamReader.next();
725 if (event == XMLStreamReader.START_ELEMENT) {
726 return xmlStreamReader.getLocalName();
727 }
728 }
729 } catch (XMLStreamException | IOException ignored) {
730 // Ignored.
731 }
732
733 return null;
734 }
735 }