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:org.smartfrog.avalanche.client.sf.apps.utils.SystemUtils.java

public static void addUser(String user, Properties props) throws UtilsException {

    if ((null == user) || (user.length() == 0)) {
        log.error("User name cannot be null");
        throw new UtilsException("User name cannot be null");
    }/*from  w  ww .jav a  2s .c  o  m*/

    String cmd = "adduser";

    if ((null == props) || (props.isEmpty())) {
        log.error("Please provide user information....");
        throw new UtilsException("Please provide user information....");
    }

    String passwd = (String) props.getProperty("-p");
    if ((null == passwd) || (passwd.length() == 0)) {
        log.error("Password is not provided....Cannot create user");
        throw new UtilsException("Password is not provided...." + "Cannot create user");
    }
    String epasswd = jcrypt.crypt("Tb", passwd);
    if (epasswd.length() == 0) {
        log.error("Error in encrypting passwd...");
        throw new UtilsException("Error in encrypting passwd...");
    }
    props.setProperty("-p", epasswd);
    props.setProperty("-c", "User-" + user);

    String key = null;
    String value = null;
    Enumeration e = props.keys();
    while (e.hasMoreElements()) {
        key = (String) e.nextElement();
        value = (String) props.getProperty(key);
        if ((null != value) || (value.length() != 0))
            cmd += " " + key + " " + value;
        else
            cmd += " " + key;
    }

    cmd += " " + user;

    Process p = null;
    Runtime rt = Runtime.getRuntime();
    BufferedReader cmdError = null;
    int exitVal = 0;
    try {
        p = rt.exec(cmd);
        exitVal = p.waitFor();
        cmdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        if (exitVal != 0) {
            String err = "Error in adding user " + user + "... returned with exit value 0 : ";
            log.error(err);
            String line = null;
            while ((line = cmdError.readLine()) != null) {
                log.error(line);
                err += line;
            }
            throw new UtilsException(err);
        }
    } catch (IOException ioe) {
        log.error(ioe);
        throw new UtilsException(ioe);
    } catch (InterruptedException ie) {
        log.error(ie);
        throw new UtilsException(ie);
    }

    log.info("User " + user + " added successfully");
}

From source file:net.floodlightcontroller.queuepusher.QueuePusherSwitchMapper.java

/**
 * Runs the given command//  w w  w .  ja v a  2  s  .com
 * 
 * @param cmd Command to execute
 * @return 0: (int)exit code 1: (string)stdout 2: (string)stderr
 */

private static Object[] eval(String cmd) {

    Object[] rsp = new Object[3];
    Runtime rt = Runtime.getRuntime();
    Process proc = null;

    try {
        proc = rt.exec(cmd);
        proc.waitFor();
        rsp[0] = proc.exitValue();
    } catch (InterruptedException e) {
        rsp[0] = 1;
    } catch (IOException e) {
        rsp[0] = 1;
    } finally {
        if (proc == null) {
            rsp[0] = 1;
        } else {

            try {

                BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream()));
                BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

                String temp;
                StringBuilder sb = new StringBuilder();
                while ((temp = stdout.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[1] = sb.toString();
                sb = new StringBuilder();
                while ((temp = stderr.readLine()) != null) {
                    sb.append(temp);
                }

                rsp[2] = sb.toString();

            } catch (IOException e) {
                rsp[0] = 1;
            }

        }
    }

    return rsp;

}

From source file:Main.java

public static int findProcessIdWithPidOf(String command) throws Exception {
    int procId = -1;
    Runtime r = Runtime.getRuntime();
    Process procPs = null;//ww  w  .  ja v a 2  s.  c om

    String baseName = new File(command).getName();
    // fix contributed my mikos on 2010.12.10
    procPs = r.exec(new String[] { SHELL_CMD_PIDOF, baseName });
    // procPs = r.exec(SHELL_CMD_PIDOF);

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {

        try {
            // this line should just be the process id
            procId = Integer.parseInt(line.trim());
            break;
        } catch (NumberFormatException e) {
            Log.e("TorServiceUtils", "unable to parse process pid: " + line, e);
        }
    }

    return procId;

}

From source file:net.pickapack.io.cmd.CommandLineHelper.java

/**
 *
 * @param cmd//  ww w. j  a v  a2s . c o m
 * @param waitFor
 * @return
 */
