├── .gitignore ├── LICENSE ├── README.md ├── ccl_abx ├── README.md ├── TEST FILES │ ├── test-basic.xml │ ├── test-basic.xml.abx │ ├── test-typed-attribute.xml │ ├── test-typed-attribute.xml.abx │ ├── test_interned_strings.xml │ └── test_interned_strings.xml.abx └── ccl_abx.py └── makeabx ├── LICENSE └── src ├── META-INF └── MANIFEST.MF ├── com ├── android │ └── org │ │ └── kxml2 │ │ └── io │ │ └── KXmlParser.java └── ccl │ └── abxmaker │ ├── BinaryXmlSerializer.java │ ├── Converter.java │ ├── FastDataOutput.java │ ├── FastXmlSerializer.java │ ├── Main.java │ └── TypedXmlSerializer.java ├── libcore └── internal │ └── StringPool.java └── org └── xmlpull └── v1 ├── XmlPullParser.java ├── XmlPullParserException.java ├── XmlPullParserFactory.java └── XmlSerializer.java /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | __pycache__/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 CCL Solutions Group 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # android-bits 2 | Various Android tools, utilities and modules 3 | -------------------------------------------------------------------------------- /ccl_abx/README.md: -------------------------------------------------------------------------------- 1 | # ccl_abx 2 | `ccl_abx` is a Python module for reading Android Binary XML (ABX) files and converting them back to XML for processing. The module can also be executed at the command line to convert ABX files there. 3 | 4 | ## Command line usage 5 | To convert an ABX file at the command line: 6 | 7 | `ccl_abx.py file_path_here.xml` 8 | 9 | The converted data will be outputted to `STDOUT`, so if you want to save the file you can redirect the output: 10 | 11 | `ccl_abx.py file_path_here.xml > processed_file_path.xml` 12 | 13 | If the file being converted has multiple roots (such as the `settings_secure.xml` file) you can add the `-mr` switch to account for these multple roots: 14 | 15 | `ccl_abx.py file_path_here.xml -mr` 16 | 17 | ## Using the module in your scripts 18 | Use of the module is fairly straight-forward, a minimal example which reads a file provided at the command line might look like: 19 | 20 | ```python 21 | import sys 22 | import pathlib 23 | import ccl_abx 24 | 25 | input_path = pathlib.Path(sys.argv[1]) 26 | with input_path.open("rb") as f: 27 | reader = ccl_abx.AbxReader(f) # Pass a binary file-like object into the AbxReader constructor 28 | doc = reader.read() # Call the reader object's read() function which returns an ElementTree Element which is the root of the document 29 | 30 | ``` 31 | 32 | ## Known issues 33 | Our testing so far suggests that the module will round-trip an ABX created from a known XML file except for 34 | * Ignorable whitespace (e.g layout whitespace around tags) will be discarded 35 | * Elements with mixed content (text *and* child elements) will cause an exception to be raised - it doesn't appear that the methods that create ABX files in Android will create this structure though, so it appears to be a non-issue for now. 36 | * If the code which *encodes* the ABX file attempts to convert numerical attributes to floating-point numbers then the usual caveats around floating-point accuracy apply 37 | 38 | We have provided some test files so that you can confirm the behaviour of the module, and the `makeabx` Java application found in this repo can be used to generate further test files if needed. 39 | -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test-basic.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Text content in e1_1_1 4 | Text content in e1_1_2 5 | 6 | 7 | 8 | Text content in e1_2_1 9 | Text content in e1_2_2 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test-basic.xml.abx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cclgroupltd/android-bits/50910571ca81ad3db87ce1dcda9033a79b37ab72/ccl_abx/TEST FILES/test-basic.xml.abx -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test-typed-attribute.xml: -------------------------------------------------------------------------------- 1 | 2 | 100 stored as an int 3 | 0x64 stored as an int 4 | 100 stored as an long 5 | 0x64 stored as an long 6 | 0.5 stored as a float 7 | 0.3 stored as a float 8 | 0.5 stored as a double 9 | 0.3 stored as a double 10 | true stored as a bool 11 | false stored as a bool 12 | 123456aabbccddeeffc0ffee as bytes (hex) 13 | us5k (0xbace64) as bytes (base64) 14 | -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test-typed-attribute.xml.abx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cclgroupltd/android-bits/50910571ca81ad3db87ce1dcda9033a79b37ab72/ccl_abx/TEST FILES/test-typed-attribute.xml.abx -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test_interned_strings.xml: -------------------------------------------------------------------------------- 1 | 2 | First repeated element name 3 | Second repeated element name 4 | Third repeated element name 5 | Fourth repeated element name 6 | Fifth repeated element name 7 | Sixth repeated element name 8 | Seventh repeated element name 9 | Eighth repeated element name 10 | -------------------------------------------------------------------------------- /ccl_abx/TEST FILES/test_interned_strings.xml.abx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cclgroupltd/android-bits/50910571ca81ad3db87ce1dcda9033a79b37ab72/ccl_abx/TEST FILES/test_interned_strings.xml.abx -------------------------------------------------------------------------------- /ccl_abx/ccl_abx.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2021-2024, CCL Forensics 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of 4 | this software and associated documentation files (the "Software"), to deal in 5 | the Software without restriction, including without limitation the rights to 6 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 7 | of the Software, and to permit persons to whom the Software is furnished to do 8 | so, subject to the following conditions: 9 | The above copyright notice and this permission notice shall be included in all 10 | copies or substantial portions of the Software. 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | SOFTWARE. 18 | """ 19 | 20 | import base64 21 | import enum 22 | import struct 23 | import typing 24 | import xml.etree.ElementTree as etree 25 | 26 | 27 | __version__ = "0.3.0" 28 | __description__ = "Python module to convert Android ABX binary XML files" 29 | __contact__ = "Alex Caithness" 30 | 31 | # See: base/core/java/com/android/internal/util/BinaryXmlSerializer.java 32 | 33 | 34 | class AbxDecodeError(Exception): 35 | pass 36 | 37 | 38 | class XmlType(enum.IntEnum): 39 | # These first constants are from: libcore/xml/src/main/java/org/xmlpull/v1/XmlPullParser.java 40 | # most of them are unused, but here for completeness 41 | START_DOCUMENT = 0 42 | END_DOCUMENT = 1 43 | START_TAG = 2 44 | END_TAG = 3 45 | TEXT = 4 46 | CDSECT = 5 47 | ENTITY_REF = 6 48 | IGNORABLE_WHITESPACE = 7 49 | PROCESSING_INSTRUCTION = 8 50 | COMMENT = 9 51 | DOCDECL = 10 52 | 53 | ATTRIBUTE = 15 54 | 55 | 56 | class DataType(enum.IntEnum): 57 | TYPE_NULL = 1 << 4 58 | TYPE_STRING = 2 << 4 59 | TYPE_STRING_INTERNED = 3 << 4 60 | TYPE_BYTES_HEX = 4 << 4 61 | TYPE_BYTES_BASE64 = 5 << 4 62 | TYPE_INT = 6 << 4 63 | TYPE_INT_HEX = 7 << 4 64 | TYPE_LONG = 8 << 4 65 | TYPE_LONG_HEX = 9 << 4 66 | TYPE_FLOAT = 10 << 4 67 | TYPE_DOUBLE = 11 << 4 68 | TYPE_BOOLEAN_TRUE = 12 << 4 69 | TYPE_BOOLEAN_FALSE = 13 << 4 70 | 71 | 72 | class AbxReader: 73 | MAGIC = b"ABX\x00" 74 | 75 | def _read_raw(self, length): 76 | buff = self._stream.read(length) 77 | if len(buff) < length: 78 | raise ValueError(f"couldn't read enough data at offset: {self._stream.tell() - len(buff)}") 79 | return buff 80 | 81 | def _read_byte(self): 82 | buff = self._read_raw(1) 83 | return buff[0] 84 | 85 | def _read_short(self): 86 | buff = self._read_raw(2) 87 | return struct.unpack(">h", buff)[0] 88 | 89 | def _read_unsigned_short(self): 90 | buff = self._read_raw(2) 91 | return struct.unpack(">H", buff)[0] 92 | 93 | def _read_int(self): 94 | buff = self._read_raw(4) 95 | return struct.unpack(">i", buff)[0] 96 | 97 | def _read_long(self): 98 | buff = self._read_raw(8) 99 | return struct.unpack(">q", buff)[0] 100 | 101 | def _read_float(self): 102 | buff = self._read_raw(4) 103 | return struct.unpack(">f", buff)[0] 104 | 105 | def _read_double(self): 106 | buff = self._read_raw(8) 107 | return struct.unpack(">d", buff)[0] 108 | 109 | def _read_string_raw(self): 110 | length = self._read_unsigned_short() 111 | # if length < 0: 112 | # raise ValueError(f"Negative string length at offset {self._stream.tell() - 2}") 113 | buff = self._read_raw(length) 114 | return buff.decode("utf-8") 115 | 116 | def _read_interned_string(self): 117 | reference = self._read_short() 118 | if reference == -1: 119 | value = self._read_string_raw() 120 | self._interned_strings.append(value) 121 | else: 122 | value = self._interned_strings[reference] 123 | return value 124 | 125 | def __init__(self, stream: typing.BinaryIO): 126 | self._interned_strings = [] 127 | self._stream = stream 128 | 129 | def read(self, *, is_multi_root=False): 130 | """ 131 | Read the ABX file 132 | :param is_multi_root: some xml files on Android contain multiple root elements making reading them using a 133 | document model problematic. For these files, set is_multi_root to True and the output ElementTree will wrap 134 | the elements in a single "root" element. 135 | :return: ElementTree representation of the data. 136 | """ 137 | magic = self._read_raw(len(AbxReader.MAGIC)) 138 | if magic != AbxReader.MAGIC: 139 | raise ValueError(f"Invalid magic. Expected {AbxReader.MAGIC.hex()}; got: {magic.hex()}") 140 | 141 | #document_opened = False 142 | document_opened = True 143 | root_closed = False 144 | root = None 145 | element_stack = [] # because ElementTree doesn't support parents we maintain a stack 146 | if is_multi_root: 147 | root = etree.Element("root") 148 | element_stack.append(root) 149 | 150 | while True: 151 | # Read the token. This gives us the XML data type and the raw data type. 152 | token_raw = self._stream.read(1) 153 | if not token_raw: 154 | break 155 | token = token_raw[0] 156 | 157 | data_start_offset = self._stream.tell() 158 | 159 | # The lower nibble gives us the XML type. This is mostly defined in XmlPullParser.java, other than 160 | # ATTRIBUTE which is from BinaryXmlSerializer 161 | xml_type = token & 0x0f 162 | if xml_type == XmlType.START_DOCUMENT: 163 | # Since Android 13, START_DOCUMENT can essentially be considered no-op as it's implied by the reader to 164 | # always be present (regardless of whether it is). 165 | if token & 0xf0 != DataType.TYPE_NULL: 166 | raise AbxDecodeError( 167 | f"START_DOCUMENT with an invalid data type at offset {data_start_offset - 1}") 168 | #if document_opened: 169 | # if not root_closed: 170 | # raise AbxDecodeError(f"Unexpected START_DOCUMENT at offset {data_start_offset - 1}") 171 | document_opened = True 172 | 173 | elif xml_type == XmlType.END_DOCUMENT: 174 | if token & 0xf0 != DataType.TYPE_NULL: 175 | raise AbxDecodeError(f"END_DOCUMENT with an invalid data type at offset {data_start_offset - 1}") 176 | if not (len(element_stack) == 0 or (len(element_stack) == 1 and is_multi_root)): 177 | raise AbxDecodeError(f"END_DOCUMENT with unclosed elements at offset {data_start_offset - 1}") 178 | if not document_opened: 179 | raise AbxDecodeError(f"END_DOCUMENT before document started at offset {data_start_offset - 1}") 180 | break 181 | 182 | elif xml_type == XmlType.START_TAG: 183 | if token & 0xf0 != DataType.TYPE_STRING_INTERNED: 184 | raise AbxDecodeError(f"START_TAG with an invalid data type at offset {data_start_offset - 1}") 185 | if not document_opened: 186 | raise AbxDecodeError(f"START_TAG before document started at offset {data_start_offset - 1}") 187 | if root_closed: 188 | raise AbxDecodeError(f"START_TAG after root was closed started at offset {data_start_offset - 1}") 189 | 190 | tag_name = self._read_interned_string() 191 | if len(element_stack) == 0: 192 | element = etree.Element(tag_name) 193 | element_stack.append(element) 194 | root = element 195 | else: 196 | element = etree.SubElement(element_stack[-1], tag_name) 197 | element_stack.append(element) 198 | 199 | elif xml_type == XmlType.END_TAG: 200 | if token & 0xf0 != DataType.TYPE_STRING_INTERNED: 201 | raise AbxDecodeError(f"END_TAG with an invalid data type at offset {data_start_offset}") 202 | if len(element_stack) == 0 or (is_multi_root and len(element_stack) == 1): 203 | raise AbxDecodeError(f"END_TAG without any elements left at offset {data_start_offset}") 204 | 205 | tag_name = self._read_interned_string() 206 | if element_stack[-1].tag != tag_name: 207 | raise AbxDecodeError( 208 | f"Unexpected END_TAG name at {data_start_offset}. " 209 | f"Expected: {element_stack[-1].tag}; got: {tag_name}") 210 | 211 | last = element_stack.pop() 212 | if len(element_stack) == 0: 213 | root_closed = True 214 | root = last 215 | elif xml_type == XmlType.TEXT: 216 | value = self._read_string_raw() 217 | if len(element_stack[-1]): 218 | if len(value.strip()) == 0: # layout whitespace can be safely discarded 219 | continue 220 | raise NotImplementedError("Can't deal with elements with mixed text and element contents") 221 | 222 | if element_stack[-1].text is None: 223 | element_stack[-1].text = value 224 | else: 225 | element_stack[-1].text += value 226 | elif xml_type == XmlType.ATTRIBUTE: 227 | if len(element_stack) == 0 or (is_multi_root and len(element_stack) == 1): 228 | raise AbxDecodeError(f"ATTRIBUTE without any elements left at offset {data_start_offset}") 229 | 230 | attribute_name = self._read_interned_string() 231 | 232 | if attribute_name in element_stack[-1].attrib: 233 | raise AbxDecodeError(f"ATTRIBUTE name already in target element at offset {data_start_offset}") 234 | 235 | data_type = token & 0xf0 236 | 237 | if data_type == DataType.TYPE_NULL: 238 | value = None # remember to output xml as "null" 239 | elif data_type == DataType.TYPE_BOOLEAN_TRUE: 240 | # value = True # remember to output xml as "true" 241 | value = "true" 242 | elif data_type == DataType.TYPE_BOOLEAN_FALSE: 243 | # value = False # remember to output xml as "false" 244 | value = "false" 245 | elif data_type == DataType.TYPE_INT: 246 | value = self._read_int() 247 | elif data_type == DataType.TYPE_INT_HEX: 248 | value = f"{self._read_int():x}" # don't do this conversion in dict 249 | elif data_type == DataType.TYPE_LONG: 250 | value = self._read_long() 251 | elif data_type == DataType.TYPE_LONG_HEX: 252 | value = f"{self._read_long():x}" # don't do this conversion in dict 253 | elif data_type == DataType.TYPE_FLOAT: 254 | value = self._read_float() 255 | elif data_type == DataType.TYPE_DOUBLE: 256 | value = self._read_double() 257 | elif data_type == DataType.TYPE_STRING: 258 | value = self._read_string_raw() 259 | elif data_type == DataType.TYPE_STRING_INTERNED: 260 | value = self._read_interned_string() 261 | elif data_type == DataType.TYPE_BYTES_HEX: 262 | length = self._read_short() # is this safe? 263 | value = self._read_raw(length) 264 | value = value.hex() # skip this step for dict 265 | elif data_type == DataType.TYPE_BYTES_BASE64: 266 | length = self._read_short() # is this safe? 267 | value = self._read_raw(length) 268 | value = base64.encodebytes(value).decode().strip() 269 | else: 270 | raise AbxDecodeError(f"Unexpected attribute datatype at offset: {data_start_offset}") 271 | 272 | element_stack[-1].attrib[attribute_name] = str(value) 273 | else: 274 | raise NotImplementedError(f"unexpected XML type: {xml_type}") 275 | 276 | if not (root_closed or (is_multi_root and len(element_stack) == 1 and element_stack[0] is root)): 277 | raise AbxDecodeError("Elements still in the stack when completing the document") 278 | 279 | if root is None: 280 | raise AbxDecodeError("Document was never assigned a root element") 281 | 282 | tree = etree.ElementTree(root) 283 | 284 | return tree 285 | 286 | 287 | def main(args): 288 | in_path = pathlib.Path(args[0]) 289 | multi_root = "-mr" in args[1:] 290 | with in_path.open("rb") as f: 291 | reader = AbxReader(f) 292 | doc = reader.read(is_multi_root=multi_root) 293 | 294 | print(etree.tostring(doc.getroot()).decode()) 295 | 296 | 297 | if __name__ == '__main__': 298 | import sys 299 | import pathlib 300 | main(sys.argv[1:]) 301 | -------------------------------------------------------------------------------- /makeabx/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2022, CCL Forensics 2 | Permission is hereby granted, free of charge, to any person obtaining a copy of 3 | this software and associated documentation files (the "Software"), to deal in 4 | the Software without restriction, including without limitation the rights to 5 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 6 | of the Software, and to permit persons to whom the Software is furnished to do 7 | so, subject to the following conditions: 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 11 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 12 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 13 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 14 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 15 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 16 | SOFTWARE. 17 | 18 | --------------------------------- 19 | This code makes use of code from the Android Open Source Project: 20 | 21 | Copyright (C) 2010 The Android Open Source Project 22 | 23 | Licensed under the Apache License, Version 2.0 (the "License"); 24 | you may not use this file except in compliance with the License. 25 | 26 | You may obtain a copy of the License at 27 | http://www.apache.org/licenses/LICENSE-2.0 28 | 29 | Unless required by applicable law or agreed to in writing, software 30 | distributed under the License is distributed on an "AS IS" BASIS, 31 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 32 | See the License for the specific language governing permissions and 33 | limitations under the License. -------------------------------------------------------------------------------- /makeabx/src/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Main-Class: com.ccl.abxmaker.Main 3 | 4 | -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/BinaryXmlSerializer.java: -------------------------------------------------------------------------------- 1 | /* Modified version of BinaryXmlSerializer 2 | * Original License: 3 | * 4 | * Copyright (C) 2020 The Android Open Source Project 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.ccl.abxmaker; 20 | 21 | import static org.xmlpull.v1.XmlPullParser.CDSECT; 22 | import static org.xmlpull.v1.XmlPullParser.COMMENT; 23 | import static org.xmlpull.v1.XmlPullParser.DOCDECL; 24 | import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 25 | import static org.xmlpull.v1.XmlPullParser.END_TAG; 26 | import static org.xmlpull.v1.XmlPullParser.ENTITY_REF; 27 | import static org.xmlpull.v1.XmlPullParser.IGNORABLE_WHITESPACE; 28 | import static org.xmlpull.v1.XmlPullParser.PROCESSING_INSTRUCTION; 29 | import static org.xmlpull.v1.XmlPullParser.START_DOCUMENT; 30 | import static org.xmlpull.v1.XmlPullParser.START_TAG; 31 | import static org.xmlpull.v1.XmlPullParser.TEXT; 32 | 33 | //import android.annotation.NonNull; 34 | //import android.annotation.Nullable; 35 | //import android.util.TypedXmlSerializer; 36 | 37 | import org.xmlpull.v1.XmlPullParser; 38 | import org.xmlpull.v1.XmlSerializer; 39 | 40 | import java.io.IOException; 41 | import java.io.OutputStream; 42 | import java.io.Writer; 43 | import java.nio.charset.StandardCharsets; 44 | import java.util.Arrays; 45 | 46 | /** 47 | * Serializer that writes XML documents using a custom binary wire protocol 48 | * which benchmarking has shown to be 4.3x faster and use 2.4x less disk space 49 | * than {@code Xml.newFastSerializer()} for a typical {@code packages.xml}. 50 | *

