Example usage for java.lang ProcessBuilder ProcessBuilder

List of usage examples for java.lang ProcessBuilder ProcessBuilder

Introduction

In this page you can find the example usage for java.lang ProcessBuilder ProcessBuilder.

Prototype

public ProcessBuilder(String... command) 

Source Link

Document

Constructs a process builder with the specified operating system program and arguments.

Usage

From source file:actors.ConfigUtil.java

static ProcessBuilder buildProcess(String javaCmd, String etlJobName, long whEtlExecId, String cmdParam,
        Properties etlJobProperties) {
    String classPath = System.getProperty("java.class.path");
    String outDir = etlJobProperties.getProperty(Constant.WH_APP_FOLDER_KEY, WH_APPLICATION_DEFAULT_DIRECTORY);
    String configFile = outDir + "/" + whEtlExecId + ".properties";

    String[] cmdParams = isNotBlank(cmdParam) ? cmdParam.trim().split(" ") : new String[0];

    ProcessBuilder pb = new ProcessBuilder(new ImmutableList.Builder<String>().add(javaCmd)
            .addAll(Arrays.asList(cmdParams)).add("-cp").add(classPath).add("-Dconfig=" + configFile)
            .add("-DCONTEXT=" + etlJobName).add("-Dlogback.configurationFile=etl_logback.xml")
            .add("-DLOG_DIR=" + outDir).add(Launcher.class.getCanonicalName()).build());
    pb.redirectOutput(ProcessBuilder.Redirect.to(new File(outDir + "/stdout")));
    pb.redirectError(ProcessBuilder.Redirect.to(new File(outDir + "/stderr")));
    return pb;//from w w  w.ja  v a2 s .c om
}

From source file:com.xebialabs.overcast.command.CommandProcessor.java

public CommandResponse run(final Command command) {

    logger.debug("Executing command {}", command);

    try {/*from  w  w  w. ja va2s.  c om*/
        Process p = new ProcessBuilder(command.asList()).directory(new File(execDir)).start();

        // We do this small trick to have stdout and stderr of the process on the console and
        // at the same time capture them to strings.
        ByteArrayOutputStream errors = new ByteArrayOutputStream();
        ByteArrayOutputStream messages = new ByteArrayOutputStream();

        Thread t1 = showProcessOutput(new TeeInputStream(p.getErrorStream(), errors), System.err);
        Thread t2 = showProcessOutput(new TeeInputStream(p.getInputStream(), messages), System.out);

        int code = p.waitFor();

        t1.join();
        t2.join();

        CommandResponse response = new CommandResponse(code, errors.toString(), messages.toString());

        if (!response.isSuccessful()) {
            throw new NonZeroCodeException(command, response);
        }

        return response;

    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException("Cannot execute " + command.toString(), e);
    } catch (IOException e) {
        throw new RuntimeException("Cannot execute " + command.toString(), e);
    }
}

From source file:com.github.pemapmodder.pocketminegui.utils.Utils.java

