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:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java

/**
 * Run a command and wait/*from   www.  j  a v  a2 s .  co  m*/
 *
 * @param cmd The command to run
 * @param workingDir The folder where the command is run
 * @param executeFrom For logging message to the center of where to execute the command.
 * @return
 */
public static String executeCommandGetOutput(String cmd, String workingDir, String executeFrom) {
    logger.debug("Execute command: " + cmd);
    if (workingDir == null) {
        workingDir = "/tmp";
    }
    try {
        String[] splitStr = cmd.split("\\s+");
        ProcessBuilder pb = new ProcessBuilder(splitStr);
        pb.directory(new File(workingDir));
        pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output
        Map<String, String> env = pb.environment();
        String path = env.get("PATH");
        path = path + File.pathSeparator + "/usr/bin:/usr/sbin";
        logger.debug("PATH to execute command: " + pb.environment().get("PATH"));
        env.put("PATH", path);

        Process p = pb.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        StringBuffer output = new StringBuffer();
        int lineCount = 0;
        while ((line = reader.readLine()) != null) {
            if (lineCount < 10) { // only get 10 lines to prevent the overflow
                output.append(line);
            }
            lineCount += 1;
            logger.debug(line);
        }
        if (lineCount >= 10) {
            logger.debug("... there are alot of more output here which is not shown ! ...");
        }
        p.waitFor();
        System.out.println("Execute Commang output: " + output.toString().trim());

        if (p.exitValue() == 0) {
            logger.debug("Command exit 0, result: " + output.toString().trim());
            return output.toString().trim();
        } else {
            logger.debug("Command return non zero code: " + p.exitValue());
            return null;
        }
    } catch (InterruptedException | IOException e1) {
        logger.error("Error when execute command. Error: " + e1);
    }
    return null;
}

From source file:BrowserLauncher.java

/**
 * Attempts to open the default web browser to the given URL.
 * @param url The URL to open//from ww  w  .  ja  v a2s  . c o m
 * @throws IOException If the web browser could not be located or does not run
 */
public static void openURL(String url) throws IOException {
    if (!loadedWithoutErrors) {
        throw new IOException("Exception in finding browser: " + errorMessage);
    }
    Object browser = locateBrowser();
    if (browser == null) {
        throw new IOException("Unable to locate browser: " + errorMessage);
    }

    switch (jvm) {
    case MRJ_2_0:
        Object aeDesc = null;
        try {
            aeDesc = aeDescConstructor.newInstance(new Object[] { url });
            putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
            sendNoReply.invoke(browser, new Object[] {});
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
        } catch (InstantiationException ie) {
            throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
        } finally {
            aeDesc = null; // Encourage it to get disposed if it was created
            browser = null; // Ditto
        }
        break;
    case MRJ_2_1:
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    case MRJ_3_0:
        int[] instance = new int[1];
        int result = ICStart(instance, 0);
        if (result == 0) {
            int[] selectionStart = new int[] { 0 };
            byte[] urlBytes = url.getBytes();
            int[] selectionEnd = new int[] { urlBytes.length };
            result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes, urlBytes.length, selectionStart,
                    selectionEnd);
            if (result == 0) {
                // Ignore the return value; the URL was launched successfully
                // regardless of what happens here.
                ICStop(instance);
            } else {
                throw new IOException("Unable to launch URL: " + result);
            }
        } else {
            throw new IOException("Unable to create an Internet Config instance: " + result);
        }
        break;
    case MRJ_3_1:
        try {
            openURL.invoke(null, new Object[] { url });
        } catch (InvocationTargetException ite) {
            throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
        } catch (IllegalAccessException iae) {
            throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
        }
        break;
    case WINDOWS_NT:
    case WINDOWS_9x:
        // Add quotes around the URL to allow ampersands and other special
        // characters to work.
        Process process = Runtime.getRuntime().exec(new String[] { (String) browser, FIRST_WINDOWS_PARAMETER,
                SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER, '"' + url + '"' });
        // This avoids a memory leak on some versions of Java on Windows.
        // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
        try {
            process.waitFor();
            process.exitValue();
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    case OTHER:
        // Assume that we're on Unix and that Netscape is installed

        // First, attempt to open the URL in a currently running session of Netscape
        process = Runtime.getRuntime().exec(new String[] { (String) browser, NETSCAPE_REMOTE_PARAMETER,
                NETSCAPE_OPEN_PARAMETER_START + url + NETSCAPE_OPEN_PARAMETER_END });
        try {
            int exitCode = process.waitFor();
            if (exitCode != 0) { // if Netscape was not open
                Runtime.getRuntime().exec(new String[] { (String) browser, url });
            }
        } catch (InterruptedException ie) {
            throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
        }
        break;
    default:
        // This should never occur, but if it does, we'll try the simplest thing possible
        Runtime.getRuntime().exec(new String[] { (String) browser, url });
        break;
    }
}

From source file:energy.usef.environment.tool.security.VaultService.java

/**
 * Executes a class's static main method with the current java executable and classpath in a separate process.
 * /*from   w ww.j av a2  s.  c om*/
 * @param klass the class to call the static main method for
 * @param params the parameters to provide
 * @return the exit code of the process
 * @throws IOException
 * @throws InterruptedException
 */
public static int exec(@SuppressWarnings("rawtypes") Class klass, List<String> params)
        throws IOException, InterruptedException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = System.getProperty("java.class.path");
    String className = klass.getCanonicalName();

    // construct the command line
    List<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-cp");
    command.add(classpath);
    command.add(className);
    command.addAll(params);
    LOGGER.debug("executing class '{}' with params '{}' in classpath '{}' with java binary '{}'", className,
            params.toString(), classpath, javaBin);

    // build and start the Vault's process
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();
    process.waitFor();

    // get the input and error streams of the process and log them
    InputStream in = process.getInputStream();
    InputStream en = process.getErrorStream();
    InputStreamReader is = new InputStreamReader(in);
    InputStreamReader es = new InputStreamReader(en);
    BufferedReader br = new BufferedReader(is);
    BufferedReader be = new BufferedReader(es);

    String read = br.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = br.readLine();
    }
    read = be.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = be.readLine();
    }

    br.close();
    is.close();
    in.close();

    return process.exitValue();
}

From source file:com.moviejukebox.scanner.AttachmentScanner.java

/**
 * Extract an attachment//from   ww  w .  ja va  2s.c o  m
 *
 * @param attachment the attachment to extract
 * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension
 * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file)
 * @return
 */
private static File extractAttachment(Attachment attachment) {
    File sourceFile = attachment.getSourceFile();
    if (sourceFile == null) {
        // source file must exist
        return null;
    } else if (!sourceFile.exists()) {
        // source file must exist
        return null;
    }

    // build return file name
    StringBuilder returnFileName = new StringBuilder();
    returnFileName.append(tempDirectory.getAbsolutePath());
    returnFileName.append(File.separatorChar);
    returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName()));
    // add attachment id so the extracted file becomes unique per movie file
    returnFileName.append(".");
    returnFileName.append(attachment.getAttachmentId());

    switch (attachment.getContentType()) {
    case NFO:
        returnFileName.append(".nfo");
        break;
    case POSTER:
    case FANART:
    case BANNER:
    case SET_POSTER:
    case SET_FANART:
    case SET_BANNER:
    case VIDEOIMAGE:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    default:
        returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType()));
        break;
    }

    File returnFile = new File(returnFileName.toString());
    if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) {
        // already present or extracted
        LOG.debug("File to extract already exists; no extraction needed");
        return returnFile;
    }

    LOG.trace("Extract attachement ({})", attachment);
    try {
        // Create the command line
        List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE);
        commandMedia.add("attachments");
        commandMedia.add(sourceFile.getAbsolutePath());
        commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString());

        ProcessBuilder pb = new ProcessBuilder(commandMedia);
        pb.directory(MT_PATH);
        Process p = pb.start();

        if (p.waitFor() != 0) {
            LOG.error("Error during extraction - ErrorCode={}", p.exitValue());
            returnFile = null;
        }
    } catch (IOException | InterruptedException ex) {
        LOG.error(SystemTools.getStackTrace(ex));
        returnFile = null;
    }

    if (returnFile != null) {
        if (returnFile.exists()) {
            // need to reset last modification date to last modification date
            // of source file to fulfill later checks
            try {
                returnFile.setLastModified(sourceFile.lastModified());
            } catch (Exception ignore) {
                // nothing to do anymore
            }
        } else {
            // reset return file to null if not existent
            returnFile = null;
        }
    }
    return returnFile;
}

From source file:com.github.maven_nar.NarUtil.java

public static int runCommand(final String cmd, final String[] args, final File workingDirectory,
        final String[] env, final TextStream out, final TextStream err, final TextStream dbg, final Log log,
        final boolean expectFailure) throws MojoExecutionException, MojoFailureException {
    final Commandline cmdLine = new Commandline();

    try {/*  w  ww .ja  v  a 2 s  . com*/
        dbg.println("RunCommand: " + cmd);
        cmdLine.setExecutable(cmd);
        if (args != null) {
            for (final String arg : args) {
                dbg.println("  '" + arg + "'");
            }
            cmdLine.addArguments(args);
        }
        if (workingDirectory != null) {
            dbg.println("in: " + workingDirectory.getPath());
            cmdLine.setWorkingDirectory(workingDirectory);
        }

        if (env != null) {
            dbg.println("with Env:");
            for (final String element : env) {
                final String[] nameValue = element.split("=", 2);
                if (nameValue.length < 2) {
                    throw new MojoFailureException("   Misformed env: '" + element + "'");
                }
                dbg.println("   '" + nameValue[0] + "=" + nameValue[1] + "'");
                cmdLine.addEnvironment(nameValue[0], nameValue[1]);
            }
        }

        final Process process = cmdLine.execute();
        final StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), err);
        final StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), out);

        errorGobbler.start();
        outputGobbler.start();
        process.waitFor();
        final int exitValue = process.exitValue();
        dbg.println("ExitValue: " + exitValue);
        final int timeout = 5000;
        errorGobbler.join(timeout);
        outputGobbler.join(timeout);
        if (exitValue != 0 ^ expectFailure) {
            if (log == null) {
                System.err.println(err.toString());
                System.err.println(out.toString());
                System.err.println(dbg.toString());
            } else {
                log.warn(err.toString());
                log.warn(out.toString());
                log.warn(dbg.toString());
            }
            throw new MojoExecutionException("exit code: " + exitValue);
        }
        return exitValue;
    } catch (final MojoExecutionException e) {
        throw e;
    } catch (final Exception e) {
        throw new MojoExecutionException("Could not launch " + cmdLine, e);
    }
}

From source file:org.rapidcontext.app.plugin.cmdline.CmdLineExecProcedure.java

/**
 * Waits for the specified process to terminate, reading its
 * standard output and error streams meanwhile.
 *
 * @param process        the process to monitor
 * @param cx             the procedure call context
 *
 * @return the data object with the process output results
 *
 * @throws IOException if the stream reading failed
 *///from   w w  w  . ja  v a 2  s  .c  om
private static Dict waitFor(Process process, CallContext cx) throws IOException {

    StringBuffer output = new StringBuffer();
    StringBuffer error = new StringBuffer();
    InputStream isOut = process.getInputStream();
    InputStream isErr = process.getErrorStream();
    byte[] buffer = new byte[4096];
    int exitValue = 0;
    process.getOutputStream().close();
    while (true) {
        if (cx.isInterrupted()) {
            // TODO: isOut.close();
            // TODO: isErr.close();
            process.destroy();
            throw new IOException("procedure call interrupted");
        }
        try {
            readStream(isOut, buffer, output);
            readStream(isErr, buffer, error);
            log(cx, error);
            exitValue = process.exitValue();
            break;
        } catch (IllegalThreadStateException e) {
            try {
                Thread.sleep(50);
            } catch (InterruptedException ignore) {
                // Ignore this exception
            }
        }
    }
    Dict res = new Dict();
    res.setInt("exitValue", exitValue);
    res.set("output", output);
    return res;
}

From source file:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line/*from w  w w. j a  v  a  2 s  . c o m*/
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}

From source file:ca.weblite.jdeploy.JDeploy.java

public static boolean isAlive(Process p) {
    try {/*from  w w  w . j av  a2s  .  c o  m*/
        p.exitValue();
        return false;
    } catch (IllegalThreadStateException e) {
        return true;
    }
}

From source file:com.ms.commons.file.service.ImageUtil.java

public static String rotateImage(String originalImagePath, Double rotation) {
    // FIXME?Java?
    // JavaRuntime?
    // convert 1372771154717.jpg -virtual-pixel none +distort SRT '20' rotate_normal2.png
    String destImage = TEMP_IMAGE_PATH + System.currentTimeMillis() + ".png";
    try {//  w w  w  . j  a v  a  2s.c o  m
        String command = null;
        command = "convert " + originalImagePath + " -virtual-pixel none +distort SRT '" + rotation + "' "
                + destImage;
        Process process = Runtime.getRuntime().exec(command);
        process.waitFor();
        int exitValue = process.exitValue();
        return exitValue == 0 ? destImage : StringUtils.EMPTY;
    } catch (IOException e1) {
        e1.printStackTrace();
        return StringUtils.EMPTY;
    } catch (InterruptedException e) {
        e.printStackTrace();
        return StringUtils.EMPTY;
    }
    // ConvertCmd convert = new ConvertCmd();
    // IMOperation op = new IMOperation();
    // op.addImage(originalImagePath);
    // op.addRawArgs(" -virtual-pixel none +distort SRT '" + rotation + "' ");
    // op.addImage(destImage);
    // try {
    // convert.run(op);
    // return destImage;
    // } catch (Exception e) {
    // e.printStackTrace();
    // return StringUtils.EMPTY;
    // }

}

From source file:org.apache.ambari.server.utils.ShellCommandUtil.java

public static Result runCommand(String[] args) throws IOException, InterruptedException {
    ProcessBuilder builder = new ProcessBuilder(args);
    Process process;
    if (WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();//from   ww w .  j  a  v a  2 s .c om
        }
    } else {
        process = builder.start();
    }
    //TODO: not sure whether output buffering will work properly
    // if command output is too intensive
    process.waitFor();
    String stdout = streamToString(process.getInputStream());
    String stderr = streamToString(process.getErrorStream());
    int exitCode = process.exitValue();
    return new Result(exitCode, stdout, stderr);
}