Skip to content

Commit

Permalink
StreamsStrings example
Browse files Browse the repository at this point in the history
  • Loading branch information
jesperancinha committed Jan 16, 2024
1 parent 1795600 commit ca20f78
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.jesperancinha.ktd

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import java.io.InputStream

class StreamsStrings {
suspend fun executeCommand(commandArgs: List<String>): ProcessResult = withContext(
Dispatchers.IO
) {
runCatching {
val process = ProcessBuilder(commandArgs).start()
val outputStream = async {
println("Context for output stream -> $coroutineContext -> Thread -> ${Thread.currentThread()}")
readStream(process.inputStream) }
val errorStream = async {
println("Context for error stream -> $coroutineContext -> Thread -> ${Thread.currentThread()}")
readStream(process.errorStream)
}
println("Context for exit code -> $coroutineContext -> Thread -> ${Thread.currentThread()}")
val exitCode = process.waitFor()
ProcessResult(
exitCode = exitCode,
message = outputStream.await(),
errorMessage = errorStream.await()
)
}.onFailure{
ProcessResult(
exitCode = -1,
message = "",
errorMessage = it.localizedMessage
)
}.getOrThrow()
}

private fun readStream(inputStream: InputStream) =
inputStream.bufferedReader().use { reader -> reader.readText() }

data class ProcessResult(val exitCode: Int, val message: String, val errorMessage: String)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.jesperancinha.ktd

import io.kotest.common.runBlocking
import io.kotest.matchers.string.shouldContain
import kotlin.test.Test

class StreamsStringsTest {

private val streamsStrings by lazy { StreamsStrings() }

@Test
fun `should run command correctly`(): Unit = runBlocking {

val executeCommand = streamsStrings.executeCommand(listOf("java", "-version"))
println(executeCommand)
executeCommand.errorMessage shouldContain "JDK"

}
}

0 comments on commit ca20f78

Please sign in to comment.