diff options
Diffstat (limited to 'app/src/main/java/org/pacien/tincapp/commands/Executor.kt')
-rw-r--r-- | app/src/main/java/org/pacien/tincapp/commands/Executor.kt | 26 |
1 files changed, 18 insertions, 8 deletions
diff --git a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt index c93de64..eccd2f9 100644 --- a/app/src/main/java/org/pacien/tincapp/commands/Executor.kt +++ b/app/src/main/java/org/pacien/tincapp/commands/Executor.kt | |||
@@ -1,7 +1,9 @@ | |||
1 | package org.pacien.tincapp.commands | 1 | package org.pacien.tincapp.commands |
2 | 2 | ||
3 | import java8.util.concurrent.CompletableFuture | ||
3 | import java.io.BufferedReader | 4 | import java.io.BufferedReader |
4 | import java.io.IOException | 5 | import java.io.IOException |
6 | import java.io.InputStream | ||
5 | import java.io.InputStreamReader | 7 | import java.io.InputStreamReader |
6 | 8 | ||
7 | /** | 9 | /** |
@@ -9,6 +11,8 @@ import java.io.InputStreamReader | |||
9 | */ | 11 | */ |
10 | internal object Executor { | 12 | internal object Executor { |
11 | 13 | ||
14 | class CommandExecutionException(msg: String) : Exception(msg) | ||
15 | |||
12 | init { | 16 | init { |
13 | System.loadLibrary("exec") | 17 | System.loadLibrary("exec") |
14 | } | 18 | } |
@@ -18,17 +22,23 @@ internal object Executor { | |||
18 | */ | 22 | */ |
19 | private external fun forkExec(argcv: Array<String>): Int | 23 | private external fun forkExec(argcv: Array<String>): Int |
20 | 24 | ||
21 | @Throws(IOException::class) | 25 | private fun read(stream: InputStream) = BufferedReader(InputStreamReader(stream)).readLines() |
26 | |||
22 | fun forkExec(cmd: Command) { | 27 | fun forkExec(cmd: Command) { |
23 | if (forkExec(cmd.asArray()) == -1) | 28 | if (forkExec(cmd.asArray()) == -1) throw CommandExecutionException("Could not fork child process.") |
24 | throw IOException() | ||
25 | } | 29 | } |
26 | 30 | ||
27 | @Throws(IOException::class) | 31 | fun call(cmd: Command): CompletableFuture<List<String>> { |
28 | fun call(cmd: Command): List<String> { | 32 | val proc = try { |
29 | val proc = ProcessBuilder(cmd.asList()).start() | 33 | ProcessBuilder(cmd.asList()).start() |
30 | val outputReader = BufferedReader(InputStreamReader(proc.inputStream)) | 34 | } catch (e: IOException) { |
31 | return outputReader.readLines() | 35 | throw CommandExecutionException(e.message ?: "Could not start process.") |
36 | } | ||
37 | |||
38 | return CompletableFuture.supplyAsync<List<String>> { | ||
39 | if (proc.waitFor() == 0) read(proc.inputStream) | ||
40 | else throw CommandExecutionException(read(proc.errorStream).lastOrNull() ?: "Non-zero exit status.") | ||
41 | } | ||
32 | } | 42 | } |
33 | 43 | ||
34 | } | 44 | } |