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:nl.nn.adapterframework.xcom.XComSender.java

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc)
        throws SenderException, TimeOutException {
    for (Iterator filenameIt = getFileList(message).iterator(); filenameIt.hasNext();) {
        String filename = (String) filenameIt.next();
        log.debug("Start sending " + filename);

        // get file to send
        File localFile = new File(filename);

        // execute command in a new operating process
        try {// w  w  w .  java2  s . c om
            String cmd = getCommand(prc.getSession(), localFile, true);

            Process p = Runtime.getRuntime().exec(cmd, null, workingDir);

            // read the output of the process
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuffer output = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                output.append(line);
            }

            // wait until the process is completely finished
            try {
                p.waitFor();
            } catch (InterruptedException e) {
            }

            log.debug("output for " + localFile.getName() + " = " + output.toString());
            log.debug(localFile.getName() + " exits with " + p.exitValue());

            // throw an exception if the command returns an error exit value
            if (p.exitValue() != 0) {
                throw new SenderException("XComSender failed for file " + localFile.getAbsolutePath() + "\r\n"
                        + output.toString());
            }
        } catch (IOException e) {
            throw new SenderException(
                    "Error while executing command " + getCommand(prc.getSession(), localFile, false), e);
        }
    }
    return message;
}

From source file:ch.entwine.weblounge.common.impl.util.process.ProcessExecutor.java

/**
 * Executes the process. During execution, {@link #onLineRead(String)} will be
 * called for process output. When finished, {@link #onProcessFinished(int)}
 * is called./*  w w w. ja v  a2s .co m*/
 * 
 * @throws ProcessExcecutorException
 *           if an error occurs during execution
 */
public final void execute() throws ProcessExcecutorException {
    BufferedReader in = null;
    Process process = null;
    StreamHelper errorStreamHelper = null;
    try {
        // create process.
        // no special working directory is set which means the working directory
        // of the current java process is used.
        ProcessBuilder pbuilder = new ProcessBuilder(commandLine);
        pbuilder.redirectErrorStream(redirectErrorStream);
        process = pbuilder.start();
        // Consume error stream if necessary
        if (!redirectErrorStream) {
            errorStreamHelper = new StreamHelper(process.getErrorStream());
        }
        // Read input and
        in = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            if (!onLineRead(line))
                break;
        }

        // wait until the task is finished
        process.waitFor();
        int exitCode = process.exitValue();
        onProcessFinished(exitCode);
    } catch (Throwable t) {
        String msg = null;
        if (errorStreamHelper != null) {
            msg = errorStreamHelper.contentBuffer.toString();
        } else {
            msg = t.getMessage();
        }

        // TODO: What if the error stream has been redirected? Can we still get
        // the error message?

        throw new ProcessExcecutorException(msg, t);
    } finally {
        if (process != null)
            process.destroy();
        IOUtils.closeQuietly(in);
    }
}

From source file:com.adito.community.unix.UNIXUserDatabase.java

public void changePassword(String username, String oldPassword, String password,
        boolean forcePasswordChangeAtLogon) throws UserDatabaseException, InvalidLoginCredentialsException {
    if (!supportsPasswordChange()) {
        throw new InvalidLoginCredentialsException("Database doesn't support password change.");
    }//  ww  w  .java2  s .  c om
    if (forcePasswordChangeAtLogon) {
        LOG.warn(
                "Password change function of UNIX user database does not support forcePassswordChangeAtLogon.");
    }
    Process p = null;
    try {
        p = Runtime.getRuntime()
                .exec("true".equals(SystemProperties.get("adito.useDevConfig", "false"))
                        ? "sudo /usr/sbin/chpasswd"
                        : "/usr/sbin/chpasswd");
        new StreamReaderThread(p.getInputStream());
        new StreamReaderThread(p.getErrorStream());
        OutputStream out = p.getOutputStream();
        PrintWriter pw = new PrintWriter(out);
        pw.println(username + ":" + password);
        pw.flush();
        out.close();
        try {
            p.waitFor();
        } catch (InterruptedException ie) {

        }
        int ret = p.exitValue();
        if (ret != 0) {
            throw new UserDatabaseException(
                    "Failed to change password. chpasswd returned exit code " + ret + ".");
        }

    } catch (IOException e) {
        throw new UserDatabaseException("Failed to change password.", e);
    } finally {
        if (p != null) {
            Util.closeStream(p.getOutputStream());
            Util.closeStream(p.getInputStream());
            Util.closeStream(p.getErrorStream());
        }
    }
}

