in.specmatic.core.utilities.StubServerWatcher.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of specmatic-core Show documentation
Show all versions of specmatic-core Show documentation
Turn your contracts into executable specifications. Contract Driven Development - Collaboratively Design & Independently Deploy MicroServices & MicroFrontends.
Deprecation Notice for group ID "in.specmatic"
******************************************************************************************************
Updates for "specmatic-core" will no longer be available under the deprecated group ID "in.specmatic".
Please update your dependencies to use the new group ID "io.specmatic".
******************************************************************************************************
package `in`.specmatic.core.utilities
import `in`.specmatic.core.log.consoleLog
import `in`.specmatic.core.CONTRACT_EXTENSIONS
import `in`.specmatic.core.DATA_DIR_SUFFIX
import `in`.specmatic.core.log.StringLog
import java.io.File
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
import java.nio.file.WatchKey
class StubServerWatcher(private val contractPaths: List) {
fun watchForChanges(restartServer: () -> Unit) {
FileSystems.getDefault().newWatchService().use { watchService ->
val paths: List = getPaths(contractPaths).toSet().toList().sorted().map { File(it).toPath() }
paths.forEach { contractPath ->
contractPath.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE)
}
var key: WatchKey
while (watchService.take().also { key = it } != null) {
key.reset()
val events = key.pollEvents().joinToString(", ") { it.context().toString() }
consoleLog(StringLog("""Detected event(s) for $events, restarting stub server."""))
restartServer()
}
}
}
private fun getPaths(contractPaths: List): List {
return contractPaths.map { File(it) }.flatMap {
when {
it.isFile && it.extension.lowercase() in CONTRACT_EXTENSIONS ->
listOf(it.absoluteFile.parentFile.path).plus(getPaths(listOf(dataDirOf(it))))
it.isFile && it.extension.equals("yaml", ignoreCase = true) ->
listOf(it.absolutePath)
it.isFile && it.extension.equals("json", ignoreCase = true) ->
listOf(it.absoluteFile.parentFile.path)
it.isDirectory ->
listOf(it.absolutePath).plus(getPaths(it.listFiles()?.toList()?.map { file -> file.absolutePath } ?: emptyList()))
else -> emptyList()
}
}
}
internal fun dataDirOf(contractFile: File): String {
val examplesDir = examplesDirFor("${contractFile.absoluteFile.parent}/${contractFile.name}", DATA_DIR_SUFFIX)
return "${examplesDir.absoluteFile.parent}/${examplesDir.name}"
}
}