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:com.mdsh.test.media.encoding.process.AbstractProcess.java

/**
 * Waits for the given process to end./*from  w  ww .  j  ava2s .  c  om*/
 * <p>Warning: will throw an IOException if an InterruptedException
 * is caught.
 * @param process
 * @throws IOException when the process exit value is non-zero or when
 * the current thread is interrupted before the process has ended.
 */
protected void waitForProcess(final Process process) throws IOException {
    try {
        process.waitFor();
    } catch (final InterruptedException e) {
        throw new IOException("interrupted while waiting for process: " + e.toString(), e);
    }

    final int ret = process.exitValue();

    if (0 != ret)
        throw new IOException("precess exit value was: " + ret);
}

From source file:io.syndesis.verifier.LocalProcessVerifier.java

private String getConnectorClasspath(Connector connector) throws IOException, InterruptedException {
    byte[] pom = new byte[0]; // TODO: Fix generation to use an Action projectGenerator.generatePom(connector);
    java.nio.file.Path tmpDir = Files.createTempDirectory("syndesis-connector");
    try {//  w ww .ja  v  a2  s.c  om
        Files.write(tmpDir.resolve("pom.xml"), pom);
        ArrayList<String> args = new ArrayList<>();
        args.add("mvn");
        args.add("org.apache.maven.plugins:maven-dependency-plugin:3.0.0:build-classpath");
        if (localMavenRepoLocation != null) {
            args.add("-Dmaven.repo.local=" + localMavenRepoLocation);
        }
        ProcessBuilder builder = new ProcessBuilder().command(args)
                .redirectError(ProcessBuilder.Redirect.INHERIT).directory(tmpDir.toFile());
        Map<String, String> environment = builder.environment();
        environment.put("MAVEN_OPTS", "-Xmx64M");
        Process mvn = builder.start();
        try {
            String result = parseClasspath(mvn.getInputStream());
            if (mvn.waitFor() != 0) {
                throw new IOException(
                        "Could not get the connector classpath, mvn exit value: " + mvn.exitValue());
            }
            return result;
        } finally {
            mvn.getInputStream().close();
            mvn.getOutputStream().close();
        }
    } finally {
        FileSystemUtils.deleteRecursively(tmpDir.toFile());
    }
}

From source file:org.opencb.opencga.core.common.networks.Layout.java

private int executeGraphviz(File inputFile, String layoutAlgorithm, String outputFormat, File outputFile)
        throws IOException, InterruptedException {
    //        FileUtils.checkFile(inputFile);
    //        FileUtils.checkDirectory(outputFile.getParent());

    if (inputFile.exists()) {
        throw new IOException("input file not exists");
    }//  w w w. j  av a  2  s . c  o m
    if (outputFile.getParentFile().exists()) {
        throw new IOException("output parent file not exists");
    }

    String command = "dot -K" + layoutAlgorithm + " -T" + outputFormat + " -o" + outputFile + " " + inputFile;
    logger.debug("Graphviz command line: " + command);
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    logger.debug("Graphviz exit status: " + process.exitValue());
    return process.exitValue();
}

From source file:com.varaneckas.hawkscope.plugins.execute.InputCommandKeyListener.java

/**
 * Gets synchronous command executor/*  w w w  .j  av  a  2s  .co  m*/
 * 
 * @param cmd
 * @return
 */
private Runnable getSyncExecutor(final String cmd) {
    return new Runnable() {
        public void run() {
            try {
                final long start = System.currentTimeMillis();
                final Process p = Runtime.getRuntime().exec(cmd);
                new Thread(new Runnable() {
                    public void run() {
                        while (true) {
                            try {

                                p.exitValue();
                                return;
                            } catch (final Exception e) {
                                //logging would spam
                            }
                            if ((System.currentTimeMillis() - start) > 30000) {
                                p.destroy();
                                shell.getDisplay().syncExec(new Runnable() {
                                    public void run() {
                                        output.append("Synchronous process timeout: " + cmd + '\n');
                                    }
                                });
                                return;
                            }
                            try {
                                Thread.sleep(50L);
                            } catch (final InterruptedException e) {
                                log.warn("Interrupted while executing task:" + cmd, e);
                            }
                        }
                    }
                }).start();
                final InputStream in = p.getInputStream();
                int c;
                while ((c = in.read()) != -1) {
                    output.append(String.valueOf((char) c));
                }
                in.close();
            } catch (final Exception e) {
                output.append(e.getMessage() + '\n');
            }
        }
    };
}

