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.codelibs.fess.helper.ProcessHelper.java

protected int destroyProcess(final String sessionId, final JobProcess jobProcess) {
    if (jobProcess != null) {
        final InputStreamThread ist = jobProcess.getInputStreamThread();
        try {/*from  ww  w  .j  ava  2 s .c o m*/
            ist.interrupt();
        } catch (final Exception e) {
            logger.warn("Could not interrupt a thread of an input stream.", e);
        }

        final CountDownLatch latch = new CountDownLatch(3);
        final Process process = jobProcess.getProcess();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getInputStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process input stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-input-" + sessionId).start();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getErrorStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process error stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-error-" + sessionId).start();
        new Thread(() -> {
            try {
                CloseableUtil.closeQuietly(process.getOutputStream());
            } catch (final Exception e) {
                logger.warn("Could not close a process output stream.", e);
            } finally {
                latch.countDown();
            }
        }, "ProcessCloser-output-" + sessionId).start();

        try {
            latch.await(10, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            logger.warn("Interrupted to wait a process.", e);
        }
        try {
            process.destroyForcibly().waitFor(processDestroyTimeout, TimeUnit.SECONDS);
            return process.exitValue();
        } catch (final Exception e) {
            logger.error("Could not destroy a process correctly.", e);
        }
    }
    return -1;
}

From source file:com.kdmanalytics.toif.framework.toolAdaptor.ToolAdaptor.java

/**
 * Run the tool. A command needs to be constructed, the same as you would if
 * you were running it from the command line.
 * /* w ww .j av  a 2s  .c  o m*/
 * @return return the process which was created by running the tool.
 * @throws ToifException
 */
public java.io.File runTool() throws ToifException {
    ProcessBuilder process = null;
    java.io.File file = null;

    final String[] command = getCommands();

    synchronized (this) {
        StringBuilder sb = new StringBuilder();
        for (String cmd : command) {
            sb.append(cmd).append(" ");
        }
    }

    process = new ProcessBuilder(command);

    // DISABLED Nicing Windows. It seems that the cmd is dodgy and
    // occasionally loses the path that we set in the environment,
    // and it certainly does not like having absolute paths to
    // executables (at least ones with spaces).
    // Put the executable directory in path
    // if(SystemUtils.IS_OS_WINDOWS && execDir != null)
    // {
    // Map<String,String> env = process.environment();
    // String envPath = env.get("PATH");
    // if(envPath != null)
    // {
    // envPath = execDir.toString() + ";" + envPath;
    // }
    // else
    // {
    // envPath = execDir.toString();
    // }
    // System.err.println("SETTING PATH: " + envPath);
    // env.put("PATH", envPath);
    // }

    // This doesn't work without spawning a bat or shell wrapper
    // // Extra path information
    // java.io.File paths = options.getPaths();
    // if(paths != null)
    // {
    // Map<String,String> env = process.environment();
    // String envPath = env.get("PATH");
    // if(envPath != null)
    // {
    // envPath = paths + ";" + envPath;
    // }
    // else
    // {
    // envPath = paths.toString();
    // }
    // System.err.println("SETTING PATH: " + envPath);
    // env.put("PATH", envPath);
    // }

    if (workingDirectory != null) {
        process.directory(workingDirectory);
    }

    java.io.File outputDirectory = options.getOutputDirectory();
    outputDirectory.mkdirs();

    file = null;
    if (adaptorImpl.getAdaptorName().equals("Splint")) {
        file = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName());

        java.io.File file2 = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName());

        java.io.File tmp = null;
        try {
            tmp = java.io.File.createTempFile("splint", ".tmp");
        } catch (IOException e) {
            LOG.error("", e);
            throw new ToifException();
        }
        if (tmp != null) {
            tmp.deleteOnExit();
            process.redirectOutput(tmp);
        }
        process.redirectError(file2);
    }
    // if (adaptorImpl.getAdaptorName().equals("Cppcheck"))
    // {
    // file = new java.io.File(options.getOutputDirectory(),
    // options.getInputFile().getName() + "." +
    // adaptorImpl.getRuntoolName());
    // java.io.File file2 = new java.io.File(options.getOutputDirectory(),
    // options.getInputFile().getName() + "-err."
    // + adaptorImpl.getRuntoolName());
    //
    // process.redirectOutput(file2);
    // process.redirectError(file);
    // }
    else {
        file = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName());
        java.io.File file2 = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName());

        process.redirectOutput(file);
        process.redirectError(file2);
    }
    try {
        Process p = process.start();

        p.waitFor();

        // Check the exit value to ensure that process did not fail
        // except splint, splint is stupid and is always non-zero
        String name = adaptorImpl.getAdaptorName();
        if ((p.exitValue() != 0) && (!"Splint".equals(name))) {
            int status = p.exitValue();
            final String msg = "Adaptor process failure detected for '" + name + "': status=" + status + " "
                    + options.getAdaptor().toString();

            LOG.error(msg);
            throw new ToifException(msg);
        }
        return file;
    } catch (final IOException | InterruptedException e) {
        final String msg = options.getAdaptor().toString() + ": Could not write to output. " + e;
        LOG.error(msg);
        throw new ToifException(e);
    }
}

