Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

To view the source code for java.lang ProcessBuilder command.

Click Source Link

Usage

From source file:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line/*w w w.j  a  v a 2  s  .  com*/
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}

From source file:com.tascape.qa.th.Utils.java

public static Process cmd(String[] commands, final File file, final File workingDir,
        final String... ignoreRegex) throws IOException {
    FileUtils.touch(file);/*  w  ww  .j a va2s  . c  om*/
    LOG.debug("Saving console output to {}", file.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);
    pb.directory(workingDir);
    LOG.info("Running command {}:  {}", workingDir == null ? "" : workingDir.getAbsolutePath(),
            pb.command().toString().replaceAll(",", ""));
    final Process p = pb.start();

    Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) {
        @Override
        public void run() {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String console = "console-" + stdIn.hashCode();
            try (PrintWriter pw = new PrintWriter(file)) {
                for (String line = stdIn.readLine(); line != null;) {
                    LOG.trace("{}: {}", console, line);
                    if (null == ignoreRegex || ignoreRegex.length == 0) {
                        pw.println(line);
                    } else {
                        boolean ignore = false;
                        for (String regex : ignoreRegex) {
                            if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore) {
                            pw.println(line);
                        }
                    }
                    pw.flush();
                    line = stdIn.readLine();
                }
            } catch (IOException ex) {
                LOG.warn(ex.getMessage());
            }
            LOG.trace("command is done");
        }
    };
    t.setDaemon(true);
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (p != null) {
                p.destroy();
            }
        }
    });
    return p;
}

From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java

/**
 * Execute the python script that builds MulVAL inputs
 *
 * @return boolean true if the execution was right
 *//*ww  w .  j  a v a  2 s .  c o m*/
