I want to run a command
such as kubectl logs aggregator --namespace load-test --follow
, which is a stream, and print all of its output until a certain argument
comes in the stream.
public class Command {
String collect;
public void execute(String command, String argument) throws IOException {
final boolean IS_WINDOWS = System.getProperty("os.name").toLowerCase().startsWith("windows");
String[] cmd;
Process process;
// Make the command work on Windows or Linux
// This assumes programs like kubectl or minikube are in PATH
if (IS_WINDOWS) {
cmd = new String[]{"cmd.exe", "/c", command};
} else {
cmd = new String[]{"/bin/bash", "- c", command};
}
// Create the ProcessBuilder
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
// Start the process
process = pb.start();
InputStream stdin = process.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
Stream<String> ss = Stream.of(br.readLine());
Stream<String> ss2 = Stream.of(br.readLine());
// Run, say, the live log stream catcher, until it hits the argument
boolean anyMatch = ss.anyMatch((value) -> value.contains(argument));
// If it did hit the argument, collect the output into the String
if (anyMatch) {
collect = ss2.collect(Collectors.joining("\n"));
}
// Clean-up
process.destroy();
}
public String returnAsString() {
return collect;
}
I'm having trouble with creating two streams (e.g., with streamSupplier
) or two BufferedReaders
, or finding any workable way for what I'm trying to achieve. How can I do it?