public static int invokeNativeCommand(String[] cmd, boolean waitFor) {
    try {
        Runtime r = Runtime.getRuntime();
        final Process ps = r.exec(cmd);
        //            ProcessBuilder pb = new ProcessBuilder(cmd);
        //            Process ps = pb.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getInputStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            {
                setDaemon(true);
            }

            @Override
            public void run() {
                try {
                    IOUtils.copy(ps.getErrorStream(), System.out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        if (waitFor) {
            int exitValue = ps.waitFor();
            if (exitValue != 0) {
                System.out.println("WARN: Process exits with non-zero code: " + exitValue);
            }

            ps.destroy();

            return exitValue;
        }

        return 0;
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:protubuf.MessageHelper.java

public static void registerMessage(String protoFile) throws IdgsException {
    if (fileCache.containsKey(protoFile)) {
        return;/*from ww w . jav a2s . c  om*/
    }
    String source = new File(protoFile).getParent();
    String cmd = "protoc -I=" + source + " --descriptor_set_out=" + protoFile + ".desc " + protoFile;
    log.info(cmd);

    Runtime run = Runtime.getRuntime();
    Process p = null;
    try {
        p = run.exec(cmd);
    } catch (IOException e) {
        log.error("create desc file of proto file " + protoFile + " error");
        throw new IdgsException(e);
    }

    try {
        if (p.waitFor() != 0) {
            if (p.exitValue() == 1) {
                log.error("create desc file of proto file " + protoFile + " error.");
                throw new IdgsException("create desc file of proto file " + protoFile + " error.");
            }
        }
    } catch (InterruptedException e) {
        log.error("create desc file of proto file " + protoFile + " error.");
        throw new IdgsException(e);
    }

    File file = new File(protoFile + ".desc");
    FileInputStream fin = null;
    try {
        log.info("register file " + protoFile);
        fin = new FileInputStream(file);
        FileDescriptorSet descriptorSet = FileDescriptorSet.parseFrom(fin);
        for (FileDescriptorProto fdp : descriptorSet.getFileList()) {
            FileDescriptor fd = FileDescriptor.buildFrom(fdp, new FileDescriptor[] {});
            for (Descriptor descriptor : fd.getMessageTypes()) {
                log.info("register message " + descriptor.getFullName());
                cache.put(descriptor.getFullName(), descriptor);
            }
        }

        fileCache.put(protoFile, descriptorSet);
    } catch (FileNotFoundException e) {
        log.error("desc file of proto file " + protoFile + " is not found.");
        throw new IdgsException(e);
    } catch (IOException e) {
        log.error("parse desc file of proto file " + protoFile + " error");
        throw new IdgsException(e);
    } catch (DescriptorValidationException e) {
        log.error("register proto file " + protoFile + " error");
        throw new IdgsException(e);
    } finally {
        if (fin != null) {
            try {
                fin.close();
            } catch (IOException e) {
                throw new IdgsException(e);
            }
        }
    }

    file.delete();
}

From source file:Main.java

public static int findProcessIdWithPidOf(String command) throws Exception {

    int procId = -1;

    Runtime r = Runtime.getRuntime();

    Process procPs = null;/*w  w  w.  j av  a2 s. c  o  m*/

    String baseName = new File(command).getName();
    //fix contributed my mikos on 2010.12.10
    procPs = r.exec(new String[] { SHELL_CMD_PIDOF, baseName });
    //procPs = r.exec(SHELL_CMD_PIDOF);

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {

        try {
            //this line should just be the process id
            procId = Integer.parseInt(line.trim());
            break;
        } catch (NumberFormatException e) {
            Log.e("TorServiceUtils", "unable to parse process pid: " + line, e);
        }
    }

    return procId;

}

From source file:Main.java

public static int findProcessIdWithPidOf(String command) throws Exception {

    int procId = -1;

    Runtime r = Runtime.getRuntime();

    Process procPs = null;/* ww w  .  j  av  a  2s. co  m*/

    String baseName = new File(command).getName();
    // fix contributed my mikos on 2010.12.10
    procPs = r.exec(new String[] { SHELL_CMD_PIDOF, baseName });
    // procPs = r.exec(SHELL_CMD_PIDOF);

    BufferedReader reader = new BufferedReader(new InputStreamReader(procPs.getInputStream()));
    String line = null;

    while ((line = reader.readLine()) != null) {

        try {
            // this line should just be the process id
            procId = Integer.parseInt(line.trim());
            break;
        } catch (NumberFormatException e) {
            Log.e("TorServiceUtils", "unable to parse process pid: " + line, e);
        }
    }

    return procId;

}

From source file:theofilin.CameraApps.java

public static void StartCamera(JLabel tampil, int width, int height) throws IOException {
    ActionListener actionlistener;
    actionlistener = new ActionListener() {
        @Override/*from   w w  w.ja  va  2s .  c o m*/
        public void actionPerformed(ActionEvent ae) {

            try {
                Runtime rt = Runtime.getRuntime();
                String command = "raspistill -n -t 1 -drc high -ISO 200 " + "-w " + width + " -h " + height
                        + " -o -";
                Process p = rt.exec(command);

                InputStream is = p.getInputStream();
                byte[] curr = IOUtils.toByteArray(is);
                ImageIcon disp = new ImageIcon(curr);
                tampil.setIcon(disp);
            } catch (IOException ex) {
                Logger.getLogger(CameraApps.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    };
    timer = new Timer(100, actionlistener);
    timer.start();
}

From source file:org.jkcsoft.java.util.OsHelper.java

public static boolean isExecutable(File file, Log log) throws Exception {
    boolean is = true;

    if (isLinux()) {
        // e.g., /usr/bin/test -x /home/coles/build/build-tsess.sh && echo yes || echo no
        try {/*from w  w  w  .ja  v  a 2s.  c  o  m*/

            Runtime rt = Runtime.getRuntime();
            String stTest = "/usr/bin/test -x " + file.getAbsolutePath() + " && echo yes || echo no";
            log.debug("Command=" + stTest);

            Process p = rt.exec(stTest);

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

            String stLine = null;

            // read any errors from the attempted command
            log.info("Here is the standard error of the command (if any):");
            while ((stLine = stdError.readLine()) != null) {
                log.warn(stLine);
            }

            // read the output from the command
            StringBuilder sbResponse = new StringBuilder();
            while ((stLine = stdInput.readLine()) != null) {
                sbResponse.append(stLine);
            }

            is = "yes".equalsIgnoreCase(sbResponse.toString());

        } catch (IOException e) {
            log.error("In isExecutable()", e);
            throw e;
        }
    } else {
        log.info("Not Linux -- assume executable");
    }

    return is;
}

From source file:com.grarak.romswitcher.Utils.Utils.java

public static void deleteFiles(String path) {

    File file = new File(path);

    if (file.exists()) {
        String deleteCmd = "rm -rf " + path;
        Runtime runtime = Runtime.getRuntime();
        try {//from   w w w  .ja v  a  2 s  . c  om
            runtime.exec(deleteCmd);
        } catch (IOException e) {
        }
    }
}