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.openstreetmap.josm.plugins.mapillary.utils.MapillaryUtils.java

/**
 * Open the default browser in the given URL.
 *
 * @param url The (not-null) URL that is going to be opened.
 * @throws IOException when the URL could not be opened
 *///from w w  w.jav a  2s .c  o  m
public static void browse(URL url) throws IOException {
    if (url == null) {
        throw new IllegalArgumentException();
    }
    Desktop desktop = Desktop.getDesktop();
    if (desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(url.toURI());
        } catch (URISyntaxException e1) {
            throw new IOException(e1);
        }
    } else {
        Runtime runtime = Runtime.getRuntime();
        runtime.exec("xdg-open " + url);
    }
}

From source file:theofilin.CameraApps.java

public static void BurstNow(JLabel tampil, double r_gain, double b_gain, int width, int height, int num)
        throws IOException {
    try {//from  w w  w  .j av a2  s .c  o m
        Runtime rt = Runtime.getRuntime();
        String command = "raspistill -n --raw -t 1 -sa 0 -co 0 -br 40 -sh 0 -awb off -awbg " + r_gain + ","
                + b_gain + " -ISO 200 -ss 45000 " + "-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);
        is = new ByteArrayInputStream(curr);
        img = ImageIO.read(is);
        ImageIO.write(img, "jpg", new File("/home/pi/" + num + ".jpg"));
    } catch (IOException ex) {
        Logger.getLogger(CameraApps.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:localization.split.java

public static boolean checkLPU(String filepath, String passoloPath) {
    File logfile = new File(filepath.substring(0, filepath.lastIndexOf("\\") + 1) + "error.log");
    try {/*from w w w. jav  a 2 s . com*/
        String cmd = "cmd.exe /c " + passoloPath + " /openproject:" + filepath;
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd);
        InputStreamReader isr = new InputStreamReader(proc.getInputStream());
        BufferedReader br = new BufferedReader(isr);
        String line = null;
        while ((line = br.readLine()) != null) {
            if (line.contains("Opening in read-only mode")) {
                if (!logfile.exists()) {
                    logfile.createNewFile();
                }
                String content = filepath
                        + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2011."
                        + "\n";
                FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(content);
                bw.close();
                return false;
            }
        }
        int exitVal = proc.waitFor();
        if (exitVal == 10) {
            if (!logfile.exists()) {
                logfile.createNewFile();
            }
            String content = filepath
                    + " is not able to process because it is a type of Passolo 2011. Please process it with Passolo 2015."
                    + "\n";
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            return false;
        }

    } catch (Exception e) {
        try {
            String content = e.getMessage();
            FileWriter fw = new FileWriter(logfile.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (Exception e1) {

        }

        return false;
    }
    return true;
}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;//from   w  w  w  .  j a va  2s .co m
    Runtime runtime = Runtime.getRuntime();
    OutputStreamWriter outputStreamWriter;

    try {
        String command = dbName + " " + "'" + query + "'" + ";";
        process = runtime.exec("su");

        outputStreamWriter = new OutputStreamWriter(process.getOutputStream());

        outputStreamWriter.write("sqlite3 " + command);

        outputStreamWriter.flush();
        outputStreamWriter.close();
        outputStreamWriter.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());

    (new Thread() {
        @Override
        public void run() {
            try {

                BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    Log.d("com.suraj.waext", "WhatsAppDBHelper:" + s);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    }).start();

    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s;
        StringBuilder op = new StringBuilder();

        while ((s = bufferedReader.readLine()) != null) {
            op.append(s).append("\n");
        }

        return op.toString().split("\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}

From source file:org.apache.cloudstack.network.contrail.management.TestDbSetup.java

public static void stopMysqlServer(int port, String stopMysqlScript) throws Exception {

    try {/*from w ww. ja v a 2 s .  co  m*/
        Runtime r = Runtime.getRuntime();
        String script = stopMysqlScript;
        if (script == null) {
            script = "test/resources/mysql_db_stop.sh " + port;
        }
        Process process = r.exec("sh " + script);
        process.waitFor();
        System.out.println("sql server instance running at port " + port + " stopped");
    } catch (Exception e) {

        String cause = e.getMessage();
        if (cause.equals("sh: not found"))
            System.out.println("No sh interpreter found.");
        throw e;
    }
}

From source file:org.apache.cloudstack.network.contrail.management.TestDbSetup.java

public static void startMysqlServer(int port, String startMysqlScript) throws Exception {

    try {/*from   w w  w  . ja va2  s  .  com*/
        String cwd = new java.io.File(".").getCanonicalPath();
        Runtime r = Runtime.getRuntime();
        String script = startMysqlScript;
        if (script == null) {
            script = "test/resources/mysql_db_start.sh " + port;
        }
        Process process = r.exec("sh " + cwd + "/" + script);
        process.waitFor();
        System.out.println("new sql server instance launched on port: " + port);
    } catch (Exception e) {

        String cause = e.getMessage();
        if (cause.equals("sh: not found"))
            System.out.println("No sh interpreter found.");
        throw e;
    }
}

From source file:Exec.java

static Process execUnix(String[] cmdarray, String[] envp, File directory) throws IOException {
    // instead of calling command directly, we'll call the shell to change
    // directory and set environment variables.

    // start constructing the sh command line.
    StringBuffer buf = new StringBuffer();

    if (directory != null) {
        // change to directory
        buf.append("cd '");
        buf.append(escapeQuote(directory.toString()));
        buf.append("'; ");
    }/*from  ww  w .  j a  v a  2  s .c  om*/

    if (envp != null) {
        // set environment variables.  Quote the value (but not the name).
        for (int i = 0; i < envp.length; ++i) {
            String nameval = envp[i];
            int equals = nameval.indexOf('=');
            if (equals == -1)
                throw new IOException("environment variable '" + nameval + "' should have form NAME=VALUE");
            buf.append(nameval.substring(0, equals + 1));
            buf.append('\'');
            buf.append(escapeQuote(nameval.substring(equals + 1)));
            buf.append("\' ");
        }
    }

    // now that we have the directory and environment, run "which" 
    // to test if the command name is found somewhere in the path.
    // If "which" fails, throw an IOException.
    String cmdname = escapeQuote(cmdarray[0]);
    Runtime rt = Runtime.getRuntime();
    String[] sharray = new String[] { "sh", "-c", buf.toString() + " which \'" + cmdname + "\'" };
    Process which = rt.exec(sharray);
    try {
        which.waitFor();
    } catch (InterruptedException e) {
        throw new IOException("interrupted");
    }

    if (which.exitValue() != 0)
        throw new IOException("can't execute " + cmdname + ": bad command or filename");

    // finish in 
    buf.append("exec \'");
    buf.append(cmdname);
    buf.append("\' ");

    // quote each argument in the command
    for (int i = 1; i < cmdarray.length; ++i) {
        buf.append('\'');
        buf.append(escapeQuote(cmdarray[i]));
        buf.append("\' ");
    }

    System.out.println("executing " + buf);
    sharray[2] = buf.toString();
    return rt.exec(sharray);
}

From source file:opendap.aws.glacier.BesMetadataExtractor.java

private static String runSysCommand(String sysCmd) throws IOException {

    Process p = null;/* w  w  w  .j a  va 2 s.co m*/

    try {
        System.out.println("COMMAND: " + sysCmd);

        Runtime rt = Runtime.getRuntime();
        p = rt.exec(sysCmd.toString());
        InputStream in = p.getInputStream();
        OutputStream out = p.getOutputStream();
        InputStream err = p.getErrorStream();

        CharArrayWriter caw = new CharArrayWriter();

        IOUtils.copy(in, caw);
        IOUtils.copy(err, System.err);

        return caw.toString();
    } finally {
        if (p != null)
            p.destroy();
    }

}

From source file:com.krawler.portal.util.SystemEnv.java

public static Properties getProperties() {
    Properties props = new Properties();

    try {//  w w  w . j  a va  2  s .  co m
        Runtime runtime = Runtime.getRuntime();
        Process process = null;

        String osName = System.getProperty("os.name").toLowerCase();

        if (osName.indexOf("windows ") > -1) {
            if (osName.indexOf("windows 9") > -1) {
                process = runtime.exec("command.com /c set");
            } else {
                process = runtime.exec("cmd.exe /c set");
            }
        } else {
            process = runtime.exec("env");
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;

        while ((line = br.readLine()) != null) {
            int pos = line.indexOf(StringPool.EQUAL);

            if (pos != -1) {
                String key = line.substring(0, pos);
                String value = line.substring(pos + 1);

                props.setProperty(key, value);
            }
        }
    } catch (IOException ioe) {
        logger.warn(ioe.getMessage(), ioe);
    }

    return props;
}

From source file:net.morimekta.idltool.IdlUtils.java

public static Git getCacheRepository(File cacheDir, String repository) throws IOException, GitAPIException {
    File repoCache = getCacheDirectory(cacheDir, repository);

    Runtime runtime = Runtime.getRuntime();
    if (!repoCache.exists()) {
        Process p = runtime
                .exec(new String[] { "git", "clone", repository, repoCache.getAbsoluteFile().toString() });
        try {//  ww w .j  a va  2s  .  c  om
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    } else {
        Process p = runtime.exec(new String[] { "git", "fetch", "origin", "-p" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "add", "-A" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }

        p = runtime.exec(new String[] { "git", "reset", "origin/master", "--hard" }, null, repoCache);
        try {
            int response = p.waitFor();
            if (response != 0) {
                throw new IOException(IOUtils.readString(p.getErrorStream()));
            }
        } catch (InterruptedException e) {
            throw new IOException(e.getMessage(), e);
        }
    }
    return Git.open(repoCache);
}