Example usage for java.lang Process waitFor

List of usage examples for java.lang Process waitFor

Introduction

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

Prototype

public abstract int waitFor() throws InterruptedException;

Source Link

Document

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated.

Usage

From source file:com.sonar.it.android.AndroidTest.java

@Test
@Ignore("Deactivated awaiting resolution of http://jira.sonarsource.com/browse/JC-145")
public void should_run_lint_after_export_and_import_results() throws Exception {
    assumeTrue(AndroidTestSuite.isAtLeastPlugin1_1());
    String response = exportProfile("it-profile");
    File baseDir = new File("projects/SonarAndroidSample/app");
    FileUtils.write(new File(baseDir, "lint.xml"), response, Charsets.UTF_8);
    ProcessBuilder pb = new ProcessBuilder("CMD", "/C", "gradle lint");
    pb.directory(baseDir);/*from w ww  . jav  a2s.c o m*/
    pb.inheritIO();
    Process gradleProcess = pb.start();
    int exitStatus = gradleProcess.waitFor();
    if (exitStatus != 0) {
        fail("Failed to execute gradle lint.");
    }
    SonarRunner analysis = SonarRunner.create().setProfile("it-profile").setProjectName("SonarAndroidSample2")
            .setProjectKey("SonarAndroidSample2").setProjectVersion("1.0").setSourceDirs("src/main")
            .setProjectDir(baseDir).setProperty("sonar.android.lint.report", "lint-report-build.xml")
            .setProperty("sonar.import_unknown_files", "true");
    orchestrator.executeBuild(analysis);
    Resource project = sonar.find(ResourceQuery.createForMetrics("SonarAndroidSample2", "violations"));

    assertThat(project.getMeasureIntValue("violations")).isEqualTo(2);

}

From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java

public void executeAll() throws IOException, InterruptedException {

    File target = new File("target");
    target.mkdir();/*  w w w  . j av a  2s.  co  m*/

    ProcessBuilder pb = new ProcessBuilder("/usr/bin/make", "clean");
    Map<String, String> env = pb.environment();
    pb.directory(new File(homeDir, "linux"));
    File logFile = new File("log");
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    Process p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/make");
    pb.directory(new File(homeDir, "linux"));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/local/bin/protoc", "-I/usr/include", "--proto_path=src/main/protobuf",
            "src/main/protobuf/sample.proto",
            "--plugin=" + this.homeDir.getAbsolutePath() + "/linux/protoc-gen-docbook", "--docbook_out=target");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    pb = new ProcessBuilder("/usr/bin/fop", "-xml", "target/docbook_out.xml", "-xsl",
            "/usr/share/xml/docbook/stylesheet/docbook-xsl/fo/docbook.xsl", "-pdf", "target/docbook_out.pdf",
            "-param", "page.orientation", "landscape", "-param", "paper.type", "USletter");
    pb.directory(new File("."));
    pb.redirectErrorStream(true);
    pb.redirectOutput(Redirect.appendTo(logFile));
    p = pb.start();
    p.waitFor();

    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = br.readLine()) != null) {
        if (this.log.isInfoEnabled())
            this.log.info(line);
    }
}

From source file:jenkins.plugins.tanaguru.TanaguruRunner.java

public void callTanaguruService() throws IOException, InterruptedException {
    File logFile = TanaguruRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");//from   www. j a v a2s  . c  om
    File scenarioFile = TanaguruRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            TanaguruRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.deleteQuietly(logFile);
    }

    FileUtils.deleteQuietly(scenarioFile);
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else/*from   w  ww.  j ava2 s . c o  m*/
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:com.uber.hoodie.cli.commands.HDFSParquetImportCommand.java

@CliCommand(value = "hdfsparquetimport", help = "Imports hdfs dataset to a hoodie dataset")
public String convert(
        @CliOption(key = "srcPath", mandatory = true, help = "Base path for the input dataset") final String srcPath,
        @CliOption(key = "srcType", mandatory = true, help = "Source type for the input dataset") final String srcType,
        @CliOption(key = "targetPath", mandatory = true, help = "Base path for the target hoodie dataset") final String targetPath,
        @CliOption(key = "tableName", mandatory = true, help = "Table name") final String tableName,
        @CliOption(key = "tableType", mandatory = true, help = "Table type") final String tableType,
        @CliOption(key = "rowKeyField", mandatory = true, help = "Row key field name") final String rowKeyField,
        @CliOption(key = "partitionPathField", mandatory = true, help = "Partition path field name") final String partitionPathField,
        @CliOption(key = {//from  w  w w  .j  ava2s .co  m
                "parallelism" }, mandatory = true, help = "Parallelism for hoodie insert") final String parallelism,
        @CliOption(key = "schemaFilePath", mandatory = true, help = "Path for Avro schema file") final String schemaFilePath,
        @CliOption(key = "format", mandatory = true, help = "Format for the input data") final String format,
        @CliOption(key = "sparkMemory", mandatory = true, help = "Spark executor memory") final String sparkMemory,
        @CliOption(key = "retry", mandatory = true, help = "Number of retries") final String retry)
        throws Exception {

    validate(format, srcType);

    boolean initialized = HoodieCLI.initConf();
    HoodieCLI.initFS(initialized);

    String sparkPropertiesPath = Utils
            .getDefaultPropertiesFile(scala.collection.JavaConversions.asScalaMap(System.getenv()));
    SparkLauncher sparkLauncher = SparkUtil.initLauncher(sparkPropertiesPath);

    sparkLauncher.addAppArgs(SparkCommand.IMPORT.toString(), srcPath, targetPath, tableName, tableType,
            rowKeyField, partitionPathField, parallelism, schemaFilePath, sparkMemory, retry);
    Process process = sparkLauncher.launch();
    InputStreamConsumer.captureOutput(process);
    int exitCode = process.waitFor();
    if (exitCode != 0) {
        return "Failed to import dataset to hoodie format";
    }
    return "Dataset imported to hoodie format";
}

