All Downloads are FREE. Search and download functionalities are using the official Maven repository.

datamaintain.core.util.AppSubProcessUtils.kt Maven / Gradle / Ivy

There is a newer version: 2.1.1
Show newest version
package datamaintain.core.util

import java.io.File
import java.io.IOException
import java.lang.StringBuilder


data class ProcessResult(val exitValue: Int, val output: String)

/**
 * Execute App.kt class as a subprocess. The class is execute with java command.
 * This allow the subprocess to call "exit 1" without crashing the main test process
 *
 * @see https://lankydan.dev/running-a-kotlin-class-as-a-subprocess
 */
@Throws(IOException::class, InterruptedException::class)
fun execAppInSubprocess(args: List = emptyList(), jvmArgs: List = emptyList()): ProcessResult {
    val javaHome = System.getProperty("java.home")
    val javaBin = javaHome + File.separator + "bin" + File.separator + "java"
    val classpath = System.getProperty("java.class.path")
    val className = "datamaintain.cli.app.DatamaintainCLIKt"

    val command = ArrayList()
    command.add(javaBin)
    command.addAll(jvmArgs)
    command.add("-cp")
    command.add(classpath)
    command.add(className)
    command.addAll(args)

    val process = ProcessBuilder(command)
        .redirectOutput(ProcessBuilder.Redirect.PIPE)
        .redirectError(ProcessBuilder.Redirect.PIPE)
        .redirectErrorStream(true)
        .start()

    // Read output, print it and add it to processOutput
    val processOutput = StringBuilder()
    process.inputStream.bufferedReader().lines()
        .peek { processOutput.append(it).append(System.lineSeparator()) }
        .forEach { println(it) }

    process.waitFor()
    return ProcessResult(process.exitValue(), processOutput.toString())
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy