19
19
package com .streamxhub .streamx .common .util
20
20
21
21
import java .io ._
22
- import java .lang .{Iterable => JavaIter }
22
+ import java .lang .{Iterable => JavaIterable }
23
23
import java .util .Scanner
24
24
import java .util .function .Consumer
25
25
import scala .collection .JavaConversions ._
@@ -30,24 +30,15 @@ object CommandUtils extends Logger {
30
30
31
31
def execute (command : String ): String = {
32
32
val buffer = new StringBuffer ()
33
- Try {
34
- val process = new ProcessBuilder (List (command)).redirectErrorStream(true ).start
35
- val reader = new InputStreamReader (process.getInputStream)
36
- val scanner = new Scanner (reader)
37
- while (scanner.hasNextLine) {
38
- buffer.append(scanner.nextLine()).append(" \n " )
33
+ this .execute(List (command), new Consumer [String ] {
34
+ override def accept (line : String ): Unit = {
35
+ buffer.append(line).append(" \n " )
39
36
}
40
- processClose(process)
41
- scanner.close()
42
- reader.close()
43
- } match {
44
- case Success (_) =>
45
- case Failure (e) => throw e
46
- }
37
+ })
47
38
buffer.toString
48
39
}
49
40
50
- def execute (commands : JavaIter [String ], consumer : Consumer [String ]): Unit = {
41
+ def execute (commands : JavaIterable [String ], consumer : Consumer [String ]): Unit = {
51
42
Try {
52
43
require(commands != null && commands.nonEmpty, " [StreamX] CommandUtils.execute: commands must not be null." )
53
44
logDebug(s " Command execute: \n ${commands.mkString(" \n " )} " )
@@ -63,7 +54,11 @@ object CommandUtils extends Logger {
63
54
while (scanner.hasNextLine) {
64
55
consumer.accept(scanner.nextLine)
65
56
}
66
- processClose(process)
57
+ process.waitFor()
58
+ process.getErrorStream.close()
59
+ process.getInputStream.close()
60
+ process.getOutputStream.close()
61
+ process.destroy()
67
62
scanner.close()
68
63
out.close()
69
64
} match {
@@ -72,12 +67,4 @@ object CommandUtils extends Logger {
72
67
}
73
68
}
74
69
75
- def processClose (process : Process ): Unit = {
76
- process.waitFor()
77
- process.getErrorStream.close()
78
- process.getInputStream.close()
79
- process.getOutputStream.close()
80
- process.destroy()
81
- }
82
-
83
70
}
0 commit comments