51 | * The high-level design of the wire protocol is to directly serialize the event 52 | * stream, while efficiently and compactly writing strongly-typed primitives 53 | * delivered through the {@link TypedXmlSerializer} interface. 54 | *

55 | * Each serialized event is a single byte where the lower half is a normal 56 | * {@link XmlPullParser} token and the upper half is an optional data type 57 | * signal, such as {@link #TYPE_INT}. 58 | *

59 | * This serializer has some specific limitations: 60 | *

67 | */ 68 | public final class BinaryXmlSerializer implements TypedXmlSerializer { 69 | /** 70 | * The wire protocol always begins with a well-known magic value of 71 | * {@code ABX_}, representing "Android Binary XML." The final byte is a 72 | * version number which may be incremented as the protocol changes. 73 | */ 74 | public static final byte[] PROTOCOL_MAGIC_VERSION_0 = new byte[] { 0x41, 0x42, 0x58, 0x00 }; 75 | 76 | /** 77 | * Internal token which represents an attribute associated with the most 78 | * recent {@link #} token. 79 | */ 80 | static final int ATTRIBUTE = 15; 81 | 82 | static final int TYPE_NULL = 1 << 4; 83 | static final int TYPE_STRING = 2 << 4; 84 | static final int TYPE_STRING_INTERNED = 3 << 4; 85 | static final int TYPE_BYTES_HEX = 4 << 4; 86 | static final int TYPE_BYTES_BASE64 = 5 << 4; 87 | static final int TYPE_INT = 6 << 4; 88 | static final int TYPE_INT_HEX = 7 << 4; 89 | static final int TYPE_LONG = 8 << 4; 90 | static final int TYPE_LONG_HEX = 9 << 4; 91 | static final int TYPE_FLOAT = 10 << 4; 92 | static final int TYPE_DOUBLE = 11 << 4; 93 | static final int TYPE_BOOLEAN_TRUE = 12 << 4; 94 | static final int TYPE_BOOLEAN_FALSE = 13 << 4; 95 | 96 | /** 97 | * Default buffer size, which matches {@code FastXmlSerializer}. This should 98 | * be kept in sync with {@link }. 99 | */ 100 | private static final int BUFFER_SIZE = 32_768; 101 | 102 | private FastDataOutput mOut; 103 | 104 | /** 105 | * Stack of tags which are currently active via {@link #startTag} and which 106 | * haven't been terminated via {@link #endTag}. 107 | */ 108 | private int mTagCount = 0; 109 | private String[] mTagNames; 110 | 111 | /** 112 | * Write the given token and optional {@link String} into our buffer. 113 | */ 114 | private void writeToken(int token, String text) throws IOException { 115 | if (text != null) { 116 | mOut.writeByte(token | TYPE_STRING); 117 | mOut.writeUTF(text); 118 | } else { 119 | mOut.writeByte(token | TYPE_NULL); 120 | } 121 | } 122 | 123 | @Override 124 | public void setOutput(OutputStream os, String encoding) throws IOException { 125 | if (encoding != null && !StandardCharsets.UTF_8.name().equalsIgnoreCase(encoding)) { 126 | throw new UnsupportedOperationException(); 127 | } 128 | 129 | mOut = new FastDataOutput(os, BUFFER_SIZE); 130 | mOut.write(PROTOCOL_MAGIC_VERSION_0); 131 | 132 | mTagCount = 0; 133 | mTagNames = new String[8]; 134 | } 135 | 136 | @Override 137 | public void setOutput(Writer writer) { 138 | throw new UnsupportedOperationException(); 139 | } 140 | 141 | @Override 142 | public void flush() throws IOException { 143 | mOut.flush(); 144 | } 145 | 146 | @Override 147 | public void startDocument(String encoding, Boolean standalone) 148 | throws IOException { 149 | if (encoding != null && !StandardCharsets.UTF_8.name().equalsIgnoreCase(encoding)) { 150 | throw new UnsupportedOperationException(); 151 | } 152 | if (standalone != null && !standalone) { 153 | throw new UnsupportedOperationException(); 154 | } 155 | mOut.writeByte(START_DOCUMENT | TYPE_NULL); 156 | } 157 | 158 | @Override 159 | public void endDocument() throws IOException { 160 | mOut.writeByte(END_DOCUMENT | TYPE_NULL); 161 | flush(); 162 | } 163 | 164 | @Override 165 | public int getDepth() { 166 | return mTagCount; 167 | } 168 | 169 | @Override 170 | public String getNamespace() { 171 | // Namespaces are unsupported 172 | return XmlPullParser.NO_NAMESPACE; 173 | } 174 | 175 | @Override 176 | public String getName() { 177 | return mTagNames[mTagCount - 1]; 178 | } 179 | 180 | @Override 181 | public XmlSerializer startTag(String namespace, String name) throws IOException { 182 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 183 | if (mTagCount == mTagNames.length) { 184 | mTagNames = Arrays.copyOf(mTagNames, mTagCount + (mTagCount >> 1)); 185 | } 186 | mTagNames[mTagCount++] = name; 187 | mOut.writeByte(START_TAG | TYPE_STRING_INTERNED); 188 | mOut.writeInternedUTF(name); 189 | return this; 190 | } 191 | 192 | @Override 193 | public XmlSerializer endTag(String namespace, String name) throws IOException { 194 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 195 | mTagCount--; 196 | mOut.writeByte(END_TAG | TYPE_STRING_INTERNED); 197 | mOut.writeInternedUTF(name); 198 | return this; 199 | } 200 | 201 | @Override 202 | public XmlSerializer attribute(String namespace, String name, String value) throws IOException { 203 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 204 | mOut.writeByte(ATTRIBUTE | TYPE_STRING); 205 | mOut.writeInternedUTF(name); 206 | mOut.writeUTF(value); 207 | return this; 208 | } 209 | 210 | @Override 211 | public XmlSerializer attributeInterned(String namespace, String name, String value) 212 | throws IOException { 213 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 214 | mOut.writeByte(ATTRIBUTE | TYPE_STRING_INTERNED); 215 | mOut.writeInternedUTF(name); 216 | mOut.writeInternedUTF(value); 217 | return this; 218 | } 219 | 220 | @Override 221 | public XmlSerializer attributeBytesHex(String namespace, String name, byte[] value) 222 | throws IOException { 223 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 224 | mOut.writeByte(ATTRIBUTE | TYPE_BYTES_HEX); 225 | mOut.writeInternedUTF(name); 226 | mOut.writeShort(value.length); 227 | mOut.write(value); 228 | return this; 229 | } 230 | 231 | @Override 232 | public XmlSerializer attributeBytesBase64(String namespace, String name, byte[] value) 233 | throws IOException { 234 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 235 | mOut.writeByte(ATTRIBUTE | TYPE_BYTES_BASE64); 236 | mOut.writeInternedUTF(name); 237 | mOut.writeShort(value.length); 238 | mOut.write(value); 239 | return this; 240 | } 241 | 242 | @Override 243 | public XmlSerializer attributeInt(String namespace, String name, int value) 244 | throws IOException { 245 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 246 | mOut.writeByte(ATTRIBUTE | TYPE_INT); 247 | mOut.writeInternedUTF(name); 248 | mOut.writeInt(value); 249 | return this; 250 | } 251 | 252 | @Override 253 | public XmlSerializer attributeIntHex(String namespace, String name, int value) 254 | throws IOException { 255 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 256 | mOut.writeByte(ATTRIBUTE | TYPE_INT_HEX); 257 | mOut.writeInternedUTF(name); 258 | mOut.writeInt(value); 259 | return this; 260 | } 261 | 262 | @Override 263 | public XmlSerializer attributeLong(String namespace, String name, long value) 264 | throws IOException { 265 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 266 | mOut.writeByte(ATTRIBUTE | TYPE_LONG); 267 | mOut.writeInternedUTF(name); 268 | mOut.writeLong(value); 269 | return this; 270 | } 271 | 272 | @Override 273 | public XmlSerializer attributeLongHex(String namespace, String name, long value) 274 | throws IOException { 275 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 276 | mOut.writeByte(ATTRIBUTE | TYPE_LONG_HEX); 277 | mOut.writeInternedUTF(name); 278 | mOut.writeLong(value); 279 | return this; 280 | } 281 | 282 | @Override 283 | public XmlSerializer attributeFloat(String namespace, String name, float value) 284 | throws IOException { 285 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 286 | mOut.writeByte(ATTRIBUTE | TYPE_FLOAT); 287 | mOut.writeInternedUTF(name); 288 | mOut.writeFloat(value); 289 | return this; 290 | } 291 | 292 | @Override 293 | public XmlSerializer attributeDouble(String namespace, String name, double value) 294 | throws IOException { 295 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 296 | mOut.writeByte(ATTRIBUTE | TYPE_DOUBLE); 297 | mOut.writeInternedUTF(name); 298 | mOut.writeDouble(value); 299 | return this; 300 | } 301 | 302 | @Override 303 | public XmlSerializer attributeBoolean(String namespace, String name, boolean value) 304 | throws IOException { 305 | if (namespace != null && !namespace.isEmpty()) throw illegalNamespace(); 306 | if (value) { 307 | mOut.writeByte(ATTRIBUTE | TYPE_BOOLEAN_TRUE); 308 | mOut.writeInternedUTF(name); 309 | } else { 310 | mOut.writeByte(ATTRIBUTE | TYPE_BOOLEAN_FALSE); 311 | mOut.writeInternedUTF(name); 312 | } 313 | return this; 314 | } 315 | 316 | @Override 317 | public XmlSerializer text(char[] buf, int start, int len) throws IOException { 318 | writeToken(TEXT, new String(buf, start, len)); 319 | return this; 320 | } 321 | 322 | @Override 323 | public XmlSerializer text(String text) throws IOException { 324 | writeToken(TEXT, text); 325 | return this; 326 | } 327 | 328 | @Override 329 | public void cdsect(String text) throws IOException { 330 | writeToken(CDSECT, text); 331 | } 332 | 333 | @Override 334 | public void entityRef(String text) throws IOException { 335 | writeToken(ENTITY_REF, text); 336 | } 337 | 338 | @Override 339 | public void processingInstruction(String text) throws IOException { 340 | writeToken(PROCESSING_INSTRUCTION, text); 341 | } 342 | 343 | @Override 344 | public void comment(String text) throws IOException { 345 | writeToken(COMMENT, text); 346 | } 347 | 348 | @Override 349 | public void docdecl(String text) throws IOException { 350 | writeToken(DOCDECL, text); 351 | } 352 | 353 | @Override 354 | public void ignorableWhitespace(String text) throws IOException { 355 | writeToken(IGNORABLE_WHITESPACE, text); 356 | } 357 | 358 | @Override 359 | public void setFeature(String name, boolean state) { 360 | // Quietly handle no-op features 361 | if ("http://xmlpull.org/v1/doc/features.html#indent-output".equals(name)) { 362 | return; 363 | } 364 | // Features are not supported 365 | throw new UnsupportedOperationException(); 366 | } 367 | 368 | @Override 369 | public boolean getFeature(String name) { 370 | // Features are not supported 371 | throw new UnsupportedOperationException(); 372 | } 373 | 374 | @Override 375 | public void setProperty(String name, Object value) { 376 | // Properties are not supported 377 | throw new UnsupportedOperationException(); 378 | } 379 | 380 | @Override 381 | public Object getProperty(String name) { 382 | // Properties are not supported 383 | throw new UnsupportedOperationException(); 384 | } 385 | 386 | @Override 387 | public void setPrefix(String prefix, String namespace) { 388 | // Prefixes are not supported 389 | throw new UnsupportedOperationException(); 390 | } 391 | 392 | @Override 393 | public String getPrefix(String namespace, boolean generatePrefix) { 394 | // Prefixes are not supported 395 | throw new UnsupportedOperationException(); 396 | } 397 | 398 | private static IllegalArgumentException illegalNamespace() { 399 | throw new IllegalArgumentException("Namespaces are not supported"); 400 | } 401 | } -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/Converter.java: -------------------------------------------------------------------------------- 1 | package com.ccl.abxmaker; 2 | 3 | import com.android.org.kxml2.io.KXmlParser; 4 | import org.xmlpull.v1.XmlPullParser; 5 | import org.xmlpull.v1.XmlPullParserException; 6 | import org.xmlpull.v1.XmlSerializer; 7 | 8 | import java.io.*; 9 | import java.nio.charset.StandardCharsets; 10 | import java.util.Locale; 11 | 12 | import static org.xmlpull.v1.XmlPullParser.CDSECT; 13 | import static org.xmlpull.v1.XmlPullParser.COMMENT; 14 | import static org.xmlpull.v1.XmlPullParser.DOCDECL; 15 | import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 16 | import static org.xmlpull.v1.XmlPullParser.END_TAG; 17 | import static org.xmlpull.v1.XmlPullParser.ENTITY_REF; 18 | import static org.xmlpull.v1.XmlPullParser.IGNORABLE_WHITESPACE; 19 | import static org.xmlpull.v1.XmlPullParser.PROCESSING_INSTRUCTION; 20 | import static org.xmlpull.v1.XmlPullParser.START_DOCUMENT; 21 | import static org.xmlpull.v1.XmlPullParser.START_TAG; 22 | import static org.xmlpull.v1.XmlPullParser.TEXT; 23 | 24 | public class Converter { 25 | public static int nibbleToInt(char c){ 26 | if(c >= '0' && c <= '9'){ return c - '0';} 27 | if(c >= 'A' && c <= 'F'){ return c - 'A' + 10;} 28 | if(c >= 'a' && c <= 'f'){ return c - 'a' + 10;} 29 | return -1; 30 | } 31 | 32 | public static byte[] hexToBytes(String hex){ 33 | final int len = hex.length(); 34 | if(len % 2 != 0){ 35 | throw new IllegalArgumentException("invalid length for hex text"); 36 | } 37 | byte[] result = new byte[len / 2]; 38 | for(int i = 0; i < len; i += 2){ 39 | int high = nibbleToInt(hex.charAt(i)); 40 | int low = nibbleToInt(hex.charAt(i + 1)); 41 | if(high == -1 || low == -1){ 42 | throw new IllegalArgumentException("invalid characters for hex text"); 43 | } 44 | result[i / 2] = (byte) ((high * 16) + low); 45 | } 46 | return result; 47 | } 48 | 49 | public static byte[] Convert(Reader reader) throws IOException { 50 | KXmlParser parser = new KXmlParser(); 51 | //Reader reader = new StringReader(doc); 52 | try { 53 | parser.setInput(reader); 54 | } catch (XmlPullParserException e) { 55 | e.printStackTrace(); 56 | return null; 57 | } 58 | 59 | BinaryXmlSerializer serializer = new BinaryXmlSerializer(); 60 | ByteArrayOutputStream writer = new ByteArrayOutputStream(); 61 | serializer.setOutput(writer, null); 62 | serializer.startDocument(null, null); 63 | 64 | int event; 65 | do{ 66 | try { 67 | event = parser.next(); 68 | } catch (XmlPullParserException e) { 69 | e.printStackTrace(); 70 | return null; 71 | } 72 | 73 | switch (event){ 74 | case START_TAG: 75 | serializer.startTag(null, parser.getName()); 76 | for(int i = 0; i < parser.getAttributeCount(); i++){ 77 | // TODO: Infer types for typed attributes? 78 | String attributeName = parser.getAttributeName(i); 79 | int dashIndex = attributeName.lastIndexOf("-"); 80 | if(dashIndex > 0){ 81 | String typeName = attributeName.substring(dashIndex + 1).toLowerCase(Locale.ROOT); 82 | switch (typeName){ 83 | case "int": 84 | serializer.attributeInt( 85 | null, 86 | attributeName, 87 | Integer.parseInt(parser.getAttributeValue(i))); 88 | break; 89 | case "inthex": 90 | serializer.attributeIntHex( 91 | null, 92 | attributeName, 93 | Integer.parseInt(parser.getAttributeValue(i), 16)); 94 | break; 95 | case "long": 96 | serializer.attributeLong( 97 | null, 98 | attributeName, 99 | Long.parseLong(parser.getAttributeValue(i))); 100 | break; 101 | case "longhex": 102 | serializer.attributeLongHex( 103 | null, 104 | attributeName, 105 | Long.parseLong(parser.getAttributeValue(i), 16)); 106 | break; 107 | case "float": 108 | serializer.attributeFloat( 109 | null, 110 | attributeName, 111 | Float.parseFloat(parser.getAttributeValue(i))); 112 | break; 113 | case "double": 114 | serializer.attributeDouble( 115 | null, 116 | attributeName, 117 | Double.parseDouble(parser.getAttributeValue(i))); 118 | break; 119 | case "bool": 120 | if(parser.getAttributeValue(i).toLowerCase(Locale.ROOT) == "true"){ 121 | serializer.attributeBoolean(null, attributeName, true); 122 | }else if(parser.getAttributeValue(i).toLowerCase(Locale.ROOT) == "false"){ 123 | serializer.attributeBoolean(null, attributeName, false); 124 | }else{ 125 | serializer.attribute(null,attributeName, parser.getAttributeValue(i)); 126 | } 127 | break; 128 | case "byteshex": 129 | serializer.attributeBytesHex( 130 | null, 131 | attributeName, 132 | hexToBytes(parser.getAttributeValue(i))); 133 | break; 134 | case "base64": 135 | byte[] tmp = java.util.Base64.getDecoder().decode(parser.getAttributeValue(i)); 136 | serializer.attributeBytesBase64( 137 | null, 138 | attributeName, 139 | java.util.Base64.getDecoder().decode(parser.getAttributeValue(i))); 140 | break; 141 | default: 142 | serializer.attribute(null,attributeName, parser.getAttributeValue(i)); 143 | } 144 | }else{ 145 | serializer.attribute(null,attributeName, parser.getAttributeValue(i)); 146 | } 147 | 148 | 149 | 150 | } 151 | break; 152 | case END_TAG: 153 | serializer.endTag(null, parser.getName()); 154 | break; 155 | case TEXT: 156 | serializer.text(parser.getText()); 157 | break; 158 | case END_DOCUMENT: 159 | serializer.endDocument(); 160 | break; 161 | default: 162 | throw new UnsupportedOperationException(); 163 | } 164 | }while (event != END_DOCUMENT); 165 | 166 | 167 | reader.close(); 168 | byte[] result = writer.toByteArray(); 169 | return result; 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/FastDataOutput.java: -------------------------------------------------------------------------------- 1 | /* Modified version of FastDataOutput 2 | * Original License: 3 | * 4 | * Copyright (C) 2020 The Android Open Source Project 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.ccl.abxmaker; 20 | 21 | import java.io.BufferedOutputStream; 22 | import java.io.Closeable; 23 | import java.io.DataOutput; 24 | import java.io.DataOutputStream; 25 | import java.io.Flushable; 26 | import java.io.IOException; 27 | import java.io.OutputStream; 28 | import java.nio.charset.StandardCharsets; 29 | import java.util.HashMap; 30 | import java.util.Objects; 31 | 32 | /** 33 | * Optimized implementation of {@link DataOutput} which buffers data in memory 34 | * before flushing to the underlying {@link OutputStream}. 35 | *

36 | * Benchmarks have demonstrated this class is 2x more efficient than using a 37 | * {@link DataOutputStream} with a {@link BufferedOutputStream}. 38 | */ 39 | public class FastDataOutput implements DataOutput, Flushable, Closeable { 40 | private static final int MAX_UNSIGNED_SHORT = 65_535; 41 | 42 | //private final VMRuntime mRuntime; 43 | private final OutputStream mOut; 44 | 45 | private final byte[] mBuffer; 46 | //private final long mBufferPtr; 47 | private final int mBufferCap; 48 | 49 | private int mBufferPos; 50 | 51 | /** 52 | * Values that have been "interned" by {@link #writeInternedUTF(String)}. 53 | */ 54 | private HashMap mStringRefs = new HashMap<>(); 55 | 56 | public FastDataOutput( OutputStream out, int bufferSize) { 57 | //mRuntime = VMRuntime.getRuntime(); 58 | mOut = Objects.requireNonNull(out); 59 | if (bufferSize < 8) { 60 | throw new IllegalArgumentException(); 61 | } 62 | 63 | //mBuffer = (byte[]) mRuntime.newNonMovableArray(byte.class, bufferSize); 64 | mBuffer = new byte[bufferSize]; 65 | //mBufferPtr = mRuntime.addressOf(mBuffer); 66 | mBufferCap = mBuffer.length; 67 | } 68 | 69 | private void drain() throws IOException { 70 | if (mBufferPos > 0) { 71 | mOut.write(mBuffer, 0, mBufferPos); 72 | mBufferPos = 0; 73 | } 74 | } 75 | 76 | @Override 77 | public void flush() throws IOException { 78 | drain(); 79 | mOut.flush(); 80 | } 81 | 82 | @Override 83 | public void close() throws IOException { 84 | mOut.close(); 85 | } 86 | 87 | @Override 88 | public void write(int b) throws IOException { 89 | writeByte(b); 90 | } 91 | 92 | @Override 93 | public void write(byte[] b) throws IOException { 94 | write(b, 0, b.length); 95 | } 96 | 97 | @Override 98 | public void write(byte[] b, int off, int len) throws IOException { 99 | if (mBufferCap < len) { 100 | drain(); 101 | mOut.write(b, off, len); 102 | } else { 103 | if (mBufferCap - mBufferPos < len) drain(); 104 | System.arraycopy(b, off, mBuffer, mBufferPos, len); 105 | mBufferPos += len; 106 | } 107 | } 108 | 109 | @Override 110 | public void writeUTF(String s) throws IOException { 111 | // Attempt to write directly to buffer space if there's enough room, 112 | // otherwise fall back to chunking into place 113 | if (mBufferCap - mBufferPos < 2 + s.length()) drain(); 114 | 115 | // Monkey patching out all of the speed stuff, just do this easy and slow 116 | byte[] buffer = s.getBytes(StandardCharsets.UTF_8); 117 | writeShort(buffer.length); 118 | write(buffer, 0, buffer.length); 119 | // 120 | // // Magnitude of this returned value indicates the number of bytes 121 | // // required to encode the string; sign indicates success/failure 122 | // int len = CharsetUtils.toModifiedUtf8Bytes(s, mBufferPtr, mBufferPos + 2, mBufferCap); 123 | // 124 | // if (Math.abs(len) > MAX_UNSIGNED_SHORT) { 125 | // throw new IOException("Modified UTF-8 length too large: " + len); 126 | // } 127 | // 128 | // if (len >= 0) { 129 | // // Positive value indicates the string was encoded into the buffer 130 | // // successfully, so we only need to prefix with length 131 | // writeShort(len); 132 | // mBufferPos += len; 133 | // } else { 134 | // // Negative value indicates buffer was too small and we need to 135 | // // allocate a temporary buffer for encoding 136 | // len = -len; 137 | // //final byte[] tmp = (byte[]) mRuntime.newNonMovableArray(byte.class, len + 1); 138 | // final byte[] tmp = new byte[len + 1]; 139 | // CharsetUtils.toModifiedUtf8Bytes(s, mRuntime.addressOf(tmp), 0, tmp.length); 140 | // writeShort(len); 141 | // write(tmp, 0, len); 142 | // } 143 | } 144 | 145 | /** 146 | * Write a {@link String} value with the additional signal that the given 147 | * value is a candidate for being canonicalized, similar to 148 | * {@link String#intern()}. 149 | *

150 | * Canonicalization is implemented by writing each unique string value once 151 | * the first time it appears, and then writing a lightweight {@code short} 152 | * reference when that string is written again in the future. 153 | * 154 | * 155 | */ 156 | public void writeInternedUTF( String s) throws IOException { 157 | Short ref = mStringRefs.get(s); 158 | if (ref != null) { 159 | writeShort(ref); 160 | } else { 161 | writeShort(MAX_UNSIGNED_SHORT); 162 | writeUTF(s); 163 | 164 | // We can only safely intern when we have remaining values; if we're 165 | // full we at least sent the string value above 166 | ref = (short) mStringRefs.size(); 167 | if (ref < MAX_UNSIGNED_SHORT) { 168 | mStringRefs.put(s, ref); 169 | } 170 | } 171 | } 172 | 173 | @Override 174 | public void writeBoolean(boolean v) throws IOException { 175 | writeByte(v ? 1 : 0); 176 | } 177 | 178 | @Override 179 | public void writeByte(int v) throws IOException { 180 | if (mBufferCap - mBufferPos < 1) drain(); 181 | mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff); 182 | } 183 | 184 | @Override 185 | public void writeShort(int v) throws IOException { 186 | if (mBufferCap - mBufferPos < 2) drain(); 187 | mBuffer[mBufferPos++] = (byte) ((v >> 8) & 0xff); 188 | mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff); 189 | } 190 | 191 | @Override 192 | public void writeChar(int v) throws IOException { 193 | writeShort((short) v); 194 | } 195 | 196 | @Override 197 | public void writeInt(int v) throws IOException { 198 | if (mBufferCap - mBufferPos < 4) drain(); 199 | mBuffer[mBufferPos++] = (byte) ((v >> 24) & 0xff); 200 | mBuffer[mBufferPos++] = (byte) ((v >> 16) & 0xff); 201 | mBuffer[mBufferPos++] = (byte) ((v >> 8) & 0xff); 202 | mBuffer[mBufferPos++] = (byte) ((v >> 0) & 0xff); 203 | } 204 | 205 | @Override 206 | public void writeLong(long v) throws IOException { 207 | if (mBufferCap - mBufferPos < 8) drain(); 208 | int i = (int) (v >> 32); 209 | mBuffer[mBufferPos++] = (byte) ((i >> 24) & 0xff); 210 | mBuffer[mBufferPos++] = (byte) ((i >> 16) & 0xff); 211 | mBuffer[mBufferPos++] = (byte) ((i >> 8) & 0xff); 212 | mBuffer[mBufferPos++] = (byte) ((i >> 0) & 0xff); 213 | i = (int) v; 214 | mBuffer[mBufferPos++] = (byte) ((i >> 24) & 0xff); 215 | mBuffer[mBufferPos++] = (byte) ((i >> 16) & 0xff); 216 | mBuffer[mBufferPos++] = (byte) ((i >> 8) & 0xff); 217 | mBuffer[mBufferPos++] = (byte) ((i >> 0) & 0xff); 218 | } 219 | 220 | @Override 221 | public void writeFloat(float v) throws IOException { 222 | writeInt(Float.floatToIntBits(v)); 223 | } 224 | 225 | @Override 226 | public void writeDouble(double v) throws IOException { 227 | writeLong(Double.doubleToLongBits(v)); 228 | } 229 | 230 | @Override 231 | public void writeBytes(String s) throws IOException { 232 | // Callers should use writeUTF() 233 | throw new UnsupportedOperationException(); 234 | } 235 | 236 | @Override 237 | public void writeChars(String s) throws IOException { 238 | // Callers should use writeUTF() 239 | throw new UnsupportedOperationException(); 240 | } 241 | } 242 | 243 | 244 | -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/FastXmlSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Modified version of FastXmlSerializer 3 | * Original License: 4 | * 5 | * Copyright (C) 2006 The Android Open Source Project 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | 21 | package com.ccl.abxmaker; 22 | 23 | 24 | //import android.compat.annotation.UnsupportedAppUsage; 25 | 26 | import org.xmlpull.v1.XmlSerializer; 27 | 28 | import java.io.IOException; 29 | import java.io.OutputStream; 30 | import java.io.OutputStreamWriter; 31 | import java.io.UnsupportedEncodingException; 32 | import java.io.Writer; 33 | import java.nio.ByteBuffer; 34 | import java.nio.CharBuffer; 35 | import java.nio.charset.Charset; 36 | import java.nio.charset.CharsetEncoder; 37 | import java.nio.charset.CoderResult; 38 | import java.nio.charset.CodingErrorAction; 39 | import java.nio.charset.IllegalCharsetNameException; 40 | import java.nio.charset.UnsupportedCharsetException; 41 | 42 | /** 43 | * This is a quick and dirty implementation of XmlSerializer that isn't horribly 44 | * painfully slow like the normal one. It only does what is needed for the 45 | * specific XML files being written with it. 46 | */ 47 | public class FastXmlSerializer implements XmlSerializer { 48 | private static final String ESCAPE_TABLE[] = new String[] { 49 | "�", "", "", "", "", "", "", "", // 0-7 50 | "", " ", " ", " ", " ", " ", "", "", // 8-15 51 | "", "", "", "", "", "", "", "", // 16-23 52 | "", "", "", "", "", "", "", "", // 24-31 53 | null, null, """, null, null, null, "&", null, // 32-39 54 | null, null, null, null, null, null, null, null, // 40-47 55 | null, null, null, null, null, null, null, null, // 48-55 56 | null, null, null, null, "<", null, ">", null, // 56-63 57 | }; 58 | 59 | private static final int DEFAULT_BUFFER_LEN = 32*1024; 60 | 61 | private static String sSpace = " "; 62 | 63 | private final int mBufferLen; 64 | private final char[] mText; 65 | private int mPos; 66 | 67 | private Writer mWriter; 68 | 69 | private OutputStream mOutputStream; 70 | private CharsetEncoder mCharset; 71 | private ByteBuffer mBytes; 72 | 73 | private boolean mIndent = false; 74 | private boolean mInTag; 75 | 76 | private int mNesting = 0; 77 | private boolean mLineStart = true; 78 | 79 | //@UnsupportedAppUsage 80 | public FastXmlSerializer() { 81 | this(DEFAULT_BUFFER_LEN); 82 | } 83 | 84 | /** 85 | * Allocate a FastXmlSerializer with the given internal output buffer size. If the 86 | * size is zero or negative, then the default buffer size will be used. 87 | * 88 | * @param bufferSize Size in bytes of the in-memory output buffer that the writer will use. 89 | */ 90 | public FastXmlSerializer(int bufferSize) { 91 | mBufferLen = (bufferSize > 0) ? bufferSize : DEFAULT_BUFFER_LEN; 92 | mText = new char[mBufferLen]; 93 | mBytes = ByteBuffer.allocate(mBufferLen); 94 | } 95 | 96 | private void append(char c) throws IOException { 97 | int pos = mPos; 98 | if (pos >= (mBufferLen-1)) { 99 | flush(); 100 | pos = mPos; 101 | } 102 | mText[pos] = c; 103 | mPos = pos+1; 104 | } 105 | 106 | private void append(String str, int i, final int length) throws IOException { 107 | if (length > mBufferLen) { 108 | final int end = i + length; 109 | while (i < end) { 110 | int next = i + mBufferLen; 111 | append(str, i, next mBufferLen) { 118 | flush(); 119 | pos = mPos; 120 | } 121 | str.getChars(i, i+length, mText, pos); 122 | mPos = pos + length; 123 | } 124 | 125 | private void append(char[] buf, int i, final int length) throws IOException { 126 | if (length > mBufferLen) { 127 | final int end = i + length; 128 | while (i < end) { 129 | int next = i + mBufferLen; 130 | append(buf, i, next mBufferLen) { 137 | flush(); 138 | pos = mPos; 139 | } 140 | System.arraycopy(buf, i, mText, pos, length); 141 | mPos = pos + length; 142 | } 143 | 144 | private void append(String str) throws IOException { 145 | append(str, 0, str.length()); 146 | } 147 | 148 | private void appendIndent(int indent) throws IOException { 149 | indent *= 4; 150 | if (indent > sSpace.length()) { 151 | indent = sSpace.length(); 152 | } 153 | append(sSpace, 0, indent); 154 | } 155 | 156 | private void escapeAndAppendString(final String string) throws IOException { 157 | final int N = string.length(); 158 | final char NE = (char)ESCAPE_TABLE.length; 159 | final String[] escapes = ESCAPE_TABLE; 160 | int lastPos = 0; 161 | int pos; 162 | for (pos=0; pos= NE) continue; 165 | String escape = escapes[c]; 166 | if (escape == null) continue; 167 | if (lastPos < pos) append(string, lastPos, pos-lastPos); 168 | lastPos = pos + 1; 169 | append(escape); 170 | } 171 | if (lastPos < pos) append(string, lastPos, pos-lastPos); 172 | } 173 | 174 | private void escapeAndAppendString(char[] buf, int start, int len) throws IOException { 175 | final char NE = (char)ESCAPE_TABLE.length; 176 | final String[] escapes = ESCAPE_TABLE; 177 | int end = start+len; 178 | int lastPos = start; 179 | int pos; 180 | for (pos=start; pos= NE) continue; 183 | String escape = escapes[c]; 184 | if (escape == null) continue; 185 | if (lastPos < pos) append(buf, lastPos, pos-lastPos); 186 | lastPos = pos + 1; 187 | append(escape); 188 | } 189 | if (lastPos < pos) append(buf, lastPos, pos-lastPos); 190 | } 191 | 192 | public XmlSerializer attribute(String namespace, String name, String value) throws IOException, 193 | IllegalArgumentException, IllegalStateException { 194 | append(' '); 195 | if (namespace != null) { 196 | append(namespace); 197 | append(':'); 198 | } 199 | append(name); 200 | append("=\""); 201 | 202 | escapeAndAppendString(value); 203 | append('"'); 204 | mLineStart = false; 205 | return this; 206 | } 207 | 208 | public void cdsect(String text) throws IOException, IllegalArgumentException, 209 | IllegalStateException { 210 | throw new UnsupportedOperationException(); 211 | } 212 | 213 | public void comment(String text) throws IOException, IllegalArgumentException, 214 | IllegalStateException { 215 | throw new UnsupportedOperationException(); 216 | } 217 | 218 | public void docdecl(String text) throws IOException, IllegalArgumentException, 219 | IllegalStateException { 220 | throw new UnsupportedOperationException(); 221 | } 222 | 223 | public void endDocument() throws IOException, IllegalArgumentException, IllegalStateException { 224 | flush(); 225 | } 226 | 227 | public XmlSerializer endTag(String namespace, String name) throws IOException, 228 | IllegalArgumentException, IllegalStateException { 229 | mNesting--; 230 | if (mInTag) { 231 | append(" />\n"); 232 | } else { 233 | if (mIndent && mLineStart) { 234 | appendIndent(mNesting); 235 | } 236 | append("\n"); 243 | } 244 | mLineStart = true; 245 | mInTag = false; 246 | return this; 247 | } 248 | 249 | public void entityRef(String text) throws IOException, IllegalArgumentException, 250 | IllegalStateException { 251 | throw new UnsupportedOperationException(); 252 | } 253 | 254 | private void flushBytes() throws IOException { 255 | int position; 256 | if ((position = mBytes.position()) > 0) { 257 | mBytes.flip(); 258 | mOutputStream.write(mBytes.array(), 0, position); 259 | mBytes.clear(); 260 | } 261 | } 262 | 263 | public void flush() throws IOException { 264 | //Log.i("PackageManager", "flush mPos=" + mPos); 265 | if (mPos > 0) { 266 | if (mOutputStream != null) { 267 | CharBuffer charBuffer = CharBuffer.wrap(mText, 0, mPos); 268 | CoderResult result = mCharset.encode(charBuffer, mBytes, true); 269 | while (true) { 270 | if (result.isError()) { 271 | throw new IOException(result.toString()); 272 | } else if (result.isOverflow()) { 273 | flushBytes(); 274 | result = mCharset.encode(charBuffer, mBytes, true); 275 | continue; 276 | } 277 | break; 278 | } 279 | flushBytes(); 280 | mOutputStream.flush(); 281 | } else { 282 | mWriter.write(mText, 0, mPos); 283 | mWriter.flush(); 284 | } 285 | mPos = 0; 286 | } 287 | } 288 | 289 | public int getDepth() { 290 | throw new UnsupportedOperationException(); 291 | } 292 | 293 | public boolean getFeature(String name) { 294 | throw new UnsupportedOperationException(); 295 | } 296 | 297 | public String getName() { 298 | throw new UnsupportedOperationException(); 299 | } 300 | 301 | public String getNamespace() { 302 | throw new UnsupportedOperationException(); 303 | } 304 | 305 | public String getPrefix(String namespace, boolean generatePrefix) 306 | throws IllegalArgumentException { 307 | throw new UnsupportedOperationException(); 308 | } 309 | 310 | public Object getProperty(String name) { 311 | throw new UnsupportedOperationException(); 312 | } 313 | 314 | public void ignorableWhitespace(String text) throws IOException, IllegalArgumentException, 315 | IllegalStateException { 316 | throw new UnsupportedOperationException(); 317 | } 318 | 319 | public void processingInstruction(String text) throws IOException, IllegalArgumentException, 320 | IllegalStateException { 321 | throw new UnsupportedOperationException(); 322 | } 323 | 324 | public void setFeature(String name, boolean state) throws IllegalArgumentException, 325 | IllegalStateException { 326 | if (name.equals("http://xmlpull.org/v1/doc/features.html#indent-output")) { 327 | mIndent = true; 328 | return; 329 | } 330 | throw new UnsupportedOperationException(); 331 | } 332 | 333 | public void setOutput(OutputStream os, String encoding) throws IOException, 334 | IllegalArgumentException, IllegalStateException { 335 | if (os == null) 336 | throw new IllegalArgumentException(); 337 | if (true) { 338 | try { 339 | mCharset = Charset.forName(encoding).newEncoder() 340 | .onMalformedInput(CodingErrorAction.REPLACE) 341 | .onUnmappableCharacter(CodingErrorAction.REPLACE); 342 | } catch (IllegalCharsetNameException e) { 343 | throw (UnsupportedEncodingException) (new UnsupportedEncodingException( 344 | encoding).initCause(e)); 345 | } catch (UnsupportedCharsetException e) { 346 | throw (UnsupportedEncodingException) (new UnsupportedEncodingException( 347 | encoding).initCause(e)); 348 | } 349 | mOutputStream = os; 350 | } else { 351 | setOutput( 352 | encoding == null 353 | ? new OutputStreamWriter(os) 354 | : new OutputStreamWriter(os, encoding)); 355 | } 356 | } 357 | 358 | public void setOutput(Writer writer) throws IOException, IllegalArgumentException, 359 | IllegalStateException { 360 | mWriter = writer; 361 | } 362 | 363 | public void setPrefix(String prefix, String namespace) throws IOException, 364 | IllegalArgumentException, IllegalStateException { 365 | throw new UnsupportedOperationException(); 366 | } 367 | 368 | public void setProperty(String name, Object value) throws IllegalArgumentException, 369 | IllegalStateException { 370 | throw new UnsupportedOperationException(); 371 | } 372 | 373 | public void startDocument(String encoding, Boolean standalone) throws IOException, 374 | IllegalArgumentException, IllegalStateException { 375 | append("\n"); 380 | mLineStart = true; 381 | } 382 | 383 | public XmlSerializer startTag(String namespace, String name) throws IOException, 384 | IllegalArgumentException, IllegalStateException { 385 | if (mInTag) { 386 | append(">\n"); 387 | } 388 | if (mIndent) { 389 | appendIndent(mNesting); 390 | } 391 | mNesting++; 392 | append('<'); 393 | if (namespace != null) { 394 | append(namespace); 395 | append(':'); 396 | } 397 | append(name); 398 | mInTag = true; 399 | mLineStart = false; 400 | return this; 401 | } 402 | 403 | public XmlSerializer text(char[] buf, int start, int len) throws IOException, 404 | IllegalArgumentException, IllegalStateException { 405 | if (mInTag) { 406 | append(">"); 407 | mInTag = false; 408 | } 409 | escapeAndAppendString(buf, start, len); 410 | if (mIndent) { 411 | mLineStart = buf[start+len-1] == '\n'; 412 | } 413 | return this; 414 | } 415 | 416 | public XmlSerializer text(String text) throws IOException, IllegalArgumentException, 417 | IllegalStateException { 418 | if (mInTag) { 419 | append(">"); 420 | mInTag = false; 421 | } 422 | escapeAndAppendString(text); 423 | if (mIndent) { 424 | mLineStart = text.length() > 0 && (text.charAt(text.length()-1) == '\n'); 425 | } 426 | return this; 427 | } 428 | 429 | } 430 | -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/Main.java: -------------------------------------------------------------------------------- 1 | package com.ccl.abxmaker; 2 | 3 | import java.io.*; 4 | import java.net.URISyntaxException; 5 | 6 | public class Main { 7 | 8 | public static void main(String[] args) throws IOException, URISyntaxException { 9 | // write your code here 10 | if(args.length < 1){ 11 | String me = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getName(); 12 | 13 | System.out.println(); 14 | System.out.printf("USAGE: %s \n", me); 15 | System.out.println(); 16 | System.out.println("Converts an XML file to an ABX file (the output will have the same path as the input"); 17 | System.out.println("with an '.abx' extension added)."); 18 | System.out.println(); 19 | System.out.println("If one of the following suffixes are found on an attribute's name, they will be"); 20 | System.out.println("treated as typed values:"); 21 | System.out.println("-int, -inthex -long -longhex -float -double -bool -byteshex -base64"); 22 | System.out.println("eg. Attribute will be parsed as hex"); 23 | System.out.println(); 24 | 25 | return; 26 | } 27 | 28 | String inputPath = args[0]; 29 | FileReader reader = new FileReader(inputPath); 30 | byte[] result = Converter.Convert(reader); 31 | if(result == null){ 32 | return; 33 | } 34 | String outputPath = inputPath + ".abx"; 35 | if(new File(outputPath).exists()){ 36 | System.out.printf("ERROR: '%s' already exists\n", outputPath); 37 | } 38 | FileOutputStream outStream = new FileOutputStream(outputPath); 39 | outStream.write(result); 40 | 41 | reader.close(); 42 | outStream.close(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /makeabx/src/com/ccl/abxmaker/TypedXmlSerializer.java: -------------------------------------------------------------------------------- 1 | /* Modified version of TypedXmlSerializer 2 | * Original License: 3 | * 4 | * Copyright (C) 2020 The Android Open Source Project 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package com.ccl.abxmaker; 20 | 21 | import org.xmlpull.v1.XmlSerializer; 22 | 23 | import java.io.IOException; 24 | 25 | /** 26 | * Specialization of {@link XmlSerializer} which adds explicit methods to 27 | * support consistent and efficient conversion of primitive data types. 28 | * 29 | * @hide 30 | */ 31 | public interface TypedXmlSerializer extends XmlSerializer { 32 | /** 33 | * Functionally equivalent to {@link #attribute(String, String, String)} but 34 | * with the additional signal that the given value is a candidate for being 35 | * canonicalized, similar to {@link String#intern()}. 36 | */ 37 | XmlSerializer attributeInterned( String namespace, String name, 38 | String value) throws IOException; 39 | 40 | /** 41 | * Encode the given strongly-typed value and serialize using 42 | * {@link #attribute(String, String, String)}. 43 | */ 44 | XmlSerializer attributeBytesHex( String namespace, String name, 45 | byte[] value) throws IOException; 46 | 47 | /** 48 | * Encode the given strongly-typed value and serialize using 49 | * {@link #attribute(String, String, String)}. 50 | */ 51 | XmlSerializer attributeBytesBase64( String namespace, String name, 52 | byte[] value) throws IOException; 53 | 54 | /** 55 | * Encode the given strongly-typed value and serialize using 56 | * {@link #attribute(String, String, String)}. 57 | */ 58 | XmlSerializer attributeInt( String namespace, String name, 59 | int value) throws IOException; 60 | 61 | /** 62 | * Encode the given strongly-typed value and serialize using 63 | * {@link #attribute(String, String, String)}. 64 | */ 65 | XmlSerializer attributeIntHex( String namespace, String name, 66 | int value) throws IOException; 67 | 68 | /** 69 | * Encode the given strongly-typed value and serialize using 70 | * {@link #attribute(String, String, String)}. 71 | */ 72 | XmlSerializer attributeLong( String namespace, String name, 73 | long value) throws IOException; 74 | 75 | /** 76 | * Encode the given strongly-typed value and serialize using 77 | * {@link #attribute(String, String, String)}. 78 | */ 79 | XmlSerializer attributeLongHex( String namespace, String name, 80 | long value) throws IOException; 81 | 82 | /** 83 | * Encode the given strongly-typed value and serialize using 84 | * {@link #attribute(String, String, String)}. 85 | */ 86 | XmlSerializer attributeFloat( String namespace, String name, 87 | float value) throws IOException; 88 | 89 | /** 90 | * Encode the given strongly-typed value and serialize using 91 | * {@link #attribute(String, String, String)}. 92 | */ 93 | XmlSerializer attributeDouble( String namespace, String name, 94 | double value) throws IOException; 95 | 96 | /** 97 | * Encode the given strongly-typed value and serialize using 98 | * {@link #attribute(String, String, String)}. 99 | */ 100 | XmlSerializer attributeBoolean( String namespace, String name, 101 | boolean value) throws IOException; 102 | } 103 | 104 | -------------------------------------------------------------------------------- /makeabx/src/libcore/internal/StringPool.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 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 libcore.internal; 18 | 19 | /** 20 | * A pool of string instances. Unlike the {@link String#intern() VM's 21 | * interned strings}, this pool provides no guarantee of reference equality. 22 | * It is intended only to save allocations. This class is not thread safe. 23 | * 24 | * @hide 25 | */ 26 | public final class StringPool { 27 | 28 | private final String[] pool = new String[512]; 29 | 30 | public StringPool() { 31 | } 32 | 33 | private static boolean contentEquals(String s, char[] chars, int start, int length) { 34 | if (s.length() != length) { 35 | return false; 36 | } 37 | for (int i = 0; i < length; i++) { 38 | if (chars[start + i] != s.charAt(i)) { 39 | return false; 40 | } 41 | } 42 | return true; 43 | } 44 | 45 | /** 46 | * Returns a string equal to {@code new String(array, start, length)}. 47 | */ 48 | public String get(char[] array, int start, int length) { 49 | // Compute an arbitrary hash of the content 50 | int hashCode = 0; 51 | for (int i = start; i < start + length; i++) { 52 | hashCode = (hashCode * 31) + array[i]; 53 | } 54 | 55 | // Pick a bucket using Doug Lea's supplemental secondaryHash function (from HashMap) 56 | hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); 57 | hashCode ^= (hashCode >>> 7) ^ (hashCode >>> 4); 58 | int index = hashCode & (pool.length - 1); 59 | 60 | String pooled = pool[index]; 61 | if (pooled != null && contentEquals(pooled, array, start, length)) { 62 | return pooled; 63 | } 64 | 65 | String result = new String(array, start, length); 66 | pool[index] = result; 67 | return result; 68 | } 69 | } -------------------------------------------------------------------------------- /makeabx/src/org/xmlpull/v1/XmlPullParser.java: -------------------------------------------------------------------------------- 1 | /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ 2 | // for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) 3 | 4 | package org.xmlpull.v1; 5 | 6 | import java.io.InputStream; 7 | import java.io.IOException; 8 | import java.io.Reader; 9 | 10 | /** 11 | * XML Pull Parser is an interface that defines parsing functionality provided 12 | * in XMLPULL V1 API (visit this website to 13 | * learn more about API and its implementations). 14 | * 15 | *

There are following different 16 | * kinds of parser depending on which features are set:

28 | * 29 | * 30 | *

There are two key methods: next() and nextToken(). While next() provides 31 | * access to high level parsing events, nextToken() allows access to lower 32 | * level tokens. 33 | * 34 | *

The current event state of the parser 35 | * can be determined by calling the 36 | * getEventType() method. 37 | * Initially, the parser is in the START_DOCUMENT 38 | * state. 39 | * 40 | *

The method next() advances the parser to the 41 | * next event. The int value returned from next determines the current parser 42 | * state and is identical to the value returned from following calls to 43 | * getEventType (). 44 | * 45 | *

Th following event types are seen by next()

46 | *
START_TAG
An XML start tag was read. 47 | *
TEXT
Text content was read; 48 | * the text content can be retrieved using the getText() method. 49 | * (when in validating mode next() will not report ignorable whitespace, use nextToken() instead) 50 | *
END_TAG
An end tag was read 51 | *
END_DOCUMENT
No more events are available 52 | *
53 | * 54 | *

after first next() or nextToken() (or any other next*() method) 55 | * is called user application can obtain 56 | * XML version, standalone and encoding from XML declaration 57 | * in following ways:

70 | * 71 | * A minimal example for using this API may look as follows: 72 | *
  73 |  * import java.io.IOException;
  74 |  * import java.io.StringReader;
  75 |  *
  76 |  * import org.xmlpull.v1.XmlPullParser;
  77 |  * import org.xmlpull.v1.XmlPullParserException;
  78 |  * import org.xmlpull.v1.XmlPullParserFactory;
  79 |  *
  80 |  * public class SimpleXmlPullApp
  81 |  * {
  82 |  *
  83 |  *     public static void main (String args[])
  84 |  *         throws XmlPullParserException, IOException
  85 |  *     {
  86 |  *         XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
  87 |  *         factory.setNamespaceAware(true);
  88 |  *         XmlPullParser xpp = factory.newPullParser();
  89 |  *
  90 |  *         xpp.setInput( new StringReader ( "<foo>Hello World!</foo>" ) );
  91 |  *         int eventType = xpp.getEventType();
  92 |  *         while (eventType != XmlPullParser.END_DOCUMENT) {
  93 |  *          if(eventType == XmlPullParser.START_DOCUMENT) {
  94 |  *              System.out.println("Start document");
  95 |  *          } else if(eventType == XmlPullParser.START_TAG) {
  96 |  *              System.out.println("Start tag "+xpp.getName());
  97 |  *          } else if(eventType == XmlPullParser.END_TAG) {
  98 |  *              System.out.println("End tag "+xpp.getName());
  99 |  *          } else if(eventType == XmlPullParser.TEXT) {
 100 |  *              System.out.println("Text "+xpp.getText());
 101 |  *          }
 102 |  *          eventType = xpp.next();
 103 |  *         }
 104 |  *         System.out.println("End document");
 105 |  *     }
 106 |  * }
 107 |  * 
108 | * 109 | *

The above example will generate the following output: 110 | *

 111 |  * Start document
 112 |  * Start tag foo
 113 |  * Text Hello World!
 114 |  * End tag foo
 115 |  * End document
 116 |  * 
117 | * 118 | *

For more details on API usage, please refer to the 119 | * quick Introduction available at http://www.xmlpull.org 120 | * 121 | * @see XmlPullParserFactory 122 | * @see #defineEntityReplacementText 123 | * @see #getName 124 | * @see #getNamespace 125 | * @see #getText 126 | * @see #next 127 | * @see #nextToken 128 | * @see #setInput 129 | * @see #FEATURE_PROCESS_DOCDECL 130 | * @see #FEATURE_VALIDATION 131 | * @see #START_DOCUMENT 132 | * @see #START_TAG 133 | * @see #TEXT 134 | * @see #END_TAG 135 | * @see #END_DOCUMENT 136 | * 137 | * @author Stefan Haustein 138 | * @author Aleksander Slominski 139 | */ 140 | 141 | public interface XmlPullParser { 142 | 143 | /** This constant represents the default namespace (empty string "") */ 144 | String NO_NAMESPACE = ""; 145 | 146 | // ---------------------------------------------------------------------------- 147 | // EVENT TYPES as reported by next() 148 | 149 | /** 150 | * Signalize that parser is at the very beginning of the document 151 | * and nothing was read yet. 152 | * This event type can only be observed by calling getEvent() 153 | * before the first call to next(), nextToken, or nextTag()). 154 | * 155 | * @see #next 156 | * @see #nextToken 157 | */ 158 | int START_DOCUMENT = 0; 159 | 160 | /** 161 | * Logical end of the xml document. Returned from getEventType, next() 162 | * and nextToken() 163 | * when the end of the input document has been reached. 164 | *

NOTE: subsequent calls to 165 | * next() or nextToken() 166 | * may result in exception being thrown. 167 | * 168 | * @see #next 169 | * @see #nextToken 170 | */ 171 | int END_DOCUMENT = 1; 172 | 173 | /** 174 | * Returned from getEventType(), 175 | * next(), nextToken() when 176 | * a start tag was read. 177 | * The name of start tag is available from getName(), its namespace and prefix are 178 | * available from getNamespace() and getPrefix() 179 | * if namespaces are enabled. 180 | * See getAttribute* methods to retrieve element attributes. 181 | * See getNamespace* methods to retrieve newly declared namespaces. 182 | * 183 | * @see #next 184 | * @see #nextToken 185 | * @see #getName 186 | * @see #getPrefix 187 | * @see #getNamespace 188 | * @see #getAttributeCount 189 | * @see #getDepth 190 | * @see #getNamespaceCount 191 | * @see #getNamespace 192 | * @see #FEATURE_PROCESS_NAMESPACES 193 | */ 194 | int START_TAG = 2; 195 | 196 | /** 197 | * Returned from getEventType(), next(), or 198 | * nextToken() when an end tag was read. 199 | * The name of start tag is available from getName(), its 200 | * namespace and prefix are 201 | * available from getNamespace() and getPrefix(). 202 | * 203 | * @see #next 204 | * @see #nextToken 205 | * @see #getName 206 | * @see #getPrefix 207 | * @see #getNamespace 208 | * @see #FEATURE_PROCESS_NAMESPACES 209 | */ 210 | int END_TAG = 3; 211 | 212 | 213 | /** 214 | * Character data was read and will is available by calling getText(). 215 | *

Please note: next() will 216 | * accumulate multiple 217 | * events into one TEXT event, skipping IGNORABLE_WHITESPACE, 218 | * PROCESSING_INSTRUCTION and COMMENT events, 219 | * In contrast, nextToken() will stop reading 220 | * text when any other event is observed. 221 | * Also, when the state was reached by calling next(), the text value will 222 | * be normalized, whereas getText() will 223 | * return unnormalized content in the case of nextToken(). This allows 224 | * an exact roundtrip without changing line ends when examining low 225 | * level events, whereas for high level applications the text is 226 | * normalized appropriately. 227 | * 228 | * @see #next 229 | * @see #nextToken 230 | * @see #getText 231 | */ 232 | int TEXT = 4; 233 | 234 | // ---------------------------------------------------------------------------- 235 | // additional events exposed by lower level nextToken() 236 | 237 | /** 238 | * A CDATA sections was just read; 239 | * this token is available only from calls to nextToken(). 240 | * A call to next() will accumulate various text events into a single event 241 | * of type TEXT. The text contained in the CDATA section is available 242 | * by calling getText(). 243 | * 244 | * @see #nextToken 245 | * @see #getText 246 | */ 247 | int CDSECT = 5; 248 | 249 | /** 250 | * An entity reference was just read; 251 | * this token is available from nextToken() 252 | * only. The entity name is available by calling getName(). If available, 253 | * the replacement text can be obtained by calling getText(); otherwise, 254 | * the user is responsible for resolving the entity reference. 255 | * This event type is never returned from next(); next() will 256 | * accumulate the replacement text and other text 257 | * events to a single TEXT event. 258 | * 259 | * @see #nextToken 260 | * @see #getText 261 | */ 262 | int ENTITY_REF = 6; 263 | 264 | /** 265 | * Ignorable whitespace was just read. 266 | * This token is available only from nextToken()). 267 | * For non-validating 268 | * parsers, this event is only reported by nextToken() when outside 269 | * the root element. 270 | * Validating parsers may be able to detect ignorable whitespace at 271 | * other locations. 272 | * The ignorable whitespace string is available by calling getText() 273 | * 274 | *

NOTE: this is different from calling the 275 | * isWhitespace() method, since text content 276 | * may be whitespace but not ignorable. 277 | * 278 | * Ignorable whitespace is skipped by next() automatically; this event 279 | * type is never returned from next(). 280 | * 281 | * @see #nextToken 282 | * @see #getText 283 | */ 284 | int IGNORABLE_WHITESPACE = 7; 285 | 286 | /** 287 | * An XML processing instruction declaration was just read. This 288 | * event type is available only via nextToken(). 289 | * getText() will return text that is inside the processing instruction. 290 | * Calls to next() will skip processing instructions automatically. 291 | * @see #nextToken 292 | * @see #getText 293 | */ 294 | int PROCESSING_INSTRUCTION = 8; 295 | 296 | /** 297 | * An XML comment was just read. This event type is this token is 298 | * available via nextToken() only; 299 | * calls to next() will skip comments automatically. 300 | * The content of the comment can be accessed using the getText() 301 | * method. 302 | * 303 | * @see #nextToken 304 | * @see #getText 305 | */ 306 | int COMMENT = 9; 307 | 308 | /** 309 | * An XML document type declaration was just read. This token is 310 | * available from nextToken() only. 311 | * The unparsed text inside the doctype is available via 312 | * the getText() method. 313 | * 314 | * @see #nextToken 315 | * @see #getText 316 | */ 317 | int DOCDECL = 10; 318 | 319 | /** 320 | * This array can be used to convert the event type integer constants 321 | * such as START_TAG or TEXT to 322 | * to a string. For example, the value of TYPES[START_TAG] is 323 | * the string "START_TAG". 324 | * 325 | * This array is intended for diagnostic output only. Relying 326 | * on the contents of the array may be dangerous since malicious 327 | * applications may alter the array, although it is final, due 328 | * to limitations of the Java language. 329 | */ 330 | String [] TYPES = { 331 | "START_DOCUMENT", 332 | "END_DOCUMENT", 333 | "START_TAG", 334 | "END_TAG", 335 | "TEXT", 336 | "CDSECT", 337 | "ENTITY_REF", 338 | "IGNORABLE_WHITESPACE", 339 | "PROCESSING_INSTRUCTION", 340 | "COMMENT", 341 | "DOCDECL" 342 | }; 343 | 344 | 345 | // ---------------------------------------------------------------------------- 346 | // namespace related features 347 | 348 | /** 349 | * This feature determines whether the parser processes 350 | * namespaces. As for all features, the default value is false. 351 | *

NOTE: The value can not be changed during 352 | * parsing an must be set before parsing. 353 | * 354 | * @see #getFeature 355 | * @see #setFeature 356 | */ 357 | String FEATURE_PROCESS_NAMESPACES = 358 | "http://xmlpull.org/v1/doc/features.html#process-namespaces"; 359 | 360 | /** 361 | * This feature determines whether namespace attributes are 362 | * exposed via the attribute access methods. Like all features, 363 | * the default value is false. This feature cannot be changed 364 | * during parsing. 365 | * 366 | * @see #getFeature 367 | * @see #setFeature 368 | */ 369 | String FEATURE_REPORT_NAMESPACE_ATTRIBUTES = 370 | "http://xmlpull.org/v1/doc/features.html#report-namespace-prefixes"; 371 | 372 | /** 373 | * This feature determines whether the document declaration 374 | * is processed. If set to false, 375 | * the DOCDECL event type is reported by nextToken() 376 | * and ignored by next(). 377 | * 378 | * If this feature is activated, then the document declaration 379 | * must be processed by the parser. 380 | * 381 | *

Please note: If the document type declaration 382 | * was ignored, entity references may cause exceptions 383 | * later in the parsing process. 384 | * The default value of this feature is false. It cannot be changed 385 | * during parsing. 386 | * 387 | * @see #getFeature 388 | * @see #setFeature 389 | */ 390 | String FEATURE_PROCESS_DOCDECL = 391 | "http://xmlpull.org/v1/doc/features.html#process-docdecl"; 392 | 393 | /** 394 | * If this feature is activated, all validation errors as 395 | * defined in the XML 1.0 specification are reported. 396 | * This implies that FEATURE_PROCESS_DOCDECL is true and both, the 397 | * internal and external document type declaration will be processed. 398 | *

Please Note: This feature can not be changed 399 | * during parsing. The default value is false. 400 | * 401 | * @see #getFeature 402 | * @see #setFeature 403 | */ 404 | String FEATURE_VALIDATION = 405 | "http://xmlpull.org/v1/doc/features.html#validation"; 406 | 407 | /** 408 | * Use this call to change the general behaviour of the parser, 409 | * such as namespace processing or doctype declaration handling. 410 | * This method must be called before the first call to next or 411 | * nextToken. Otherwise, an exception is thrown. 412 | *

Example: call setFeature(FEATURE_PROCESS_NAMESPACES, true) in order 413 | * to switch on namespace processing. The initial settings correspond 414 | * to the properties requested from the XML Pull Parser factory. 415 | * If none were requested, all features are deactivated by default. 416 | * 417 | * @exception XmlPullParserException If the feature is not supported or can not be set 418 | * @exception IllegalArgumentException If string with the feature name is null 419 | */ 420 | void setFeature(String name, 421 | boolean state) throws XmlPullParserException; 422 | 423 | /** 424 | * Returns the current value of the given feature. 425 | *

Please note: unknown features are 426 | * always returned as false. 427 | * 428 | * @param name The name of feature to be retrieved. 429 | * @return The value of the feature. 430 | * @exception IllegalArgumentException if string the feature name is null 431 | */ 432 | 433 | boolean getFeature(String name); 434 | 435 | /** 436 | * Set the value of a property. 437 | * 438 | * The property name is any fully-qualified URI. 439 | * 440 | * @exception XmlPullParserException If the property is not supported or can not be set 441 | * @exception IllegalArgumentException If string with the property name is null 442 | */ 443 | void setProperty(String name, 444 | Object value) throws XmlPullParserException; 445 | 446 | /** 447 | * Look up the value of a property. 448 | * 449 | * The property name is any fully-qualified URI. 450 | *

NOTE: unknown properties are always 451 | * returned as null. 452 | * 453 | * @param name The name of property to be retrieved. 454 | * @return The value of named property. 455 | */ 456 | Object getProperty(String name); 457 | 458 | 459 | /** 460 | * Set the input source for parser to the given reader and 461 | * resets the parser. The event type is set to the initial value 462 | * START_DOCUMENT. 463 | * Setting the reader to null will just stop parsing and 464 | * reset parser state, 465 | * allowing the parser to free internal resources 466 | * such as parsing buffers. 467 | */ 468 | void setInput(Reader in) throws XmlPullParserException; 469 | 470 | 471 | /** 472 | * Sets the input stream the parser is going to process. 473 | * This call resets the parser state and sets the event type 474 | * to the initial value START_DOCUMENT. 475 | * 476 | *

NOTE: If an input encoding string is passed, 477 | * it MUST be used. Otherwise, 478 | * if inputEncoding is null, the parser SHOULD try to determine 479 | * input encoding following XML 1.0 specification (see below). 480 | * If encoding detection is supported then following feature 481 | * http://xmlpull.org/v1/doc/features.html#detect-encoding 482 | * MUST be true amd otherwise it must be false 483 | * 484 | * @param inputStream contains a raw byte input stream of possibly 485 | * unknown encoding (when inputEncoding is null). 486 | * 487 | * @param inputEncoding if not null it MUST be used as encoding for inputStream 488 | */ 489 | void setInput(InputStream inputStream, String inputEncoding) 490 | throws XmlPullParserException; 491 | 492 | /** 493 | * Returns the input encoding if known, null otherwise. 494 | * If setInput(InputStream, inputEncoding) was called with an inputEncoding 495 | * value other than null, this value must be returned 496 | * from this method. Otherwise, if inputEncoding is null and 497 | * the parser supports the encoding detection feature 498 | * (http://xmlpull.org/v1/doc/features.html#detect-encoding), 499 | * it must return the detected encoding. 500 | * If setInput(Reader) was called, null is returned. 501 | * After first call to next if XML declaration was present this method 502 | * will return encoding declared. 503 | */ 504 | String getInputEncoding(); 505 | 506 | /** 507 | * Set new value for entity replacement text as defined in 508 | * XML 1.0 Section 4.5 509 | * Construction of Internal Entity Replacement Text. 510 | * If FEATURE_PROCESS_DOCDECL or FEATURE_VALIDATION are set, calling this 511 | * function will result in an exception -- when processing of DOCDECL is 512 | * enabled, there is no need to the entity replacement text manually. 513 | * 514 | *

The motivation for this function is to allow very small 515 | * implementations of XMLPULL that will work in J2ME environments. 516 | * Though these implementations may not be able to process the document type 517 | * declaration, they still can work with known DTDs by using this function. 518 | * 519 | *

Please notes: The given value is used literally as replacement text 520 | * and it corresponds to declaring entity in DTD that has all special characters 521 | * escaped: left angle bracket is replaced with &lt;, ampersand with &amp; 522 | * and so on. 523 | * 524 | *

Note: The given value is the literal replacement text and must not 525 | * contain any other entity reference (if it contains any entity reference 526 | * there will be no further replacement). 527 | * 528 | *

Note: The list of pre-defined entity names will 529 | * always contain standard XML entities such as 530 | * amp (&amp;), lt (&lt;), gt (&gt;), quot (&quot;), and apos (&apos;). 531 | * Those cannot be redefined by this method! 532 | * 533 | * @see #setInput 534 | * @see #FEATURE_PROCESS_DOCDECL 535 | * @see #FEATURE_VALIDATION 536 | */ 537 | void defineEntityReplacementText( String entityName, 538 | String replacementText ) throws XmlPullParserException; 539 | 540 | /** 541 | * Returns the numbers of elements in the namespace stack for the given 542 | * depth. 543 | * If namespaces are not enabled, 0 is returned. 544 | * 545 | *

NOTE: when parser is on END_TAG then it is allowed to call 546 | * this function with getDepth()+1 argument to retrieve position of namespace 547 | * prefixes and URIs that were declared on corresponding START_TAG. 548 | *

NOTE: to retrieve list of namespaces declared in current element:

 549 |      *       XmlPullParser pp = ...
 550 |      *       int nsStart = pp.getNamespaceCount(pp.getDepth()-1);
 551 |      *       int nsEnd = pp.getNamespaceCount(pp.getDepth());
 552 |      *       for (int i = nsStart; i < nsEnd; i++) {
 553 |      *          String prefix = pp.getNamespacePrefix(i);
 554 |      *          String ns = pp.getNamespaceUri(i);
 555 |      *           // ...
 556 |      *      }
 557 |      * 
558 | * 559 | * @see #getNamespacePrefix 560 | * @see #getNamespaceUri 561 | * @see #getNamespace() 562 | * @see #getNamespace(String) 563 | */ 564 | int getNamespaceCount(int depth) throws XmlPullParserException; 565 | 566 | /** 567 | * Returns the namespace prefix for the given position 568 | * in the namespace stack. 569 | * Default namespace declaration (xmlns='...') will have null as prefix. 570 | * If the given index is out of range, an exception is thrown. 571 | *

Please note: when the parser is on an END_TAG, 572 | * namespace prefixes that were declared 573 | * in the corresponding START_TAG are still accessible 574 | * although they are no longer in scope. 575 | */ 576 | String getNamespacePrefix(int pos) throws XmlPullParserException; 577 | 578 | /** 579 | * Returns the namespace URI for the given position in the 580 | * namespace stack 581 | * If the position is out of range, an exception is thrown. 582 | *

NOTE: when parser is on END_TAG then namespace prefixes that were declared 583 | * in corresponding START_TAG are still accessible even though they are not in scope 584 | */ 585 | String getNamespaceUri(int pos) throws XmlPullParserException; 586 | 587 | /** 588 | * Returns the URI corresponding to the given prefix, 589 | * depending on current state of the parser. 590 | * 591 | *

If the prefix was not declared in the current scope, 592 | * null is returned. The default namespace is included 593 | * in the namespace table and is available via 594 | * getNamespace (null). 595 | * 596 | *

This method is a convenience method for 597 | * 598 | *

 599 |      *  for (int i = getNamespaceCount(getDepth ())-1; i >= 0; i--) {
 600 |      *   if (getNamespacePrefix(i).equals( prefix )) {
 601 |      *     return getNamespaceUri(i);
 602 |      *   }
 603 |      *  }
 604 |      *  return null;
 605 |      * 
606 | * 607 | *

Please note: parser implementations 608 | * may provide more efficient lookup, e.g. using a Hashtable. 609 | * The 'xml' prefix is bound to "http://www.w3.org/XML/1998/namespace", as 610 | * defined in the 611 | * Namespaces in XML 612 | * specification. Analogous, the 'xmlns' prefix is resolved to 613 | * http://www.w3.org/2000/xmlns/ 614 | * 615 | * @see #getNamespaceCount 616 | * @see #getNamespacePrefix 617 | * @see #getNamespaceUri 618 | */ 619 | String getNamespace (String prefix); 620 | 621 | 622 | // -------------------------------------------------------------------------- 623 | // miscellaneous reporting methods 624 | 625 | /** 626 | * Returns the current depth of the element. 627 | * Outside the root element, the depth is 0. The 628 | * depth is incremented by 1 when a start tag is reached. 629 | * The depth is decremented AFTER the end tag 630 | * event was observed. 631 | * 632 | *

 633 |      * <!-- outside -->     0
 634 |      * <root>                  1
 635 |      *   sometext                 1
 636 |      *     <foobar>         2
 637 |      *     </foobar>        2
 638 |      * </root>              1
 639 |      * <!-- outside -->     0
 640 |      * 
641 | */ 642 | int getDepth(); 643 | 644 | /** 645 | * Returns a short text describing the current parser state, including 646 | * the position, a 647 | * description of the current event and the data source if known. 648 | * This method is especially useful to provide meaningful 649 | * error messages and for debugging purposes. 650 | */ 651 | String getPositionDescription (); 652 | 653 | 654 | /** 655 | * Returns the current line number, starting from 1. 656 | * When the parser does not know the current line number 657 | * or can not determine it, -1 is returned (e.g. for WBXML). 658 | * 659 | * @return current line number or -1 if unknown. 660 | */ 661 | int getLineNumber(); 662 | 663 | /** 664 | * Returns the current column number, starting from 1. 665 | * When the parser does not know the current column number 666 | * or can not determine it, -1 is returned (e.g. for WBXML). 667 | * 668 | * @return current column number or -1 if unknown. 669 | */ 670 | int getColumnNumber(); 671 | 672 | 673 | // -------------------------------------------------------------------------- 674 | // TEXT related methods 675 | 676 | /** 677 | * Checks whether the current TEXT event contains only whitespace 678 | * characters. 679 | * For IGNORABLE_WHITESPACE, this is always true. 680 | * For TEXT and CDSECT, false is returned when the current event text 681 | * contains at least one non-white space character. For any other 682 | * event type an exception is thrown. 683 | * 684 | *

Please note: non-validating parsers are not 685 | * able to distinguish whitespace and ignorable whitespace, 686 | * except from whitespace outside the root element. Ignorable 687 | * whitespace is reported as separate event, which is exposed 688 | * via nextToken only. 689 | * 690 | */ 691 | boolean isWhitespace() throws XmlPullParserException; 692 | 693 | /** 694 | * Returns the text content of the current event as String. 695 | * The value returned depends on current event type, 696 | * for example for TEXT event it is element content 697 | * (this is typical case when next() is used). 698 | * 699 | * See description of nextToken() for detailed description of 700 | * possible returned values for different types of events. 701 | * 702 | *

NOTE: in case of ENTITY_REF, this method returns 703 | * the entity replacement text (or null if not available). This is 704 | * the only case where 705 | * getText() and getTextCharacters() return different values. 706 | * 707 | * @see #getEventType 708 | * @see #next 709 | * @see #nextToken 710 | */ 711 | String getText (); 712 | 713 | 714 | /** 715 | * Returns the buffer that contains the text of the current event, 716 | * as well as the start offset and length relevant for the current 717 | * event. See getText(), next() and nextToken() for description of possible returned values. 718 | * 719 | *

Please note: this buffer must not 720 | * be modified and its content MAY change after a call to 721 | * next() or nextToken(). This method will always return the 722 | * same value as getText(), except for ENTITY_REF. In the case 723 | * of ENTITY ref, getText() returns the replacement text and 724 | * this method returns the actual input buffer containing the 725 | * entity name. 726 | * If getText() returns null, this method returns null as well and 727 | * the values returned in the holder array MUST be -1 (both start 728 | * and length). 729 | * 730 | * @see #getText 731 | * @see #next 732 | * @see #nextToken 733 | * 734 | * @param holderForStartAndLength Must hold an 2-element int array 735 | * into which the start offset and length values will be written. 736 | * @return char buffer that contains the text of the current event 737 | * (null if the current event has no text associated). 738 | */ 739 | char[] getTextCharacters(int [] holderForStartAndLength); 740 | 741 | // -------------------------------------------------------------------------- 742 | // START_TAG / END_TAG shared methods 743 | 744 | /** 745 | * Returns the namespace URI of the current element. 746 | * The default namespace is represented 747 | * as empty string. 748 | * If namespaces are not enabled, an empty String ("") is always returned. 749 | * The current event must be START_TAG or END_TAG; otherwise, 750 | * null is returned. 751 | */ 752 | String getNamespace (); 753 | 754 | /** 755 | * For START_TAG or END_TAG events, the (local) name of the current 756 | * element is returned when namespaces are enabled. When namespace 757 | * processing is disabled, the raw name is returned. 758 | * For ENTITY_REF events, the entity name is returned. 759 | * If the current event is not START_TAG, END_TAG, or ENTITY_REF, 760 | * null is returned. 761 | *

Please note: To reconstruct the raw element name 762 | * when namespaces are enabled and the prefix is not null, 763 | * you will need to add the prefix and a colon to localName.. 764 | * 765 | */ 766 | String getName(); 767 | 768 | /** 769 | * Returns the prefix of the current element. 770 | * If the element is in the default namespace (has no prefix), 771 | * null is returned. 772 | * If namespaces are not enabled, or the current event 773 | * is not START_TAG or END_TAG, null is returned. 774 | */ 775 | String getPrefix(); 776 | 777 | /** 778 | * Returns true if the current event is START_TAG and the tag 779 | * is degenerated 780 | * (e.g. <foobar/>). 781 | *

NOTE: if the parser is not on START_TAG, an exception 782 | * will be thrown. 783 | */ 784 | boolean isEmptyElementTag() throws XmlPullParserException; 785 | 786 | // -------------------------------------------------------------------------- 787 | // START_TAG Attributes retrieval methods 788 | 789 | /** 790 | * Returns the number of attributes of the current start tag, or 791 | * -1 if the current event type is not START_TAG 792 | * 793 | * @see #getAttributeNamespace 794 | * @see #getAttributeName 795 | * @see #getAttributePrefix 796 | * @see #getAttributeValue 797 | */ 798 | int getAttributeCount(); 799 | 800 | /** 801 | * Returns the namespace URI of the attribute 802 | * with the given index (starts from 0). 803 | * Returns an empty string ("") if namespaces are not enabled 804 | * or the attribute has no namespace. 805 | * Throws an IndexOutOfBoundsException if the index is out of range 806 | * or the current event type is not START_TAG. 807 | * 808 | *

NOTE: if FEATURE_REPORT_NAMESPACE_ATTRIBUTES is set 809 | * then namespace attributes (xmlns:ns='...') must be reported 810 | * with namespace 811 | * http://www.w3.org/2000/xmlns/ 812 | * (visit this URL for description!). 813 | * The default namespace attribute (xmlns="...") will be reported with empty namespace. 814 | *

NOTE:The xml prefix is bound as defined in 815 | * Namespaces in XML 816 | * specification to "http://www.w3.org/XML/1998/namespace". 817 | * 818 | * @param index zero-based index of attribute 819 | * @return attribute namespace, 820 | * empty string ("") is returned if namespaces processing is not enabled or 821 | * namespaces processing is enabled but attribute has no namespace (it has no prefix). 822 | */ 823 | String getAttributeNamespace (int index); 824 | 825 | /** 826 | * Returns the local name of the specified attribute 827 | * if namespaces are enabled or just attribute name if namespaces are disabled. 828 | * Throws an IndexOutOfBoundsException if the index is out of range 829 | * or current event type is not START_TAG. 830 | * 831 | * @param index zero-based index of attribute 832 | * @return attribute name (null is never returned) 833 | */ 834 | String getAttributeName (int index); 835 | 836 | /** 837 | * Returns the prefix of the specified attribute 838 | * Returns null if the element has no prefix. 839 | * If namespaces are disabled it will always return null. 840 | * Throws an IndexOutOfBoundsException if the index is out of range 841 | * or current event type is not START_TAG. 842 | * 843 | * @param index zero-based index of attribute 844 | * @return attribute prefix or null if namespaces processing is not enabled. 845 | */ 846 | String getAttributePrefix(int index); 847 | 848 | /** 849 | * Returns the type of the specified attribute 850 | * If parser is non-validating it MUST return CDATA. 851 | * 852 | * @param index zero-based index of attribute 853 | * @return attribute type (null is never returned) 854 | */ 855 | String getAttributeType(int index); 856 | 857 | /** 858 | * Returns if the specified attribute was not in input was declared in XML. 859 | * If parser is non-validating it MUST always return false. 860 | * This information is part of XML infoset: 861 | * 862 | * @param index zero-based index of attribute 863 | * @return false if attribute was in input 864 | */ 865 | boolean isAttributeDefault(int index); 866 | 867 | /** 868 | * Returns the given attributes value. 869 | * Throws an IndexOutOfBoundsException if the index is out of range 870 | * or current event type is not START_TAG. 871 | * 872 | *

NOTE: attribute value must be normalized 873 | * (including entity replacement text if PROCESS_DOCDECL is false) as described in 874 | * XML 1.0 section 875 | * 3.3.3 Attribute-Value Normalization 876 | * 877 | * @see #defineEntityReplacementText 878 | * 879 | * @param index zero-based index of attribute 880 | * @return value of attribute (null is never returned) 881 | */ 882 | String getAttributeValue(int index); 883 | 884 | /** 885 | * Returns the attributes value identified by namespace URI and namespace localName. 886 | * If namespaces are disabled namespace must be null. 887 | * If current event type is not START_TAG then IndexOutOfBoundsException will be thrown. 888 | * 889 | *

NOTE: attribute value must be normalized 890 | * (including entity replacement text if PROCESS_DOCDECL is false) as described in 891 | * XML 1.0 section 892 | * 3.3.3 Attribute-Value Normalization 893 | * 894 | * @see #defineEntityReplacementText 895 | * 896 | * @param namespace Namespace of the attribute if namespaces are enabled otherwise must be null 897 | * @param name If namespaces enabled local name of attribute otherwise just attribute name 898 | * @return value of attribute or null if attribute with given name does not exist 899 | */ 900 | String getAttributeValue(String namespace, 901 | String name); 902 | 903 | // -------------------------------------------------------------------------- 904 | // actual parsing methods 905 | 906 | /** 907 | * Returns the type of the current event (START_TAG, END_TAG, TEXT, etc.) 908 | * 909 | * @see #next() 910 | * @see #nextToken() 911 | */ 912 | int getEventType() 913 | throws XmlPullParserException; 914 | 915 | /** 916 | * Get next parsing event - element content will be coalesced and only one 917 | * TEXT event must be returned for whole element content 918 | * (comments and processing instructions will be ignored and entity references 919 | * must be expanded or exception must be thrown if entity reference can not be expanded). 920 | * If element content is empty (content is "") then no TEXT event will be reported. 921 | * 922 | *

NOTE: empty element (such as <tag/>) will be reported 923 | * with two separate events: START_TAG, END_TAG - it must be so to preserve 924 | * parsing equivalency of empty element to <tag></tag>. 925 | * (see isEmptyElementTag ()) 926 | * 927 | * @see #isEmptyElementTag 928 | * @see #START_TAG 929 | * @see #TEXT 930 | * @see #END_TAG 931 | * @see #END_DOCUMENT 932 | */ 933 | 934 | int next() 935 | throws XmlPullParserException, IOException; 936 | 937 | 938 | /** 939 | * This method works similarly to next() but will expose 940 | * additional event types (COMMENT, CDSECT, DOCDECL, ENTITY_REF, PROCESSING_INSTRUCTION, or 941 | * IGNORABLE_WHITESPACE) if they are available in input. 942 | * 943 | *

If special feature 944 | * FEATURE_XML_ROUNDTRIP 945 | * (identified by URI: http://xmlpull.org/v1/doc/features.html#xml-roundtrip) 946 | * is enabled it is possible to do XML document round trip ie. reproduce 947 | * exectly on output the XML input using getText(): 948 | * returned content is always unnormalized (exactly as in input). 949 | * Otherwise returned content is end-of-line normalized as described 950 | * XML 1.0 End-of-Line Handling 951 | * and. Also when this feature is enabled exact content of START_TAG, END_TAG, 952 | * DOCDECL and PROCESSING_INSTRUCTION is available. 953 | * 954 | *

Here is the list of tokens that can be returned from nextToken() 955 | * and what getText() and getTextCharacters() returns:

956 | *
START_DOCUMENT
null 957 | *
END_DOCUMENT
null 958 | *
START_TAG
null unless FEATURE_XML_ROUNDTRIP 959 | * enabled and then returns XML tag, ex: <tag attr='val'> 960 | *
END_TAG
null unless FEATURE_XML_ROUNDTRIP 961 | * id enabled and then returns XML tag, ex: </tag> 962 | *
TEXT
return element content. 963 | *
Note: that element content may be delivered in multiple consecutive TEXT events. 964 | *
IGNORABLE_WHITESPACE
return characters that are determined to be ignorable white 965 | * space. If the FEATURE_XML_ROUNDTRIP is enabled all whitespace content outside root 966 | * element will always reported as IGNORABLE_WHITESPACE otherwise reporting is optional. 967 | *
Note: that element content may be delivered in multiple consecutive IGNORABLE_WHITESPACE events. 968 | *
CDSECT
969 | * return text inside CDATA 970 | * (ex. 'fo<o' from <!CDATA[fo<o]]>) 971 | *
PROCESSING_INSTRUCTION
972 | * if FEATURE_XML_ROUNDTRIP is true 973 | * return exact PI content ex: 'pi foo' from <?pi foo?> 974 | * otherwise it may be exact PI content or concatenation of PI target, 975 | * space and data so for example for 976 | * <?target data?> string "target data" may 977 | * be returned if FEATURE_XML_ROUNDTRIP is false. 978 | *
COMMENT
return comment content ex. 'foo bar' from <!--foo bar--> 979 | *
ENTITY_REF
getText() MUST return entity replacement text if PROCESS_DOCDECL is false 980 | * otherwise getText() MAY return null, 981 | * additionally getTextCharacters() MUST return entity name 982 | * (for example 'entity_name' for &entity_name;). 983 | *
NOTE: this is the only place where value returned from getText() and 984 | * getTextCharacters() are different 985 | *
NOTE: it is user responsibility to resolve entity reference 986 | * if PROCESS_DOCDECL is false and there is no entity replacement text set in 987 | * defineEntityReplacementText() method (getText() will be null) 988 | *
NOTE: character entities (ex. &#32;) and standard entities such as 989 | * &amp; &lt; &gt; &quot; &apos; are reported as well 990 | * and are not reported as TEXT tokens but as ENTITY_REF tokens! 991 | * This requirement is added to allow to do roundtrip of XML documents! 992 | *
DOCDECL
993 | * if FEATURE_XML_ROUNDTRIP is true or PROCESS_DOCDECL is false 994 | * then return what is inside of DOCDECL for example it returns:
 995 |      * " titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
 996 |      * [<!ENTITY % active.links "INCLUDE">]"
997 | *

for input document that contained:

 998 |      * <!DOCTYPE titlepage SYSTEM "http://www.foo.bar/dtds/typo.dtd"
 999 |      * [<!ENTITY % active.links "INCLUDE">]>
1000 | * otherwise if FEATURE_XML_ROUNDTRIP is false and PROCESS_DOCDECL is true 1001 | * then what is returned is undefined (it may be even null) 1002 | *
1003 | *
1004 | * 1005 | *

NOTE: there is no guarantee that there will only one TEXT or 1006 | * IGNORABLE_WHITESPACE event from nextToken() as parser may chose to deliver element content in 1007 | * multiple tokens (dividing element content into chunks) 1008 | * 1009 | *

NOTE: whether returned text of token is end-of-line normalized 1010 | * is depending on FEATURE_XML_ROUNDTRIP. 1011 | * 1012 | *

NOTE: XMLDecl (<?xml ...?>) is not reported but its content 1013 | * is available through optional properties (see class description above). 1014 | * 1015 | * @see #next 1016 | * @see #START_TAG 1017 | * @see #TEXT 1018 | * @see #END_TAG 1019 | * @see #END_DOCUMENT 1020 | * @see #COMMENT 1021 | * @see #DOCDECL 1022 | * @see #PROCESSING_INSTRUCTION 1023 | * @see #ENTITY_REF 1024 | * @see #IGNORABLE_WHITESPACE 1025 | */ 1026 | int nextToken() 1027 | throws XmlPullParserException, IOException; 1028 | 1029 | //----------------------------------------------------------------------------- 1030 | // utility methods to mak XML parsing easier ... 1031 | 1032 | /** 1033 | * Test if the current event is of the given type and if the 1034 | * namespace and name do match. null will match any namespace 1035 | * and any name. If the test is not passed, an exception is 1036 | * thrown. The exception text indicates the parser position, 1037 | * the expected event and the current event that is not meeting the 1038 | * requirement. 1039 | * 1040 | *

Essentially it does this 1041 | *

1042 |      *  if (type != getEventType()
1043 |      *  || (namespace != null &&  !namespace.equals( getNamespace () ) )
1044 |      *  || (name != null &&  !name.equals( getName() ) ) )
1045 |      *     throw new XmlPullParserException( "expected "+ TYPES[ type ]+getPositionDescription());
1046 |      * 
1047 | */ 1048 | void require(int type, String namespace, String name) 1049 | throws XmlPullParserException, IOException; 1050 | 1051 | /** 1052 | * If current event is START_TAG then if next element is TEXT then element content is returned 1053 | * or if next event is END_TAG then empty string is returned, otherwise exception is thrown. 1054 | * After calling this function successfully parser will be positioned on END_TAG. 1055 | * 1056 | *

The motivation for this function is to allow to parse consistently both 1057 | * empty elements and elements that has non empty content, for example for input:

    1058 | *
  1. <tag>foo</tag> 1059 | *
  2. <tag></tag> (which is equivalent to <tag/> 1060 | * both input can be parsed with the same code: 1061 | *
    1062 |      *   p.nextTag()
    1063 |      *   p.requireEvent(p.START_TAG, "", "tag");
    1064 |      *   String content = p.nextText();
    1065 |      *   p.requireEvent(p.END_TAG, "", "tag");
    1066 |      * 
    1067 | * This function together with nextTag make it very easy to parse XML that has 1068 | * no mixed content. 1069 | * 1070 | * 1071 | *

    Essentially it does this 1072 | *

    1073 |      *  if(getEventType() != START_TAG) {
    1074 |      *     throw new XmlPullParserException(
    1075 |      *       "parser must be on START_TAG to read next text", this, null);
    1076 |      *  }
    1077 |      *  int eventType = next();
    1078 |      *  if(eventType == TEXT) {
    1079 |      *     String result = getText();
    1080 |      *     eventType = next();
    1081 |      *     if(eventType != END_TAG) {
    1082 |      *       throw new XmlPullParserException(
    1083 |      *          "event TEXT it must be immediately followed by END_TAG", this, null);
    1084 |      *      }
    1085 |      *      return result;
    1086 |      *  } else if(eventType == END_TAG) {
    1087 |      *     return "";
    1088 |      *  } else {
    1089 |      *     throw new XmlPullParserException(
    1090 |      *       "parser must be on START_TAG or TEXT to read text", this, null);
    1091 |      *  }
    1092 |      * 
    1093 | * 1094 | *

    Warning: Prior to API level 14, the pull parser returned by {@code 1095 | * android.util.Xml} did not always advance to the END_TAG event when this method was called. 1096 | * Work around by using manually advancing after calls to nextText():

    1097 |      *  String text = xpp.nextText();
    1098 |      *  if (xpp.getEventType() != XmlPullParser.END_TAG) {
    1099 |      *      xpp.next();
    1100 |      *  }
    1101 |      * 
    1102 | */ 1103 | String nextText() throws XmlPullParserException, IOException; 1104 | 1105 | /** 1106 | * Call next() and return event if it is START_TAG or END_TAG 1107 | * otherwise throw an exception. 1108 | * It will skip whitespace TEXT before actual tag if any. 1109 | * 1110 | *

    essentially it does this 1111 | *

    1112 |      *   int eventType = next();
    1113 |      *   if(eventType == TEXT &&  isWhitespace()) {   // skip whitespace
    1114 |      *      eventType = next();
    1115 |      *   }
    1116 |      *   if (eventType != START_TAG &&  eventType != END_TAG) {
    1117 |      *      throw new XmlPullParserException("expected start or end tag", this, null);
    1118 |      *   }
    1119 |      *   return eventType;
    1120 |      * 
    1121 | */ 1122 | int nextTag() throws XmlPullParserException, IOException; 1123 | 1124 | } -------------------------------------------------------------------------------- /makeabx/src/org/xmlpull/v1/XmlPullParserException.java: -------------------------------------------------------------------------------- 1 | /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ 2 | // for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) 3 | 4 | package org.xmlpull.v1; 5 | 6 | /** 7 | * This exception is thrown to signal XML Pull Parser related faults. 8 | * 9 | * @author Aleksander Slominski 10 | */ 11 | public class XmlPullParserException extends Exception { 12 | protected Throwable detail; 13 | protected int row = -1; 14 | protected int column = -1; 15 | 16 | /* public XmlPullParserException() { 17 | }*/ 18 | 19 | public XmlPullParserException(String s) { 20 | super(s); 21 | } 22 | 23 | /* 24 | public XmlPullParserException(String s, Throwable thrwble) { 25 | super(s); 26 | this.detail = thrwble; 27 | } 28 | 29 | public XmlPullParserException(String s, int row, int column) { 30 | super(s); 31 | this.row = row; 32 | this.column = column; 33 | } 34 | */ 35 | 36 | public XmlPullParserException(String msg, XmlPullParser parser, Throwable chain) { 37 | super ((msg == null ? "" : msg+" ") 38 | + (parser == null ? "" : "(position:"+parser.getPositionDescription()+") ") 39 | + (chain == null ? "" : "caused by: "+chain)); 40 | 41 | if (parser != null) { 42 | this.row = parser.getLineNumber(); 43 | this.column = parser.getColumnNumber(); 44 | } 45 | this.detail = chain; 46 | } 47 | 48 | public Throwable getDetail() { return detail; } 49 | // public void setDetail(Throwable cause) { this.detail = cause; } 50 | public int getLineNumber() { return row; } 51 | public int getColumnNumber() { return column; } 52 | 53 | /* 54 | public String getMessage() { 55 | if(detail == null) 56 | return super.getMessage(); 57 | else 58 | return super.getMessage() + "; nested exception is: \n\t" 59 | + detail.getMessage(); 60 | } 61 | */ 62 | 63 | //NOTE: code that prints this and detail is difficult in J2ME 64 | public void printStackTrace() { 65 | if (detail == null) { 66 | super.printStackTrace(); 67 | } else { 68 | synchronized(System.err) { 69 | System.err.println(super.getMessage() + "; nested exception is:"); 70 | detail.printStackTrace(); 71 | } 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /makeabx/src/org/xmlpull/v1/XmlPullParserFactory.java: -------------------------------------------------------------------------------- 1 | /* -*- c-basic-offset: 4; indent-tabs-mode: nil; -*- //------100-columns-wide------>|*/ 2 | // for license please see accompanying LICENSE.txt file (available also at http://www.xmlpull.org/) 3 | 4 | package org.xmlpull.v1; 5 | 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | /** 11 | * This class is used to create implementations of XML Pull Parser defined in XMPULL V1 API. 12 | * 13 | * @see XmlPullParser 14 | * 15 | * @author Aleksander Slominski 16 | * @author Stefan Haustein 17 | */ 18 | 19 | public class XmlPullParserFactory { 20 | 21 | public static final String PROPERTY_NAME = "org.xmlpull.v1.XmlPullParserFactory"; 22 | protected ArrayList parserClasses; 23 | protected ArrayList serializerClasses; 24 | 25 | /** Unused, but we have to keep it because it's public API. */ 26 | protected String classNamesLocation = null; 27 | 28 | // features are kept there 29 | // TODO: This can't be made final because it's a public API. 30 | protected HashMap features = new HashMap(); 31 | 32 | /** 33 | * Protected constructor to be called by factory implementations. 34 | */ 35 | protected XmlPullParserFactory() { 36 | parserClasses = new ArrayList(); 37 | serializerClasses = new ArrayList(); 38 | 39 | try { 40 | parserClasses.add(Class.forName("com.android.org.kxml2.io.KXmlParser")); 41 | serializerClasses.add(Class.forName("com.android.org.kxml2.io.KXmlSerializer")); 42 | } catch (ClassNotFoundException e) { 43 | throw new AssertionError(); 44 | } 45 | } 46 | 47 | /** 48 | * Set the features to be set when XML Pull Parser is created by this factory. 49 | *

    NOTE: factory features are not used for XML Serializer. 50 | * 51 | * @param name string with URI identifying feature 52 | * @param state if true feature will be set; if false will be ignored 53 | */ 54 | public void setFeature(String name, boolean state) throws XmlPullParserException { 55 | features.put(name, state); 56 | } 57 | 58 | 59 | /** 60 | * Return the current value of the feature with given name. 61 | *

    NOTE: factory features are not used for XML Serializer. 62 | * 63 | * @param name The name of feature to be retrieved. 64 | * @return The value of named feature. 65 | * Unknown features are always returned as false 66 | */ 67 | public boolean getFeature(String name) { 68 | Boolean value = features.get(name); 69 | return value != null ? value.booleanValue() : false; 70 | } 71 | 72 | /** 73 | * Specifies that the parser produced by this factory will provide 74 | * support for XML namespaces. 75 | * By default the value of this is set to false. 76 | * 77 | * @param awareness true if the parser produced by this code 78 | * will provide support for XML namespaces; false otherwise. 79 | */ 80 | public void setNamespaceAware(boolean awareness) { 81 | features.put (XmlPullParser.FEATURE_PROCESS_NAMESPACES, awareness); 82 | } 83 | 84 | /** 85 | * Indicates whether or not the factory is configured to produce 86 | * parsers which are namespace aware 87 | * (it simply set feature XmlPullParser.FEATURE_PROCESS_NAMESPACES to true or false). 88 | * 89 | * @return true if the factory is configured to produce parsers 90 | * which are namespace aware; false otherwise. 91 | */ 92 | public boolean isNamespaceAware() { 93 | return getFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES); 94 | } 95 | 96 | /** 97 | * Specifies that the parser produced by this factory will be validating 98 | * (it simply set feature XmlPullParser.FEATURE_VALIDATION to true or false). 99 | * 100 | * By default the value of this is set to false. 101 | * 102 | * @param validating - if true the parsers created by this factory must be validating. 103 | */ 104 | public void setValidating(boolean validating) { 105 | features.put(XmlPullParser.FEATURE_VALIDATION, validating); 106 | } 107 | 108 | /** 109 | * Indicates whether or not the factory is configured to produce parsers 110 | * which validate the XML content during parse. 111 | * 112 | * @return true if the factory is configured to produce parsers 113 | * which validate the XML content during parse; false otherwise. 114 | */ 115 | 116 | public boolean isValidating() { 117 | return getFeature(XmlPullParser.FEATURE_VALIDATION); 118 | } 119 | 120 | /** 121 | * Creates a new instance of a XML Pull Parser 122 | * using the currently configured factory features. 123 | * 124 | * @return A new instance of a XML Pull Parser. 125 | */ 126 | public XmlPullParser newPullParser() throws XmlPullParserException { 127 | final XmlPullParser pp = getParserInstance(); 128 | for (Map.Entry entry : features.entrySet()) { 129 | // NOTE: This test is needed for compatibility reasons. We guarantee 130 | // that we only set a feature on a parser if its value is true. 131 | if (entry.getValue()) { 132 | pp.setFeature(entry.getKey(), entry.getValue()); 133 | } 134 | } 135 | 136 | return pp; 137 | } 138 | 139 | private XmlPullParser getParserInstance() throws XmlPullParserException { 140 | ArrayList exceptions = null; 141 | 142 | if (parserClasses != null && !parserClasses.isEmpty()) { 143 | exceptions = new ArrayList(); 144 | for (Object o : parserClasses) { 145 | try { 146 | if (o != null) { 147 | Class parserClass = (Class) o; 148 | return (XmlPullParser) parserClass.newInstance(); 149 | } 150 | } catch (InstantiationException e) { 151 | exceptions.add(e); 152 | } catch (IllegalAccessException e) { 153 | exceptions.add(e); 154 | } catch (ClassCastException e) { 155 | exceptions.add(e); 156 | } 157 | } 158 | } 159 | 160 | throw newInstantiationException("Invalid parser class list", exceptions); 161 | } 162 | 163 | private XmlSerializer getSerializerInstance() throws XmlPullParserException { 164 | ArrayList exceptions = null; 165 | 166 | if (serializerClasses != null && !serializerClasses.isEmpty()) { 167 | exceptions = new ArrayList(); 168 | for (Object o : serializerClasses) { 169 | try { 170 | if (o != null) { 171 | Class serializerClass = (Class) o; 172 | return (XmlSerializer) serializerClass.newInstance(); 173 | } 174 | } catch (InstantiationException e) { 175 | exceptions.add(e); 176 | } catch (IllegalAccessException e) { 177 | exceptions.add(e); 178 | } catch (ClassCastException e) { 179 | exceptions.add(e); 180 | } 181 | } 182 | } 183 | 184 | throw newInstantiationException("Invalid serializer class list", exceptions); 185 | } 186 | 187 | private static XmlPullParserException newInstantiationException(String message, 188 | ArrayList exceptions) { 189 | if (exceptions == null || exceptions.isEmpty()) { 190 | return new XmlPullParserException(message); 191 | } else { 192 | XmlPullParserException exception = new XmlPullParserException(message); 193 | for (Exception ex : exceptions) { 194 | exception.addSuppressed(ex); 195 | } 196 | 197 | return exception; 198 | } 199 | } 200 | 201 | /** 202 | * Creates a new instance of a XML Serializer. 203 | * 204 | *

    NOTE: factory features are not used for XML Serializer. 205 | * 206 | * @return A new instance of a XML Serializer. 207 | * @throws XmlPullParserException if a parser cannot be created which satisfies the 208 | * requested configuration. 209 | */ 210 | 211 | public XmlSerializer newSerializer() throws XmlPullParserException { 212 | return getSerializerInstance(); 213 | } 214 | 215 | /** 216 | * Creates a new instance of a PullParserFactory that can be used 217 | * to create XML pull parsers. The factory will always return instances 218 | * of Android's built-in {@link XmlPullParser} and {@link XmlSerializer}. 219 | */ 220 | public static XmlPullParserFactory newInstance () throws XmlPullParserException { 221 | return new XmlPullParserFactory(); 222 | } 223 | 224 | /** 225 | * Creates a factory that always returns instances of Android's built-in 226 | * {@link XmlPullParser} and {@link XmlSerializer} implementation. This 227 | * does not support factories capable of creating arbitrary parser 228 | * and serializer implementations. Both arguments to this method are unused. 229 | */ 230 | public static XmlPullParserFactory newInstance (String unused, Class unused2) 231 | throws XmlPullParserException { 232 | return newInstance(); 233 | } 234 | } -------------------------------------------------------------------------------- /makeabx/src/org/xmlpull/v1/XmlSerializer.java: -------------------------------------------------------------------------------- 1 | package org.xmlpull.v1; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | import java.io.Writer; 6 | 7 | /** 8 | * Define an interface to serialization of XML Infoset. 9 | * This interface abstracts away if serialized XML is XML 1.0 compatible text or 10 | * other formats of XML 1.0 serializations (such as binary XML for example with WBXML). 11 | * 12 | *

    PLEASE NOTE: This interface will be part of XmlPull 1.2 API. 13 | * It is included as basis for discussion. It may change in any way. 14 | * 15 | *

    Exceptions that may be thrown are: IOException or runtime exception 16 | * (more runtime exceptions can be thrown but are not declared and as such 17 | * have no semantics defined for this interface): 18 | *

      19 | *
    • IllegalArgumentException - for almost all methods to signal that 20 | * argument is illegal 21 | *
    • IllegalStateException - to signal that call has good arguments but 22 | * is not expected here (violation of contract) and for features/properties 23 | * when requesting setting unimplemented feature/property 24 | * (UnsupportedOperationException would be better but it is not in MIDP) 25 | *
    26 | * 27 | *

    NOTE: writing CDSECT, ENTITY_REF, IGNORABLE_WHITESPACE, 28 | * PROCESSING_INSTRUCTION, COMMENT, and DOCDECL in some implementations 29 | * may not be supported (for example when serializing to WBXML). 30 | * In such case IllegalStateException will be thrown and it is recommended 31 | * to use an optional feature to signal that implementation is not 32 | * supporting this kind of output. 33 | */ 34 | 35 | public interface XmlSerializer { 36 | 37 | /** 38 | * Set feature identified by name (recommended to be URI for uniqueness). 39 | * Some well known optional features are defined in 40 | * 41 | * http://www.xmlpull.org/v1/doc/features.html. 42 | * 43 | * If feature is not recognized or can not be set 44 | * then IllegalStateException MUST be thrown. 45 | * 46 | * @exception IllegalStateException If the feature is not supported or can not be set 47 | */ 48 | void setFeature(String name, 49 | boolean state) 50 | throws IllegalArgumentException, IllegalStateException; 51 | 52 | 53 | /** 54 | * Return the current value of the feature with given name. 55 | *

    NOTE: unknown properties are always returned as null 56 | * 57 | * @param name The name of feature to be retrieved. 58 | * @return The value of named feature. 59 | * @exception IllegalArgumentException if feature string is null 60 | */ 61 | boolean getFeature(String name); 62 | 63 | 64 | /** 65 | * Set the value of a property. 66 | * (the property name is recommended to be URI for uniqueness). 67 | * Some well known optional properties are defined in 68 | * 69 | * http://www.xmlpull.org/v1/doc/properties.html. 70 | * 71 | * If property is not recognized or can not be set 72 | * then IllegalStateException MUST be thrown. 73 | * 74 | * @exception IllegalStateException if the property is not supported or can not be set 75 | */ 76 | void setProperty(String name, 77 | Object value) 78 | throws IllegalArgumentException, IllegalStateException; 79 | 80 | /** 81 | * Look up the value of a property. 82 | * 83 | * The property name is any fully-qualified URI. I 84 | *

    NOTE: unknown properties are always returned as null 85 | * 86 | * @param name The name of property to be retrieved. 87 | * @return The value of named property. 88 | */ 89 | Object getProperty(String name); 90 | 91 | /** 92 | * Set to use binary output stream with given encoding. 93 | */ 94 | void setOutput (OutputStream os, String encoding) 95 | throws IOException, IllegalArgumentException, IllegalStateException; 96 | 97 | /** 98 | * Set the output to the given writer. 99 | *

    WARNING no information about encoding is available! 100 | */ 101 | void setOutput (Writer writer) 102 | throws IOException, IllegalArgumentException, IllegalStateException; 103 | 104 | /** 105 | * Write <?xml declaration with encoding (if encoding not null) 106 | * and standalone flag (if standalone not null) 107 | * This method can only be called just after setOutput. 108 | */ 109 | void startDocument (String encoding, Boolean standalone) 110 | throws IOException, IllegalArgumentException, IllegalStateException; 111 | 112 | /** 113 | * Finish writing. All unclosed start tags will be closed and output 114 | * will be flushed. After calling this method no more output can be 115 | * serialized until next call to setOutput() 116 | */ 117 | void endDocument () 118 | throws IOException, IllegalArgumentException, IllegalStateException; 119 | 120 | /** 121 | * Binds the given prefix to the given namespace. 122 | * This call is valid for the next element including child elements. 123 | * The prefix and namespace MUST be always declared even if prefix 124 | * is not used in element (startTag() or attribute()) - for XML 1.0 125 | * it must result in declaring xmlns:prefix='namespace' 126 | * (or xmlns:prefix="namespace" depending what character is used 127 | * to quote attribute value). 128 | * 129 | *

    NOTE: this method MUST be called directly before startTag() 130 | * and if anything but startTag() or setPrefix() is called next there will be exception. 131 | *

    NOTE: prefixes "xml" and "xmlns" are already bound 132 | * and can not be redefined see: 133 | * Namespaces in XML Errata. 134 | *

    NOTE: to set default namespace use as prefix empty string. 135 | * 136 | * @param prefix must be not null (or IllegalArgumentException is thrown) 137 | * @param namespace must be not null 138 | */ 139 | void setPrefix (String prefix, String namespace) 140 | throws IOException, IllegalArgumentException, IllegalStateException; 141 | 142 | /** 143 | * Return namespace that corresponds to given prefix 144 | * If there is no prefix bound to this namespace return null 145 | * but if generatePrefix is false then return generated prefix. 146 | * 147 | *

    NOTE: if the prefix is empty string "" and default namespace is bound 148 | * to this prefix then empty string ("") is returned. 149 | * 150 | *

    NOTE: prefixes "xml" and "xmlns" are already bound 151 | * will have values as defined 152 | * Namespaces in XML specification 153 | */ 154 | String getPrefix (String namespace, boolean generatePrefix) 155 | throws IllegalArgumentException; 156 | 157 | /** 158 | * Returns the current depth of the element. 159 | * Outside the root element, the depth is 0. The 160 | * depth is incremented by 1 when startTag() is called. 161 | * The depth is decremented after the call to endTag() 162 | * event was observed. 163 | * 164 | *

    165 |      * <!-- outside -->     0
    166 |      * <root>               1
    167 |      *   sometext                 1
    168 |      *     <foobar>         2
    169 |      *     </foobar>        2
    170 |      * </root>              1
    171 |      * <!-- outside -->     0
    172 |      * 
    173 | */ 174 | int getDepth(); 175 | 176 | /** 177 | * Returns the namespace URI of the current element as set by startTag(). 178 | * 179 | *

    NOTE: that means in particular that:

      180 | *
    • if there was startTag("", ...) then getNamespace() returns "" 181 | *
    • if there was startTag(null, ...) then getNamespace() returns null 182 | *
    183 | * 184 | * @return namespace set by startTag() that is currently in scope 185 | */ 186 | String getNamespace (); 187 | 188 | /** 189 | * Returns the name of the current element as set by startTag(). 190 | * It can only be null before first call to startTag() 191 | * or when last endTag() is called to close first startTag(). 192 | * 193 | * @return namespace set by startTag() that is currently in scope 194 | */ 195 | String getName(); 196 | 197 | /** 198 | * Writes a start tag with the given namespace and name. 199 | * If there is no prefix defined for the given namespace, 200 | * a prefix will be defined automatically. 201 | * The explicit prefixes for namespaces can be established by calling setPrefix() 202 | * immediately before this method. 203 | * If namespace is null no namespace prefix is printed but just name. 204 | * If namespace is empty string then serializer will make sure that 205 | * default empty namespace is declared (in XML 1.0 xmlns='') 206 | * or throw IllegalStateException if default namespace is already bound 207 | * to non-empty string. 208 | */ 209 | XmlSerializer startTag (String namespace, String name) 210 | throws IOException, IllegalArgumentException, IllegalStateException; 211 | 212 | /** 213 | * Write an attribute. Calls to attribute() MUST follow a call to 214 | * startTag() immediately. If there is no prefix defined for the 215 | * given namespace, a prefix will be defined automatically. 216 | * If namespace is null or empty string 217 | * no namespace prefix is printed but just name. 218 | */ 219 | XmlSerializer attribute (String namespace, String name, String value) 220 | throws IOException, IllegalArgumentException, IllegalStateException; 221 | 222 | /** 223 | * Write end tag. Repetition of namespace and name is just for avoiding errors. 224 | *

    Background: in kXML endTag had no arguments, and non matching tags were 225 | * very difficult to find... 226 | * If namespace is null no namespace prefix is printed but just name. 227 | * If namespace is empty string then serializer will make sure that 228 | * default empty namespace is declared (in XML 1.0 xmlns=''). 229 | */ 230 | XmlSerializer endTag (String namespace, String name) 231 | throws IOException, IllegalArgumentException, IllegalStateException; 232 | 233 | 234 | // /** 235 | // * Writes a start tag with the given namespace and name. 236 | // *
    If there is no prefix defined (prefix == null) for the given namespace, 237 | // * a prefix will be defined automatically. 238 | // *
    If explicit prefixes is passed (prefix != null) then it will be used 239 | // *and namespace declared if not already declared or 240 | // * throw IllegalStateException the same prefix was already set on this 241 | // * element (setPrefix()) and was bound to different namespace. 242 | // *
    If namespace is null then prefix must be null too or IllegalStateException is thrown. 243 | // *
    If namespace is null then no namespace prefix is printed but just name. 244 | // *
    If namespace is empty string then serializer will make sure that 245 | // * default empty namespace is declared (in XML 1.0 xmlns='') 246 | // * or throw IllegalStateException if default namespace is already bound 247 | // * to non-empty string. 248 | // */ 249 | // XmlSerializer startTag (String prefix, String namespace, String name) 250 | // throws IOException, IllegalArgumentException, IllegalStateException; 251 | // 252 | // /** 253 | // * Write an attribute. Calls to attribute() MUST follow a call to 254 | // * startTag() immediately. 255 | // *
    If there is no prefix defined (prefix == null) for the given namespace, 256 | // * a prefix will be defined automatically. 257 | // *
    If explicit prefixes is passed (prefix != null) then it will be used 258 | // * and namespace declared if not already declared or 259 | // * throw IllegalStateException the same prefix was already set on this 260 | // * element (setPrefix()) and was bound to different namespace. 261 | // *
    If namespace is null then prefix must be null too or IllegalStateException is thrown. 262 | // *
    If namespace is null then no namespace prefix is printed but just name. 263 | // *
    If namespace is empty string then serializer will make sure that 264 | // * default empty namespace is declared (in XML 1.0 xmlns='') 265 | // * or throw IllegalStateException if default namespace is already bound 266 | // * to non-empty string. 267 | // */ 268 | // XmlSerializer attribute (String prefix, String namespace, String name, String value) 269 | // throws IOException, IllegalArgumentException, IllegalStateException; 270 | // 271 | // /** 272 | // * Write end tag. Repetition of namespace, prefix, and name is just for avoiding errors. 273 | // *
    If namespace or name arguments are different from corresponding startTag call 274 | // * then IllegalArgumentException is thrown, if prefix argument is not null and is different 275 | // * from corresponding starTag then IllegalArgumentException is thrown. 276 | // *
    If namespace is null then prefix must be null too or IllegalStateException is thrown. 277 | // *
    If namespace is null then no namespace prefix is printed but just name. 278 | // *
    If namespace is empty string then serializer will make sure that 279 | // * default empty namespace is declared (in XML 1.0 xmlns=''). 280 | // *

    Background: in kXML endTag had no arguments, and non matching tags were 281 | // * very difficult to find...

    282 | // */ 283 | // ALEK: This is really optional as prefix in end tag MUST correspond to start tag but good for error checking 284 | // XmlSerializer endTag (String prefix, String namespace, String name) 285 | // throws IOException, IllegalArgumentException, IllegalStateException; 286 | 287 | /** 288 | * Writes text, where special XML chars are escaped automatically 289 | */ 290 | XmlSerializer text (String text) 291 | throws IOException, IllegalArgumentException, IllegalStateException; 292 | 293 | /** 294 | * Writes text, where special XML chars are escaped automatically 295 | */ 296 | XmlSerializer text (char [] buf, int start, int len) 297 | throws IOException, IllegalArgumentException, IllegalStateException; 298 | 299 | void cdsect (String text) 300 | throws IOException, IllegalArgumentException, IllegalStateException; 301 | void entityRef (String text) throws IOException, 302 | IllegalArgumentException, IllegalStateException; 303 | void processingInstruction (String text) 304 | throws IOException, IllegalArgumentException, IllegalStateException; 305 | void comment (String text) 306 | throws IOException, IllegalArgumentException, IllegalStateException; 307 | void docdecl (String text) 308 | throws IOException, IllegalArgumentException, IllegalStateException; 309 | void ignorableWhitespace (String text) 310 | throws IOException, IllegalArgumentException, IllegalStateException; 311 | 312 | /** 313 | * Write all pending output to the stream. 314 | * If method startTag() or attribute() was called then start tag is closed (final >) 315 | * before flush() is called on underlying output stream. 316 | * 317 | *

    NOTE: if there is need to close start tag 318 | * (so no more attribute() calls are allowed) but without flushing output 319 | * call method text() with empty string (text("")). 320 | * 321 | */ 322 | void flush () 323 | throws IOException; 324 | 325 | } --------------------------------------------------------------------------------