private static File installLinuxPHP(File home, InstallProgressReporter progress) {
    progress.report(0.0);/*from   ww  w  .j  a va  2 s  . co m*/
    File bin = new File(home, ".pmgui_tmp_pm_linux_installer");
    bin.mkdirs();
    try {
        InputStream get = new URL("http", "get.pocketmine.net", "").openStream();
        Process bash = new ProcessBuilder("bash -s - -v development").directory(bin)
                .redirectOutput(ProcessBuilder.Redirect.INHERIT).redirectError(ProcessBuilder.Redirect.INHERIT)
                .start();
        progress.report(0.25);
        byte[] bytes = IOUtils.toByteArray(get);
        progress.report(0.5);
        bash.getOutputStream().write(bytes);
        int result = bash.waitFor();
        progress.report(0.75);
        if (result == 0) {
            File out = new File(bin, "bin");
            FileUtils.copyDirectory(out, new File(home, "bin"));
            FileUtils.deleteDirectory(bin);
            File output = new File(out, "php7/bin/php");
            progress.completed(output);
            return output;
        } else {
            FileUtils.deleteDirectory(bin);
            return null;
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        try {
            FileUtils.deleteDirectory(bin);
        } catch (IOException e1) {
        }
        return null;
    }
}

From source file:br.com.semanticwot.cd.infra.LocalShell.java

public void executeCommand(final String command) {
    final ArrayList<String> commands = new ArrayList<String>();
    commands.add("/bin/bash");
    commands.add("-c");
    commands.add(command);/*  ww  w  .j a v a 2s  .c om*/
    System.out.println("Entrei em executeCommand");
    BufferedReader br = null;
    try {
        p = new ProcessBuilder(commands);
        this.process = p.start();
        //            final InputStream is = process.getInputStream();
        //            final InputStreamReader isr = new InputStreamReader(is);
        //            br = new BufferedReader(isr);
        //            String line;
        //            while ((line = br.readLine()) != null) {
        //              System.out.println("Retorno do comando = [" + line + "]");
        //            }
    } catch (IOException ioe) {
        log.log(Level.SEVERE, "Erro ao executar comando shell{0}", ioe.getMessage());
        System.out.println("ERROR IOException");
    } finally {
        secureClose(br);
    }
}

From source file:com.googlecode.promnetpp.research.main.CompareOutputMain.java

private static void doSeedRun(int seed) throws IOException, InterruptedException {
    System.out.println("Running with seed " + seed);
    String pattern = "int random = <INSERT_SEED_HERE>;";
    int start = sourceCode.indexOf(pattern);
    int end = start + pattern.length();
    String line = sourceCode.substring(start, end);
    line = line.replace("<INSERT_SEED_HERE>", Integer.toString(seed));
    String sourceCodeWithSeed = sourceCode.replace(pattern, line);
    File tempFile = new File("temp.pml");
    FileUtils.writeStringToFile(tempFile, sourceCodeWithSeed);
    //Create a "project" folder
    String fileNameWithoutExtension = fileName.split("[.]")[0];
    File folder = new File("test1-" + fileNameWithoutExtension);
    if (folder.exists()) {
        FileUtils.deleteDirectory(folder);
    }//from w w  w . ja  v a  2s .c om
    folder.mkdir();
    //Copy temp.pml to our new folder
    FileUtils.copyFileToDirectory(tempFile, folder);
    //Simulate the model using Spin
    List<String> spinCommand = new ArrayList<String>();
    spinCommand.add(GeneralData.spinHome + "/spin");
    spinCommand.add("-u1000000");
    spinCommand.add("temp.pml");
    ProcessBuilder processBuilder = new ProcessBuilder(spinCommand);
    processBuilder.directory(folder);
    processBuilder.redirectOutput(new File(folder, "spin-" + seed + ".txt"));
    Process process = processBuilder.start();
    process.waitFor();
    //Translate via PROMNeT++
    List<String> PROMNeTppCommand = new ArrayList<String>();
    PROMNeTppCommand.add("java");
    PROMNeTppCommand.add("-enableassertions");
    PROMNeTppCommand.add("-jar");
    PROMNeTppCommand.add("\"" + GeneralData.getJARFilePath() + "\"");
    PROMNeTppCommand.add("temp.pml");
    processBuilder = new ProcessBuilder(PROMNeTppCommand);
    processBuilder.directory(folder);
    processBuilder.environment().put("PROMNETPP_HOME", GeneralData.PROMNeTppHome);
    process = processBuilder.start();
    process.waitFor();
    //Run opp_makemake
    FileUtils.copyFileToDirectory(new File("opp_makemake.bat"), folder);
    List<String> makemakeCommand = new ArrayList<String>();
    if (Utilities.operatingSystemType.equals("windows")) {
        makemakeCommand.add("cmd");
        makemakeCommand.add("/c");
        makemakeCommand.add("opp_makemake.bat");
    } else {
        throw new RuntimeException("Support for Linux/OS X not implemented" + " here yet.");
    }
    processBuilder = new ProcessBuilder(makemakeCommand);
    processBuilder.directory(folder);
    process = processBuilder.start();
    process.waitFor();
    //Run make
    FileUtils.copyFileToDirectory(new File("opp_make.bat"), folder);
    List<String> makeCommand = new ArrayList<String>();
    if (Utilities.operatingSystemType.equals("windows")) {
        makeCommand.add("cmd");
        makeCommand.add("/c");
        makeCommand.add("opp_make.bat");
    } else {
        throw new RuntimeException("Support for Linux/OS X not implemented" + " here yet.");
    }
    processBuilder = new ProcessBuilder(makeCommand);
    processBuilder.directory(folder);
    process = processBuilder.start();
    process.waitFor();
    System.out.println(Utilities.getStreamAsString(process.getInputStream()));
    System.exit(1);
}

From source file:com.jbrisbin.vpc.jobsched.exe.ExeMessageHandler.java

public ExeMessage handleMessage(final ExeMessage msg) throws Exception {
    log.debug("handling message: " + msg.toString());

    List<String> args = msg.getArgs();
    args.add(0, msg.getExe());//from  ww w  .j av a  2 s  .  c o m

    try {
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.environment().putAll(msg.getEnv());
        pb.directory(new File(msg.getDir()));
        pb.redirectErrorStream(true);
        Process p = pb.start();

        BufferedInputStream stdout = new BufferedInputStream(p.getInputStream());
        byte[] buff = new byte[4096];
        for (int bytesRead = 0; bytesRead > -1; bytesRead = stdout.read(buff)) {
            msg.getOut().write(buff, 0, bytesRead);
        }

        p.waitFor();
    } catch (Throwable t) {
        log.error(t.getMessage(), t);
        Object errmsg = t.getMessage();
        if (null != errmsg) {
            msg.getOut().write(((String) errmsg).getBytes());
        }
    }
    return msg;
}

From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java

private static void decompressUtil(Path archiveFilePath, Path workingDir, boolean stripParent)
        throws Exception {
    try {//w  w w . j av  a2s  .  co  m
        MutableList<String> tarArgs = Lists.mutable.of(UNIX_TAR, "xvzf",
                archiveFilePath.toFile().getAbsolutePath());

        if (stripParent) {
            tarArgs = tarArgs.with("--strip").with("1");
        }
        Process process = new ProcessBuilder(tarArgs.toList()).directory(workingDir.toFile()).start();
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            logStdout(process.getInputStream());
            logStdErr(process.getErrorStream());
            throw new Exception("Failed to decompress");
        }
    } catch (Exception e) {
        throw new Exception("Failed to decompress", e);
    }
}