From source file:com.teasoft.teavote.util.Utilities.java

public boolean restoreDB(String dbUserName, String dbPassword, String path) throws Exception {
    //Create a batch file
    String destpath = "restore_command.bat";
    //creating batch file 
    PrintWriter writer = new PrintWriter(destpath);
    String command = "mysql -u" + dbUserName + " -p" + dbPassword + " < \"" + path + "\"";
    writer.println(command);/*  www.  j  av  a  2s .  c o m*/
    writer.close();

    //String executeCmd = "mysql -u" + dbUserName + " -p" + dbPassword + " < " + path;
    Process runtimeProcess;
    runtimeProcess = Runtime.getRuntime().exec(destpath);
    int processComplete = runtimeProcess.waitFor();
    //Delete the bat file
    new File(destpath).delete();
    return processComplete == 0;
}

From source file:com.teasoft.teavote.util.Utilities.java

public boolean restoreDB2(String dbUserName, String dbPassword, String path) throws Exception {
    //Create a batch file
    String destpath = "restore_command.bat";
    //creating batch file 
    PrintWriter writer = new PrintWriter(destpath);
    String command = "mysql -u" + dbUserName + " -p" + dbPassword + " < \"" + path + "\"";
    writer.println(command);//ww w  .  ja  va2  s. c  o m
    writer.close();

    //String executeCmd = "mysql -u" + dbUserName + " -p" + dbPassword + " < " + path;
    Process runtimeProcess;
    runtimeProcess = Runtime.getRuntime().exec(destpath);
    int processComplete = runtimeProcess.waitFor();
    //Delete the bat file
    new File(destpath).delete();
    return processComplete == 0;
}

From source file:greenapi.core.model.software.os.commands.impl.linux.NetworkInterfaceDescriptionImpl.java

@Override
public Result<NetworkInterface> execute(Argument... args) {

    if (this.isRootRequired() && !isRoot()) {
        return Result.newFailureResult(new GreenApiException("Please, execute this command as a root user!"));
    }//from  ww w .java  2s .c  o  m

    if (this.id == null && (args == null || args.length == 0 || args[0] == null)) {

        return Result.newFailureResult(new GreenApiException("networkId is null!"));

    } else if (this.id == null && (args != null && args.length > 0)) {

        this.id = args[0].value().toString();
    }

    String[][] commands = getCommandToExecute(args);

    try {
        Process process = Runtime.getRuntime().exec(commands[0], commands[1]);
        process.waitFor();

        try (InputStream is = process.getInputStream()) {
            Nodes nodes = Lshw.unmarshall(IOUtils.toString(is).trim());

            setResult(new Result<NetworkInterface>(
                    NetworkInterface.valueOf(nodes.findNodeByHardwareId(id.trim()))));
        }
    } catch (IOException | InterruptedException | LshwParserException | IllegalArgumentException exception) {
        setResult(Result.<NetworkInterface>newFailureResult(exception));
    }

    return this.result();
}

From source file:com.intbit.PhantomImageConverter.java

public File getImage(String htmlString, JSONArray json_font_list, String width, String height, String x,
        String y) throws Exception {
    File createdHtmlFile = tempHTML(htmlString, json_font_list);
    File createdJSFile = tempJS(createdHtmlFile, width, height, x, y);

    Runtime runTime = Runtime.getRuntime();
    String execPath = "phantomjs " + createdJSFile.getPath();
    //String execPath = "/Users/AR/Downloads/DevSoftware/PhantomJS/phantomjs " + createdJSFile.getPath();

    Process process = runTime.exec(execPath);
    int exitStatus = process.waitFor();
    File tempImagePath = new File(tempPath + File.separator + createdJSFile.getName().replace("js", "png"));
    logger.info(tempImagePath.getPath());

    File fileToSend = tempImagePath;
    if (!StringUtil.isEmpty(this.outputFilePath)) {
        File outputFile = new File(outputFilePath + File.separator + tempImagePath.getName());
        FileUtils.copyFile(tempImagePath, outputFile);
        fileToSend = outputFile;/*from  www  .j av a  2 s .c  o m*/
        tempImagePath.delete();
    }

    createdHtmlFile.delete();
    createdJSFile.delete();

    return fileToSend;
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {
    Process proc = null;
    int exitCode = -1;

    if (runAsRoot) {
        proc = Runtime.getRuntime().exec("su");
    } else {/*from   ww  w .  j  a v  a 2s. c  om*/
        proc = Runtime.getRuntime().exec("sh");
    }

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {
        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();
    }

    return exitCode;
}