backend/src/main/java/dev/dinauer/ProcessRunner.java
2025-12-20 18:42:59 +01:00

83 lines
2.2 KiB
Java

package dev.dinauer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.eclipse.microprofile.context.ManagedExecutor;
import org.jboss.logging.Logger;
@ApplicationScoped
public class ProcessRunner
{
@Inject
Logger LOG;
@Inject
ManagedExecutor executor;
public String runToText(String command)
{
return String.join("\n", runToLines(command));
}
public List<String> runToLines(String command)
{
LOG.infof("Running command: %s", command);
ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
pb.redirectErrorStream(true);
try
{
return runAndCollectLogs(pb);
}
catch (InterruptedException | IOException e)
{
throw new RuntimeException(e);
}
}
private List<String> runAndCollectLogs(ProcessBuilder processBuilder) throws InterruptedException, IOException
{
List<String> text = new ArrayList<>();
Process process = processBuilder.start();
executor.submit(() -> {
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())))
{
String line;
while ((line = br.readLine()) != null)
{
text.add(line);
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
});
boolean endedInTime = process.waitFor(10, TimeUnit.SECONDS);
int exitCode = process.exitValue();
process.destroyForcibly();
if (endedInTime)
{
if (exitCode == 0)
{
return text;
}
else
{
throw new RuntimeException("Process finished with code " + exitCode);
}
}
else
{
throw new RuntimeException("Process exceeded wait time of 10 sec.");
}
}
}