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.codelabor.system.xplatform.ant.Xml2bin.java

/**
 * Compiles XPLATFORM files./*from w w  w  . j a v a 2 s.co  m*/
 */
protected void xml2bin() {
    String[] commandArray = null;
    if (logFile != null) {
        commandArray = new String[] { executable, iniFile.getAbsolutePath(), logFile };
    } else {
        commandArray = new String[] { executable, iniFile.getAbsolutePath() };
    }

    Process proc = null;
    BufferedReader stdOut = null;
    BufferedReader stdError = null;
    try {
        proc = new ProcessBuilder(commandArray).start();
        stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        String lineOfText = null;
        while (true) {
            lineOfText = stdOut.readLine();
            if (lineOfText == null) {
                break;
            } else {
                log(lineOfText, verbosity);
            }
        }
        while (true) {
            lineOfText = stdError.readLine();
            if (lineOfText == null) {
                break;
            } else {
                log(lineOfText, Project.MSG_ERR);
            }
        }

        exitValue = proc.exitValue();
        log("Result: " + exitValue, verbosity);

        if (exitValue != 0) {
            if (failonerror) {
                throw new BuildException("Exec returned: " + exitValue, getLocation());
            }
        }
    } catch (IOException e) {
        if (failonerror) {
            throw new BuildException(e);
        } else {
            log("Warning: " + getMessage(e), Project.MSG_ERR);
        }
    } finally {
        try {
            if (stdOut != null) {
                stdOut.close();
            }
            if (stdError != null) {
                stdError.close();
            }
        } catch (IOException e) {
            if (failonerror) {
                throw new BuildException(e);
            } else {
                log("Warning: " + getMessage(e), Project.MSG_ERR);
            }
        }

    }
}

From source file:org.apache.hive.hcatalog.templeton.tool.LaunchMapper.java

@Override
public void run(Context context) throws IOException, InterruptedException {

    Configuration conf = context.getConfiguration();
    LauncherDelegator.JobType jobType = LauncherDelegator.JobType.valueOf(conf.get(JOB_TYPE));
    String statusdir = conf.get(STATUSDIR_NAME);
    if (statusdir != null) {
        try {//from w  ww  .  ja  v a  2  s.  co  m
            statusdir = TempletonUtils.addUserHomeDirectoryIfApplicable(statusdir, conf.get("user.name"));
        } catch (URISyntaxException e) {
            String msg = "Invalid status dir URI";
            LOG.error(msg, e);
            throw new IOException(msg, e);
        }
    }

    // Try to reconnect to a child job if one is found
    if (tryReconnectToRunningJob(conf, context, jobType, statusdir)) {
        return;
    }

    // Kill previously launched child MR jobs started by this launcher to prevent having
    // same jobs running side-by-side
    killLauncherChildJobs(conf, context.getJobID().toString());

    // Start the job
    Process proc = startJob(conf, context.getJobID().toString(), conf.get("user.name"),
            conf.get(OVERRIDE_CLASSPATH));

    ExecutorService pool = Executors.newCachedThreadPool();
    executeWatcher(pool, conf, context.getJobID(), proc.getInputStream(), statusdir, STDOUT_FNAME);
    executeWatcher(pool, conf, context.getJobID(), proc.getErrorStream(), statusdir, STDERR_FNAME);
    KeepAlive keepAlive = startCounterKeepAlive(pool, context);

    proc.waitFor();
    keepAlive.sendReport = false;
    pool.shutdown();
    if (!pool.awaitTermination(WATCHER_TIMEOUT_SECS, TimeUnit.SECONDS)) {
        pool.shutdownNow();
    }

    updateJobStateToDoneAndWriteExitValue(conf, statusdir, context.getJobID().toString(), proc.exitValue());

    Boolean enablelog = Boolean.parseBoolean(conf.get(ENABLE_LOG));
    if (enablelog && TempletonUtils.isset(statusdir)) {
        LOG.info("templeton: collecting logs for " + context.getJobID().toString() + " to " + statusdir
                + "/logs");
        LogRetriever logRetriever = new LogRetriever(statusdir, jobType, conf);
        logRetriever.run();
    }
}

From source file:org.alfresco.util.exec.RuntimeExec.java

/**
 * Executes the statement that this instance was constructed with an optional
 * timeout after which the command is asked to 
 * //from  w  w  w.  j  a  va2  s .  c om
 * @param properties the properties that the command might be executed with.
 * <code>null</code> properties will be treated as an empty string for substitution
 * purposes.
 * @param timeoutMs a timeout after which {@link Process#destroy()} is called.
 *        ignored if less than or equal to zero. Note this method does not guarantee
 *        to terminate the process (it is not a kill -9).
 * 
 * @return Returns the full execution results
 */
public ExecutionResult execute(Map<String, String> properties, final long timeoutMs) {
    int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1;

    // check that the command has been set
    if (command == null) {
        throw new AlfrescoRuntimeException("Runtime command has not been set: \n" + this);
    }

    // create the properties
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    String[] commandToExecute = null;
    try {
        // execute the command with full property replacement
        commandToExecute = getCommand(properties);
        final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory);
        process = thisProcess;
        if (timeoutMs > 0) {
            final String[] command = commandToExecute;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // Only try to kill the process if it is still running
                    try {
                        thisProcess.exitValue();
                    } catch (IllegalThreadStateException stillRunning) {
                        if (transformerDebugLogger.isDebugEnabled()) {
                            transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000)
                                    + " seconds). Killing process " + Arrays.deepToString(command));
                        }
                        thisProcess.destroy();
                    }
                }
            }, timeoutMs);
        }
    } catch (IOException e) {
        // The process could not be executed here, so just drop out with an appropriate error state
        String execOut = "";
        String execErr = e.getMessage();
        int exitValue = defaultFailureExitValue;
        ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut,
                execErr);
        logFullEnvironmentDump(result);
        return result;
    }

    // create the stream gobblers
    InputStreamReaderThread stdOutGobbler = new InputStreamReaderThread(process.getInputStream(), charset);
    InputStreamReaderThread stdErrGobbler = new InputStreamReaderThread(process.getErrorStream(), charset);

    // start gobbling
    stdOutGobbler.start();
    stdErrGobbler.start();

    // wait for the process to finish
    int exitValue = 0;
    try {
        if (waitForCompletion) {
            exitValue = process.waitFor();
        }
    } catch (InterruptedException e) {
        // process was interrupted - generate an error message
        stdErrGobbler.addToBuffer(e.toString());
        exitValue = defaultFailureExitValue;
    }

    if (waitForCompletion) {
        // ensure that the stream gobblers get to finish
        stdOutGobbler.waitForCompletion();
        stdErrGobbler.waitForCompletion();
    }

    // get the stream values
    String execOut = stdOutGobbler.getBuffer();
    String execErr = stdErrGobbler.getBuffer();

    // construct the return value
    ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut,
            execErr);

    // done
    logFullEnvironmentDump(result);
    return result;
}

From source file:org.jwebsocket.plugins.tts.SpeakAloudProvider.java

@Override
public byte[] generateAudioFromString(String aText, String aGender, String aSpeaker, String aFormat) {
    synchronized (this) {
        byte[] lResult = null;
        Process lProcess = null;
        try {//w ww .j av  a  2 s. c  o  m
            String lUUID = "speak"; // UUID.randomUUID().toString();
            String lTextFN = mTextPath + lUUID + ".txt";

            mLog.debug("Executing '" + mExePath + " " + lTextFN + "'...");

            // write text from client into text file of server harddisk
            File lTextFile = new File(lTextFN);
            FileUtils.writeStringToFile(lTextFile, aText, "Cp1252");

            // call conversion tool with appropriate arguments
            Runtime lRT = Runtime.getRuntime();
            // pass the text file to be converted.
            String[] lCmd = { mExePath, lTextFN };
            lProcess = lRT.exec(lCmd);

            InputStream lIS = lProcess.getInputStream();
            InputStreamReader lISR = new InputStreamReader(lIS);
            BufferedReader lBR = new BufferedReader(lISR);
            String lLine;
            while ((lLine = lBR.readLine()) != null) {
                //                  System.out.println(lLine);
            }
            // wait until process has performed completely
            if (lProcess.waitFor() != 0) {
                mLog.error("Converter exited with value " + lProcess.exitValue());
            } else {
                mLog.info("Audiostream successfully generated!");
            }
            String lAudioFN = mTextPath + lUUID + ".MP3";
            File lAudioFile = new File(lAudioFN);
            lResult = FileUtils.readFileToByteArray(lAudioFile);

            FileUtils.deleteQuietly(lTextFile);
            FileUtils.deleteQuietly(lAudioFile);

        } catch (Exception lEx) {
            mLog.error(Logging.getSimpleExceptionMessage(lEx, "performing TTS conversion"));
        } finally {
            if (null != lProcess) {
                lProcess.destroy();
            }
        }
        return lResult;
    }
}

