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:preprocessing.Utils.java

public static String executeTesseractNumbers(String file) throws IOException {
    Runtime rt = Runtime.getRuntime();
    //rt.exec("cd "+tesseract);
    String[] commands = { tesseract + "\\tesseract", carpeta_temp + "" + file, "stdout", "digits" };
    Process proc = rt.exec(commands);

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

    // read the output from the command
    //System.out.println("Here is the standard output of the command:\n");
    String s = null;//from  w  ww.j  a  v  a  2  s .  c  o m
    String total = "";
    while ((s = stdInput.readLine()) != null) {
        //System.out.println(s);
        total += " " + s;
    }
    return total;
}

From source file:org.mhisoft.common.util.FileUtils.java

/**
 * Launch the URL using the default browser.
 *
 * @param url/*w w  w  .  j  a va 2s  . c  o  m*/
 */
public static void launchURL(String url) {

    try {
        if (Desktop.isDesktopSupported()) {
            // Windows
            Desktop.getDesktop().browse(new URI(url));
        } else {
            // Ubuntu
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("/usr/bin/firefox -new-window " + url);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

From source file:preprocessing.Utils.java

public static String executeTesseract(String file) throws IOException {
    Runtime rt = Runtime.getRuntime();
    //rt.exec("cd "+tesseract);
    String[] commands = { tesseract + "\\tesseract", carpeta_temp + "" + file, "stdout", "-psm 8", "letters" };
    Process proc = rt
            .exec(tesseract + "\\tesseract " + carpeta_temp + "" + file + " stdout -psm 8 nodict letters");

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

    // read the output from the command
    //System.out.println("Here is the standard output of the command:\n");
    String s = null;/*from  w w w .j  a v  a2 s .  co  m*/
    String total = "";
    while ((s = stdInput.readLine()) != null) {
        //System.out.println(s);
        total += " " + s;
    }
    return total;
}

From source file:org.jts.gui.exportCJSIDL.Export.java

public static void exportServiceSetCJSIDL(com.u2d.generated.ServiceSet serviceSet, File outputFile)
        throws ExportException {
    lastServiceSetExportPath = outputFile.getParentFile();

    java.util.List<File> files = new ArrayList<File>();
    File tmpfolder = null;/*from w w w  .  jav a  2s  .c  om*/
    try {
        tmpfolder = org.jts.gui.importCJSIDL.Import.createTempDir();
    } catch (IOException ex) {
        Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
    }
    File tmpfile = null;

    RelationalList defs = serviceSet.getServiceDefs();
    com.u2d.app.Context.getInstance().getViewMechanism().message("Exporting ServiceDefs from ServiceSet... ");

    java.util.List<Object> items = defs.getItems();
    java.util.List<Object> jsidlDefs = new ArrayList<Object>();

    for (Object def : items) {
        if (def instanceof com.u2d.generated.ServiceDef) {

            org.jts.jsidl.binding.ServiceDef sd = org.jts.gui.jmatterToJAXB.ServiceDef
                    .convert((com.u2d.generated.ServiceDef) def);
            RemoveJSIDLPlus.removeJSIDLPlus(sd);
            jsidlDefs.add(sd);

            try {
                tmpfile = serializeJAXB(sd, tmpfolder.getCanonicalPath());
                files.add(tmpfile);
            } catch (IOException ex) {
                Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
            }

        } else {
            String message = "Invalid object type found when processing serviceDefs: "
                    + def.getClass().getName();
            System.out.println(message);
            throw new ExportException(message);
        }
    }
    // this could replace the following section of code, if the antlr lib conflicts can be resolved
    //        try {
    //
    //            Conversion conv = new Conversion();
    //            System.err.println(tmpfolder.getCanonicalPath());
    //            System.err.println(outputFile.getCanonicalPath());
    //
    //            conv.convertFromJSIDL(tmpfolder.getCanonicalPath(), outputFile.getCanonicalPath());
    //
    //            com.u2d.app.Context.getInstance().getViewMechanism().message(
    //                    "ServiceDef Export Complete!  ");
    //        } catch (ConversionException e) {
    //            System.out.println("SAXException: ");
    //            e.printStackTrace();
    //        } catch (IOException ex) {
    //            String message = "Invalid path or file name when exporting a service def: " + outputFile;
    //            System.out.println(message);
    //            throw new ExportException(message, ex);
    //        }

    try {
        System.out.println("Initiating Conversion process 'convertFromJSIDL'");
        String execStr = ("java " + classpath
                + " org.jts.eclipse.conversion.cjsidl.Conversion \"convertFromJSIDL\" \""
                + tmpfolder.getCanonicalPath() + "\" \"" + outputFile.getCanonicalPath() + "\"");
        // if this is Linux or Mac OS X, we can't have double quotes around the
        // parameters, and classpath uses : instead of ;
        if (!System.getProperty("os.name").startsWith("Windows")) {
            execStr = execStr.replace("\"", "");
            execStr = execStr.replace(";", ":");
        }

        java.lang.Runtime rt = java.lang.Runtime.getRuntime();
        java.lang.Process p = rt.exec(execStr);
        StreamReader gerrors = new StreamReader(p.getErrorStream(), "ERROR");
        StreamReader goutput = new StreamReader(p.getInputStream(), "OUTPUT");
        gerrors.start();
        goutput.start();
        try {
            p.waitFor();
        } catch (InterruptedException ex) {
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
        }
        String errors = gerrors.getData();
        String log = goutput.getData();
        if (!errors.isEmpty()) {
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, errors);
            JOptionPane.showMessageDialog(GUI.getFrame(), errors, "CJSIDL Export Error",
                    JOptionPane.ERROR_MESSAGE);
        }

        System.out.println("Process exited with code = " + p.exitValue());
    } catch (IOException ex) {
        Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:core.PlanC.java

/**
 * retrive global identificator from <code>wmic</code>
 * /*  ww w . j  a  va 2  s.  co  m*/
 * @param gid - gobal id
 * @param vn - variable name
 * 
 * @return variable value
 */
private static String getWmicValue(String gid, String vn) {
    String rval = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(new String[] { "wmic", gid, "get", vn });
        InputStream is = process.getInputStream();
        Scanner sc = new Scanner(is);
        while (sc.hasNext()) {
            String next = sc.next();
            if (vn.equals(next)) {
                rval = sc.next().trim();
                break;
            }
        }
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return rval;
}

From source file:com.sssemil.advancedsettings.MainService.java

public static void grandPermissions(Context context) throws IOException {
    Runtime rt = Runtime.getRuntime();
    String package_name = context.getPackageName();
    String[] commands = { "su", "-c", "\"pm", "grant",
            package_name + " android.permission.CHANGE_CONFIGURATION\"" };
    Process proc = rt.exec(commands);

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

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

    String s;/*from   w w w .  j  av a2 s  .  c o m*/
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:madkitgroupextension.export.Export.java

public static void execExternalProcess(String command, final boolean screen_output,
        final boolean screen_erroutput) throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    final Process process = runtime.exec(command);

    // Consommation de la sortie standard de l'application externe dans un Thread separe
    new Thread() {
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                try {
                    while ((line = reader.readLine()) != null) {
                        if (screen_output) {
                            System.out.println(line);
                        }//from  www  . j a  v  a 2s  .  co m
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }.start();

    // Consommation de la sortie d'erreur de l'application externe dans un Thread separe
    new Thread() {
        public void run() {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                String line = "";
                try {
                    while ((line = reader.readLine()) != null) {
                        if (screen_erroutput) {
                            System.out.println(line);
                        }
                    }
                } finally {
                    reader.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }.start();
    process.waitFor();
}

From source file:net.mybox.mybox.Common.java

/**
 * Run a system command on the local machine
 * @param command/* w  w w  .ja  va 2 s  .  c om*/
 * @return
 */
public static SysResult syscommand(String[] command) {
    Runtime r = Runtime.getRuntime();

    SysResult result = new SysResult();

    System.out.println("syscommand array: " + StringUtils.join(command, " "));

    try {

        Process p = r.exec(command);
        // should use a thread so it can be killed if it has not finished and another one needs to be started
        InputStream in = p.getInputStream();

        InputStream stderr = p.getErrorStream();
        InputStreamReader inreadErr = new InputStreamReader(stderr);
        BufferedReader brErr = new BufferedReader(inreadErr);

        BufferedInputStream buf = new BufferedInputStream(in);
        InputStreamReader inread = new InputStreamReader(buf);
        BufferedReader bufferedreader = new BufferedReader(inread);

        // Read the ls output
        String line;
        while ((line = bufferedreader.readLine()) != null) {
            result.output += line + "\n";
            System.err.print("  output> " + result.output);
            // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times
        }

        result.worked = true;

        // Check for failure
        try {
            if (p.waitFor() != 0) {
                System.err.println("exit value = " + p.exitValue());
                System.err.println("command> " + command);
                System.err.println("output> " + result.output);
                System.err.print("error> ");

                while ((line = brErr.readLine()) != null)
                    System.err.println(line);

                result.worked = false;
            }
            result.returnCode = p.waitFor();
        } catch (InterruptedException e) {
            System.err.println(e);
            result.worked = false;
        } finally {
            // Close the InputStream
            bufferedreader.close();
            inread.close();
            buf.close();
            in.close();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        result.worked = false;
    }

    result.output = result.output.trim();

    return result;
}

From source file:com.evolveum.midpoint.test.util.TestUtil.java

public static String execSystemCommand(String command, boolean ignoreExitCode)
        throws IOException, InterruptedException {
    Runtime runtime = Runtime.getRuntime();
    LOGGER.debug("Executing system command: {}", command);
    Process process = runtime.exec(command);
    int exitCode = process.waitFor();
    LOGGER.debug("Command exit code: {}", exitCode);
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    StringBuilder output = new StringBuilder();
    String line = null;//from  w  w w.ja  v  a  2 s  .  c om
    while ((line = reader.readLine()) != null) {
        output.append(line);
    }
    reader.close();
    String outstring = output.toString();
    LOGGER.debug("Command output:\n{}", outstring);
    if (!ignoreExitCode && exitCode != 0) {
        String msg = "Execution of command '" + command + "' failed with exit code " + exitCode;
        LOGGER.error("{}", msg);
        throw new IOException(msg);
    }
    return outstring;
}

From source file:org.globus.workspace.WorkspaceUtil.java

/**
 * @param command command array/*from   w  w w . j  av  a2 s.c  om*/
 * @param event passing in false disables the event log
 * @param stdin stdin for process
 * @param eventLog log events to info?
 * @param traceLog alternatively, log events to trace?
 * @param trackingID optional for event logging, an id > 0?
 * @return stdout
 * @throws WorkspaceException exc
 * @throws ReturnException if exit code != 0, will contain return code
 *         as well as stdout and stderr if they exist.
 */
public static String runCommand(String[] command, boolean event, String stdin, boolean eventLog,
        boolean traceLog, int trackingID) throws WorkspaceException, ReturnException {

    if (command == null) {
        logger.error("Command cannot be null");
        throw new WorkspaceException("Command cannot be null");
    }

    if (eventLog && event) {
        logger.info(Lager.ev(trackingID) + printCmd(command));
    } else if (traceLog && event) {
        logger.trace(printCmd(command));
    }

    final Runtime runtime = Runtime.getRuntime();
    String stdout = null;
    String stderr = null;
    InputStream processStdoutStream = null;
    InputStream processStderrStream = null;

    try {
        final Process process = runtime.exec(command);

        // Unfortunately there can be buffer overflow problems if there are
        // not threads consuming stdout/stderr, seen that with workspace-
        // control create commands on certain platforms.

        processStderrStream = process.getErrorStream();
        final FutureTask stderrConsumer = new FutureTask(new StreamConsumer(processStderrStream));

        processStdoutStream = process.getInputStream();
        final FutureTask stdoutConsumer = new FutureTask(new StreamConsumer(processStdoutStream));

        executor.submit(stdoutConsumer);
        executor.submit(stderrConsumer);

        if (stdin != null) {
            if (traceLog) {
                logger.trace("stdin provided");
            }
            BufferedWriter in = null;
            OutputStreamWriter osw = null;
            OutputStream os = null;
            try {
                os = process.getOutputStream();
                osw = new OutputStreamWriter(os);
                in = new BufferedWriter(osw);
                in.write(stdin);
                in.newLine();
                in.flush();
            } finally {
                if (in != null) {
                    in.close();
                }
                if (osw != null) {
                    osw.close();
                }
                if (os != null) {
                    os.close();
                }
            }
            if (traceLog) {
                logger.trace("stdin sent");
            }
        } else {
            OutputStream os = null;
            try {
                os = process.getOutputStream();
            } finally {
                if (os != null) {
                    os.close();
                }
            }
        }

        final int returnCode;
        try {
            returnCode = process.waitFor();
        } catch (InterruptedException exp) {
            logger.error("Interupped exp thrown ", exp);
            throw new WorkspaceException("Interrupted: ", exp);
        }

        if (eventLog && event) {
            logger.info(Lager.ev(trackingID) + "Return code is " + returnCode);
        } else if (traceLog && event) {
            logger.trace("Return code is " + returnCode);
        }

        try {
            stdout = (String) stdoutConsumer.get(60L, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        try {
            stderr = (String) stderrConsumer.get(60L, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        if (returnCode != 0) {
            if (stderr != null && stdout != null) {

                logger.error(Lager.ev(trackingID) + "system command FAILURE" + "\nSTDOUT:\n" + stdout
                        + "\n\nSTDERR:\n" + stderr);

                throw new ReturnException(returnCode, stderr, stdout);

            } else if (stderr != null) {

                logger.error(Lager.ev(trackingID) + "system command FAILURE" + "\nSTDERR:\n" + stderr);
                throw new ReturnException(returnCode, stderr);

            } else {

                logger.error(Lager.ev(trackingID) + "system command FAILURE, no stdout or stderr");
                throw new ReturnException(returnCode);
            }

        } else {
            if (stdout != null) {
                if (eventLog && event) {
                    logger.info(Lager.ev(trackingID) + "\n" + "STDOUT:\n" + stdout);
                } else if (traceLog && event) {
                    logger.trace("\nSTDOUT:\n" + stdout);
                }
            }
        }
    } catch (IOException ioe) {
        logger.error(ioe);
        throw new WorkspaceException("", ioe);
    } finally {
        try {

            if (processStdoutStream != null) {
                processStdoutStream.close();
            }
            if (processStderrStream != null) {
                processStderrStream.close();
            }
        } catch (IOException exp) {
            logger.error("Could not close stream", exp);
        }
    }

    // may be null
    return stdout;
}