From source file:org.abs_models.backend.erlang.ErlangBackend.java

public void compile(Model m, File destDir, EnumSet<CompileOptions> options)
        throws IOException, InterruptedException, InternalBackendException {
    int version = getErlangVersion();
    if (version < minErlangVersion) {
        String message = "ABS requires at least erlang version " + Integer.toString(minErlangVersion)
                + ", installed version is " + Integer.toString(version);
        throw new InternalBackendException(message);
    }/*  ww  w .  j  a  va2s  . c  o  m*/
    ErlApp erlApp = new ErlApp(destDir, http_index_file, http_static_dir);
    m.generateErlangCode(erlApp, options);
    erlApp.close();

    List<String> compile_command = new ArrayList<String>();
    // We used to call "rebar compile" here but calling erlc directly
    // removes 1.5s from the compile time
    compile_command.add("erlc");
    if (options.contains(CompileOptions.DEBUG)) {
        compile_command.add("+debug_info");
    }
    compile_command.add("-I");
    compile_command.add(destDir + "/absmodel/include");
    compile_command.add("-o");
    compile_command.add(destDir + "/absmodel/ebin");
    Arrays.stream(new File(destDir, "absmodel/src/").listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.endsWith(".erl");
        }
    })).forEach((File f) -> compile_command.add(f.toString()));
    Process p = Runtime.getRuntime().exec(compile_command.toArray(new String[0]));
    if (options.contains(CompileOptions.VERBOSE))
        IOUtils.copy(p.getInputStream(), System.out);
    else
        IOUtils.copy(p.getInputStream(), new NullOutputStream());
    p.waitFor();
    if (p.exitValue() != 0) {
        String message = "Compilation of generated erlang code failed with exit value " + p.exitValue();
        if (!options.contains(CompileOptions.VERBOSE))
            message = message + "\n  (use -v for detailed compiler output)";
        throw new InternalBackendException(message);
        // TODO: consider removing the generated code here.  For now,
        // let's leave it in place for diagnosis.
    } else {
        if (options.contains(CompileOptions.VERBOSE)) {
            System.out.println();
            System.out.println("Finished.  \"gen/erl/run\" to start the model.");
            System.out.println("          (\"gen/erl/run --help\" for more options)");
        }
    }
}

From source file:com.sap.prd.mobile.ios.mios.PListAccessor.java

