Example usage for java.lang Process exitValue

List of usage examples for java.lang Process exitValue

Introduction

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

Prototype

public abstract int exitValue();

Source Link

Document

Returns the exit value for the process.

Usage

From source file:nz.co.fortytwo.freeboard.installer.UploadProcessor.java

/**
 * Executes avrdude with relevant params
 * /*from  www.j a v a 2s.c o  m*/
 * @param config2
 * @param hexFile
 * @param argList
 * @param chartName
 * @param list
 * @throws IOException
 * @throws InterruptedException
 */
@SuppressWarnings("static-access")
private void executeAvrdude(File hexFile, List<String> argList) throws IOException, InterruptedException {

    ProcessBuilder pb = new ProcessBuilder(argList);
    pb.directory(hexFile.getParentFile());
    //pb.inheritIO();
    if (manager) {
        ForkWorker fork = new ForkWorker(textArea, pb);
        fork.execute();
        //fork.doInBackground();
        while (!fork.isDone()) {
            Thread.currentThread().sleep(500);
            // System.out.print(".");
        }
        if (fork.getResult() == 0) {
            System.out.print("Avrdude completed normally, and the code has been uploaded\n");
        } else {
            System.out
                    .print("ERROR: avrdude did not complete normally, and the device may not work correctly\n");
        }
    } else {
        Process p = pb.start();
        p.waitFor();
        if (p.exitValue() > 0) {
            if (manager) {
                System.out.print("ERROR: avrdude did not complete normally\n");
            }
            logger.error("avrdude did not complete normally");
            return;
        } else {
            System.out.print("Completed upload\n");
        }
    }

}

From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.core.CoreRestorer.java

protected void runRestore(DatabaseDriver databaseDriver, String fileName)
        throws IOException, InterruptedException, RunProcessException {
    int i = 1;// ww  w  .jav a 2  s . c o m
    while (true) {
        Process p = this.runCommandLine(databaseDriver.getRestoreCommandLine(), true);
        this.filer.retrieve(p.getOutputStream(), fileName);
        p.waitFor();
        if (p.exitValue() == 0) {
            break;
        }
        if (i >= this.dbCommandRetry) {
            throw new RunProcessException("\nError during process (exit code is " + p.exitValue() + "): ");
        }
        logger.warn("Retry {}/{}: fail to restore data for file {}.", i, dbCommandRetry, fileName);
        Thread.sleep(10000);
        i++;
    }
}

From source file:org.sdw.mapping.RMLmapper.java

/**
 * Execute command on local shell//from  w  w  w . jav a 2s  . co m
 * @param command : Command to be executed
 * @return : A string array with exit code and output of execution
 */
private String[] executeCommandShell(String command) {
    LOG.info("Shell command: $" + command);
    StringBuffer op = new StringBuffer();
    String out[] = new String[2];
    Process process;
    try {
        process = Runtime.getRuntime().exec(command);
        process.waitFor();
        int exitStatus = process.exitValue();
        out[0] = Integer.toString(exitStatus);
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            op.append(line + "\n");
        }
        out[1] = op.toString();
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

    return out;
}

From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Elasticsearch server ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//from   w  w  w  . j ava 2s  .c o  m
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getElasticsearchStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0)
            logger.info("Elasticsearch server has been stopped");
        else {
            logger.error("Unable to stop Elasticsearch server. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Elasticsearch correctly", e);
    }
}

From source file:com.teradata.benchto.driver.macro.shell.ShellMacroExecutionDriver.java

public void runBenchmarkMacro(String macroName, Map<String, String> environment) {
    try {/*from ww w  . j  av a 2s. c om*/
        String macroCommand = getMacroCommand(macroName);
        ProcessBuilder processBuilder = new ProcessBuilder(SHELL, "-c", macroCommand);
        processBuilder.environment().putAll(environment);
        Process macroProcess = processBuilder.start();
        LOGGER.info("Executing macro: '{}'", macroCommand);
        macroProcess.waitFor();
        boolean completedSuccessfully = macroProcess.exitValue() == 0;
        printOutput(macroProcess, !completedSuccessfully);
        checkState(completedSuccessfully, "Macro %s exited with code %s", macroName, macroProcess.exitValue());
    } catch (IOException | InterruptedException e) {
        throw new BenchmarkExecutionException("Could not execute macro " + macroName, e);
    }
}

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void stop() throws IOException {
    logger.info("Stopping Storage process ....");
    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);/* w ww  .  ja  v  a 2  s  .  c  om*/
        command.add("-n");
        command.add("-E");
    }
    for (String param : config.getStorageStopScript().split(" ")) {
        if (StringUtils.isNotBlank(param))
            command.add(param);
    }
    ProcessBuilder stopCass = new ProcessBuilder(command);
    stopCass.directory(new File("/"));
    stopCass.redirectErrorStream(true);
    Process stopper = stopCass.start();

    sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
    try {
        int code = stopper.exitValue();
        if (code == 0) {
            logger.info("Storage process has been stopped");
            instanceState.setStorageProxyAlive(false);
        } else {
            logger.error("Unable to stop storage process. Error code: {}", code);
            logProcessOutput(stopper);
        }
    } catch (Exception e) {
        logger.warn("couldn't shut down Storage process correctly", e);
    }
}

