Как запустить бесконечный поток до аргумента, а затем собрать указанный поток в строку? - PullRequest
0 голосов
/ 09 апреля 2020

Я хочу запустить command, такой как kubectl logs aggregator --namespace load-test --follow, который является потоком, и печатать весь его вывод до тех пор, пока в поток не войдет определенное argument.

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 ' У меня проблемы с созданием двух потоков (например, с streamSupplier) или двух BufferedReaders, или с поиском любого подходящего способа для того, чего я пытаюсь достичь. Как я могу это сделать?

...