From source file:io.wcm.maven.plugins.nodejs.mojo.Task.java

/**
 * Executes the {@link Process} with commands returned by {@link #getCommand(NodeInstallationInformation)}.
 * @param information//ww  w  .  j a v  a  2s .c om
 * @throws MojoExecutionException
 */
public void execute(NodeInstallationInformation information) throws MojoExecutionException {
    ProcessBuilder processBuilder = new ProcessBuilder(getCommand(information));
    if (workingDirectory != null) {
        if (!workingDirectory.exists()) {
            workingDirectory.mkdir();
        }
        processBuilder.directory(workingDirectory);
    }
    setNodePath(processBuilder, information);
    startProcess(processBuilder);
}

From source file:com.adguard.compiler.PackageUtils.java

private static void execute(String... commands) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(commands);
    Process p = pb.start();/*from www  . j a va 2s .c  om*/
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = reader.readLine()) != null) {
        log.debug(line);
    }
    p.waitFor();
    if (p.exitValue() != 0) {
        reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((line = reader.readLine()) != null) {
            log.error(line);
        }
        throw new IOException("Command " + ArrayUtils.toString(commands) + " not success");
    }
}

From source file:gsilva.lirc.io.CommandLineIOEngine.java

public boolean startIOEngine() {
    try {/*w w  w  .  j a v a 2  s. c  o  m*/
        List<String> cmd = new ArrayList<String>();
        cmd.add(command);
        if (device != null)
            cmd.add(device);

        ProcessBuilder pb = new ProcessBuilder(cmd);
        process = pb.start();

        stdout = process.getInputStream();
        stderr = process.getErrorStream();
        stdin = process.getOutputStream();

        new ErrorThread().start();

        return true;
    } catch (Exception e) {
        log.error("Error starting command: " + command, e);
        return false;
    }
}