Example usage for java.lang Runtime exec

List of usage examples for java.lang Runtime exec

Introduction

In this page you can find the example usage for java.lang Runtime exec.

Prototype

public Process exec(String cmdarray[]) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process.

Usage

From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java

private static void validateNodeJSVersion() {
    Runtime rt = Runtime.getRuntime();
    String result = null;/* w w  w .j  a v a2  s. c  om*/
    Process p = null;
    try {
        p = rt.exec(NODE_COMMAND_PREFIX + " node -v");
        p.waitFor();
        result = getProcessOutput(p.getInputStream());
    } catch (Exception e) {
        throw new InvalidNodeJSInstance("Node.js is not installed", e);
    } finally {
        if (p != null)
            p.destroy();
    }

    String versionNum = result.replace("v", "");
    String[] tokens = versionNum.split("\\.");
    if (Integer.parseInt(tokens[0]) < REQUIRED_MAJOR_NODE_JS
            || Integer.parseInt(tokens[1]) < REQUIRED_MINOR_NODE_JS)
        throw new InvalidNodeJSInstance("Current node.js version " + versionNum + "is lower than "
                + "required (" + REQUIRED_MAJOR_NODE_JS + "." + REQUIRED_MINOR_NODE_JS + " or greater)");
}

From source file:ca.uqac.dim.net.verify.NetworkChecker.java

/**
 * Runs the NuSMV program as a spawned command-line process, and passes the
 * file to process through that process' standard input
 * @param file_contents A String containing the NuSMV model to process
 *//*w  w  w . jav a 2 s  .co m*/
private static RuntimeInfos runNuSMV(String file_contents) throws IOException, InterruptedException {
    StringBuilder sb = new StringBuilder();
    Runtime rt = Runtime.getRuntime();
    long time_start = 0, time_end = 0;
    // Start NuSMV, and feed the model through its standard input
    time_start = System.currentTimeMillis();
    Process p = rt.exec(NUSMV_EXEC);
    OutputStream o = p.getOutputStream();
    InputStream i = p.getInputStream();
    InputStream e = p.getErrorStream();
    Writer w = new PrintWriter(o);
    w.write(file_contents);
    w.close(); // Close stdin so NuSMV can start processing it
    // Wait for NuSMV to be done, then collect its standard output
    int exitVal = p.waitFor();
    if (exitVal != 0)
        throw new IOException("NuSMV's return value indicates an error in processing its input");
    BufferedReader br = new BufferedReader(new InputStreamReader(i));
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line).append("\n");
    }
    time_end = System.currentTimeMillis();
    i.close(); // Close stdout
    e.close(); // Close stderr
    return new RuntimeInfos(sb.toString(), time_end - time_start);
}

From source file:io.appium.java_client.service.local.AppiumServiceBuilder.java

private static File findNodeInCurrentFileSystem() {
    Runtime rt = Runtime.getRuntime();
    String instancePath;//from   ww  w. j  ava  2 s . com
    Process p = null;
    try {
        p = rt.exec(returnCommandThatSearchesForDefaultNode());
        p.waitFor();
        instancePath = getProcessOutput(p.getInputStream());
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (p != null)
            p.destroy();
    }

    File result;
    if (StringUtils.isBlank(instancePath)
            || !(result = new File(instancePath + File.separator + NODE_MODULES_FOLDER + APPIUM_NODE_MASK))
                    .exists())
        throw new InvalidServerInstanceException(
                "There is no installed nodes! Please install "
                        + " node via NPM (https://www.npmjs.com/package/appium#using-node-js) or download and "
                        + "install Appium app (http://appium.io/downloads.html)",
                new IOException("The installed appium node package has not been found."));

    return result;
}

From source file:com.supermap.desktop.icloud.CloudLicenseDialog.java

