net.dankito.utils.PackageInfo.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
package net.dankito.utils
import org.slf4j.LoggerFactory
import java.io.File
import java.net.URLDecoder
open class PackageInfo {
companion object {
fun getAppVersionFromManifest(): String {
return PackageInfo().getAppVersionFromManifest()
}
private val log = LoggerFactory.getLogger(PackageInfo::class.java)
}
open fun getAppVersionFromManifest(): String {
val javaPackage = javaClass.getPackage()
if(javaPackage != null && javaPackage.implementationVersion != null) {
return javaPackage.implementationVersion
}
else { // when debugging there is no jar (with manifest) to extract version from
return "Develop"
}
}
/**
* Returns the path of .jar file where [aClassFromJarFile] is packaged.
*
* If not running from a .jar file (e. g. when debugging or running unit tests) returns the path code has
* been started from
*/
@JvmOverloads
open fun getClassJarPath(aClassFromJarFile: Class<*> = PackageInfo::class.java): File? {
try {
val path = aClassFromJarFile.protectionDomain.codeSource.location.path
val decodedPath = URLDecoder.decode(path, "UTF-8")
return File(decodedPath)
} catch (e: Exception) {
log.error("Could not get .jar file current code is running in", e)
}
return null
}
}