From source file:org.intermine.install.swing.CreateDatabaseWorker.java

/**
 * Create a database using the Postgres <code>createdb</code> program.
 * /*from   w  w w.  j  a  v  a2 s .  c  o  m*/
 * @param server The database server.
 * @param databaseName The database name.
 * @param userName The database user name.
 * @param password The user password.
 * @param encoding The encoding for the database.
 * 
 * @throws IOException if there is a problem running <code>createdb</code>.
 *  
 * @throws InterruptedException if the thread is interrupted while running
 * the <code>createdb</code>.
 * 
 * @throws DatabaseCreationException if the process completes but failed
 * to create the database.
 */
protected void createDatabaseWithCreatedb(String server, String databaseName, String userName, String password,
        String encoding) throws IOException, InterruptedException, DatabaseCreationException {

    String[] commands = { "/usr/bin/createdb", "-h", server, "-E", encoding, "-O", userName, "-W", "-T",
            "template0", databaseName };

    if (logger.isDebugEnabled()) {
        StringBuilder command = new StringBuilder();
        for (int i = 0; i < commands.length; i++) {
            if (i > 0) {
                command.append(' ');
            }
            command.append(commands[i]);
        }
        logger.debug(command);
    }

    StringBuilder output = new StringBuilder();
    StringBuilder errorOutput = new StringBuilder();

    Integer exitCode = null;
    Process p = Runtime.getRuntime().exec(commands);
    try {
        BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        boolean passwordSet = false;
        while (true) {
            try {
                while (stdin.ready()) {
                    char c = (char) stdin.read();
                    output.append(c);
                }
                while (stderr.ready()) {
                    char c = (char) stderr.read();
                    errorOutput.append(c);
                }

                if (!passwordSet && errorOutput.indexOf("Password:") >= 0) {
                    PrintStream out = new PrintStream(p.getOutputStream(), true);
                    out.println(password);
                    passwordSet = true;
                }

                exitCode = p.exitValue();
                // If this succeeds, we're done.
                break;
            } catch (IllegalThreadStateException e) {
                // Process not done, so wait and continue.
                Thread.sleep(250);
            }
        }
    } finally {
        try {
            p.exitValue();
        } catch (IllegalThreadStateException e) {
            // Not finished, but something has failed.
            p.destroy();
        }
    }

    if (errorOutput.length() > 0) {
        throw new DatabaseCreationException(exitCode, output.toString(), errorOutput.toString());
    }

    if (exitCode != 0) {
        throw new DatabaseCreationException("Return code from createdb = " + exitCode, exitCode,
                output.toString(), errorOutput.toString());
    }
}

From source file:org.applause.applausedsl.ui.generator.formatter.UncrustifyFormatter.java

/**
 * Formats the given string with Uncrustify.
 * //from w  w w  . j a v  a 2s  .  co  m
 * @param unformatted
 *            Unformatted code
 * @param args
 * @return Formatted code
 */