private static void openUrl(String url) {
    Runtime runtime = Runtime.getRuntime();
    try {/*from w w  w.  j  a  v a  2 s  . co  m*/
        if (SystemPropertyUtilities.isWindows()) {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } else {
            String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror", "netscape", "opera", "links",
                    "lynx" };

            StringBuffer cmd = new StringBuffer();
            for (int i = 0; i < browsers.length; i++)
                cmd.append((i == 0 ? "" : " || ") + browsers[i] + " \"" + url + "\" ");
            runtime.exec(new String[] { "sh", "-c", cmd.toString() });
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.github.DroidPHP.ServerUtils.java

/**
 * //from   w ww.j  av a2 s  .  co  m
 * @param mCommand
 *            hold the command which will be executed by invoking {@link
 *            Runtime.getRuntime.exec(...)}
 * @return boolean
 * @throws IOException
 *             if it unable to execute the command
 */

final public static boolean execCommand(String mCommand) {

    /*
     * Create a new Instance of Runtime
     */
    Runtime r = Runtime.getRuntime();
    try {
        /**
         * Executes the command
         */
        r.exec(mCommand);

    } catch (java.io.IOException e) {

        Log.e(TAG, "execCommand", e);

        r = null;

        return false;
    }

    return true;

}

From source file:org.eclipse.kura.deployment.rp.sh.impl.ShellScriptResourceProcessorImpl.java

private static void executeScript(File file, String action) throws Exception {
    String path = file.getCanonicalPath();
    String[] cmdarray = { "/bin/bash", path, action };
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmdarray);

    ProcessMonitorThread pmt = new ProcessMonitorThread(proc, null, 0);
    pmt.start();/*  w  w w. j a va2s .c o m*/
    pmt.join();
    s_logger.error("Script stdout: {}", pmt.getStdout());
    s_logger.error("Script stderr: {}", pmt.getStderr());
    Exception e = pmt.getException();
    if (e != null) {
        s_logger.error("Exception executing install action for script: '{}'", e);
        throw e;
    } else {
        if (!pmt.isTimedOut()) {
            Integer exitValue = pmt.getExitValue();
            if (exitValue != 0) {
                s_logger.error("Install action for script: '{}' failed with exit value: {}", path, exitValue);
                throw new Exception(
                        "Install action for script: " + path + " failed with exit value: " + exitValue);
            }
        }
    }
}

From source file:org.glite.slcs.util.Utils.java

/**
 * Sets permissions on a given file. The permissions are set using the
 * <i>chmod</i> command and will only work on Unix machines. Chmod command
 * must be in the path.//  w  w w . j a  v  a  2 s  .co m
 * 
 * @param file
 *            the file to set the permissions of.
 * @param mode
 *            the Unix style permissions.
 * @return true, if change was successful, otherwise false. It can return
 *         false, in many instances, e.g. when file does not exits, when
 *         chmod is not found, or other error occurs.
 */
public static boolean setFilePermissions(File file, int mode) {
    String filename = file.getPath();
    if (!file.exists()) {
        try {
            file.createNewFile();
        } catch (IOException e) {
            // ignored e.printStackTrace();
            LOG.warn("Failed to create new empty file: " + filename, e);
        }
    }
    // only on Unix
    if (!SystemUtils.IS_OS_WINDOWS) {
        Runtime runtime = Runtime.getRuntime();
        String[] cmd = new String[] { "chmod", String.valueOf(mode), filename };
        try {
            Process process = runtime.exec(cmd);
            return (process.waitFor() == 0) ? true : false;
        } catch (Exception e) {
            LOG.warn("Command 'chmod " + mode + " " + filename + "' failed", e);
            return false;
        }
    }
    // on Windows always return true
    else {
        LOG.info("Windows: Not possible to set file permissions " + mode + " on " + filename);
        return true;
    }

}

From source file:iics.Connection.java

static void openweb(String url) {
    String os = System.getProperty("os.name").toLowerCase();
    Runtime rt = Runtime.getRuntime();
    changefile();/*from   w ww .  j  a va 2  s . c om*/
    try {

        if (os.indexOf("win") >= 0) {

            // this doesn't support showing urls in the form of "page.html#nameLink" 
            rt.exec("rundll32 url.dll,FileProtocolHandler " + url);

        } else if (os.indexOf("mac") >= 0) {

            rt.exec("open " + url);

        } else if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {

            // Do a best guess on unix until we get a platform independent way
            // Build a list of browsers to try, in this order.
            String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror", "netscape", "opera", "links",
                    "lynx" };

            // Build a command string which looks like "browser1 "url" || browser2 "url" ||..."
            StringBuffer cmd = new StringBuffer();
            for (int i = 0; i < browsers.length; i++) {
                cmd.append(i == 0 ? "" : " || ").append(browsers[i]).append(" \"").append(url).append("\" ");
            }

            rt.exec(new String[] { "sh", "-c", cmd.toString() });

        } else {
            return;
        }
    } catch (Exception e) {
        return;
    }
    changefile();
}

From source file:com.liferay.sync.engine.util.SyncSystemTestUtil.java

protected static Process executeCommand(String action) throws Exception {
    Runtime runtime = Runtime.getRuntime();

    String command = null;/*from   w  w  w  .  j av a  2 s  .  c o  m*/

    String dirName = System.getProperty("app.server.tomcat.dir");

    if (OSDetector.isWindows()) {
        command = dirName + "/bin/catalina.bat " + action;
    } else {
        command = dirName + "/bin/catalina.sh " + action;
    }

    return runtime.exec(command);
}

From source file:edu.stanford.junction.director.JAVADirector.java

/**
 * Method to Open the Browser with Given URL
 * @param url/*  w w  w. j av  a2s . co  m*/
 */
public static Process openUrl(String url) {
    String os = System.getProperty("os.name");
    Runtime runtime = Runtime.getRuntime();
    try {
        // Block for Windows Platform
        if (os.startsWith("Windows")) {
            String cmd = "rundll32 url.dll,FileProtocolHandler " + url;
            Process p = runtime.exec(cmd);
            return p;
        }
        //Block for Mac OS
        else if (os.startsWith("Mac OS")) {
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
            openURL.invoke(null, new Object[] { url });
            return null; // TODO find a better way
        }
        //Block for UNIX Platform 
        else {
            String[] browsers = { "firefox", "chrome", "opera", "konqueror", "epiphany", "mozilla",
                    "netscape" };
            String browser = null;
            for (int count = 0; count < browsers.length && browser == null; count++)
                if (runtime.exec(new String[] { "which", browsers[count] }).waitFor() == 0)
                    browser = browsers[count];
            if (browser == null)
                throw new Exception("Could not find web browser");
            else
                return runtime.exec(new String[] { browser, url });
        }
    } catch (Exception x) {
        System.err.println("Exception occurd while invoking Browser!");
        x.printStackTrace();
        return null;
    }
}