public String printValue(String key) throws IOException {

    try {//from  ww w . j  a v a2 s  . co m
        String command = "/usr/libexec/PlistBuddy -c \"Print :" + key + "\" \"" + plist.getAbsolutePath()
                + "\"";
        System.out.println("[INFO] PlistBuddy Add command is: '" + command + "'.");
        String[] args = new String[] { "bash", "-c", command };

        Process p = Runtime.getRuntime().exec(args);

        InputStream is = p.getInputStream();
        p.waitFor();
        int exitValue = p.exitValue();

        if (exitValue != 0) {
            String errorMessage = "n/a";
            try {
                errorMessage = new Scanner(p.getErrorStream(), Charset.defaultCharset().name())
                        .useDelimiter("\\Z").next();
            } catch (Exception ex) {
                System.out.println("[ERROR] Exception caught during retrieving error message of command '"
                        + command + "': " + ex);
            }
            throw new IllegalStateException("Execution of \"" + StringUtils.join(args, " ")
                    + "\" command failed: " + errorMessage + ". Exit code was: " + exitValue);
        }

        byte[] buff = new byte[64];
        StringBuilder sb = new StringBuilder();
        for (int i = 0; (i = is.read(buff)) != -1;) {
            sb.append(new String(buff, 0, i, Charset.defaultCharset().name()));
        }
        BufferedReader reader = new BufferedReader(new StringReader(sb.toString()));

        try {
            return reader.readLine();
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }

    catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.tools.openshift.internal.common.core.util.CommandLocationLookupStrategy.java

private String readProcess(Process p) {
    try {//  w  w w  . j  a  v a2 s .  c o  m
        p.waitFor();
    } catch (InterruptedException ie) {
        // Ignore, expected
    }
    InputStream is = null;
    if (p.exitValue() == 0) {
        is = p.getInputStream();
    } else {
        // For debugging only
        //is = p.getErrorStream();
    }
    if (is != null) {
        try {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String cmdOutput = s.hasNext() ? s.next() : "";
            if (!cmdOutput.isEmpty()) {
                cmdOutput = StringUtils.trim(cmdOutput);
                return cmdOutput;
            }
        } finally {
            try {
                if (p != null) {
                    p.destroy();
                }
                is.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    return null;
}

From source file:pl.robakowski.repository.Repository.java

@Override
public List<JSONObject> getNextResults(final IProgressMonitor monitor) {
    moreResults = false;//from  w  ww.j  a  va 2s  .c om
    List<JSONObject> list = new ArrayList<JSONObject>(30);
    if (!checkRuntime()) {
        sync.asyncExec(new Runnable() {
            @Override
            public void run() {
                MessageDialog dialog = new MessageDialog(shell, "Wrong paths", null,
                        "Invalid path to PHP or composer.phar", MessageDialog.ERROR, new String[] { "OK" }, 0);
                dialog.setBlockOnOpen(true);
                dialog.open();
                Map<String, String> params = new HashMap<String, String>();
                params.put("preferencePageId", "pl.robakowski.composer.plugin.page1");
                ParameterizedCommand command = commandService.createCommand("org.eclipse.ui.window.preferences",
                        params);
                handlerService.executeHandler(command);
            }
        });
        return list;
    }

    writeJson(json);

    try {
        final Process exec = new ProcessBuilder().command(phpPath, composerPath, "search", query).start();
        Thread killer = new Thread() {

            private boolean terminated(Process exec) {
                try {
                    exec.exitValue();
                    return true;
                } catch (IllegalThreadStateException e) {
                    return false;
                }
            }

            @Override
            public void run() {
                while (!terminated(exec)) {
                    if (monitor.isCanceled()) {
                        exec.destroy();
                    }
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                    }
                }
            };
        };
        killer.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            int space = line.indexOf(' ');
            String name = line.substring(0, space);
            String repository = line.substring(space + 1);
            JSONObject obj = new JSONObject();
            obj.put("name", name);
            obj.put("description", repository);
            list.add(obj);
        }
        exec.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return list;
}

From source file:edu.clemson.cs.nestbed.server.management.instrumentation.ProgramCompileManagerImpl.java

private void generateMigClass(File headerFile, String messageType, File directory) throws IOException {

    ProcessBuilder processBuilder;

    log.info("Generating MIG classes from header file: " + headerFile.getAbsolutePath() + " for messageType: "
            + messageType + " to directory " + directory.getAbsolutePath());

    processBuilder = new ProcessBuilder(MIG, "java", "-java-classname=" + messageType,
            headerFile.getAbsolutePath(), messageType, "-o",
            directory.getAbsolutePath() + "/" + messageType + ".java");

    processBuilder.redirectErrorStream(true);
    Process process = processBuilder.start();

    try {/*from   www.  j  a v a2s  .co m*/
        process.waitFor();
        int exitValue = process.exitValue();

        if (exitValue != 0) {
            log.error("MIG Failed with exit code:  " + exitValue);
            throw new IOException("MIG Failed with exit code " + exitValue);
        }
    } catch (InterruptedException ex) {
        log.warn("MIG interrupted");
    }
}

From source file:processing.app.CommandLineTest.java

@Test
public void testCommandLinePreferencesSave() throws Exception {
    Runtime rt = Runtime.getRuntime();
    File prefFile = File.createTempFile("test_pref", ".txt");
    prefFile.deleteOnExit();/*  w  ww.  j  a  v a 2  s.  com*/

    Process pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--save-prefs", "--preferences-file",
            prefFile.getAbsolutePath(), "--get-pref", // avoids starting the GUI
    });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--pref", "test_pref=xxx", "--preferences-file",
            prefFile.getAbsolutePath(), });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    PreferencesMap prefs = new PreferencesMap(prefFile);
    assertNull("preference should not be saved", prefs.get("test_pref"));

    pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--pref", "test_pref=xxx", "--preferences-file",
            prefFile.getAbsolutePath(), "--save-prefs", });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    prefs = new PreferencesMap(prefFile);
    assertEquals("preference should be saved", "xxx", prefs.get("test_pref"));
}