public CharSequence format(CharSequence unformatted, List<String> args) {
    if (unformatted == null) {
        return null;
    }
    if (args == null) {
        throw new IllegalArgumentException("args is null");
    }
    Process proc = null;
    // Store original code as fallback
    CharSequence result = unformatted;
    try {
        int rc;

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

        proc = pb.start();

        Writer stdinWriter = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
        IOUtils.copy(new StringReader(unformatted.toString()), stdinWriter);
        stdinWriter.close();

        rc = proc.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String lineRead;
        while ((lineRead = br.readLine()) != null) {
            if (lineRead.startsWith("Parsing:")) {
                LOG.debug(lineRead);
            } else {
                LOG.warn(lineRead);
            }
        }
        if (rc != 0) {
            LOG.warn("Execution of uncrustify failed with error.");
        } else {
            StringWriter sw = new StringWriter(unformatted.length());
            IOUtils.copy(proc.getInputStream(), sw);
            result = sw.getBuffer();
            rc = proc.exitValue();
            if (rc != 0) {
                LOG.warn("Execution of uncrustify failed with error.");

            } else {
                if (LOG.isDebugEnabled())
                    LOG.debug("Execution of uncrustify was successful.");
            }
        }
    } catch (Exception re) {
        LOG.warn(re.getClass().getSimpleName() + ": " + re.getMessage());
    } finally {
        if (proc != null) {
            IOUtils.closeQuietly(proc.getErrorStream());
            IOUtils.closeQuietly(proc.getInputStream());
            IOUtils.closeQuietly(proc.getOutputStream());
        }
    }
    return result;
}

From source file:de.flyingsnail.ipv6droid.android.VpnThread.java

/**
 *     Android 4.4 has introduced a bug with VPN routing. The android developers appear very
 *     pleased with their broken idea and unwilling to fix in any forseeable future.
 *     This methods tries to check if our device suffers from this problem.
 *     @return true if routing is OK/*from  ww  w  .ja  va 2  s.  c  om*/
 */
private boolean checkRouting() {
    try {
        Process routeChecker = Runtime.getRuntime()
                .exec(new String[] { "/system/bin/ip", "-f", "inet6", "route", "show", "default", "::/1" });
        BufferedReader reader = new BufferedReader(new InputStreamReader(routeChecker.getInputStream()));
        BufferedReader errreader = new BufferedReader(new InputStreamReader(routeChecker.getErrorStream()));
        String output = reader.readLine();
        String errors = errreader.readLine();
        try {
            routeChecker.waitFor();
        } catch (InterruptedException e) {
            // we got interrupted, so we kill our process
            routeChecker.destroy();
        }
        int exitValue = 0;
        try {
            exitValue = routeChecker.exitValue();
        } catch (IllegalStateException ise) {
            // command still running. Hmmm.
        }
        if (output == null || exitValue != 0) {
            Log.e(TAG, "error checking route: " + errors);
            return false; // default route is not set on ipv6
        } else
            return true;
    } catch (IOException e) {
        return false; // we cannot even check :-(
    }
}

From source file:org.gytheio.util.exec.RuntimeExec.java

/**
 * Executes the statement that this instance was constructed with an optional
 * timeout after which the command is asked to 
 * //w ww.j av a2 s.  c  o m
 * @param properties the properties that the command might be executed with.
 * <code>null</code> properties will be treated as an empty string for substitution
 * purposes.
 * @param timeoutMs a timeout after which {@link Process#destroy()} is called.
 *        ignored if less than or equal to zero. Note this method does not guarantee
 *        to terminate the process (it is not a kill -9).
 * @param stdOutGobblerFactory the object used to create the output input stream reader
 *        If null the defaultInputStreamReaderThreadFactory will be used
 * @param stdErrGobblerFactory the object used to create the error input stream reader
 *        If null the defaultInputStreamReaderThreadFactory will be used
 * 
 * @return Returns the full execution results
 */
