com.gitlab.mvysny.konsumexml.Utils.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of konsume-xml Show documentation
Show all versions of konsume-xml Show documentation
Konsume-XML: A simple functional XML parser with no annotations
The newest version!
package com.gitlab.mvysny.konsumexml
import java.io.Closeable
import javax.xml.namespace.QName
/**
* Tries to run given block on a [Closeable]. If the block fails, this closable is closed; if the block succeeds,
* this closeable is not closed since it's expected that the closeable will be used further.
*
* Used when the Closeable is closed elsewhere, for example:
* ```kotlin
* fun File.buffered(): BufferedInputStream = inputStream().andTry { it.buffered() }
* ```
*/
public inline fun T.andTry(block: (T) -> R): R = try {
block(this)
} catch (e: Exception) {
try {
close()
} catch (ce: Exception) {
// we don't depend on slf4j so we can't use that;
// we need to run on older Androids and therefore we can't use Throwable.addSuppressed()
// JUL is not supported properly on Androids
// the safest thing is to fall back and call printStackTrace()
ce.printStackTrace()
}
throw e
}
/**
* Returns the tag name. The tag name is [QName.localPart] but it includes a
* prefix if not null, for example `atom:link`.
*/
public val QName.tagName: String get() = buildString {
if (prefix.isNotBlank()) {
append(prefix)
append(':')
}
append(localPart)
}
/**
* Formats this QName in the form of `{namespace}prefix:localName`.
*/
public fun QName.getFullName(): String = buildString {
if (namespaceURI.isNotBlank()) {
append('{')
append(namespaceURI)
append('}')
}
append(tagName)
}
public val QName.hasNamespace: Boolean get() = namespaceURI.isNotEmpty()
internal fun existsClass(className: String): Boolean = try {
Class.forName(className, true, Konsumer::class.java.classLoader)
true
} catch (e: ClassNotFoundException) {
false
}