From source file:com.netflix.dynomitemanager.defaultimpl.StorageProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting Storage process"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//from   w  w  w  .  jav a2  s.com
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startStorage = new ProcessBuilder(command);

    startStorage.directory(new File("/"));
    startStorage.redirectErrorStream(true);
    Process starter = startStorage.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Storage process has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Storage process. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Storage process has an error", e);
    }
}

From source file:cu.uci.uengine.runner.impl.FileRunner.java

@Override
public RunnerResult run(Runnable runnable, RunnerContext runnerContext)
        throws IOException, InterruptedException {

    String command = buildCommand(runnable.getLanguageName(), runnable.getRunnableFile().getAbsolutePath(),
            runnerContext.getTemporaryDirectory().getAbsolutePath());

    log.debug("Running dataset " + runnerContext.getInputFile().getName());

    String name = FilenameUtils.getBaseName(runnerContext.getInputFile().getName());

    File outFile = new File(runnerContext.getTemporaryDirectory(), name + ".out");
    File errFile = new File(runnerContext.getTemporaryDirectory(), name + ".err");

    ProcessBuilder pb = buildProcessBuilder(runnable.getLimits(), runnable.getLanguageName(),
            runnerContext.getInputFile().getAbsolutePath(), outFile, errFile, command,
            String.valueOf(runnable.getId()), runnable.isTrusted());

    Process process = pb.start();

    process.waitFor();//from w  w  w .j  a  va2 s .  c  o m

    if (process.exitValue() != 0) {
        byte[] processError = new byte[process.getErrorStream().available()];
        process.getErrorStream().read(processError);
        return new RunnerResult(RunnerResult.Result.IE,
                FileUtils.readFileToString(errFile) + new String(processError));
    }
    // result,usertime,cputime,memory
    String[] results = IOUtils.toString(process.getInputStream()).split(",");

    // el resultado OK significa que no dio problema ejecutar
    // con libsandbox. Los demas resultados son errores internos
    // o resultados que no precisan que se siga ejecutando (TLE,
    // MLE, etc.)
    // En OK se debe seguir con el proximo juego de datos, los
    // demas resultados ya detienen la ejecucion.
    RunnerResult result = null;

    String resultCode = results[SandboxResults.RESULT];

    switch (resultCode) {
    case "OK":
        result = new RunnerResult(RunnerResult.Result.OK, name, Long.valueOf(results[SandboxResults.USER_TIME]),
                Long.valueOf(results[SandboxResults.CPU_TIME]),
                Long.valueOf(results[SandboxResults.MEMORY]) * 1024);
        break;
    case "AT":
        result = new RunnerResult(RunnerResult.Result.RT);
        result.messageConcat(FileUtils.readFileToString(errFile));
        break;
    case "TL":
        result = new RunnerResult(RunnerResult.Result.CTL);
        break;
    case "RF":
    case "ML":
    case "OL":
    case "RT":
    case "IE":
    case "BP":
    case "PD":
        result = new RunnerResult(RunnerResult.Result.valueOf(resultCode));
        result.messageConcat(FileUtils.readFileToString(errFile));
        break;
    }

    if (outFile.length() > runnable.getLimits().getMaxOutput()) {
        result = new RunnerResult(RunnerResult.Result.OL);
    }

    return result;
}

From source file:Main.java

public static int shellExecute(String strCommand, boolean bDisplayProgramOutput) {
    Process p = null;
    try {/*ww  w  .  j  a v  a2  s. c  om*/
        p = Runtime.getRuntime().exec(strCommand);
    } catch (IOException e) {
        e.printStackTrace();
    }

    if (p != null) {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        try {
            line = input.readLine();
            if (bDisplayProgramOutput && line != null)
                System.out.println(line);
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        while (line != null) {
            try {
                line = input.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (bDisplayProgramOutput && line != null)
                System.out.println(line);
        }

        try {
            p.waitFor();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return p.exitValue();
    }

    return -1;
}

From source file:klapersuite.prismanalysis.linux.PrismRunner.java

private int exitValueAfterTermination(Process process) {
    while (true) {
        try {//from w ww  .  ja  v a  2  s .  co  m
            logger.debug("Process exit value: " + process.waitFor());
            return process.exitValue();
        } catch (InterruptedException e) {
            logger.debug("Prism execution wait interrupted");
        }
    }
}