GpxAndroidSdk/src/main/kotlin/me/bvn13/sdk/android/gpx/GpxReader.kt

492 lines
28 KiB
Kotlin

/*
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright 2022, bvn13
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package me.bvn13.sdk.android.gpx
import me.bvn13.sdk.android.gpx.GpxConstant.Companion.DTF
import java.io.InputStream
import java.time.OffsetDateTime
import java.util.stream.Collectors
fun GpxType.Companion.read(dis: InputStream) = GpxReader().read(dis)
fun ByteArray.asString() = String(this)
class GpxReader {
fun read(dis: InputStream): GpxType {
val container = readNotSpace(dis, Container.empty())
return when (container.byte!!.toInt()) {
'<'.code -> readBeginning(dis, container)
else -> throw IllegalArgumentException("Not a GPX/XML?")
}
}
private fun readBeginning(dis: InputStream, buffer: Container): GpxType {
val container = readByte(dis, buffer)
return when (container.byte!!.toInt()) {
'?'.code -> readSignature(dis, container)
'<'.code -> readGpx(dis, container)
else -> throw IllegalArgumentException("Wrong symbol at ${container.position} from the very beginning")
}
}
private fun readSignature(dis: InputStream, buffer: Container): GpxType {
val container = readUntil(dis, buffer, '\n')
val signaturePrepared = container.buffer.asString()
.trim()
.replace("'", "\"")
.replace(" ?", "?")
if (!signaturePrepared.startsWith("<?xml") || !signaturePrepared.endsWith("?>")) {
throw IllegalArgumentException("Wrong xml signature!")
}
return readBeginning(dis, Container.empty(container.position))
}
private fun readGpx(dis: InputStream, buffer: Container): GpxType {
var tagName: String? = null
val container = readObject(dis, buffer) {
tagName = it.buffer.asString().substring(1, it.buffer.size - 1).lowercase()
if ("gpx" != tagName) {
throw IllegalArgumentException("There must be GPX tag in given InputStream")
}
}
tagName?.let {
return assembleGpxType(container)
} ?: run {
throw IllegalArgumentException("Unable to read content")
}
}
private fun assembleGpxType(container: Container): GpxType {
if (container.objects == null) {
throw IllegalArgumentException("It was not parsed properly")
}
if (container.objects!!.size != 1) {
throw IllegalArgumentException("It was parsed ${container.objects!!.size} objects, but only 1 is expected")
}
return findObject(container.objects, "gpx").let {
return GpxType(
metadata = assembleMetadataType(it.nested),
creator = findAttributeOrNull(it.attributes, "creator")
?: throw IllegalArgumentException("Gpx.Creator not found"),
wpt = findObjectsOrNull(it.nested, "wpt")?.map { assembleWptType(it) },
rte = findObjectsOrNull(it.nested, "rte")?.map { assembleRteType(it) },
trk = findObjectsOrNull(it.nested, "trk")?.map { assembleTrkType(it) },
extensions = findObjectOrNull(it.nested, "extensions")?.let { assembleExtensionType(it) }
)
}
}
private fun assembleMetadataType(objects: List<XmlObject>?): MetadataType =
findObject(objects, "metadata")
.let {
return MetadataType(
name = findObjectOrNull(it.nested, "name")?.value
?: throw IllegalArgumentException("Gpx.Metadata.Name not found"),
description = findObjectOrNull(it.nested, "desc")?.value
?: "",
authorName = findObjectOrNull(it.nested, "author").let { author ->
findObjectOrNull(author?.nested, "name")?.value
?: ""
}
)
}
private fun assembleWptType(obj: XmlObject): WptType =
WptType(
lat = findAttribute(obj.attributes, "lat").toDouble(),
lon = findAttribute(obj.attributes, "lon").toDouble(),
ele = findObjectOrNull(obj.nested, "ele")?.value?.toDouble(),
time = findObjectOrNull(obj.nested, "time")?.value?.let { OffsetDateTime.parse(it, DTF) },
magvar = findObjectOrNull(obj.nested, "magvar")?.value?.toDouble(),
geoidheight = findObjectOrNull(obj.nested, "geoidheight")?.value?.toDouble(),
name = findObjectOrNull(obj.nested, "name")?.value,
cmt = findObjectOrNull(obj.nested, "cmt")?.value,
desc = findObjectOrNull(obj.nested, "desc")?.value,
src = findObjectOrNull(obj.nested, "src")?.value,
link = findObjectsOrNull(obj.nested, "link")?.map { assembleLinkType(it) },
sym = findObjectOrNull(obj.nested, "sym")?.value,
type = findObjectOrNull(obj.nested, "type")?.value,
fix = findObjectOrNull(obj.nested, "fix")?.value?.let { assembleFixType(it) },
sat = findObjectOrNull(obj.nested, "sat")?.value?.toInt(),
hdop = findObjectOrNull(obj.nested, "hdop")?.value?.toDouble(),
vdop = findObjectOrNull(obj.nested, "vdop")?.value?.toDouble(),
pdop = findObjectOrNull(obj.nested, "pdop")?.value?.toDouble(),
ageofgpsdata = findObjectOrNull(obj.nested, "ageofgpsdata")?.value?.toInt(),
dgpsid = findObjectOrNull(obj.nested, "dgpsid")?.value?.toInt(),
extensions = findObjectOrNull(obj.nested, "extensions")?.nested?.map { assembleExtensionType(it) }
)
private fun assembleRteType(obj: XmlObject): RteType =
RteType(
name = findObjectOrNull(obj.nested, "name")?.value,
cmt = findObjectOrNull(obj.nested, "cmt")?.value,
desc = findObjectOrNull(obj.nested, "desc")?.value,
src = findObjectOrNull(obj.nested, "src")?.value,
link = findObjectsOrNull(obj.nested, "link")?.map { assembleLinkType(it) },
number = findObjectOrNull(obj.nested, "number")?.value?.toInt(),
type = findObjectOrNull(obj.nested, "type")?.value,
extensions = findObjectOrNull(obj.nested, "extensions")?.nested?.map { assembleExtensionType(it) },
rtept = findObjectsOrNull(obj.nested, "rtept")?.map { assembleWptType(it) }
)
private fun assembleTrkType(obj: XmlObject): TrkType =
TrkType(
name = findObjectOrNull(obj.nested, "name")?.value,
cmt = findObjectOrNull(obj.nested, "cmt")?.value,
desc = findObjectOrNull(obj.nested, "desc")?.value,
src = findObjectOrNull(obj.nested, "src")?.value,
link = findObjectsOrNull(
obj.nested,
"link"
)?.let { list -> if (list.isNotEmpty()) list.map { assembleLinkType(it) } else null },
number = findObjectOrNull(obj.nested, "number")?.value?.toInt(),
type = findObjectOrNull(obj.nested, "type")?.value,
extensions = findObjectOrNull(obj.nested, "extensions")?.let { assembleExtensionType(it) },
trkseg = findObjectsOrNull(obj.nested, "trkseg")?.map { assembleTrksegType(it) }
)
private fun assembleLinkType(obj: XmlObject): LinkType =
LinkType(
href = findAttribute(obj.attributes, "href"),
text = findObjectOrNull(obj.nested, "text")?.value,
type = findObjectOrNull(obj.nested, "type")?.value
)
private fun assembleFixType(value: String): FixType =
FixType.valueOf(value.uppercase())
private fun assembleExtensionType(obj: XmlObject): ExtensionType {
val nested: List<ExtensionType>? = obj.nested?.stream()
?.map { assembleExtensionType(it) }
?.collect(Collectors.toList())
return ExtensionType(
nodeName = obj.type,
value = if (obj.value == "") null else obj.value,
parameters = if (obj.attributes.isEmpty()) null else obj.attributes.toSortedMap(),
nested = nested
)
}
private fun assembleTrksegType(obj: XmlObject): TrksegType =
TrksegType(
trkpt = findObjectsOrNull(obj.nested, "trkpt")?.map { assembleWptType(it) },
extensions = findObjectOrNull(obj.nested, "extensions")?.let { assembleExtensionType(it) }
)
private fun findObjectOrNull(objects: List<XmlObject>?, name: String): XmlObject? =
objects?.firstOrNull { o ->
o.type.lowercase() == name.lowercase()
}
private fun findObject(objects: List<XmlObject>?, name: String): XmlObject =
findObjectOrNull(objects, name)
?: throw IllegalArgumentException("$name not found")
private fun findObjectsOrNull(objects: List<XmlObject>?, name: String): List<XmlObject>? =
objects?.filter { o ->
o.type.lowercase() == name.lowercase()
}
private fun findAttributeOrNull(attributes: Map<String, String>?, name: String): String? =
attributes?.firstNotNullOf { e -> if (e.key.lowercase() == name.lowercase()) e.value else null }
private fun findAttribute(attributes: Map<String, String>?, name: String): String =
findAttributeOrNull(attributes, name)
?: throw IllegalArgumentException("Unable to find attribute $name")
private fun readObject(dis: InputStream, buffer: Container, checker: ((Container) -> Unit)? = null): Container {
if (buffer.buffer[0].toInt() != '<'.code) {
throw IllegalArgumentException("Not a tag at position ${buffer.position}")
}
var container = readUntil(dis, buffer, setOf(' ', '\n', '>'))
val tagName = container.buffer.asString().substring(1, container.buffer.size - 1)
checker?.invoke(container)
val xmlObject = XmlObject(tagName)
if (container.byte!!.toInt() != '>'.code) {
container = readAttributes(dis, container)
xmlObject.attributes = container.attributes
}
if (!container.isShortClosing) {
container = readSkipping(dis, container, SKIPPING_SET)
if (container.byte!!.toInt() == '<'.code) {
container = readNestedObjects(dis, container)
xmlObject.nested = container.objects
container = readFinishingTag(dis, container, tagName)
}
if (container.buffer.asString() != "</$tagName>") {
container = readValue(dis, container, tagName)
}
}
xmlObject.value = container.buffer.asString().replace("</$tagName>", "")
container.objects = listOf(xmlObject)
return container
}
private fun readNestedObjects(dis: InputStream, buffer: Container): Container {
val list = ArrayList<XmlObject>()
var container: Container = readByte(dis, buffer)
if (container.byte!!.toInt() == '/'.code) {
return container
}
while (true) {
val objectContainer = readObject(dis, container)
val skippingContainer = readSkipping(dis, objectContainer, SKIPPING_SET)
container = readByte(dis, skippingContainer)
objectContainer.objects?.forEach {
list.add(it)
}
if (container.byte!!.toInt() == '/'.code) {
break;
}
}
container.objects = list
return container
}
private fun readFinishingTag(dis: InputStream, buffer: Container, tagName: String): Container {
if (buffer.isShortClosing) {
return buffer
}
return readExactly(dis, buffer, "</${tagName}>")
}
private fun readValue(dis: InputStream, buffer: Container, tagName: String): Container =
readUntil(dis, buffer, "</$tagName>")
private fun readAttributes(dis: InputStream, buffer: Container): Container {
if (buffer.byte!!.toInt() == '>'.code) {
return Container.empty(buffer.position)
}
val attributes = HashMap<String, String>()
var attributeContainer: Container = Container.empty(buffer.position)
do {
attributeContainer = readAttribute(dis, attributeContainer)
attributes.putAll(attributeContainer.attributes)
} while (attributeContainer.attributes.isNotEmpty()
&& attributeContainer.byte!!.toInt() != '>'.code
)
val result = Container.emptyWithAttributes(attributeContainer.position, attributes, attributeContainer.isShortClosing)
return result
}
private fun readAttribute(dis: InputStream, buffer: Container): Container {
val nameContainer = readUntil(dis, buffer, setOf(' ', '\n', '=', '\t'))
val nameAsString = nameContainer.buffer.asString()
val name = nameAsString.substring(0, nameAsString.length - 1)
val equalsContainer = readUntil(dis, Container.empty(nameContainer.position), '"')
val valueContainer = readUntil(dis, Container.empty(equalsContainer.position), '"')
val valueAsString = valueContainer.buffer.asString()
val value = valueAsString.substring(0, valueAsString.length - 1)
val result = Container.empty(valueContainer.position)
var closingContainer = readSkipping(dis, result, SKIPPING_SET)
var isShortClosing = false
if (closingContainer.byte!!.toInt() == '/'.code) {
val endingContainer = readByte(dis, closingContainer)
if (endingContainer.byte!!.toInt() != '>'.code) {
throw IllegalArgumentException("There must be valid closing tag at ${endingContainer.position}")
}
closingContainer = endingContainer
isShortClosing = true
}
val nextBlockContainer = Container.of(closingContainer.byte!!, closingContainer.position, isShortClosing)
nextBlockContainer.attributes = mapOf(name to value)
return nextBlockContainer
}
private fun readUntil(dis: InputStream, buffer: Container, ch: Char): Container {
var container = buffer
do {
container = readByte(dis, container)
} while (container.byte!!.toInt() != ch.code)
return container
}
private fun readUntil(dis: InputStream, buffer: Container, chs: Set<Char>): Container {
val chars = chs.map { c -> c.code }
var container = buffer
do {
container = readByte(dis, container)
} while (!chars.contains(container.byte!!.toInt()))
return container
}
private fun readUntil(dis: InputStream, buffer: Container, charSequence: CharSequence): Container {
var container = Container.of(buffer.byte!!, buffer.position)
var pos = 0
do {
container = readByte(dis, container)
if (container.byte!!.toInt() == charSequence[pos].code) {
pos++
} else {
pos = 0
}
} while (pos < charSequence.length)
return container
}
private fun readSkipping(dis: InputStream, buffer: Container, chs: Set<Char>): Container {
val chars = chs.map { c -> c.code }
var container = buffer
do {
container = readByte(dis, container)
} while (chars.contains(container.byte!!.toInt()))
return Container.of(container.byte!!, container.position)
}
private fun readExactly(dis: InputStream, buffer: Container, charSequence: CharSequence): Container {
var container = buffer
do {
container = readByte(dis, container)
if (charSequence.substring(0, container.buffer.size) != container.buffer.asString()) {
throw IllegalArgumentException("Expected closing tag $charSequence at position ${buffer.position}")
}
} while (container.buffer.size < charSequence.length)
return container
}
private fun readNotSpace(dis: InputStream, buffer: Container): Container {
val container = readByte(dis, buffer)
if (container.byte!!.toInt() == ' '.code
|| container.byte.toInt() == '\n'.code
) {
return readByte(dis, container)
} else {
return container
}
}
private fun readByte(dis: InputStream, container: Container): Container {
val ba = ByteArray(1);
if (-1 == dis.read(ba, 0, 1)) {
throw InterruptedException("EOF at ${container.position}\nUnparsed data: " + String(container.buffer))
} else if (ba.size != 1) {
throw InterruptedException("Reading of 1 byte returns ${ba.size} bytes at ${container.position}")
}
return Container(container.position + 1, ba[0], container.buffer.plus(ba))
}
class Container(
val position: Long = 0,
val byte: Byte?,
val buffer: ByteArray,
val isShortClosing: Boolean = false
) {
var objects: List<XmlObject>? = null
var attributes: Map<String, String> = HashMap()
var value: String? = null
companion object {
fun empty(): Container = empty(0)
fun empty(position: Long, isShortClosing: Boolean = false) = Container(position, null, ByteArray(0), isShortClosing)
fun emptyWithAttributes(position: Long, attributes: Map<String, String>, isShortClosing: Boolean = false): Container {
val container = Container.empty(position, isShortClosing)
container.attributes = attributes
return container
}
fun of(b: Byte, position: Long, isShortClosing: Boolean = false) =
Container(position, b, ByteArray(1) { _ -> b }, isShortClosing)
fun isShortClosing(c: Container, buffer: ByteArray): Container {
val container = Container(c.position, c.byte, buffer, isShortClosing = true)
container.objects = c.objects
container.attributes = c.attributes
container.value = c.value
return container
}
}
override fun toString(): String = this.buffer.asString()
}
class XmlObject(type: String) {
val type: String
var attributes: Map<String, String> = HashMap()
var nested: List<XmlObject>? = null
var value: String? = null
init {
this.type = type
}
}
companion object {
val SKIPPING_SET = setOf(' ', '\n', '\r', '\t')
}
}