public static boolean prepareMulVALInputs() {
    try {
        //Load python script properties

        String pythonPath = ProjectProperties.getProperty("python-path");
        String mulvalInputScriptFolder = ProjectProperties.getProperty("mulval-input-script-folder");
        String mulvalInputScriptPath = mulvalInputScriptFolder + "main.py";

        String hostInterfacePath = ProjectProperties.getProperty("host-interfaces-path");
        String vlansPath = ProjectProperties.getProperty("vlans-path");
        String routingPath = ProjectProperties.getProperty("routing-path");
        String flowMatrixPath = ProjectProperties.getProperty("flow-matrix-path");
        String vulnerabilityScanPath = ProjectProperties.getProperty("vulnerability-scan-path");
        String mulvalInputPath = ProjectProperties.getProperty("mulval-input");
        String topologyPath = ProjectProperties.getProperty("topology-path");

        File mulvalInputFile = new File(mulvalInputPath);
        if (mulvalInputFile.exists()) {
            mulvalInputFile.delete();
        }

        Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs");

        //TODO: use parameter nessus-files-path rather than vulnerability-scan-path, in order to manage when
        // mutliple nessus files are provided.
        ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, mulvalInputScriptPath,
                "--hosts-interfaces-file", hostInterfacePath, "--vlans-file", vlansPath, "--flow-matrix-file",
                flowMatrixPath, "--vulnerability-scan", vulnerabilityScanPath, "--routing-file", routingPath,
                "--mulval-output-file", mulvalInputFile.getAbsolutePath(), "--to-fiware-xml-topology",
                topologyPath);
        processBuilder.directory(new File(mulvalInputScriptFolder));
        StringBuilder command = new StringBuilder();
        for (String str : processBuilder.command())
            command.append(str + " ");
        Logger.getAnonymousLogger().log(Level.INFO,
                "Launch generation of MulVAL inputs with command : \n" + command.toString());
        processBuilder.redirectOutput(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        processBuilder.redirectError(
                new File(ProjectProperties.getProperty("output-path") + "/input-generation.log"));
        Process process = processBuilder.start();
        process.waitFor();

        if (!mulvalInputFile.exists()) {
            Logger.getAnonymousLogger().log(Level.WARNING,
                    "A problem happened in the generation of mulval inputs");
            return false;
        }

        return true;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.spoutcraft.launcher.entrypoint.Start.java

private static void launch(String[] args) throws Exception {
    // Text for local build (not official build)
    if (SpoutcraftLauncher.getLauncherBuild().equals("0")) {
        SpoutcraftLauncher.main(args);/* w  w w.  j av a 2  s.c om*/
        return;
    }
    // Test for exe relaunch
    SpoutcraftLauncher.setupLogger().info("Args: " + Arrays.toString(args));
    if (args.length > 0 && (args[0].equals("-Mover") || args[0].equals("-Launcher"))) {
        String[] argsCopy = new String[args.length - 1];
        for (int i = 1; i < args.length; i++) {
            argsCopy[i - 1] = args[i];
        }
        if (args[0].equals("-Mover")) {
            Mover.main(argsCopy, true);
        } else {
            SpoutcraftLauncher.main(argsCopy);
        }
        return;
    }

    migrateFolders();

    YAMLProcessor settings = SpoutcraftLauncher.setupSettings();
    if (settings == null) {
        throw new NullPointerException("The YAMLProcessor object was null for settings.");
    }
    Settings.setYAML(settings);

    int version = Integer.parseInt(SpoutcraftLauncher.getLauncherBuild());
    int latest = getLatestLauncherBuild();
    if (version < latest) {
        File codeSource = new File(Start.class.getProtectionDomain().getCodeSource().getLocation().getPath());
        File temp;
        if (codeSource.getName().endsWith(".exe")) {
            temp = new File(Utils.getWorkingDirectory(), "temp.exe");
        } else {
            temp = new File(Utils.getWorkingDirectory(), "temp.jar");
        }

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }

        ProgressSplashScreen splash = new ProgressSplashScreen();
        Download download = new Download(RestAPI.getLauncherDownloadURL(Settings.getLauncherChannel(),
                !codeSource.getName().endsWith(".exe")), temp.getPath());
        download.setListener(new LauncherDownloadListener(splash));
        download.run();

        ProcessBuilder processBuilder = new ProcessBuilder();
        ArrayList<String> commands = new ArrayList<String>();
        if (!codeSource.getName().endsWith(".exe")) {
            if (OperatingSystem.getOS().isWindows()) {
                commands.add("javaw");
            } else {
                commands.add("java");
            }
            commands.add("-Xmx256m");
            commands.add("-cp");
            commands.add(temp.getAbsolutePath());
            commands.add(Mover.class.getName());
        } else {
            commands.add(temp.getAbsolutePath());
            commands.add("-Mover");
        }
        commands.add(codeSource.getAbsolutePath());
        commands.addAll(Arrays.asList(args));
        processBuilder.command(commands);

        try {
            processBuilder.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    } else {
        SpoutcraftLauncher.main(args);
    }
}

From source file:org.apache.cassandra.utils.CLibrary.java

private static void exec(ProcessBuilder pb) throws IOException {
    Process p = pb.start();/*from w ww  . j ava2s .  co  m*/
    try {
        int errCode = p.waitFor();
        if (errCode != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            StringBuffer buff = new StringBuffer();
            String str;
            while ((str = in.readLine()) != null)
                buff.append(str).append(System.getProperty("line.separator"));
            while ((str = err.readLine()) != null)
                buff.append(str).append(System.getProperty("line.separator"));
            throw new IOException(
                    "Exception while executing the command: " + StringUtils.join(pb.command(), " ")
                            + ", command error Code: " + errCode + ", command output: " + buff.toString());
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.github.psorobka.appium.StartServerMojo.java

@Override
public void execute() throws MojoExecutionException {
    try {/*from   w  w w . ja v a  2s.  co m*/
        getLog().info("Starting Appium server...");
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("appium", "--log-timestamp", "--log",
                new File(target, "appiumLog.txt").getAbsolutePath());
        processBuilder.redirectError(new File(target, "appiumErrorLog.txt"));
        processBuilder.redirectOutput(new File(target, "appiumOutputLog.txt"));
        getLog().debug("Appium server commands " + processBuilder.command());
        Process process = processBuilder.start();
        if (!Processes.newPidProcess(process).isAlive()) {
            throw new MojoExecutionException("Failed to start Appium server");
        }
        int pid = PidUtil.getPid(process);
        getLog().info("Appium server started");
        getLog().debug("Appium server PID " + pid);
        FileUtils.writeStringToFile(new File(target, "appium.pid"), Integer.toString(pid));
        //Dumb way to sleep until appium starts - file watcher would be better
        Thread.sleep(5000);
    } catch (IOException | InterruptedException ex) {
        throw new MojoExecutionException("Failed to start Appium server", ex);
    }
}

From source file:com.blackducksoftware.integration.hub.docker.executor.Executor.java

public String[] executeCommand(final String commandString)
        throws IOException, InterruptedException, HubIntegrationException {
    final List<String> commandStringList = Arrays.asList(commandString.split(" "));
    final ProcessBuilder builder = new ProcessBuilder();
    builder.command(commandStringList.toArray(new String[commandStringList.size()]));
    builder.directory(new File("."));
    final Process process = builder.start();
    final boolean finished = process.waitFor(this.commandTimeout, TimeUnit.MILLISECONDS);
    if (!finished) {
        throw new HubIntegrationException(String.format(
                "Execution of command %s timed out (timeout: %d milliseconds)", commandString, commandTimeout));
    }/*from  ww w  .java 2 s.c  om*/
    final int errCode = process.exitValue();
    if (errCode == 0) {
        logger.debug(String.format("Execution of command: %s: Succeeded", commandString));
    } else {
        throw new HubIntegrationException(
                String.format("Execution of command: %s: Error code: %d", commandString, errCode));
    }
    final InputStream inputStream = process.getInputStream();
    final String outputString = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    logger.debug(String.format("Command output:/n%s", outputString));
    return outputString.split(System.lineSeparator());
}

From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java

/**
 * @param hiveCommd// w w w . j a v a  2 s  .c  om
 */
private static String callGenerateCommand(String hiveCommd) throws IOException {
    // Get out put path
    String tempDir = System.getProperty("java.io.tmpdir");
    logger.info("OS current temporary directory is " + tempDir);
    if (StringUtils.isEmpty(tempDir)) {
        tempDir = "/tmp";
    }
    String[] cmd = new String[2];
    String osName = System.getProperty("os.name");
    if (osName.startsWith("Windows")) {
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
    } else {
        cmd[0] = "/bin/bash";
        cmd[1] = "-c";
    }

    // hive command output
    // String hiveOutputPath = tempDir + File.separator +
    // "tmp_kylin_output";
    String hiveOutputPath = File.createTempFile("HiveOutput", null).getAbsolutePath();
    // Metadata output
    File dir = File.createTempFile("meta", null);
    dir.delete();
    dir.mkdir();
    String tableMetaOutcomeDir = dir.getAbsolutePath();

    ProcessBuilder pb = null;

    if (osName.startsWith("Windows")) {
        pb = new ProcessBuilder(cmd[0], cmd[1],
                "ssh root@sandbox 'hive -e \"" + hiveCommd + "\"' > " + hiveOutputPath);
    } else {
        pb = new ProcessBuilder(cmd[0], cmd[1], "hive -e \"" + hiveCommd + "\" > " + hiveOutputPath);
    }

    // Run hive
    pb.directory(new File(tempDir));
    pb.redirectErrorStream(true);
    Process p = pb.start();
    InputStream is = p.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = null;

    try {
        br = new BufferedReader(isr);
        String line = null;
        logger.info("Execute : " + pb.command().get(0));
        while ((line = br.readLine()) != null) {
            logger.info(line);
        }
    } finally {
        if (null != br) {
            br.close();
        }
    }
    logger.info("Hive execution completed!");

    HiveSourceTableMgmt rssMgmt = new HiveSourceTableMgmt();
    rssMgmt.extractTableDescFromFile(hiveOutputPath, tableMetaOutcomeDir);
    return tableMetaOutcomeDir;
}

From source file:org.gradle.process.internal.worker.DefaultJavaExecutableVersionProber.java

private List<String> execJavaVersion(JavaExecSpec execSpec) {
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.redirectErrorStream(true);
    processBuilder.command(execSpec.getExecutable(), "-version");
    try {/*from  w w  w . j  av  a2  s  . co  m*/
        Process process = processBuilder.start();
        return IOUtils.readLines(process.getInputStream());
    } catch (IOException e) {
        // ignore
    }
    return Collections.emptyList();
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

private static String executeVagrantManagix(ProcessBuilder pb, String command) throws Exception {
    pb.command("vagrant", "ssh", "cc", "--", pb.environment().get("MANAGIX_HOME") + command);
    Process p = pb.start();/*  ww  w.  j a v a 2 s  .  c  o  m*/
    p.waitFor();
    InputStream input = p.getInputStream();
    return IOUtils.toString(input, StandardCharsets.UTF_8.name());
}