public ExecutionResult execute(Map<String, String> properties,
        InputStreamReaderThreadFactory stdOutGobblerFactory,
        InputStreamReaderThreadFactory stdErrGobblerFactory, final long timeoutMs) {
    int defaultFailureExitValue = errCodes.size() > 0 ? ((Integer) errCodes.toArray()[0]) : 1;

    // check that the command has been set
    if (command == null) {
        throw new GytheioRuntimeException("Runtime command has not been set: \n" + this);
    }

    if (stdOutGobblerFactory == null) {
        stdOutGobblerFactory = defaultInputStreamReaderThreadFactory;
    }
    if (stdErrGobblerFactory == null) {
        stdErrGobblerFactory = defaultInputStreamReaderThreadFactory;
    }

    // create the properties
    Runtime runtime = Runtime.getRuntime();
    Process process = null;
    String[] commandToExecute = null;
    try {
        // execute the command with full property replacement
        commandToExecute = getCommand(properties);
        final Process thisProcess = runtime.exec(commandToExecute, processProperties, processDirectory);
        process = thisProcess;
        if (timeoutMs > 0) {
            final String[] command = commandToExecute;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // Only try to kill the process if it is still running
                    try {
                        thisProcess.exitValue();
                    } catch (IllegalThreadStateException stillRunning) {
                        if (transformerDebugLogger.isDebugEnabled()) {
                            transformerDebugLogger.debug("Process has taken too long (" + (timeoutMs / 1000)
                                    + " seconds). Killing process " + Arrays.deepToString(command));
                        }
                        thisProcess.destroy();
                    }
                }
            }, timeoutMs);
        }
    } catch (IOException e) {
        // The process could not be executed here, so just drop out with an appropriate error state
        String execOut = "";
        String execErr = e.getMessage();
        int exitValue = defaultFailureExitValue;
        ExecutionResult result = new ExecutionResult(null, commandToExecute, errCodes, exitValue, execOut,
                execErr);
        logFullEnvironmentDump(result);
        return result;
    }

    // create the stream gobblers
    InputStreamReaderThread stdOutGobbler = stdOutGobblerFactory.createInstance(process.getInputStream(),
            charset);
    InputStreamReaderThread stdErrGobbler = stdErrGobblerFactory.createInstance(process.getErrorStream(),
            charset);

    // start gobbling
    stdOutGobbler.start();
    stdErrGobbler.start();

    // wait for the process to finish
    int exitValue = 0;
    try {
        if (waitForCompletion) {
            exitValue = process.waitFor();
        }
    } catch (InterruptedException e) {
        // process was interrupted - generate an error message
        stdErrGobbler.addToBuffer(e.toString());
        exitValue = defaultFailureExitValue;
    }

    if (waitForCompletion) {
        // ensure that the stream gobblers get to finish
        stdOutGobbler.waitForCompletion();
        stdErrGobbler.waitForCompletion();
    }

    // get the stream values
    String execOut = stdOutGobbler.getBuffer();
    String execErr = stdErrGobbler.getBuffer();

    // construct the return value
    ExecutionResult result = new ExecutionResult(process, commandToExecute, errCodes, exitValue, execOut,
            execErr);

    // done
    logFullEnvironmentDump(result);
    return result;
}

From source file:org.jboss.qa.jcontainer.util.executor.ProcessExecutor.java

public Process asyncExecute() throws IOException {
    if (processBuilder == null) {
        processBuilder = new ProcessBuilder(commands);
    }/*from w w  w . j  av  a 2s . c  om*/

    if (outputStream == null) {
        if (SystemUtils.IS_OS_HP_UX) {
            outputStream = System.out;
        } else {
            processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);
        }
    }
    if (errorStream == null && !redirectError) {
        if (SystemUtils.IS_OS_HP_UX) {
            outputStream = System.err;
        } else {
            processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT);
        }
    }
    processBuilder.redirectErrorStream(redirectError);

    final Process process = processBuilder.start();

    final ExecutorService executeService = Executors.newCachedThreadPool();
    final List<Future> futures = new ArrayList<>();

    if (outputStream != null) {
        final Pipe pipe = Pipe.open();
        futures.add(executeService
                .submit(new CopyIntoChannel(Channels.newChannel(process.getInputStream()), pipe.sink())));
        futures.add(
                executeService.submit(new CopyIntoChannel(pipe.source(), Channels.newChannel(outputStream))));
    }
    if (errorStream != null && !redirectError) {
        final Pipe pipe = Pipe.open();
        futures.add(executeService
                .submit(new CopyIntoChannel(Channels.newChannel(process.getErrorStream()), pipe.sink())));
        futures.add(
                executeService.submit(new CopyIntoChannel(pipe.source(), Channels.newChannel(errorStream))));
    }

    final Future<Integer> future = executeService.submit(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            process.waitFor();
            for (Future f : futures) {
                f.get();
            }
            return process.exitValue();
        }
    });

    final Process proxyProcess = new ProcessWrapper(process, future);

    executeService.shutdown();
    return proxyProcess;
}