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.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java

public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) {

    String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" "));

    LOGGER.info("===================");
    LOGGER.info("Command to invoke: {}", lineToRun);

    ProcessBuilder processBuilder = new ProcessBuilder(command);
    updateEnvOfProcessBuilder(processBuilder.environment(), properties);

    if (workingDir != null) {
        processBuilder.directory(new File(workingDir));
    }// w  w  w. j  a  v a 2  s .c  o m
    processBuilder.redirectErrorStream(true);

    StringBuilder processOutput = new StringBuilder();
    Process process;
    BufferedReader stdout = null;

    try {
        process = processBuilder.start();
        stdout = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = stdout.readLine()) != null) {
            LOGGER.debug(":::::: " + line);
            processOutput.append(line);
            processOutput.append('\n');
        }

        try {
            process.waitFor();
        } catch (InterruptedException e) {
            LOGGER.error("Command '" + lineToRun + "' interrupted.", e);
        }
    } catch (IOException e) {
        LOGGER.error("Problem executing external process.", e);
        return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e);
    } finally {
        closeReader(stdout);
    }

    ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(),
            processOutput.toString(), null);

    LOGGER.info("Exit value: {}", result.getExitCode());
    LOGGER.info("===================");
    return result;
}

From source file:org.apache.kudu.client.MiniKuduCluster.java

/**
 * Starts a process using the provided command and configures it to be daemon,
 * redirects the stderr to stdout, and starts a thread that will read from the process' input
 * stream and redirect that to LOG.//from w w w  .jav  a2 s  .  co  m
 * @param port RPC port used to identify the process
 * @param command process and options
 * @return The started process
 * @throws Exception Exception if an error prevents us from starting the process,
 * or if we were able to start the process but noticed that it was then killed (in which case
 * we'll log the exit value).
 */
private Process configureAndStartProcess(int port, List<String> command) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.redirectErrorStream(true);
    if (miniKdc != null) {
        processBuilder.environment().putAll(miniKdc.getEnvVars());
    }
    Process proc = processBuilder.start();
    ProcessInputStreamLogPrinterRunnable printer = new ProcessInputStreamLogPrinterRunnable(
            proc.getInputStream());
    Thread thread = new Thread(printer);
    thread.setDaemon(true);
    thread.setName(Iterables.getLast(Splitter.on(File.separatorChar).split(command.get(0))) + ":" + port);
    PROCESS_INPUT_PRINTERS.add(thread);
    thread.start();

    Thread.sleep(300);
    try {
        int ev = proc.exitValue();
        throw new Exception(String.format("We tried starting a process (%s) but it exited with value=%s",
                command.get(0), ev));
    } catch (IllegalThreadStateException ex) {
        // This means the process is still alive, it's like reverse psychology.
    }
    return proc;
}

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Scans a matroska movie file for attachments.
 *
 * @param movieFile the movie file to scan
 *//*from   w w  w  .  j a v a  2 s  . c o m*/
