All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.dongliu.jlink.util.ProcessUtils Maven / Gradle / Ivy

package net.dongliu.jlink.util;

import net.dongliu.commons.concurrent.ThreadFactories;
import net.dongliu.commons.io.Inputs;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.concurrent.*;

/**
 * Utils for process
 *
 * @author dongliu
 */
public class ProcessUtils {

    private static final ExecutorService executor = Executors.newCachedThreadPool(
            ThreadFactories.newBuilder("process-executor").daemon(true).build());

    public static ProcessResult execute(String... command) {
        ProcessBuilder builder = new ProcessBuilder(command);

        Process process;
        try {
            process = builder.start();

            Future stdout = executor.submit(() -> {
                try (InputStream in = process.getInputStream()) {
                    return new String(Inputs.readAll(in));
                }
            });
            Future stderr = executor.submit(() -> {
                try (InputStream in = process.getErrorStream()) {
                    return new String(Inputs.readAll(in));
                }
            });
            process.waitFor(10, TimeUnit.MINUTES);
            return new ProcessResult(process.exitValue(), stdout.get(), stderr.get());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy