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:ca.canucksoftware.systoolsmgr.CommandLine.java

public boolean doCmd() {
    try {/*from www .j  ava  2  s  . co  m*/
        response = null;
        ProcessBuilder pb = new ProcessBuilder(command);
        pb.redirectErrorStream(false);
        Process p = pb.start();
        String stdout = getTextFromStream(p.getInputStream());
        String stderr = getTextFromStream(p.getErrorStream());
        if (p.waitFor() != 0) {
            returnCode = p.exitValue();
        } else {
            returnCode = 0;
        }
        if (returnCode == 0) {
            response = stdout;
        } else {
            response = stderr;
        }
    } catch (Exception e) {
        response = e.getMessage();
        returnCode = -1;
    }
    return (returnCode == 0);
}

From source file:eu.vital.vitalcep.cep.CepProcess.java

public void stopCEP() throws FileNotFoundException, IOException {

    String cmd = "kill -9 " + Integer.toString(PID);

    try {//  w w w  .jav  a2 s .  co m
        Process pr = Runtime.getRuntime().exec(cmd);
        if (pr.waitFor(500, TimeUnit.MILLISECONDS)) {
            if (pr.exitValue() == 0) {
                logger.debug("bCEP stoped: " + PID);
                PID = -1;

                try {
                    File file = new File(cepFolder//+"/"+dolceFile
                            + "/" + fileName + "_dolce");
                    file.delete();
                    be.stop_while();
                } catch (Exception e) {
                    java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, null, e);
                }
            }
        }
    } catch (IOException | InterruptedException e) {
        java.util.logging.Logger.getLogger(CepProcess.class.getName()).log(Level.SEVERE, null, e);
    }

}

From source file:it.sardegnaricerche.voiceid.sr.Voiceid.java

/**
 * Convert to wav the inputFile to be processed by diarizator.
 * /*from w ww .j  a  va  2  s.co  m*/
 * @throws IOException
 */
private void toWav() throws IOException {
    logger.fine("Gstreamer initialized");
    String filename = inputfile.getAbsolutePath();
    String name = Utils.getBasename(inputfile);
    String line[] = { "/bin/sh", "-c", "gst-launch filesrc location='" + filename
            + "' ! decodebin ! audioresample ! 'audio/x-raw-int,rate=16000' ! audioconvert !"
            + " 'audio/x-raw-int,rate=16000,depth=16,signed=true,channels=1' ! wavenc ! filesink location="
            + name + ".wav " };
    // TODO: fix for other OS' vvvvvvvvvv
    // logger.info(System.getProperty("os.name").toLowerCase());
    logger.fine(line[2]);
    try {
        Process p = Runtime.getRuntime().exec(line);
        p.waitFor();
        logger.fine(p.exitValue() + "");
    } catch (Exception err) {
        logger.severe(err.getMessage());
    }
    // Pipeline pipe = Pipeline.launch(line[2]);
    // pipe.play();
    // logger.info(pipe.getState().toString());
    this.wavPath = new File(name + ".wav");
}

From source file:org.apache.tika.batch.fs.FSBatchTestBase.java

protected void destroyProcess(Process p) {
    if (p == null)
        return;/* w  ww.  j av  a 2 s . c  om*/

    try {
        p.exitValue();
    } catch (IllegalThreadStateException e) {
        p.destroy();
    }
}

From source file:dpfmanager.shell.modules.periodic.core.ControllerWindows.java

@Override
public boolean deletePeriodicalCheck(String uuid) {
    try {//from w w  w .j a  va2s  .  com
        createIfNotExistsVBS();
        String command = "schtasks /delete /f /tn \"" + uuid + "\"";
        Process proc = Runtime.getRuntime().exec(command);
        proc.waitFor();
        return (proc.exitValue() == 0);
    } catch (Exception e) {
        return false;
    }
}

From source file:com.netflix.dynomitemanager.defaultimpl.FloridaProcessManager.java