private static void scanAttachments(MovieFile movieFile) {
    if (movieFile.isAttachmentsScanned()) {
        // attachments has been scanned during rescan of movie
        return;
    }

    // clear existing attachments
    movieFile.clearAttachments();

    // the file with possible attachments
    File scanFile = movieFile.getFile();

    LOG.debug("Scanning file {}", scanFile.getName());
    int attachmentId = 0;
    try {
        // create the command line
        List<String> commandMkvInfo = new ArrayList<>(MT_INFO_EXE);
        commandMkvInfo.add(scanFile.getAbsolutePath());

        ProcessBuilder pb = new ProcessBuilder(commandMkvInfo);

        // set up the working directory.
        pb.directory(MT_PATH);

        Process p = pb.start();

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = localInputReadLine(input);
        while (line != null) {
            if (line.contains("+ Attached")) {
                // increase the attachment id
                attachmentId++;
                // next line contains file name
                String fileNameLine = localInputReadLine(input);
                // next line contains MIME type
                String mimeTypeLine = localInputReadLine(input);

                Attachment attachment = createAttachment(attachmentId, fileNameLine, mimeTypeLine,
                        movieFile.getFirstPart(), movieFile.getLastPart());
                if (attachment != null) {
                    attachment.setSourceFile(movieFile.getFile());
                    movieFile.addAttachment(attachment);
                }
            }

            line = localInputReadLine(input);
        }

        if (p.waitFor() != 0) {
            LOG.error("Error during attachment retrieval - ErrorCode={}", p.exitValue());
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
    }

    // attachments has been scanned; no double scan of attachments needed
    movieFile.setAttachmentsScanned(Boolean.TRUE);
}

From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java

@Override
public void exportSchema(ExportParams params) throws MojoExecutionException {
    BufferedReader reader = null;
    try {//from ww  w.j  a  v  a2 s  .  c  o m
        File dumpFile = params.getDumpFile();
        String user = params.getUser();
        String password = params.getPassword();
        String schema = params.getSchema();

        createDirectory(user, password, dumpFile.getParentFile());
        ProcessBuilder pb = new ProcessBuilder("expdp", user + "/" + password, "directory=exp_dir",
                "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "reuse_dumpfiles=y", "nologfile=y");
        pb.redirectErrorStream(true);
        Process process = pb.start();

        Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows")
                ? Charset.forName("Shift_JIS")
                : Charset.forName("UTF-8");

        reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset));
        //???????????????
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        process.waitFor();
        if (process.exitValue() != 0) {
            throw new MojoExecutionException("oracle export error");
        }
        process.destroy();
    } catch (Exception e) {
        throw new MojoExecutionException("oracle export", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:net.przemkovv.sphinx.compiler.GXXCompiler.java

private CompilationResult compile(ArrayList<String> cmd, List<File> files, File output_file)
        throws IOException, ExecutionException, InterruptedException {
    if (files != null) {
        for (File file : files) {
            if (FilenameUtils.isExtension(file.getName(), "cpp")
                    || FilenameUtils.isExtension(file.getName(), "c")) {
                cmd.add(file.getAbsolutePath());
            }/*ww  w .  j  a  v a  2 s .co m*/
        }
    }

    logger.debug("Compiler command line: {}", cmd);
    final Process process = Runtime.getRuntime().exec(cmd.toArray(new String[cmd.size()]), null,
            output_file.getParentFile());

    Future<String> output_error_result = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return Utils.readAllFromInputStream(process.getErrorStream());
        }
    });
    Future<String> output_result = pool.submit(new Callable<String>() {
        @Override
        public String call() throws Exception {
            return Utils.readAllFromInputStream(process.getInputStream());
        }
    });
    process.waitFor();
    CompilationResult result = new CompilationResult();
    result.output_errror = output_error_result.get();
    result.output = output_result.get();
    result.exit_value = process.exitValue();
    result.executable_file = output_file;
    result.prepare_env = prepare_env_cmd;
    return result;
}

From source file:jp.co.tis.gsp.tools.dba.dialect.OracleDialect.java