From source file:cn.dockerfoundry.ide.eclipse.server.core.internal.ProcessLauncher.java

/**
 * Returns when the process has exited without errors. This will wait for
 * the process to exist, therefore will block the current thread in which it
 * is running. If any errors occur, throws CoreException CoreException
 * @throws CoreException if any errors occur while the process is being
 * launched/*  w  ww  .j  av a 2 s . c o  m*/
 */
public void run() throws CoreException {
    Exception error = null;
    Process p = null;
    try {

        List<String> processArguments = getProcessArguments();

        if (processArguments == null || processArguments.isEmpty()) {
            throw new CoreException(getErrorStatus("No process arguments were found")); //$NON-NLS-1$
        } else {

            ProcessBuilder processBuilder = new ProcessBuilder(processArguments);

            // Set any environment variables
            Map<String, String> envVars = getEnvironmentVariables();
            if (envVars != null) {
                Map<String, String> actualVars = processBuilder.environment();
                if (actualVars != null) {
                    for (Entry<String, String> entry : envVars.entrySet()) {
                        actualVars.put(entry.getKey(), entry.getValue());
                    }
                }
            }

            p = processBuilder.start();

            if (p == null) {
                throw new CoreException(getErrorStatus("No process was created.")); //$NON-NLS-1$
            } else {

                StringBuffer errorBuffer = new StringBuffer();
                // Clear the input and error streams to prevent the
                // process
                // from blocking
                handleProcessIOAsynch(p, null, errorBuffer);

                p.waitFor();

                if (errorBuffer.length() > 0) {
                    throw new CoreException(getErrorStatus(errorBuffer.toString()));
                } else if (p.exitValue() != 0) {
                    throw new CoreException(getErrorStatus("process exit value: " + p.exitValue())); //$NON-NLS-1$
                }
            }
        }
    } catch (InterruptedException ex) {
        error = ex;
    } catch (IOException ioe) {
        error = ioe;
    } catch (SecurityException se) {
        error = se;
    } finally {
        if (p != null) {
            p.destroy();
        }
    }

    if (error != null) {
        throw error instanceof CoreException ? (CoreException) error : CloudErrorUtil.toCoreException(error);
    }

}

From source file:dk.netarkivet.wayback.aggregator.IndexAggregator.java

/**
 * Calls the Unix sort command with the options <code>$filesNames -o
 * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR.
 * <p>/*  www.  j a v a 2 s  . c om*/
 * Sets the LC_ALL environment variable before making the call.
 *
 * @param files The files to merge and sort
 * @param outputFile The resulting sorted file
 * @param additionalArgs A list af extra arguments, which (if different from null) are added to the sort call.<p>
 * Note: If any of the args contain a whitespace the call will fail.
 */
private void processFiles(File[] files, File outputFile, List<String> additionalArgs) {
    if (files.length == 0) {
        // Empty file list will cause sort to wait for further input,
        // and the call will therefore never return
        return;
    }

    Process p = null;

    try {
        List<String> inputFileList = new LinkedList<String>();
        for (int i = 0; i < files.length; i++) {
            if (files[i].exists() && files[i].isFile()) {
                inputFileList.add(files[i].getCanonicalPath());
            } else {
                log.warn("File " + files[i] + " doesn't exist or isn't a regular file, "
                        + "dropping from list of files to " + "sort and merge");
            }
        }
        List<String> cmd = new LinkedList<String>();
        // Prepare to run the unix sort command, see sort manual page for
        // details
        cmd.add("sort");
        cmd.addAll(inputFileList);
        cmd.add("-o");
        cmd.add(outputFile.getCanonicalPath());
        cmd.add("-T");
        cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR));
        if (additionalArgs != null && !additionalArgs.isEmpty()) {
            for (String argument : additionalArgs) {
                ArgumentNotValid.checkTrue(argument.indexOf(' ') == -1,
                        "The argument '" + argument + "' contains spaces, this isn't allowed ");
            }
            cmd.addAll(additionalArgs);
        }
        ProcessBuilder pb = new ProcessBuilder(cmd);
        // Reset all locale definitions
        pb.environment().put("LC_ALL", "C");
        // Run the command in the user.dir directory
        pb.directory(new File(System.getProperty("user.dir")));
        p = pb.start();
        p.waitFor();
        if (p.exitValue() != 0) {
            log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue());
        }
    } catch (Exception e) {
        log.error("Failed to aggregate indexes ", e);
    }
}

