Debian Codegraph @

core/java/com/android/internal/util/BinaryXmlPullParser.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2020 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.internal.util;
18
19 import static com.android.internal.util.BinaryXmlSerializer.ATTRIBUTE;
20 import static com.android.internal.util.BinaryXmlSerializer.PROTOCOL_MAGIC_VERSION_0;
21 import static com.android.internal.util.BinaryXmlSerializer.TYPE_BOOLEAN_FALSE;
22 import static com.android.internal.util.BinaryXmlSerializer.TYPE_BOOLEAN_TRUE;
23 import static com.android.internal.util.BinaryXmlSerializer.TYPE_BYTES_BASE64;
24 import static com.android.internal.util.BinaryXmlSerializer.TYPE_BYTES_HEX;
25 import static com.android.internal.util.BinaryXmlSerializer.TYPE_DOUBLE;
26 import static com.android.internal.util.BinaryXmlSerializer.TYPE_FLOAT;
27 import static com.android.internal.util.BinaryXmlSerializer.TYPE_INT;
28 import static com.android.internal.util.BinaryXmlSerializer.TYPE_INT_HEX;
29 import static com.android.internal.util.BinaryXmlSerializer.TYPE_LONG;
30 import static com.android.internal.util.BinaryXmlSerializer.TYPE_LONG_HEX;
31 import static com.android.internal.util.BinaryXmlSerializer.TYPE_NULL;
32 import static com.android.internal.util.BinaryXmlSerializer.TYPE_STRING;
33 import static com.android.internal.util.BinaryXmlSerializer.TYPE_STRING_INTERNED;
34
35 import android.annotation.NonNull;
36 import android.annotation.Nullable;
37 import android.text.TextUtils;
38 import android.util.Base64;
39 import android.util.TypedXmlPullParser;
40 import android.util.TypedXmlSerializer;
41
42 import org.xmlpull.v1.XmlPullParser;
43 import org.xmlpull.v1.XmlPullParserException;
44
45 import java.io.EOFException;
46 import java.io.IOException;
47 import java.io.InputStream;
48 import java.io.Reader;
49 import java.nio.charset.StandardCharsets;
50 import java.util.Arrays;
51 import java.util.Objects;
52
53 /**
54 * Parser that reads XML documents using a custom binary wire protocol which
55 * benchmarking has shown to be 8.5x faster than {@link Xml.newFastPullParser()}
56 * for a typical {@code packages.xml}.
57 * <p>
58 * The high-level design of the wire protocol is to directly serialize the event
59 * stream, while efficiently and compactly writing strongly-typed primitives
60 * delivered through the {@link TypedXmlSerializer} interface.
61 * <p>
62 * Each serialized event is a single byte where the lower half is a normal
63 * {@link XmlPullParser} token and the upper half is an optional data type
64 * signal, such as {@link #TYPE_INT}.
65 * <p>
66 * This parser has some specific limitations:
67 * <ul>
68 * <li>Only the UTF-8 encoding is supported.
69 * <li>Variable length values, such as {@code byte[]} or {@link String}, are
70 * limited to 65,535 bytes in length. Note that {@link String} values are stored
71 * as UTF-8 on the wire.
72 * <li>Namespaces, prefixes, properties, and options are unsupported.
73 * </ul>
74 */
75 public final class BinaryXmlPullParser implements TypedXmlPullParser {
76 private FastDataInput mIn;
77
78 private int mCurrentToken = START_DOCUMENT;
79 private int mCurrentDepth = 0;
80 private String mCurrentName;
81 private String mCurrentText;
82
83 /**
84 * Pool of attributes parsed for the currently tag. All interactions should
85 * be done via {@link #obtainAttribute()}, {@link #findAttribute(String)},
86 * and {@link #resetAttributes()}.
87 */
88 private int mAttributeCount = 0;
89 private Attribute[] mAttributes;
90
91 @Override
92 public void setInput(InputStream is, String encoding) throws XmlPullParserException {
93 if (encoding != null && !StandardCharsets.UTF_8.name().equalsIgnoreCase(encoding)) {
94 throw new UnsupportedOperationException();
95 }
96
97 if (mIn != null) {
98 mIn.release();
99 mIn = null;
100 }
101
102 mIn = FastDataInput.obtainUsing4ByteSequences(is);
103
104 mCurrentToken = START_DOCUMENT;
105 mCurrentDepth = 0;
106 mCurrentName = null;
107 mCurrentText = null;
108
109 mAttributeCount = 0;
110 mAttributes = new Attribute[8];
111 for (int i = 0; i < mAttributes.length; i++) {
112 mAttributes[i] = new Attribute();
113 }
114
115 try {
116 final byte[] magic = new byte[4];
117 mIn.readFully(magic);
118 if (!Arrays.equals(magic, PROTOCOL_MAGIC_VERSION_0)) {
119 throw new IOException("Unexpected magic " + bytesToHexString(magic));
120 }
121
122 // We're willing to immediately consume a START_DOCUMENT if present,
123 // but we're okay if it's missing
124 if (peekNextExternalToken() == START_DOCUMENT) {
125 consumeToken();
126 }
127 } catch (IOException e) {
128 throw new XmlPullParserException(e.toString());
129 }
130 }
131
132 @Override
133 public void setInput(Reader in) throws XmlPullParserException {
134 throw new UnsupportedOperationException();
135 }
136
137 @Override
138 public int next() throws XmlPullParserException, IOException {
139 while (true) {
140 final int token = nextToken();
141 switch (token) {
142 case START_TAG:
143 case END_TAG:
144 case END_DOCUMENT:
145 return token;
146 case TEXT:
147 consumeAdditionalText();
148 // Per interface docs, empty text regions are skipped
149 if (mCurrentText == null || mCurrentText.length() == 0) {
150 continue;
151 } else {
152 return TEXT;
153 }
154 }
155 }
156 }
157
158 @Override
159 public int nextToken() throws XmlPullParserException, IOException {
160 if (mCurrentToken == XmlPullParser.END_TAG) {
161 mCurrentDepth--;
162 }
163
164 int token;
165 try {
166 token = peekNextExternalToken();
167 consumeToken();
168 } catch (EOFException e) {
169 token = END_DOCUMENT;
170 }
171 switch (token) {
172 case XmlPullParser.START_TAG:
173 // We need to peek forward to find the next external token so
174 // that we parse all pending INTERNAL_ATTRIBUTE tokens
175 peekNextExternalToken();
176 mCurrentDepth++;
177 break;
178 }
179 mCurrentToken = token;
180 return token;
181 }
182
183 /**
184 * Peek at the next "external" token without consuming it.
185 * <p>
186 * External tokens, such as {@link #START_TAG}, are expected by typical
187 * {@link XmlPullParser} clients. In contrast, internal tokens, such as
188 * {@link #ATTRIBUTE}, are not expected by typical clients.
189 * <p>
190 * This method consumes any internal events until it reaches the next
191 * external event.
192 */
193 private int peekNextExternalToken() throws IOException, XmlPullParserException {
194 while (true) {
195 final int token = peekNextToken();
196 switch (token) {
197 case ATTRIBUTE:
198 consumeToken();
199 continue;
200 default:
201 return token;
202 }
203 }
204 }
205
206 /**
207 * Peek at the next token in the underlying stream without consuming it.
208 */
209 private int peekNextToken() throws IOException {
210 return mIn.peekByte() & 0x0f;
211 }
212
213 /**
214 * Parse and consume the next token in the underlying stream.
215 */
216 private void consumeToken() throws IOException, XmlPullParserException {
217 final int event = mIn.readByte();
218 final int token = event & 0x0f;
219 final int type = event & 0xf0;
220 switch (token) {
221 case ATTRIBUTE: {
222 final Attribute attr = obtainAttribute();
223 attr.name = mIn.readInternedUTF();
224 attr.type = type;
225 switch (type) {
226 case TYPE_NULL:
227 case TYPE_BOOLEAN_TRUE:
228 case TYPE_BOOLEAN_FALSE:
229 // Nothing extra to fill in
230 break;
231 case TYPE_STRING:
232 attr.valueString = mIn.readUTF();
233 break;
234 case TYPE_STRING_INTERNED:
235 attr.valueString = mIn.readInternedUTF();
236 break;
237 case TYPE_BYTES_HEX:
238 case TYPE_BYTES_BASE64:
239 final int len = mIn.readUnsignedShort();
240 final byte[] res = new byte[len];
241 mIn.readFully(res);
242 attr.valueBytes = res;
243 break;
244 case TYPE_INT:
245 case TYPE_INT_HEX:
246 attr.valueInt = mIn.readInt();
247 break;
248 case TYPE_LONG:
249 case TYPE_LONG_HEX:
250 attr.valueLong = mIn.readLong();
251 break;
252 case TYPE_FLOAT:
253 attr.valueFloat = mIn.readFloat();
254 break;
255 case TYPE_DOUBLE:
256 attr.valueDouble = mIn.readDouble();
257 break;
258 default:
259 throw new IOException("Unexpected data type " + type);
260 }
261 break;
262 }
263 case XmlPullParser.START_DOCUMENT: {
264 mCurrentName = null;
265 mCurrentText = null;
266 if (mAttributeCount > 0) resetAttributes();
267 break;
268 }
269 case XmlPullParser.END_DOCUMENT: {
270 mCurrentName = null;
271 mCurrentText = null;
272 if (mAttributeCount > 0) resetAttributes();
273 break;
274 }
275 case XmlPullParser.START_TAG: {
276 mCurrentName = mIn.readInternedUTF();
277 mCurrentText = null;
278 if (mAttributeCount > 0) resetAttributes();
279 break;
280 }
281 case XmlPullParser.END_TAG: {
282 mCurrentName = mIn.readInternedUTF();
283 mCurrentText = null;
284 if (mAttributeCount > 0) resetAttributes();
285 break;
286 }
287 case XmlPullParser.TEXT:
288 case XmlPullParser.CDSECT:
289 case XmlPullParser.PROCESSING_INSTRUCTION:
290 case XmlPullParser.COMMENT:
291 case XmlPullParser.DOCDECL:
292 case XmlPullParser.IGNORABLE_WHITESPACE: {
293 mCurrentName = null;
294 mCurrentText = mIn.readUTF();
295 if (mAttributeCount > 0) resetAttributes();
296 break;
297 }
298 case XmlPullParser.ENTITY_REF: {
299 mCurrentName = mIn.readUTF();
300 mCurrentText = resolveEntity(mCurrentName);
301 if (mAttributeCount > 0) resetAttributes();
302 break;
303 }
304 default: {
305 throw new IOException("Unknown token " + token + " with type " + type);
306 }
307 }
308 }
309
310 /**
311 * When the current tag is {@link #TEXT}, consume all subsequent "text"
312 * events, as described by {@link #next}. When finished, the current event
313 * will still be {@link #TEXT}.
314 */
315 private void consumeAdditionalText() throws IOException, XmlPullParserException {
316 String combinedText = mCurrentText;
317 while (true) {
318 final int token = peekNextExternalToken();
319 switch (token) {
320 case COMMENT:
321 case PROCESSING_INSTRUCTION:
322 // Quietly consumed
323 consumeToken();
324 break;
325 case TEXT:
326 case CDSECT:
327 case ENTITY_REF:
328 // Additional text regions collected
329 consumeToken();
330 combinedText += mCurrentText;
331 break;
332 default:
333 // Next token is something non-text, so wrap things up
334 mCurrentToken = TEXT;
335 mCurrentName = null;
336 mCurrentText = combinedText;
337 return;
338 }
339 }
340 }
341
342 static @NonNull String resolveEntity(@NonNull String entity)
343 throws XmlPullParserException {
344 switch (entity) {
345 case "lt": return "<";
346 case "gt": return ">";
347 case "amp": return "&";
348 case "apos": return "'";
349 case "quot": return "\"";
350 }
351 if (entity.length() > 1 && entity.charAt(0) == '#') {
352 final char c = (char) Integer.parseInt(entity.substring(1));
353 return new String(new char[] { c });
354 }
355 throw new XmlPullParserException("Unknown entity " + entity);
356 }
357
358 @Override
359 public void require(int type, String namespace, String name)
360 throws XmlPullParserException, IOException {
361 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
362 if (mCurrentToken != type || !Objects.equals(mCurrentName, name)) {
363 throw new XmlPullParserException(getPositionDescription());
364 }
365 }
366
367 @Override
368 public String nextText() throws XmlPullParserException, IOException {
369 if (getEventType() != START_TAG) {
370 throw new XmlPullParserException(getPositionDescription());
371 }
372 int eventType = next();
373 if (eventType == TEXT) {
374 String result = getText();
375 eventType = next();
376 if (eventType != END_TAG) {
377 throw new XmlPullParserException(getPositionDescription());
378 }
379 return result;
380 } else if (eventType == END_TAG) {
381 return "";
382 } else {
383 throw new XmlPullParserException(getPositionDescription());
384 }
385 }
386
387 @Override
388 public int nextTag() throws XmlPullParserException, IOException {
389 int eventType = next();
390 if (eventType == TEXT && isWhitespace()) {
391 eventType = next();
392 }
393 if (eventType != START_TAG && eventType != END_TAG) {
394 throw new XmlPullParserException(getPositionDescription());
395 }
396 return eventType;
397 }
398
399 /**
400 * Allocate and return a new {@link Attribute} associated with the tag being
401 * currently processed. This will automatically grow the internal pool as
402 * needed.
403 */
404 private @NonNull Attribute obtainAttribute() {
405 if (mAttributeCount == mAttributes.length) {
406 final int before = mAttributes.length;
407 final int after = before + (before >> 1);
408 mAttributes = Arrays.copyOf(mAttributes, after);
409 for (int i = before; i < after; i++) {
410 mAttributes[i] = new Attribute();
411 }
412 }
413 return mAttributes[mAttributeCount++];
414 }
415
416 /**
417 * Clear any {@link Attribute} instances that have been allocated by
418 * {@link #obtainAttribute()}, returning them into the pool for recycling.
419 */
420 private void resetAttributes() {
421 for (int i = 0; i < mAttributeCount; i++) {
422 mAttributes[i].reset();
423 }
424 mAttributeCount = 0;
425 }
426
427 @Override
428 public int getAttributeIndex(String namespace, String name) {
429 if (namespace != null && !namespace.isEmpty()) throw illegalNamespace();
430 for (int i = 0; i < mAttributeCount; i++) {
431 if (Objects.equals(mAttributes[i].name, name)) {
432 return i;
433 }
434 }
435 return -1;
436 }
437
438 @Override
439 public String getAttributeValue(String namespace, String name) {
440 final int index = getAttributeIndex(namespace, name);
441 if (index != -1) {
442 return mAttributes[index].getValueString();
443 } else {
444 return null;
445 }
446 }
447
448 @Override
449 public String getAttributeValue(int index) {
450 return mAttributes[index].getValueString();
451 }
452
453 @Override
454 public byte[] getAttributeBytesHex(int index) throws XmlPullParserException {
455 return mAttributes[index].getValueBytesHex();
456 }
457
458 @Override
459 public byte[] getAttributeBytesBase64(int index) throws XmlPullParserException {
460 return mAttributes[index].getValueBytesBase64();
461 }
462
463 @Override
464 public int getAttributeInt(int index) throws XmlPullParserException {
465 return mAttributes[index].getValueInt();
466 }
467
468 @Override
469 public int getAttributeIntHex(int index) throws XmlPullParserException {
470 return mAttributes[index].getValueIntHex();
471 }
472
473 @Override
474 public long getAttributeLong(int index) throws XmlPullParserException {
475 return mAttributes[index].getValueLong();
476 }
477
478 @Override
479 public long getAttributeLongHex(int index) throws XmlPullParserException {
480 return mAttributes[index].getValueLongHex();
481 }
482
483 @Override
484 public float getAttributeFloat(int index) throws XmlPullParserException {
485 return mAttributes[index].getValueFloat();
486 }
487
488 @Override
489 public double getAttributeDouble(int index) throws XmlPullParserException {
490 return mAttributes[index].getValueDouble();
491 }
492
493 @Override
494 public boolean getAttributeBoolean(int index) throws XmlPullParserException {
495 return mAttributes[index].getValueBoolean();
496 }
497
498 @Override
499 public String getText() {
500 return mCurrentText;
501 }
502
503 @Override
504 public char[] getTextCharacters(int[] holderForStartAndLength) {
505 final char[] chars = mCurrentText.toCharArray();
506 holderForStartAndLength[0] = 0;
507 holderForStartAndLength[1] = chars.length;
508 return chars;
509 }
510
511 @Override
512 public String getInputEncoding() {
513 return StandardCharsets.UTF_8.name();
514 }
515
516 @Override
517 public int getDepth() {
518 return mCurrentDepth;
519 }
520
521 @Override
522 public String getPositionDescription() {
523 // Not very helpful, but it's the best information we have
524 return "Token " + mCurrentToken + " at depth " + mCurrentDepth;
525 }
526
527 @Override
528 public int getLineNumber() {
529 return -1;
530 }
531
532 @Override
533 public int getColumnNumber() {
534 return -1;
535 }
536
537 @Override
538 public boolean isWhitespace() throws XmlPullParserException {
539 switch (mCurrentToken) {
540 case IGNORABLE_WHITESPACE:
541 return true;
542 case TEXT:
543 case CDSECT:
544 return !TextUtils.isGraphic(mCurrentText);
545 default:
546 throw new XmlPullParserException("Not applicable for token " + mCurrentToken);
547 }
548 }
549
550 @Override
551 public String getNamespace() {
552 switch (mCurrentToken) {
553 case START_TAG:
554 case END_TAG:
555 // Namespaces are unsupported
556 return NO_NAMESPACE;
557 default:
558 return null;
559 }
560 }
561
562 @Override
563 public String getName() {
564 return mCurrentName;
565 }
566
567 @Override
568 public String getPrefix() {
569 // Prefixes are not supported
570 return null;
571 }
572
573 @Override
574 public boolean isEmptyElementTag() throws XmlPullParserException {
575 switch (mCurrentToken) {
576 case START_TAG:
577 try {
578 return (peekNextExternalToken() == END_TAG);
579 } catch (IOException e) {
580 throw new XmlPullParserException(e.toString());
581 }
582 default:
583 throw new XmlPullParserException("Not at START_TAG");
584 }
585 }
586
587 @Override
588 public int getAttributeCount() {
589 return mAttributeCount;
590 }
591
592 @Override
593 public String getAttributeNamespace(int index) {
594 // Namespaces are unsupported
595 return NO_NAMESPACE;
596 }
597
598 @Override
599 public String getAttributeName(int index) {
600 return mAttributes[index].name;
601 }
602
603 @Override
604 public String getAttributePrefix(int index) {
605 // Prefixes are not supported
606 return null;
607 }
608
609 @Override
610 public String getAttributeType(int index) {
611 // Validation is not supported
612 return "CDATA";
613 }
614
615 @Override
616 public boolean isAttributeDefault(int index) {
617 // Validation is not supported
618 return false;
619 }
620
621 @Override
622 public int getEventType() throws XmlPullParserException {
623 return mCurrentToken;
624 }
625
626 @Override
627 public int getNamespaceCount(int depth) throws XmlPullParserException {
628 // Namespaces are unsupported
629 return 0;
630 }
631
632 @Override
633 public String getNamespacePrefix(int pos) throws XmlPullParserException {
634 // Namespaces are unsupported
635 throw new UnsupportedOperationException();
636 }
637
638 @Override
639 public String getNamespaceUri(int pos) throws XmlPullParserException {
640 // Namespaces are unsupported
641 throw new UnsupportedOperationException();
642 }
643
644 @Override
645 public String getNamespace(String prefix) {
646 // Namespaces are unsupported
647 throw new UnsupportedOperationException();
648 }
649
650 @Override
651 public void defineEntityReplacementText(String entityName, String replacementText)
652 throws XmlPullParserException {
653 // Custom entities are not supported
654 throw new UnsupportedOperationException();
655 }
656
657 @Override
658 public void setFeature(String name, boolean state) throws XmlPullParserException {
659 // Features are not supported
660 throw new UnsupportedOperationException();
661 }
662
663 @Override
664 public boolean getFeature(String name) {
665 // Features are not supported
666 throw new UnsupportedOperationException();
667 }
668
669 @Override
670 public void setProperty(String name, Object value) throws XmlPullParserException {
671 // Properties are not supported
672 throw new UnsupportedOperationException();
673 }
674
675 @Override
676 public Object getProperty(String name) {
677 // Properties are not supported
678 throw new UnsupportedOperationException();
679 }
680
681 private static IllegalArgumentException illegalNamespace() {
682 throw new IllegalArgumentException("Namespaces are not supported");
683 }
684
685 /**
686 * Holder representing a single attribute. This design enables object
687 * recycling without resorting to autoboxing.
688 * <p>
689 * To support conversion between human-readable XML and binary XML, the
690 * various accessor methods will transparently convert from/to
691 * human-readable values when needed.
692 */
693 private static class Attribute {
694 public String name;
695 public int type;
696
697 public String valueString;
698 public byte[] valueBytes;
699 public int valueInt;
700 public long valueLong;
701 public float valueFloat;
702 public double valueDouble;
703
704 public void reset() {
705 name = null;
706 valueString = null;
707 valueBytes = null;
708 }
709
710 public @Nullable String getValueString() {
711 switch (type) {
712 case TYPE_NULL:
713 return null;
714 case TYPE_STRING:
715 case TYPE_STRING_INTERNED:
716 return valueString;
717 case TYPE_BYTES_HEX:
718 return bytesToHexString(valueBytes);
719 case TYPE_BYTES_BASE64:
720 return Base64.encodeToString(valueBytes, Base64.NO_WRAP);
721 case TYPE_INT:
722 return Integer.toString(valueInt);
723 case TYPE_INT_HEX:
724 return Integer.toString(valueInt, 16);
725 case TYPE_LONG:
726 return Long.toString(valueLong);
727 case TYPE_LONG_HEX:
728 return Long.toString(valueLong, 16);
729 case TYPE_FLOAT:
730 return Float.toString(valueFloat);
731 case TYPE_DOUBLE:
732 return Double.toString(valueDouble);
733 case TYPE_BOOLEAN_TRUE:
734 return "true";
735 case TYPE_BOOLEAN_FALSE:
736 return "false";
737 default:
738 // Unknown data type; null is the best we can offer
739 return null;
740 }
741 }
742
743 public @Nullable byte[] getValueBytesHex() throws XmlPullParserException {
744 switch (type) {
745 case TYPE_NULL:
746 return null;
747 case TYPE_BYTES_HEX:
748 case TYPE_BYTES_BASE64:
749 return valueBytes;
750 case TYPE_STRING:
751 case TYPE_STRING_INTERNED:
752 try {
753 return hexStringToBytes(valueString);
754 } catch (Exception e) {
755 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
756 }
757 default:
758 throw new XmlPullParserException("Invalid conversion from " + type);
759 }
760 }
761
762 public @Nullable byte[] getValueBytesBase64() throws XmlPullParserException {
763 switch (type) {
764 case TYPE_NULL:
765 return null;
766 case TYPE_BYTES_HEX:
767 case TYPE_BYTES_BASE64:
768 return valueBytes;
769 case TYPE_STRING:
770 case TYPE_STRING_INTERNED:
771 try {
772 return Base64.decode(valueString, Base64.NO_WRAP);
773 } catch (Exception e) {
774 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
775 }
776 default:
777 throw new XmlPullParserException("Invalid conversion from " + type);
778 }
779 }
780
781 public int getValueInt() throws XmlPullParserException {
782 switch (type) {
783 case TYPE_INT:
784 case TYPE_INT_HEX:
785 return valueInt;
786 case TYPE_STRING:
787 case TYPE_STRING_INTERNED:
788 try {
789 return Integer.parseInt(valueString);
790 } catch (Exception e) {
791 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
792 }
793 default:
794 throw new XmlPullParserException("Invalid conversion from " + type);
795 }
796 }
797
798 public int getValueIntHex() throws XmlPullParserException {
799 switch (type) {
800 case TYPE_INT:
801 case TYPE_INT_HEX:
802 return valueInt;
803 case TYPE_STRING:
804 case TYPE_STRING_INTERNED:
805 try {
806 return Integer.parseInt(valueString, 16);
807 } catch (Exception e) {
808 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
809 }
810 default:
811 throw new XmlPullParserException("Invalid conversion from " + type);
812 }
813 }
814
815 public long getValueLong() throws XmlPullParserException {
816 switch (type) {
817 case TYPE_LONG:
818 case TYPE_LONG_HEX:
819 return valueLong;
820 case TYPE_STRING:
821 case TYPE_STRING_INTERNED:
822 try {
823 return Long.parseLong(valueString);
824 } catch (Exception e) {
825 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
826 }
827 default:
828 throw new XmlPullParserException("Invalid conversion from " + type);
829 }
830 }
831
832 public long getValueLongHex() throws XmlPullParserException {
833 switch (type) {
834 case TYPE_LONG:
835 case TYPE_LONG_HEX:
836 return valueLong;
837 case TYPE_STRING:
838 case TYPE_STRING_INTERNED:
839 try {
840 return Long.parseLong(valueString, 16);
841 } catch (Exception e) {
842 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
843 }
844 default:
845 throw new XmlPullParserException("Invalid conversion from " + type);
846 }
847 }
848
849 public float getValueFloat() throws XmlPullParserException {
850 switch (type) {
851 case TYPE_FLOAT:
852 return valueFloat;
853 case TYPE_STRING:
854 case TYPE_STRING_INTERNED:
855 try {
856 return Float.parseFloat(valueString);
857 } catch (Exception e) {
858 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
859 }
860 default:
861 throw new XmlPullParserException("Invalid conversion from " + type);
862 }
863 }
864
865 public double getValueDouble() throws XmlPullParserException {
866 switch (type) {
867 case TYPE_DOUBLE:
868 return valueDouble;
869 case TYPE_STRING:
870 case TYPE_STRING_INTERNED:
871 try {
872 return Double.parseDouble(valueString);
873 } catch (Exception e) {
874 throw new XmlPullParserException("Invalid attribute " + name + ": " + e);
875 }
876 default:
877 throw new XmlPullParserException("Invalid conversion from " + type);
878 }
879 }
880
881 public boolean getValueBoolean() throws XmlPullParserException {
882 switch (type) {
883 case TYPE_BOOLEAN_TRUE:
884 return true;
885 case TYPE_BOOLEAN_FALSE:
886 return false;
887 case TYPE_STRING:
888 case TYPE_STRING_INTERNED:
889 if ("true".equalsIgnoreCase(valueString)) {
890 return true;
891 } else if ("false".equalsIgnoreCase(valueString)) {
892 return false;
893 } else {
894 throw new XmlPullParserException(
895 "Invalid attribute " + name + ": " + valueString);
896 }
897 default:
898 throw new XmlPullParserException("Invalid conversion from " + type);
899 }
900 }
901 }
902
903 // NOTE: To support unbundled clients, we include an inlined copy
904 // of hex conversion logic from HexDump below
905 private final static char[] HEX_DIGITS =
906 { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
907
908 private static int toByte(char c) {
909 if (c >= '0' && c <= '9') return (c - '0');
910 if (c >= 'A' && c <= 'F') return (c - 'A' + 10);
911 if (c >= 'a' && c <= 'f') return (c - 'a' + 10);
912 throw new IllegalArgumentException("Invalid hex char '" + c + "'");
913 }
914
915 static String bytesToHexString(byte[] value) {
916 final int length = value.length;
917 final char[] buf = new char[length * 2];
918 int bufIndex = 0;
919 for (int i = 0; i < length; i++) {
920 byte b = value[i];
921 buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F];
922 buf[bufIndex++] = HEX_DIGITS[b & 0x0F];
923 }
924 return new String(buf);
925 }
926
927 static byte[] hexStringToBytes(String value) {
928 final int length = value.length();
929 if (length % 2 != 0) {
930 throw new IllegalArgumentException("Invalid hex length " + length);
931 }
932 byte[] buffer = new byte[length / 2];
933 for (int i = 0; i < length; i += 2) {
934 buffer[i / 2] = (byte) ((toByte(value.charAt(i)) << 4)
935 | toByte(value.charAt(i + 1)));
936 }
937 return buffer;
938 }
939 }