From source file:org.opencastproject.gstreamer.service.impl.GStreamerServiceImpl.java

/**
 * Launch the gstreamer pipeline from the gstreamerLine.
 * //w  w w .j a va2s  .  c om
 * @param gstreamerLine
 *          The gstreamer line to execute.
 * @throws GStreamerLaunchException
 *           Thrown if the pipeline fails to execute.
 */
private void launchGStreamerLine(String gstreamerLine) throws GStreamerLaunchException {
    Process process = null;
    try {
        ArrayList<String> args = new ArrayList<String>();
        args.add(getGStreamerLocation());
        args.addAll(Arrays.asList(gstreamerLine.split(" ")));
        ProcessBuilder pb = new ProcessBuilder(args);
        pb.redirectErrorStream(true); // Unfortunately merges but necessary for deadlock prevention
        process = pb.start();
        BufferedReader inputStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
        process.waitFor();
        StringBuilder sb = new StringBuilder();
        String line = inputStream.readLine();
        while (line != null) {
            sb.append(line);
            line = inputStream.readLine();
        }
        if (process.exitValue() != 0) {
            throw new GStreamerLaunchException(
                    "gstreamer failed with error code: " + process.exitValue() + ". " + sb.toString());
        }
    } catch (IOException e) {
        throw new GStreamerLaunchException(
                "Could not start gstreamer pipeline: " + gstreamerLine + "\n" + e.getMessage());
    } catch (InterruptedException e) {
        throw new GStreamerLaunchException(
                "Could not start gstreamer pipeline: " + gstreamerLine + "\n" + e.getMessage());
    }
    logger.info("Gstreamer process finished");
}

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