@Override
public void importSchema(ImportParams params) throws MojoExecutionException {
    BufferedReader reader = null;

    try {/*w w w. j  a  va2  s. c o  m*/
        File dumpFile = params.getDumpFile();

        if (!dumpFile.exists())
            throw new MojoExecutionException(dumpFile.getName() + " is not found?");

        String user = params.getAdminUser();
        String password = params.getAdminPassword();
        String schema = params.getSchema();

        createDirectory(user, password, dumpFile.getParentFile());

        // Oracle?????
        dropAllObjects(user, password, schema);

        ProcessBuilder pb = new ProcessBuilder("impdp", user + "/" + password, "directory=exp_dir",
                "dumpfile=" + dumpFile.getName(), "schemas=" + schema, "nologfile=y", "exclude=user");
        pb.redirectErrorStream(true);
        Process process = pb.start();
        Charset terminalCharset = System.getProperty("os.name").toLowerCase().contains("windows")
                ? Charset.forName("Shift_JIS")
                : Charset.forName("UTF-8");

        reader = new BufferedReader(new InputStreamReader(process.getInputStream(), terminalCharset));
        //???????????????
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        process.waitFor();
        if (process.exitValue() != 0) {
            throw new MojoExecutionException("oracle import error");
        }
        process.destroy();
    } catch (Exception e) {
        throw new MojoExecutionException("oracle import", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

}

From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java

/**
 * Wait for a given process./*from  w  ww . j a  va2  s.  co m*/
 *
 * @param process the process one wants to wait for.
 */
protected void waitFor(Process process) {
    try {
        process.waitFor();
        setExitValue(process.exitValue());
    } catch (InterruptedException e) {
        process.destroy();
    }
}

From source file:org.opencastproject.sox.impl.SoxServiceImpl.java

private List<String> launchSoxProcess(List<String> command) throws SoxException {
    Process process = null;
    BufferedReader in = null;//  w ww  . j  a  v  a 2 s .c  o m
    try {
        logger.info("Start sox process {}", command);
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(true); // Unfortunately merges but necessary for deadlock prevention
        process = pb.start();
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        process.waitFor();
        String line = null;
        List<String> stats = new ArrayList<String>();
        while ((line = in.readLine()) != null) {
            logger.info(line);
            stats.add(line);
        }
        if (process.exitValue() != 0)
            throw new SoxException("Sox process failed with error code: " + process.exitValue());
        logger.info("Sox process finished");
        return stats;
    } catch (IOException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } catch (InterruptedException e) {
        throw new SoxException("Could not start sox process: " + command + "\n" + e.getMessage());
    } finally {
        IoSupport.closeQuietly(in);
    }
}

From source file:net.pms.service.ProcessManager.java

/**
 * Checks if the process is still alive using reflection if possible.
 *
 * @param process the {@link Process} to check.
 * @return {@code true} if the process is still alive, {@code false}
 *         otherwise./*w  ww  .  j  a v a2 s .c o m*/
 */
@SuppressFBWarnings("REC_CATCH_EXCEPTION")
public static boolean isProcessIsAlive(@Nullable Process process) {
    if (process == null) {
        return false;
    }
    // XXX replace with Process.isAlive() in Java 8
    try {
        Field field;
        field = process.getClass().getDeclaredField("handle");
        field.setAccessible(true);
        long handle = (long) field.get(process);
        field = process.getClass().getDeclaredField("STILL_ACTIVE");
        field.setAccessible(true);
        int stillActive = (int) field.get(process);
        Method method;
        method = process.getClass().getDeclaredMethod("getExitCodeProcess", long.class);
        method.setAccessible(true);
        int exitCode = (int) method.invoke(process, handle);
        return exitCode == stillActive;
    } catch (Exception e) {
        // Reflection failed, use the backup solution
    }
    try {
        process.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:egovframework.com.utl.sys.fsm.service.FileSystemUtils.java

/**
 * Performs the os command.// w ww.j a  v a 2  s  .c  o m
 *
 * @param cmdAttribs  the command line parameters
 * @param max The maximum limit for the lines returned
 * @return the parsed data
 * @throws IOException if an error occurs
 */
List performCommand(String[] cmdAttribs, int max) throws IOException {
    // this method does what it can to avoid the 'Too many open files' error
    // based on trial and error and these links:
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
    // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
    // however, its still not perfect as the JDK support is so poor
    // (see commond-exec or ant for a better multi-threaded multi-os solution)

    List lines = new ArrayList(20);
    Process proc = null;
    InputStream in = null;
    OutputStream out = null;
    InputStream err = null;
    BufferedReader inr = null;
    try {
        proc = openProcess(cmdAttribs);
        in = proc.getInputStream();
        out = proc.getOutputStream();
        err = proc.getErrorStream();
        inr = new BufferedReader(new InputStreamReader(in));
        String line = inr.readLine();
        while (line != null && lines.size() < max) {
            line = line.toLowerCase().trim();
            lines.add(line);
            line = inr.readLine();
        }

        proc.waitFor();
        if (proc.exitValue() != 0) {
            // os command problem, throw exception
            throw new IOException("Command line returned OS error code '" + proc.exitValue() + "' for command "
                    + Arrays.asList(cmdAttribs));
        }
        if (lines.size() == 0) {
            // unknown problem, throw exception
            throw new IOException(
                    "Command line did not return any info " + "for command " + Arrays.asList(cmdAttribs));
        }
        return lines;

    } catch (InterruptedException ex) {
        throw new IOException("Command line threw an InterruptedException '" + ex.getMessage()
                + "' for command " + Arrays.asList(cmdAttribs));
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(err);
        IOUtils.closeQuietly(inr);
        if (proc != null) {
            proc.destroy();
        }
    }
}