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.cloudcoder.builder2.process.ProcessRunner.java

/**
 * Check whether or not the process is still running.
 * /* ww  w.  j  a va  2  s  . co m*/
 * @return true if the process is still running, false if it has completed
 */
public boolean isRunning() {
    Process p = process;

    if (p == null) {
        // Process hasn't started yet.
        // Count that as "running".
        return true;
    }

    try {
        p.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:org.fusesource.fabric.itests.paxexam.mq.MQDistroTest.java

@Test
public void testMQ() throws Exception {

    // send message via webconsole, consume from jms openwire
    HttpClient client = new HttpClient();

    // set credentials
    client.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD));

    // need to first get the secret
    GetMethod get = new GetMethod(WEB_CONSOLE_URL + "send.jsp");
    get.setDoAuthentication(true);/* w w  w .j ava  2s.c  o m*/

    // Give console some time to start
    for (int i = 0; i < 20; i++) {
        Thread.currentThread().sleep(1000);
        try {
            i = client.executeMethod(get);
        } catch (java.net.ConnectException ignored) {
        }
    }
    assertEquals("get succeeded on " + get, 200, get.getStatusCode());

    String response = get.getResponseBodyAsString();
    final String secretMarker = "<input type=\"hidden\" name=\"secret\" value=\"";
    String secret = response.substring(response.indexOf(secretMarker) + secretMarker.length());
    secret = secret.substring(0, secret.indexOf("\"/>"));

    final String destination = "validate.console.send";
    final String content = "Hi for the " + Math.random() + "' time";

    PostMethod post = new PostMethod(WEB_CONSOLE_URL + "sendMessage.action");
    post.setDoAuthentication(true);
    post.addParameter("secret", secret);

    post.addParameter("JMSText", content);
    post.addParameter("JMSDestination", destination);
    post.addParameter("JMSDestinationType", "queue");

    // execute the send
    assertEquals("post succeeded, " + post, 302, client.executeMethod(post));

    // consume what we sent
    ActiveMQConnection connection = (ActiveMQConnection) new ActiveMQConnectionFactory()
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connection.start();
    try {
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        TextMessage textMessage = (TextMessage) session.createConsumer(new ActiveMQQueue(destination))
                .receive(10 * 1000);
        assertNotNull("got a message", textMessage);
        assertEquals("it is ours", content, textMessage.getText());
    } finally {
        connection.close();
    }

    // verify osgi registration of cf
    ConnectionFactory connectionFactory = getOsgiService(ConnectionFactory.class);
    assertTrue(connectionFactory instanceof ActiveMQConnectionFactory);
    ActiveMQConnection connectionFromOsgiFactory = (ActiveMQConnection) connectionFactory
            .createConnection(USER_NAME_ND_PASSWORD, USER_NAME_ND_PASSWORD);
    connectionFromOsgiFactory.start();
    try {
        assertEquals("same broker", connection.getBrokerName(), connectionFromOsgiFactory.getBrokerName());
    } finally {
        connectionFromOsgiFactory.close();
    }

    // verify mq-client
    Process process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar producer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("producer worked, exit(0)?", 0, process.exitValue());

    process = Runtime.getRuntime()
            .exec("java -jar extras" + File.separator + "mq-client.jar consumer --count 1 --user "
                    + USER_NAME_ND_PASSWORD + " --password " + USER_NAME_ND_PASSWORD, null, // env
                    new File(System.getProperty("user.dir")));
    process.waitFor();
    assertEquals("consumer worked, exit(0)?", 0, process.exitValue());

}

From source file:com.photon.phresco.plugins.xcode.CodeValidation.java

public void execute() throws MojoExecutionException {

    try {//w  w w .  j  a v  a2  s.c o m
        ProcessBuilder pb = new ProcessBuilder(check);
        // Include errors in output
        pb.redirectErrorStream(true);

        List<String> commands = pb.command();

        commands.add("-o");
        commands.add("make");
        commands.add("xcodebuild");
        commands.add("-scheme");
        commands.add(scheme);
        commands.add("-project");
        commands.add(xcodeProject);
        commands.add("build");
        getLog().info("List of commands" + pb.command());
        // pb.command().add("install");
        pb.directory(new File(basedir));
        Process child = pb.start();

        // Consume subprocess output and write to stdout for debugging
        InputStream is = new BufferedInputStream(child.getInputStream());
        int singleByte = 0;
        while ((singleByte = is.read()) != -1) {
            // output.write(buffer, 0, bytesRead);
            System.out.write(singleByte);
        }

        child.waitFor();
        int exitValue = child.exitValue();
        getLog().info("Exit Value: " + exitValue);
        if (exitValue != 0) {
            throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!");
        }

    } catch (IOException e) {
        getLog().error("An IOException occured.");
        throw new MojoExecutionException("An IOException occured", e);
    } catch (InterruptedException e) {
        getLog().error("The clean process was been interrupted.");
        throw new MojoExecutionException("The clean process was been interrupted", e);
    }
    createreport();
}

From source file:org.projectbuendia.openmrs.web.controller.ProfileManager.java

/**
 * Executes a command with one argument, returning true if the command succeeds.
 * Gathers the output from stdout and stderr into the provided list of lines.
 *//*  www  . j  a  v  a2s .c o m*/
private boolean execute(String command, File arg, List<String> lines) {
    ProcessBuilder pb = new ProcessBuilder(command, arg.getAbsolutePath());
    pb.redirectErrorStream(true); // redirect stderr to stdout
    try {
        Process proc = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            lines.add(line);
        }
        proc.waitFor();
        return proc.exitValue() == 0;
    } catch (Exception e) {
        log.error("Exception while executing: " + command + " " + arg, e);
        lines.add(e.getMessage());
        return false;
    }
}