private CompilationResult runCompiler(List<File> files, File output_file, List<String> args, File working_dir)
        throws InvalidCompilerException {
    try {/*w ww .j  a va 2  s. c o  m*/

        if (output_file == null) {
            output_file = new File(working_dir, RandomStringUtils.randomAlphanumeric(8) + ".exe");
        }
        ArrayList<String> cmd = new ArrayList<>();
        if (prepare_env != null) {

            cmd.add(prepare_env.getAbsolutePath());
            cmd.add("&&");
        }
        cmd.add(msvc.getAbsolutePath());
        cmd.add("/Fe" + output_file.getAbsolutePath());
        if (args != null) {
            cmd.addAll(args);
        }
        if (files != null) {
            for (File file : files) {
                if (FilenameUtils.isExtension(file.getName(), "cpp")
                        || FilenameUtils.isExtension(file.getName(), "c")) {
                    cmd.add(file.getAbsolutePath());
                }

            }
        }

        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;
        return result;
    } catch (IOException | InterruptedException ex) {
        throw new InvalidCompilerException(ex);

    } catch (ExecutionException ex) {
        java.util.logging.Logger.getLogger(MSVCCompiler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:org.auscope.portal.server.web.service.TemplateLintService.java

private List<LintResult> pylint(String template) throws PortalServiceException {
    List<LintResult> lints = new ArrayList<LintResult>();

    // Save template as a temporary python file
    Path f;//from  w w  w.j  av  a 2  s.  c om
    try {
        f = Files.createTempFile("contemplate", ".py");
        BufferedWriter writer = Files.newBufferedWriter(f);
        writer.write(template);
        writer.close();
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to write template to temporary file.", ex);
    }

    // Run pylint in the temp file's directory
    String results;
    String errors;
    ArrayList<String> cmd = new ArrayList<String>(this.pylintCommand);
    cmd.add(f.getFileName().toString());
    try {
        ProcessBuilder pb = new ProcessBuilder(cmd).directory(f.getParent().toFile());

        // Start the process, and consume the results immediately so Windows is happy.
        Process p = pb.start();
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        results = stdout.lines().collect(Collectors.joining("\n"));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        errors = stderr.lines().collect(Collectors.joining("\n"));

        if (!p.waitFor(DEFAULT_TIMEOUT, TimeUnit.SECONDS)) {
            // Timed out
            throw new PortalServiceException(String.format(
                    "pylint process failed to complete before {} second timeout elapsed", DEFAULT_TIMEOUT));
        }

        // Finished successfully? pylint returns 0 on success *with no
        // issues*, 1 on failure to run properly, 2/4/8/16 for successful
        // completion with python convention/refactor/warning/error (codes
        // 2-16 bit-ORd into final result) or 32 on usage error.
        int rv = p.exitValue();
        if (rv == 1 || rv == 32) {
            logger.error("pylint failed");
            logger.debug("\npylint stderr:\n" + errors);
            logger.debug("\npylint stdout:\n" + results);
            throw new PortalServiceException(
                    String.format("pylint process returned non-zero exit value: {}", rv));
        } else if (rv != 0) {
            logger.info("pylint found issues");
        }
    } catch (PortalServiceException pse) {
        throw pse;
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to run pylint on template", ex);
    }

    // Parse results into LintResult objects
    lints = parsePylintResults(results);

    // Clean up
    try {
        Files.delete(f);
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to delete temporary template file.", ex);
    }

    return lints;
}

From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java

@Override
public int execute(ProcessConfiguration wdProvider, EnvironmentProvider envProvider,
        ProcessContext processContext, String... commands) throws IOException {
    notNull(wdProvider, "'wdProvider' may not be null");
    notNull(envProvider, "'envProvider' may not be null");
    String wd = wdProvider.getWorkingDirectory();
    /* Working directory */
    File workingDirectory = null;
    if (StringUtils.isNotBlank(wd)) {
        workingDirectory = new File(wd);
    }//from   w w  w.j  av a 2s.  c  om
    if (workingDirectory != null) {
        if (!workingDirectory.exists()) {
            throw new FileNotFoundException("Working directory does not exist:" + workingDirectory);
        }
    }
    /* Create process with dedicated environment */
    ProcessBuilder pb = new ProcessBuilder(commands);
    Map<String, String> env = envProvider.getEnvironment();
    /* init environment */
    if (env != null) {
        Map<String, String> pbEnv = pb.environment();
        for (String key : env.keySet()) {
            pbEnv.put(key, env.get(key));
        }
    }
    /* init working directory */
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    Date started = new Date();
    Process p = startProcess(pb);
    ProcessTimeoutTerminator timeoutTerminator = null;
    if (timeOutInSeconds != ENDLESS_RUNNING) {
        timeoutTerminator = new ProcessTimeoutTerminator(p, outputHandler, timeOutInSeconds);
        timeoutTerminator.start();
    }
    ProcessCancelTerminator cancelTerminator = new ProcessCancelTerminator(p,
            processContext.getCancelStateProvider());
    Thread cancelCheckThread = new Thread(cancelTerminator, "process-cancel-terminator");
    cancelCheckThread.start();

    handleProcessStarted(envProvider, p, started, workingDirectory, commands);

    handleOutputStreams(p, timeoutTerminator, processContext.getCancelStateProvider());

    /* wait for execution */
    try {
        while (isAlive(p)) {
            waitFor(p);
        }
    } catch (InterruptedException e) {
        /* ignore */
    }
    /* done */
    int exitValue = p.exitValue();
    handleProcessEnd(p);
    return exitValue;
}

From source file:com.appcel.core.encoder.executor.FfmpegEncoderExecutor.java

public void execute(MediaRecord record, File directory) throws EncoderException {

    LOGGER.info(" ffmpeg ?  video ...  Ffmpeg  ===>>> " + args);

    final ProcessBuilder pb = new ProcessBuilder().directory(directory);
    pb.redirectErrorStream(true);//  ww w  .j  av  a2 s .c  o m
    if (null != directory) {
        LOGGER.info("ffmpeg ??==========>>>" + directory.toString());
    }

    pb.command(args);

    try {
        final Process process = pb.start();
        inputStream = process.getInputStream();

        MediaInputStreamParser.parseMediaRecord(inputStream, record);

        outputStream = process.getOutputStream();
        errorStream = process.getErrorStream();
        // ???????.
        //         BufferedInputStream in = new BufferedInputStream(inputStream);
        //         BufferedReader inBr = new BufferedReader(new InputStreamReader(in));
        //         String lineStr;
        //         while ((lineStr = inBr.readLine()) != null)
        //            LOGGER.info("process.getInputStream() ===>>> " + lineStr);

        int waitfor = process.waitFor();
        if (waitfor != 0) {
            //p.exitValue()==0?1??
            if (process.exitValue() == 1) {
                LOGGER.info("===>>> ffmpeg ? Failed!");
                throw new EncoderException("ffmpeg ? Failed!");
            } else {
                LOGGER.info("==========>>> ffmpeg ??.");
            }
        } else {
            LOGGER.info("==========>>> ffmpeg ??.");
        }

    } catch (IOException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
    } catch (InterruptedException e) {
        LOGGER.error("==========>>> ffmpeg ? Message: " + e.getMessage());
        LOGGER.error("==========>>> ffmpeg ? Cause: " + e.getCause());
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        destroy();
    }
}

From source file:org.zilverline.util.SysUtils.java

/**
 * Execute a system program on a file in a certain directory.
 * //from www .ja v a 2s  .  c  o  m
 * @param unArchiveCommand the command to run, including possible options
 * @param sourceFile the file
 * @param unPackDestinationDirectory the directory
 * @return true on succes, false otherwise
 */
public static boolean execute(final String unArchiveCommand, File sourceFile, File unPackDestinationDirectory) {
    Process proc = null;
    String[] cmd = null;
    StringBuffer cmd4Log = new StringBuffer();
    log.debug("unArchiveCommand: " + unArchiveCommand);
    // prepare the command by first creating a command array, containing the program, options and source file
    // first parse the command from config
    String[] tmpCmd = unArchiveCommand.split(" ");

    try {
        // and then copy the thing into a new larger array
        cmd = new String[tmpCmd.length + 1];
        for (int i = 0; i < tmpCmd.length; i++) {
            cmd[i] = tmpCmd[i];
            // for logging, never mind the overhead
            cmd4Log.append(cmd[i] + " ");
        }
        // cmd[tmpCmd.length] = "\"" + sourceFile.getAbsolutePath() + "\"";
        cmd[tmpCmd.length] = sourceFile.getAbsolutePath();
        cmd4Log.append(cmd[tmpCmd.length]);
        log.debug("Executing: '" + cmd4Log + "' from working directory '" + unPackDestinationDirectory + "'");
        // run the command in the target directory (unPackDestinationDirectory) on the archive (sourceFile)
        // TODO: I pass cmd4Log instead of cmd[], since hh.exe does not do well...
        proc = Runtime.getRuntime().exec(cmd4Log.toString(), null, unPackDestinationDirectory);
        // any error message?
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
        // any output?
        StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
        // kick them off
        errorGobbler.start();
        outputGobbler.start();
        proc.waitFor();
        log.debug("Exit value: " + SysUtils.getErrorTextById(proc.exitValue()));
        // everthing OK?
        if (proc.exitValue() == 0) {
            // got it right first time
            log.debug("Succesfully executed: '" + cmd4Log + "'.");
            return true;
        } else {
            // error executing proc
            log.debug("Retrying, couldn't execute: '" + cmd4Log + "'. Exit value: "
                    + SysUtils.getErrorTextById(proc.exitValue()));

            // try again with cmd
            proc = Runtime.getRuntime().exec(cmd, null, unPackDestinationDirectory);
            // any error message?
            errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR");
            // any output?
            outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT");
            // kick them off
            errorGobbler.start();
            outputGobbler.start();
            proc.waitFor();
            log.debug("Exit value: " + SysUtils.getErrorTextById(proc.exitValue()));

            if (proc.exitValue() != 0) {
                // error executing proc
                log.warn(" --> Can't execute in retry (with cmd[]): '" + cmd4Log + "'. Exit value: "
                        + proc.exitValue());
                log.warn(" --> Can't execute: '" + cmd4Log + "'. "
                        + SysUtils.getErrorTextById(proc.exitValue()));
            } else {
                log.debug("Succesfully executed in retry: '" + cmd4Log + "'.");
                return true;
            }
        }
    } catch (Exception e) {
        log.error("Can't execute: " + cmd4Log, e);

        if (proc != null) {
            log.error(" --> Can't execute: '" + cmd4Log + "'. Exit value: " + proc.exitValue());
            log.error(" --> Can't execute: '" + cmd4Log + "'. " + SysUtils.getErrorTextById(proc.exitValue()));
        }
    }
    return false;
}

From source file:com.ephesoft.dcma.filebound.FileBoundExporter.java

private void executeCommand(final List<String> cmdList, final String connectionURL, final String userName,
        final String password, final String docFieldValues, final String loanNumberValue,
        final String projectName, final String loanNumberName, final String parameterFileName)
        throws DCMAApplicationException {
    InputStreamReader inputStreamReader = null;
    BufferedReader input = null;//from w ww  .jav  a2  s  .co m
    try {
        final Runtime runtime = Runtime.getRuntime();
        if (cmdList.isEmpty()) {
            LOGGER.error("No proper commands configured in resources");
            throw new DCMAApplicationException("No proper commands configured in resources");
        } else {
            String[] cmds = new String[cmdList.size()];
            for (int i = 0; i < cmdList.size(); i++) {
                if (cmdList.get(i).contains("cmd")) {
                    LOGGER.info("inside cmd");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("/c")) {
                    LOGGER.info("inside /c");
                    cmds[i] = cmdList.get(i);
                } else if (cmdList.get(i).contains("FileBoundExport")) {
                    LOGGER.info("inside FileBoundExport");
                    cmds[i] = cmdList.get(i) + " \"" + connectionURL + "\" " + userName + " " + password + " \""
                            + projectName + FileBoundConstants.ESCAPED_SPACE + docFieldValues
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberName
                            + FileBoundConstants.ESCAPED_SPACE + loanNumberValue
                            + FileBoundConstants.ESCAPED_SPACE + parameterFileName + "\"";
                }
            }
            LOGGER.info("command formed is :" + cmds[cmdList.size() - 1]);
            final Process process = runtime.exec(cmds, null,
                    new File(System.getenv(FileBoundConstants.FILEBOUND_BASE_PATH)));
            inputStreamReader = new InputStreamReader(process.getInputStream());
            input = new BufferedReader(inputStreamReader);
            String line = null;
            do {
                line = input.readLine();
                LOGGER.debug(line);
            } while (line != null);
            final int exitValue = process.exitValue();
            LOGGER.info("Command exited with error code no " + exitValue);
            if (exitValue != 0) {
                LOGGER.error("Non-zero exit value for filebound command found. So exiting the application");
                throw new DCMAApplicationException(
                        "Non-zero exit value for filebound command found. So exiting the application");
            }
        }
    } catch (Exception e) {
        LOGGER.error("Exception while expoting ");
        throw new DCMAApplicationException("Exception while expoting ", e);
    } finally {
        try {
            if (input != null) {
                input.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
        } catch (IOException e) {
            LOGGER.error("Problem in closing stream");
        }
    }
}