public void start() throws IOException {
    logger.info(String.format("Starting dynomite server"));

    List<String> command = Lists.newArrayList();
    if (!"root".equals(System.getProperty("user.name"))) {
        command.add(SUDO_STRING);//from ww  w  . j  a  va  2  s . c om
        command.add("-n");
        command.add("-E");
    }
    command.addAll(getStartCommand());

    ProcessBuilder startDynomite = new ProcessBuilder(command);
    Map<String, String> env = startDynomite.environment();
    setEnv(env);

    startDynomite.directory(new File("/"));
    startDynomite.redirectErrorStream(true);
    Process starter = startDynomite.start();

    try {
        sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS);
        int code = starter.exitValue();
        if (code == 0) {
            logger.info("Dynomite server has been started");
            instanceState.setStorageProxyAlive(true);
        } else {
            logger.error("Unable to start Dynomite server. Error code: {}", code);
        }

        logProcessOutput(starter);
    } catch (Exception e) {
        logger.warn("Starting Dynomite has an error", e);
    }
}

From source file:org.moe.cli.manager.PrebuildCocoaPodsManager.java

private void executePrepareCommands(File zipRoot, String prepareCommand)
        throws InvalidParameterSpecException, IOException, InterruptedException {
    File root = zipRoot;/*  www .j av a2  s .  co  m*/
    File[] children = zipRoot.listFiles();
    if (children.length == 1 && !children[0].getName().endsWith(".framework")) {
        root = new File(zipRoot, children[0].getName());
    } else if (children.length == 2) {
        if (children[0].getName().equals("__MACOSX")) {
            root = new File(zipRoot, children[1].getName());
        } else if (children[1].getName().equals("__MACOSX")) {
            root = new File(zipRoot, children[2].getName());
        }
    }
    if (root != null && root.exists()) {
        String[] commandArray = prepareCommand.split("\n");
        for (String command : commandArray) {
            String[] cmd = { "/bin/sh", "-c", command.replace("\n", "") };

            Process process = Runtime.getRuntime().exec(cmd, null, root);
            process.waitFor();

            if (process.exitValue() != 0) {
                throw new InvalidParameterSpecException(
                        "An error occured during execution of preparation commands");
            }
        }
    }
}

From source file:com.samsung.sjs.SJSTest.java

public void assertSameProcessOutput(Process a, Process b) throws IOException, InterruptedException {
    a.waitFor();//from www  . ja  va 2 s  . com
    b.waitFor();
    System.out.println("result of process a: " + a.exitValue());
    System.out.println("result of process b: " + b.exitValue());
    //assertTrue(a.exitValue() == b.exitValue());
    // Requiring the same exit value and output is usually too strong when we're testing error/exception
    // code.  Both node and our compiled code will return 0 when everything is okay, and should
    // then produce the same output.  But when there's an assertion failure or exception,
    // the C standard library semantics and node's semantics differ, in both return code and
    // process output.  So we enforce a more relaxed check here:
    // - If both processes return 0, assert both output streams match for the two processses
    // - Otherwise, assert both processes are non-zero exits (both failed), and ignore the stream contents.
    // This leaves open the possibility that a test will pass when the processes fail for
    // different reasons.
    int exita = a.exitValue();
    int exitb = b.exitValue();
    StringWriter a_stdout = new StringWriter(), b_stdout = new StringWriter(), a_stderr = new StringWriter(),
            b_stderr = new StringWriter();
    IOUtils.copy(a.getInputStream(), a_stdout, Charset.defaultCharset());
    IOUtils.copy(b.getInputStream(), b_stdout, Charset.defaultCharset());
    IOUtils.copy(a.getErrorStream(), a_stderr, Charset.defaultCharset());
    IOUtils.copy(b.getErrorStream(), b_stderr, Charset.defaultCharset());
    // Trim trailing newlines from output
    String a_stdout_str = a_stdout.toString().trim();
    String b_stdout_str = b_stdout.toString().trim();
    String a_stderr_str = a_stderr.toString().trim();
    String b_stderr_str = b_stderr.toString().trim();
    // HACK get rid of GC warning message from SJS stderr
    b_stderr_str = b_stderr_str.replaceAll(
            "GC Warning: Repeated allocation of very large block \\(appr\\. size .*\\):\\n\\tMay lead to memory leak and poor performance.",
            "");
    boolean same_stdout = a_stdout_str.equals(b_stdout_str);
    boolean same_stderr = a_stderr_str.equals(b_stderr_str);
    if (0 == exita && 0 == exitb) {
        if (!same_stdout) {
            System.err.println("FAILURE: stdout mismatch");
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
        }
        assertTrue(same_stdout);
        if (!same_stderr) {
            System.err.println("FAILURE: stderr mismatch");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(same_stderr);
    } else {
        if (exita == 0 || exitb == 0) {
            System.err.println("FAILURE: Process A returned " + exita + ", Process B returned " + exitb);
            System.err.println("left stdout: [" + a_stdout_str + "]");
            System.err.println("right stdout: [" + b_stdout_str + "]");
            System.err.println("left stderr: [" + a_stderr_str + "]");
            System.err.println("right stderr: [" + b_stderr_str + "]");
        }
        assertTrue(exita != 0 && exitb != 0);
    }
}

From source file:org.opencastproject.util.FileSupport.java

/**
 * Links recursively the <em>content</em> of the specified <code>sourceDirectory</code> to
 * <code>targetDirectory</code>.
 * <p/>/*from   w  ww  .j a v  a 2 s . c o  m*/
 * If <code>overwrite</code> is set to <code>false</code>, this method throws an {@link IOException} if the target
 * file already exists.
 * 
 * @param sourceDirectory
 *          the source directory
 * @param targetDirectory
 *          the target directory to link the content of the source directory to
 * @param overwrite
 *          <code>true</code> to overwrite existing files
 * @throws IOException
 *           if copying fails
 */
public static void linkContent(File sourceDirectory, File targetDirectory, boolean overwrite)
        throws IOException {
    if (sourceDirectory == null)
        throw new IllegalArgumentException("Source directory must not by null");
    if (!sourceDirectory.isDirectory())
        throw new IllegalArgumentException(sourceDirectory.getAbsolutePath() + " is not a directory");
    if (targetDirectory == null)
        throw new IllegalArgumentException("Target directory must not by null");
    if (targetDirectory.exists() && !targetDirectory.isDirectory())
        throw new IllegalArgumentException(targetDirectory.getAbsolutePath() + " is not a directory");

    // Create the target directory if it doesn't exist yet
    if (!targetDirectory.exists()) {
        FileUtils.forceMkdir(targetDirectory);
    }

    logger.trace("Linking files in " + sourceDirectory + " to " + targetDirectory);
    Process p = null;
    StreamHelper stdout = null;
    StreamHelper stderr = null;
    StringBuffer error = new StringBuffer();
    try {
        p = createLinkDirectoryProcess(sourceDirectory, targetDirectory, overwrite);
        stdout = new StreamHelper(p.getInputStream());
        stderr = new LinkErrorStreamHelper(p.getErrorStream(), error);
        p.waitFor();
        stdout.stopReading();
        stderr.stopReading();
        // Find does not return with an error if -exec fails
        if (p.exitValue() != 0 || error.length() > 0) {
            logger.debug(
                    "Unable to link files from " + sourceDirectory + " to " + targetDirectory + ": " + error);
            copyContent(sourceDirectory, targetDirectory, overwrite);
        }
    } catch (InterruptedException e) {
        throw new IOException("Interrupted while creating links from " + sourceDirectory + " to "
                + targetDirectory + ": " + e.getMessage());
    } finally {
        IoSupport.closeQuietly(stdout);
        IoSupport.closeQuietly(stderr);
        IoSupport.closeQuietly(p);
    }

    // Link nested directories
    File[] children = sourceDirectory.listFiles();
    for (int i = 0; i < children.length; i++) {
        if (children[i].isDirectory())
            link(children[i], targetDirectory, overwrite);
    }
    // return targetDirectory;
}

From source file:com.emc.ecs.sync.filter.ShellCommandFilter.java

@Override
public void filter(SyncObject obj) {
    getNext().filter(obj);/*from w  w  w.j  a v  a2  s. co  m*/

    String[] cmdLine = new String[] { command, obj.getSourceIdentifier(), obj.getTargetIdentifier() };
    try {
        Process p = Runtime.getRuntime().exec(cmdLine);

        InputStream stdout = p.getInputStream();
        InputStream stderr = p.getErrorStream();
        while (true) {
            try {
                int exitCode = p.exitValue();
                if (exitCode != 0) {
                    throw new RuntimeException(
                            "Command: " + Arrays.asList(cmdLine) + "exited with code " + exitCode);
                } else {
                    return;
                }
            } catch (IllegalThreadStateException e) {
                // ignore; process running
            }

            // Drain stdout and stderr.  Many processes will hang if you
            // dont do this.
            drain(stdout, System.out);
            drain(stderr, System.err);
        }
    } catch (IOException e) {
        throw new RuntimeException("Error executing command: " + Arrays.asList(cmdLine) + ": " + e.getMessage(),
                e);
    }
}