From source file:org.hyperic.hq.plugin.db2jdbc.DataBaseServerDetector.java

protected List createServers(String installPath) {
    List res = new ArrayList();

    String command = getListDatabaseCommand();
    File db2exe = null;/*from  w ww .  j  a va  2  s  .  c om*/
    // http://www.db2ude.com/?q=node/121 for wind db2.exe
    if (command == null) {
        db2exe = new File(installPath + (installPath.endsWith(File.separator) ? "" : File.separator) + "bin"
                + File.separator + "db2" + (isWin32() ? "cmd.exe" : ""));
        command = db2exe.getAbsolutePath() + (isWin32() ? " /c /i /w db2 " : " ") + "list database directory";
    }
    if (db2exe.isFile()) {
        try {
            getLog().debug("[createDataBases] command= '" + command + "'");
            Process cmd = Runtime.getRuntime().exec(command);
            String sal = inputStreamAsString(cmd.getInputStream());
            String err = inputStreamAsString(cmd.getErrorStream());
            cmd.waitFor();

            if (getLog().isDebugEnabled()) {
                if (cmd.exitValue() != 0) {
                    getLog().error("[createDataBases] exit=" + cmd.exitValue());
                    getLog().error("[createDataBases] sal=" + sal);
                } else {
                    getLog().debug("[createDataBases] sal=" + sal);
                }
                if (sal.length() == 0) {
                    getLog().debug("[createDataBases] (" + cmd.exitValue() + ") err=" + err);
                }
            }

            Matcher m = regExpDataBases.matcher(sal);
            int ini = 0, end = 0;
            if (m.find()) {
                ini = m.start();
                do {
                    if (m.find()) {
                        end = m.end();
                    } else {
                        end = sal.length();
                    }

                    String db = sal.substring(ini, end).trim();
                    Properties db_props = parseProperties(db);
                    getLog().debug("db_props --> " + db_props);
                    ServerResource svr = createDataBase(db_props);
                    if (svr != null) {
                        res.add(svr);
                    }
                    ini = end;
                } while (end != sal.length());
            }
        } catch (Exception ex) {
            getLog().error(ex.getMessage(), ex);
        }
    } else {
        getLog().debug("DB2 executable was not found: " + db2exe);
    }
    return res;
}

From source file:com.antonjohansson.svncommit.core.utils.Bash.java

/** {@inheritDoc} */
@Override/*from   w ww  .  j a  va2  s .  co m*/
public void executeAndPipeOutput(Consumer<String> onData, Consumer<String> onError,
        Consumer<Boolean> onComplete, String... commandLines) {
    File scriptFile = getTemporaryScriptFile(asList(commandLines));
    Process process = execute(path, scriptFile);

    try (InputStream logStream = process.getInputStream(); InputStream errorStream = process.getErrorStream()) {
        while (isAvailable(process, logStream, errorStream)) {
            if (logStream.available() > 0) {
                accept(onData, logStream);
            }
            if (errorStream.available() > 0) {
                accept(onError, errorStream);
            }
        }
        int exitValue = process.exitValue();
        onComplete.accept(exitValue == 0);
    } catch (IOException e) {
        throw new RuntimeException("Could not execute temporary bash script", e);
    }
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean restart() {
    Process child;/*from  w w  w.  j  a  va2  s. c  om*/
    try {
        child = Runtime.getRuntime().exec(agentConfig.getRestartCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute restart command";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for restart";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean checkSyntax() {
    Process child;/*from  ww  w . ja  v  a 2  s.c  om*/
    try {
        child = Runtime.getRuntime().exec(agentConfig.getSyntaxCheckCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute syntax check";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for syntax check";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}

From source file:com.edmunds.etm.agent.impl.ProcessController.java

@Override
public boolean start() {
    Process child;// w w  w .j ava  2  s.c  o  m
    try {
        child = Runtime.getRuntime().exec(agentConfig.getStartCommand());
        child.waitFor();
    } catch (IOException e) {
        String message = "Could not execute Apache start command";
        logger.error(message, e);
        return false;
    } catch (InterruptedException e) {
        String message = "Thread interrupted while waiting for Apache start";
        logger.error(message, e);
        return false;
    }

    return child.exitValue() == PROCESS_SUCCESS_EXIT_VALUE;
}

From source file:net.mybox.mybox.Common.java

/**
 * Run a system command on the local machine
 * @param command/* w  w w.j a  va 2s  . c  o m*/
 * @return
 */
public static SysResult syscommand(String[] command) {
    Runtime r = Runtime.getRuntime();

    SysResult result = new SysResult();

    System.out.println("syscommand array: " + StringUtils.join(command, " "));

    try {

        Process p = r.exec(command);
        // should use a thread so it can be killed if it has not finished and another one needs to be started
        InputStream in = p.getInputStream();

        InputStream stderr = p.getErrorStream();
        InputStreamReader inreadErr = new InputStreamReader(stderr);
        BufferedReader brErr = new BufferedReader(inreadErr);

        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);

        // Read the ls output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            result.output += line + "\n";
            System.err.print("  output> " + result.output);
            // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times
        }

        result.worked = true;

        // Check for failure
        try {
            if (p.waitFor() != 0) {
                System.err.println("exit value = " + p.exitValue());
                System.err.println("command> " + command);
                System.err.println("output> " + result.output);
                System.err.print("error> ");

                while ((line = brErr.readLine()) != null)
                    System.err.println(line);

                result.worked = false;
            }
            result.returnCode = p.waitFor();
        } catch (InterruptedException e) {
            System.err.println(e);
            result.worked = false;
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        result.worked = false;
    }

    result.output = result.output.trim();

    return result;
}