From source file:org.uoa.eolus.template.Nest.java

public void copyUserTemplate(String user, String template, String target, boolean move)
        throws DirectoryException {
    String cmd = "mv";
    if (move)//from   w w  w . ja v a 2 s.  c o  m
        cmd = "mv " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/" + target
                + "; exit; \n";
    else
        cmd = "cp -r " + repo + "/" + user + "/" + template + " " + repo + "/" + user + "/." + target + "; mv "
                + repo + "/" + user + "/." + target + " " + repo + "/" + user + "/" + target + "; exit; \n";

    System.out.println("CMD: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {
        Process child = run.exec("/bin/bash");
        BufferedWriter outCommand = new BufferedWriter(new OutputStreamWriter(child.getOutputStream()));
        outCommand.write(cmd);
        outCommand.flush();
        //         InputStream out = child.getInputStream();
        //         InputStreamReader isr = new InputStreamReader(out);
        //         BufferedReader output = new BufferedReader(isr);
        //         InputStream err = child.getErrorStream();
        //         InputStreamReader eisr = new InputStreamReader(err);
        //         BufferedReader error = new BufferedReader(eisr);
        //         System.out.println("Waiting for");         
        child.waitFor();
        //         String o = "";
        //         String s;
        //         while ((s = output.readLine()) != null) {
        //            o += s + "\n";
        //         }
        //         System.out.println("stdout: " + o);
        //         String e = "";
        //         s = error.readLine(); // First line is a warning: Warning:
        //         // Permanently added 'XX.XX.XX.XX' (RSA) to
        //         // the list of known hosts.
        //         while ((s = error.readLine()) != null) {
        //            e += s + "\n";
        //         }
        //         System.out.println("stderr: " + e);

        if (child.exitValue() != 0)
            throw new InternalErrorException("Copy process failed.");
        else {
            System.out.println("Returning.");
        }
    } catch (Exception e) {
        throw new DirectoryException("Cannot execute rm command.", e);
    }
}

From source file:org.omegat.core.data.RealProject.java

/**
 * Clear cache of previously run external processes, terminating any that haven't finished.
 *///from w w w  .ja  v a 2 s.  co  m
private void flushProcessCache() {
    while (!processCache.isEmpty()) {
        Process p = processCache.pop();
        try {
            p.exitValue();
        } catch (IllegalThreadStateException ex) {
            p.destroy();
        }
    }
}

From source file:org.pshdl.model.simulation.codegenerator.CCodeGenerator.java

