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:org.craftercms.cstudio.publishing.processor.ShellProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    checkConfiguration(parameters, target);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, parameters.get(FileUploadServlet.PARAM_SITE)));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(parameters, changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {/*from   w  w w . j a  v a  2  s  .  c o  m*/
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:org.apache.ambari.server.security.CertificateManager.java

/**
 * Runs os command//from w w w. ja  va2 s.c om
 *
 * @return command execution exit code
 */
private int runCommand(String command) {
    String line = null;
    Process process = null;
    BufferedReader br = null;
    try {
        process = Runtime.getRuntime().exec(command);
        br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("UTF8")));

        while ((line = br.readLine()) != null) {
            LOG.info(line);
        }

        try {
            process.waitFor();
            ShellCommandUtil.logOpenSslExitCode(command, process.exitValue());
            return process.exitValue(); //command is executed
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return -1;//some exception occurred

}

From source file:org.jsweet.test.transpiler.TranspilerTests.java

@Test
public void testCommandLine() throws Throwable {
    File outDir = new File(new File(TMPOUT_DIR), getCurrentTestName() + "/" + ModuleKind.none);

    Process process = ProcessUtil.runCommand("java", line -> {
        System.out.println(line);
    }, null, "-cp", System.getProperty("java.class.path"), //
            JSweetCommandLineLauncher.class.getName(), //
            "--tsout", outDir.getPath(), //
            "--jsout", outDir.getPath(), //
            "--sourceMap", //
            "-i", TEST_DIRECTORY_NAME + "/org/jsweet/test/transpiler/source/blocksgame");

    assertTrue(process.exitValue() == 0);
    LinkedList<File> files = new LinkedList<>();
    Util.addFiles(".ts", outDir, files);
    assertTrue(!files.isEmpty());// w w  w. ja  va2s. c  o m
    Util.addFiles(".js", outDir, files);
    assertTrue(!files.isEmpty());
    Util.addFiles(".js.map", outDir, files);
    assertTrue(!files.isEmpty());

}

From source file:org.wandora.application.tools.extractors.ocr.OCRExtractor.java

private boolean processFile(File f, TopicMap tm, Topic documentTopic) throws TopicMapException {
    boolean success = false;
    this.dateFormatter = new SimpleDateFormat();
    String text = "";
    File tmp = new File(TEMP_PATH + ".txt");

    /*/* w  ww  . j a  v  a 2 s .  c  o  m*/
     * Build the command to be executed in the form 
     *  <path/to/tesseract> <path/to/input> <path/to/output> -l <lang>
     * where the output file is temporary and is disposed of 
     * once it's contents are read.
     */

    ArrayList<String> cmd = new ArrayList<String>();
    String pathToTes = System.getenv("TESSERACT_PATH") + "tesseract";
    String lang = System.getenv("TESSERACT_LANG");
    cmd.add(pathToTes);
    cmd.add(f.getAbsolutePath());
    cmd.add(TEMP_PATH);
    if (lang != null) {
        cmd.add("-l");
        cmd.add(lang);
    }

    ProcessBuilder pb = new ProcessBuilder();
    pb.command(cmd);

    try {
        Process p = pb.start();
        StreamGobbler gobbler = new StreamGobbler(p.getInputStream());
        StreamGobbler errorGobbler = new StreamGobbler((p.getErrorStream()));
        gobbler.start();
        errorGobbler.start();
        int w = p.waitFor();
        if (w == 0 && p.exitValue() == 0) { // Exited alright
            FileInputStream is = new FileInputStream(TEMP_PATH + ".txt");
            try {
                text = IOUtils.toString(is);
            } finally {
                is.close();
            }
        } else { // Something got messed up
            String error = errorGobbler.getMessage();
            if (error.length() == 0) {
                error = gobbler.getMessage();
            }
            System.out.println(error);
            throw new RuntimeException(error);
        }

        String extracted = dateFormatter.format(new Date());
        Long size = f.length();

        if (lang == null)
            lang = "eng";

        Topic langTopic = getOrCreateLangTopic(tm, lang);
        Topic documentType = createDocumentTypeTopic(tm);
        Topic contentType = getContentType(tm);
        Topic timeExtractedType = getTimeExtractedType(tm);
        Topic fileSizeType = getSizeType(tm);

        documentTopic.addType(documentType);

        documentTopic.setData(contentType, langTopic, text);
        documentTopic.setData(timeExtractedType, langTopic, extracted);
        documentTopic.setData(fileSizeType, langTopic, "" + size);

        success = true;

    } catch (RuntimeException rte) {
        log("The OCR runtime failed for " + f.getPath());
        log(rte.getMessage());
    } catch (TopicMapException tme) { // Adding the topic failed
        log("Failed to add the file topic with the path " + f.getPath());
    } catch (IOException ioe) { // A file operation failed
        log(ioe.getMessage());
    } catch (InterruptedException ie) {
        log("The OCR process failed for the file " + f.getPath());
    } finally { // Cleanup
        tmp.delete();
    }

    return success;
}

From source file:nl.nn.adapterframework.util.ProcessUtil.java

/**
 * Execute a command as a process in the operating system.
 *  //from   ww w .java2  s.  c o  m
 * @param timeout timeout in seconds, or 0 to wait indefinetely until the process ends
 * @param command 
 * @throws TimeOutException
 * @throws SenderException
 */
public static String executeCommand(List command, int timeout) throws TimeOutException, SenderException {
    String output;
    String errors;

    Process process;
    try {
        process = Runtime.getRuntime().exec((String[]) command.toArray(new String[0]));
    } catch (Throwable t) {
        throw new SenderException("Could not execute command [" + getCommandLine(command) + "]", t);
    }
    TimeoutGuard tg = new TimeoutGuard("ProcessUtil ");
    tg.activateGuard(timeout);
    try {
        // Wait until the process is completely finished, or timeout is expired
        process.waitFor();
    } catch (InterruptedException e) {
        if (tg.threadKilled()) {
            throw new TimeOutException("command [" + getCommandLine(command) + "] timed out", e);
        } else {
            throw new SenderException(
                    "command [" + getCommandLine(command) + "] interrupted while waiting for process", e);
        }
    } finally {
        tg.cancel();
    }
    // Read the output of the process
    try {
        output = readStream(process.getInputStream());
    } catch (IOException e) {
        throw new SenderException("Could not read output of command [" + getCommandLine(command) + "]", e);
    }
    // Read the errors of the process
    try {
        errors = readStream(process.getErrorStream());
    } catch (IOException e) {
        throw new SenderException("Could not read errors of command [" + getCommandLine(command) + "]", e);
    }
    // Throw an exception if the command returns an error exit value
    int exitValue = process.exitValue();
    if (exitValue != 0) {
        throw new SenderException(
                "Nonzero exit value [" + exitValue + "] for command  [" + getCommandLine(command)
                        + "], process output was [" + output + "], error output was [" + errors + "]");
    }
    if (StringUtils.isNotEmpty(errors)) {
        log.warn("command [" + getCommandLine(command) + "] had error output [" + errors + "]");
    }
    return output;
}

From source file:perflab.loadrunnerwrapperjenkins.LoadRunnerWrapper.java

/**
 * @param command - command to execute// w ww . j  a  v  a 2s.c  o  m
 * @return command exit code
 */
private int runCommand(String command) {
    int exitCode = -1;
    logger.println("Command to run: " + command);

    try {
        Process p = Runtime.getRuntime().exec(command);
        p.waitFor();
        exitCode = p.exitValue();
    } catch (Exception err) {
        err.printStackTrace();
    }

    // getLog().info("Exit value: " + exitCode);
    return exitCode;
}

From source file:org.hyperic.hq.plugin.postgresql.PostgreSQLServerDetector.java

private String getVersion(String exec) {
    String command[] = { exec, "--version" };
    log.debug("[getVersionString] command= '" + Arrays.asList(command) + "'");
    String version = "";
    try {/*from  ww w. ja v a  2s.c  o m*/
        Process cmd = Runtime.getRuntime().exec(command);
        cmd.getOutputStream().close();
        cmd.waitFor();
        String out = inputStreamAsString(cmd.getInputStream());
        String err = inputStreamAsString(cmd.getErrorStream());
        if (log.isDebugEnabled()) {
            if (cmd.exitValue() != 0) {
                log.error("[getVersionString] exit=" + cmd.exitValue());
                log.error("[getVersionString] out=" + out);
                log.error("[getVersionString] err=" + err);
            } else {
                log.debug("[getVersionString] out=" + out);
            }
        }
        version = out;
    } catch (InterruptedException ex) {
        log.debug("[getVersionString] Error:" + ex.getMessage(), ex);
    } catch (IOException ex) {
        log.debug("[getVersionString] Error:" + ex.getMessage(), ex);
    }
    return version;
}

From source file:ape.NetworkSlowCommand.java

/**
 * This method implements the event//from   w  ww.  j  a  va2s .com
 * @param time The amount of time to delay all network traffic in milliseconds
 * @param period How long the delay should last in seconds
 * @return True if successful execution, false if an error occurred
 * @throws IOException
 */
private boolean executecommand(double time, double period) throws IOException {
    String cmd = "tc qdisc add dev eth0 root netem delay " + time + "ms && sleep " + period
            + " && tc qdisc del dev eth0 root netem";
    ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
    pb.redirectErrorStream(true);
    Process p = null;

    try {
        p = pb.start();
    } catch (IOException e) {
        System.err.println(
                "Executing network connection simulation catches IOException, enter VERBOSE mode to see the Stack Trace");
        e.printStackTrace();
        return false;
    }

    try {
        int retVal = p.waitFor();
        System.out.println("The return value for '" + cmd + "' was " + retVal);
        if (retVal != 0) {
            System.err.println("Non-zero return code (" + p.exitValue() + ") when executing: '" + cmd + "'");

            ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
            Process ptmp = tmp2.start();
            try {
                if (ptmp.waitFor() == 0)
                    System.out.println("Connection Resumed");
                else {
                    System.out.println("Connection Resumed Failed");
                    return false;
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
                System.err.println("Catches an exception when trying to recover the network");
                return false;
            }

            return false;

        }
    } catch (InterruptedException e) {
        System.err.println("Executing Command catches an Interrupt, resume connection");
        ProcessBuilder tmp2 = new ProcessBuilder("bash", "-c", "tc qdisc del dev eth0 root netem");
        Process ptmp = tmp2.start();
        try {
            if (ptmp.waitFor() == 0)
                System.out.println("Connection Resumed");
            else {
                System.out.println("Connection Resumed Failed");
                return false;
            }
        } catch (InterruptedException e1) {
            e1.printStackTrace();
            System.err.println("Catches an exception when trying to recover the network");
            e.printStackTrace();
            return false;
        }
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.sipfoundry.sipxconfig.admin.CertificateManagerImpl.java

private InputStream runCommand(String[] command) {
    try {/*from w  ww .  ja  va 2  s  .co m*/
        Runtime runtime = Runtime.getRuntime();

        Process proc = runtime.exec(command);
        LOG.debug("Executing: " + StringUtils.join(command, BLANK));
        proc.waitFor();
        if (proc.exitValue() != 0) {
            throw new ScriptExitException(proc.exitValue());
        }
        return proc.getInputStream();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:cc.arduino.packages.Uploader.java

protected boolean executeUploadCommand(String command[]) throws Exception {
    // Skip empty commands
    if (command == null || command.length == 0)
        return true;

    notFoundError = false;//from  ww  w. j a  va 2s .com
    int result = -1;

    try {
        if (verbose) {
            for (String c : command)
                System.out.print(c + " ");
            System.out.println();
        }
        Process process = ProcessUtils.exec(command);
        programmerPid = process;
        new MessageSiphon(process.getInputStream(), this, 100);
        new MessageSiphon(process.getErrorStream(), this, 100);

        // wait for the process to finish, but not forever
        // kill the flasher process after 5 minutes to avoid 100% cpu spinning
        if (!process.waitFor(5, TimeUnit.MINUTES)) {
            process.destroyForcibly();
        }
        if (!process.isAlive()) {
            result = process.exitValue();
        } else {
            result = 0;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result == 0;
}