public IHDLInterpreterFactory<NativeRunner> createInterpreter(final File tempDir) {
    try {/*from w ww .ja  va2  s.c o  m*/
        final File testCFile = new File(tempDir, "test.c");
        String _generateMainCode = this.generateMainCode();
        Files.write(_generateMainCode, testCFile, StandardCharsets.UTF_8);
        final File testRunner = new File(tempDir, "runner.c");
        final InputStream runnerStream = CCodeGenerator.class
                .getResourceAsStream("/org/pshdl/model/simulation/includes/runner.c");
        final FileOutputStream fos = new FileOutputStream(testRunner);
        try {
            ByteStreams.copy(runnerStream, fos);
        } finally {
            runnerStream.close();
            fos.close();
        }
        final File executable = new File(tempDir, "testExec");
        this.writeAuxiliaryContents(tempDir);
        String _absolutePath = tempDir.getAbsolutePath();
        String _absolutePath_1 = testCFile.getAbsolutePath();
        String _absolutePath_2 = testRunner.getAbsolutePath();
        String _absolutePath_3 = executable.getAbsolutePath();
        final ProcessBuilder builder = new ProcessBuilder(CCodeGenerator.COMPILER, "-I", _absolutePath, "-O3",
                _absolutePath_1, _absolutePath_2, "-o", _absolutePath_3);
        ProcessBuilder _directory = builder.directory(tempDir);
        ProcessBuilder _inheritIO = _directory.inheritIO();
        final Process process = _inheritIO.start();
        process.waitFor();
        int _exitValue = process.exitValue();
        boolean _notEquals = (_exitValue != 0);
        if (_notEquals) {
            throw new RuntimeException("Process did not terminate with 0");
        }
        return new IHDLInterpreterFactory<NativeRunner>() {
            public NativeRunner newInstance() {
                try {
                    String _absolutePath = executable.getAbsolutePath();
                    final ProcessBuilder execBuilder = new ProcessBuilder(_absolutePath);
                    ProcessBuilder _directory = execBuilder.directory(tempDir);
                    ProcessBuilder _redirectErrorStream = _directory.redirectErrorStream(true);
                    final Process testExec = _redirectErrorStream.start();
                    InputStream _inputStream = testExec.getInputStream();
                    OutputStream _outputStream = testExec.getOutputStream();
                    String _absolutePath_1 = executable.getAbsolutePath();
                    return new NativeRunner(_inputStream, _outputStream, CCodeGenerator.this.em, testExec, 5,
                            _absolutePath_1);
                } catch (Throwable _e) {
                    throw Exceptions.sneakyThrow(_e);
                }
            }
        };
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}

From source file:adalid.commons.velocity.Writer.java

private void executeFile(VelocityContext fileContext, File templatePropertiesFile) {
    Properties properties = mergeProperties(fileContext, templatePropertiesFile);
    String command = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_COMMAND));
    String directory = StringUtils.trimToNull(properties.getProperty(TP_EXECUTE_DIRECTORY));
    if (command != null) {
        StrTokenizer tokenizer = new StrTokenizer(command);
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command(tokenizer.getTokenArray());
        if (directory != null) {
            File dir = new File(directory);
            if (dir.exists() && dir.isDirectory()) {
                if (dir.isAbsolute()) {
                    processBuilder.directory(dir);
                } else {
                    processBuilder.directory(dir.getAbsoluteFile());
                }//ww w.j ava  2s  . co  m
            }
        }
        try {
            Process process = processBuilder.start();
            int w = process.waitFor();
            int x = process.exitValue();
            logger.info(command + " = " + w + "," + x);
        } catch (IOException | InterruptedException ex) {
            error(ex);
        }
    }
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args, File outputFile)
        throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);/*from w w w  .ja v a 2s.c  o  m*/
    pb.environment().put("BASEDIR", project.getBasedir().getAbsolutePath());
    final Process p;
    ByteArrayOutputStream stdoutBaos = null;
    ByteArrayOutputStream stderrBaos = null;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    if (outputFile == null) {
        stdoutBaos = new ByteArrayOutputStream();
        copyIO(p.getInputStream(), stdoutBaos);
    } else {
        try {
            copyIO(p.getInputStream(), new FileOutputStream(outputFile));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Failed to copy output to : " + outputFile.getAbsolutePath(), e);
        }
    }
    stderrBaos = new ByteArrayOutputStream();
    copyIO(p.getErrorStream(), stderrBaos);
    copyIO(System.in, p.getOutputStream());
    try {
        boolean error = false;
        if (p.waitFor() != 0) {
            error = true;
        }
        if (getLog().isDebugEnabled() && stdoutBaos != null) {
            getLog().debug(stdoutBaos.toString());
        }
        if (getLog().isErrorEnabled() && stderrBaos != null) {
            getLog().error(stderrBaos.toString());
        }
        if (error) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:com.rapidminer.tools.Tools.java

/**
 * Waits for process to die and writes log messages. Terminates if exit value is not 0.
 *///w ww  . jav a 2  s  .c o  m
public static void waitForProcess(final Operator operator, final Process process, final String name)
        throws OperatorException {
    int exitValue = -1;
    try {

        // if operator was provided, start an observer thread
        // that check if the operator was stopped
        if (operator != null) {
            Thread observerThread = new Thread(operator.getName() + "-stop-observer") {

                @Override
                public void run() {
                    Integer exitValue = null;
                    while (exitValue == null) {
                        try {
                            Thread.sleep(500);
                            exitValue = process.exitValue();
                        } catch (IllegalThreadStateException | InterruptedException e) {
                            try {
                                operator.checkForStop();
                            } catch (ProcessStoppedException e1) {
                                LogService.getRoot().log(Level.INFO,
                                        "com.rapidminer.tools.Tools.terminating_process", name);
                                process.destroy();
                                try {
                                    exitValue = process.waitFor();
                                } catch (InterruptedException e2) {
                                    // in case of another interrupt, set exit value to error
                                    exitValue = -1;
                                }
                            }
                        }
                    }
                }
            };
            observerThread.setDaemon(true);
            observerThread.start();
        }
        LogService.getRoot().log(Level.ALL, "com.rapidminer.tools.Tools.waiting_for_process", name);
        exitValue = process.waitFor();
    } catch (InterruptedException e) {

        // if process was stopped because user aborted it, re-throw exception
        if (operator != null) {
            operator.checkForStop();
        }

        // if process was stopped because of an error, set exit value to -1
        exitValue = -1;
    }
    if (exitValue == 0) {
        LogService.getRoot().log(Level.FINE, "com.rapidminer.tools.Tools.process_terminated_successfully",
                name);
    } else {
        throw new UserError(operator, 306, new Object[] { name, exitValue });
    }
}