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, String[] envp, File dir) throws IOException 

Source Link

Document

Executes the specified command and arguments in a separate process with the specified environment and working directory.

Usage

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void deleteActivityTemplates(Object caller) throws IOException, InterruptedException {
    String[] cmd = null;//from   w ww.  ja va 2s. c  o m

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    String tmpdir = getTempLocation();
    BufferedInputStream bufferedInputStream = new BufferedInputStream(
            ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
    unZip(bufferedInputStream, tmpdir);

    if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            if (mobileTemplate != null)
                mobileTemplate.delete(caller);

            if (officeTemplate != null)
                officeTemplate.delete(caller);
        } catch (IOException ex) {
            PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
            printWriter.println("@echo off");
            printWriter.println("del \"" + templatePath + mobileServicesTemplateName + "\" /Q /S");
            printWriter.println("del \"" + templatePath + officeTemplateName + "\" /Q /S");
            printWriter.flush();
            printWriter.close();

            String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

            cmd = tmpcmd;

            ArrayList<String> tempenvlist = new ArrayList<String>();
            for (String envval : System.getenv().keySet())
                tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

            tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
            env = new String[tempenvlist.size()];
            tempenvlist.toArray(env);

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec(cmd, env, new File(tmpdir));
            proc.waitFor();
        }
    } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {
        VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
        VirtualFile officeTemplate = LocalFileSystem.getInstance()
                .findFileByIoFile(new File(templatePath + officeTemplateName));

        if (mobileTemplate != null && officeTemplate != null) {
            exec(new String[] { "osascript", "-e",
                    "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                    "-e", "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\"" },
                    tmpdir);
        }
    } else {
        try {
            VirtualFile mobileTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
            VirtualFile officeTemplate = LocalFileSystem.getInstance()
                    .findFileByIoFile(new File(templatePath + officeTemplateName));

            mobileTemplate.delete(caller);
            officeTemplate.delete(caller);
        } catch (IOException ex) {

            JPasswordField pf = new JPasswordField();
            int okCxl = JOptionPane.showConfirmDialog(null, pf,
                    "To copy Microsoft Services templates, the plugin needs your password:",
                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

            if (okCxl == JOptionPane.OK_OPTION) {
                String password = new String(pf.getPassword());

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName },
                        tmpdir);

                exec(new String[] { "echo", password, "|", "sudo", "-S", "rm", "-r",
                        tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
            }
        }
    }
}

From source file:com.microsoftopentechnologies.intellij.helpers.AndroidStudioHelper.java

public static void newActivityTemplateManager() throws IOException, InterruptedException {
    String[] cmd = null;//from   w ww  .ja  v  a2  s. c o  m

    String templatePath = URLDecoder
            .decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
    templatePath = templatePath.replace("/", File.separator);
    templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
    templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
    templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities"
            + File.separator;

    String[] env = null;

    if (!new File(templatePath + mobileServicesTemplateName).exists()) {
        String tmpdir = getTempLocation();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                ServiceCodeReferenceHelper.getTemplateResource("ActivityTemplate.zip"));
        unZip(bufferedInputStream, tmpdir);

        if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            try {
                copyFolder(new File(tmpdir + mobileServicesTemplateName),
                        new File(templatePath + mobileServicesTemplateName));
                copyFolder(new File(tmpdir + officeTemplateName), new File(templatePath + officeTemplateName));
            } catch (IOException ex) {
                PrintWriter printWriter = new PrintWriter(tmpdir + "\\script.bat");
                printWriter.println("@echo off");
                printWriter.println("md \"" + templatePath + mobileServicesTemplateName + "\"");
                printWriter.println("md \"" + templatePath + officeTemplateName + "\"");
                printWriter.println("xcopy \"" + tmpdir + mobileServicesTemplateName + "\" \"" + templatePath
                        + mobileServicesTemplateName + "\" /s /i /Y");
                printWriter.println("xcopy \"" + tmpdir + officeTemplateName + "\" \"" + templatePath
                        + officeTemplateName + "\" /s /i /Y");
                printWriter.flush();
                printWriter.close();

                String[] tmpcmd = { tmpdir + "\\elevate.exe", "script.bat", "1" };

                cmd = tmpcmd;

                ArrayList<String> tempenvlist = new ArrayList<String>();
                for (String envval : System.getenv().keySet())
                    tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

                tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
                env = new String[tempenvlist.size()];
                tempenvlist.toArray(env);

                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec(cmd, env, new File(tmpdir));
                proc.waitFor();

                //wait for elevate command to finish
                Thread.sleep(3000);

                if (!new File(templatePath + mobileServicesTemplateName).exists())
                    UIHelper.showException(
                            "Error copying template files. Please refer to documentation to copy manually.",
                            new Exception());
            }
        } else {
            if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {

                String[] strings = { "osascript",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\"",
                        //        "-e",
                        //        "do shell script \"mkdir -p \\\"/" + templatePath + officeTemplateName + "\\\"\"",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpdir + mobileServicesTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"",
                        "-e", "do shell script \"cp -Rp \\\"" + tmpdir + officeTemplateName + "\\\" \\\"/"
                                + templatePath + "\\\"\"" };

                exec(strings, tmpdir);
            } else {
                try {

                    copyFolder(new File(tmpdir + mobileServicesTemplateName),
                            new File(templatePath + mobileServicesTemplateName));
                    copyFolder(new File(tmpdir + officeTemplateName),
                            new File(templatePath + officeTemplateName));

                } catch (IOException ex) {

                    JPasswordField pf = new JPasswordField();
                    int okCxl = JOptionPane.showConfirmDialog(null, pf,
                            "To copy Microsoft Services templates, the plugin needs your password:",
                            JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    if (okCxl == JOptionPane.OK_OPTION) {
                        String password = new String(pf.getPassword());

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + mobileServicesTemplateName,
                                templatePath + mobileServicesTemplateName }, tmpdir);

                        exec(new String[] { "echo", password, "|", "sudo", "-S", "cp", "-Rp",
                                tmpdir + officeTemplateName, templatePath + officeTemplateName }, tmpdir);
                    }
                }
            }
        }
    }
}

From source file:org.kalypso.wspwin.core.Plotter.java

/**
 * Starts the plotter on the specified profile or length-section.<br>
 * The method {@link #checkPlotterExe(Shell)} should be called beforehand.
 *//*from  ww w.  java 2 s .  com*/
public static void openPrf(final File file, final boolean doPrint) throws IOException {
    final File plotterExe = getPlotterExeChecked();
    if (plotterExe == null)
        return;

    final Runtime runtime = Runtime.getRuntime();

    final Collection<String> commands = new ArrayList<>();
    commands.add(plotterExe.getAbsolutePath());
    if (doPrint)
        commands.add("-p"); //$NON-NLS-1$
    commands.add(file.getName());

    final String[] cmdArray = commands.toArray(new String[commands.size()]);
    final Process p = runtime.exec(cmdArray, null, file.getParentFile());
    new StreamStreamer(p.getInputStream(), System.out);
    new StreamStreamer(p.getErrorStream(), System.err);
}

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

/**
 * Executes a call of this procedure in the specified context
 * and with the specified call bindings.
 *
 * @param cx             the procedure call context
 * @param bindings       the call bindings to use
 *
 * @return the result of the call, or/*from w w  w . j a  v  a 2 s  .com*/
 *         null if the call produced no result
 *
 * @throws ProcedureException if the call execution caused an
 *             error
 */
static Object execCall(CallContext cx, Bindings bindings) throws ProcedureException {

    File dir = ApplicationContext.getInstance().getBaseDir();
    String str = bindings.getValue(BINDING_COMMAND).toString();
    // TODO: parse command-line properly, avoid StringTokenizer
    String cmd = replaceArguments(str, bindings).trim();
    str = ((String) bindings.getValue(BINDING_DIRECTORY, "")).trim();
    if (str.length() > 0) {
        str = replaceArguments(str, bindings);
        if (str.startsWith("/")) {
            dir = new File(str);
        } else {
            dir = new File(dir, str);
        }
    }
    String[] env = null;
    str = ((String) bindings.getValue(BINDING_ENVIRONMENT, "")).trim();
    if (str.length() > 0) {
        env = replaceArguments(str, bindings).split(";");
    }
    Runtime runtime = Runtime.getRuntime();
    LOG.fine("init exec: " + cmd);
    cx.log("Command: " + cmd);
    cx.log("Directory: " + dir);
    if (env != null) {
        cx.log("Environment: " + Arrays.toString(env));
    }
    try {
        // TODO: investigate using ProcessBuilder instead
        Process process = runtime.exec(cmd, env, dir);
        return waitFor(process, cx);
    } catch (IOException e) {
        str = "error executing '" + cmd + "': " + e.getMessage();
        LOG.log(Level.WARNING, str, e);
        throw new ProcedureException(str);
    } finally {
        LOG.fine("done exec: " + cmd);
    }
}

From source file:rega.genotype.ui.util.GenotypeLib.java

private static File getTreeEPS(File jobDir, File treeFile)
        throws IOException, InterruptedException, ApplicationException, FileNotFoundException {
    File epsFile = new File(treeFile.getPath().replace(".tre", ".eps"));
    if (epsFile.exists())
        return epsFile;

    Runtime runtime = Runtime.getRuntime();
    Process proc;//from   w w w  . j  a v a 2s .  c  o m
    int result;
    String cmd;

    cmd = Settings.treeGraphCommand + " -t " + treeFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);

    InputStream inputStream = proc.getInputStream();

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream));

    Pattern taxaCountPattern = Pattern.compile("(\\d+) taxa read.");

    int taxa = 0;
    for (;;) {
        String s = reader.readLine();
        if (s == null)
            break;
        Matcher m = taxaCountPattern.matcher(s);

        if (m.find()) {
            taxa = Integer.valueOf(m.group(1)).intValue();
        }
    }

    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    File tgfFile = new File(treeFile.getPath().replace(".tre", ".tgf"));
    File resizedTgfFile = new File(treeFile.getPath().replace(".tre", ".resized.tgf"));

    BufferedReader in = new BufferedReader(new FileReader(tgfFile));
    PrintStream out = new PrintStream(new FileOutputStream(resizedTgfFile));
    String line;
    while ((line = in.readLine()) != null) {
        line = line.replace("\\width{", "%\\width{");
        line = line.replace("\\height{", "%\\height{");
        line = line.replace("\\margin{", "%\\margin{");
        line = line.replace("\\style{r}{plain}", "%\\style{r}{plain}");
        line = line.replace("\\style{default}{plain}", "%\\style{default}{plain}");
        line = line.replaceAll("\\\\len\\{-", "\\\\len\\{");
        out.println(line);

        if (line.equals("\\begindef")) {
            out.println("\\paper{a2}");
            out.println("\\width{170}");
            out.println("\\height{" + (taxa * 8.6) + "}");
            out.println("\\margin{10}{10}{10}{10}");
            out.println("\\style{default}{plain}{13}");
            out.println("\\style{r}{plain}{13}");
        }
    }
    out.close();
    in.close();

    tgfFile.delete();
    resizedTgfFile.renameTo(tgfFile);

    cmd = Settings.treeGraphCommand + " -p " + tgfFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);
    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    return epsFile;
}

From source file:Hash.Hash.java

private static String getFullHashPS(File file) throws FileNotFoundException, IOException {
    String[] parameters = new String[] { "powershell.exe", "Get-ChildItem", "-File", "-Recurse", "|",
            "Get-FileHash", "-Algorithm", "MD5", ">>", "e:\\ps.md5" };
    String lines = "";
    try {//from   ww  w  . j  ava  2  s  .co m
        Runtime runtime = Runtime.getRuntime();
        Process p = runtime.exec(parameters, null, file);
        /*            final BufferedReader stdinReader = new BufferedReader(new InputStreamReader(p.getInputStream(), "ISO-8859-1"));
                    final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream(), "ISO-8859-1"));
                    new Thread(() -> {
        try {
            String s;
            while (( s=stdinReader.readLine()) != null) {
                System.out.println(s);
            }
        }
        catch(IOException e) {
        }
                    }).start();
                    new Thread(() -> {
        try {
            String s;
            while (( s=stderrReader.readLine()) != null) {
                System.out.println(s);
            }
        }
        catch(IOException e) {
        }
                    }).start();*/
        int returnVal = p.waitFor();
    } catch (Exception e) {
        errorOut("xmp", e);
    }
    return lines;

}

From source file:org.smartfrog.avalanche.client.sf.apps.utils.FileUtils.java

public static boolean softLink(String fileName, String destDir, String linkName)
        throws IOException, InterruptedException {
    File file = new File(fileName);
    if (!file.exists()) {
        log.error("File " + fileName + " does not exist");
        return false;
    }/*  ww w  .  j a va2 s. c  o  m*/
    if (!file.canRead()) {
        log.error("File " + fileName + " does not have read permissions");
        return false;
    }

    File dir = new File(destDir);
    if (!dir.exists()) {
        log.error("Directory " + destDir + " does not exist");
        return false;
    }
    if (!dir.isDirectory()) {
        log.error("Destination directory " + destDir + " is not a directory");
        return false;
    }
    if (!dir.canWrite()) {
        log.error("Cannot write to the directory " + destDir);
        return false;
    }

    Runtime rt = Runtime.getRuntime();
    /*int idx = file.getAbsolutePath().lastIndexOf(File.separatorChar);
    String destFile = file.getAbsolutePath().substring(idx);
    destFile = destFile.trim(); */
    String cmd = "ln -s " + file.getAbsolutePath() + " " + linkName;
    log.info("CMD : " + cmd);
    Process p = rt.exec(cmd, null, dir);

    int exitVal = 0;
    BufferedReader cmdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    exitVal = p.waitFor();
    if (exitVal != 0) {
        log.error("Error in creating soft link to " + fileName);
        String line = null;
        String error = null;
        if ((line = cmdError.readLine()) != null) {
            log.error(line);
            error = line;
            while ((line = cmdError.readLine()) != null) {
                log.error(line);
                error = error + "\n" + line;
            }
            throw new IOException(error);
        }
    }
    return true;
}

From source file:servlet.Run.java

ArrayList<String> execErroutput(String runPath, String encode, String className) throws Exception {
    Runtime rt = Runtime.getRuntime();

    Process proc = rt.exec("javac " + className + ".java", new String[] {}, new File(runPath));
    InputStream stderr = proc.getErrorStream();
    InputStreamReader isr = new InputStreamReader(stderr, encode);
    BufferedReader br = new BufferedReader(isr);
    String line = null;/*  w ww. java  2s. c o m*/
    ArrayList<String> a = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        System.err.println(line);
        a.add(line);
    }
    return a;
}

From source file:servlet.Run.java

ArrayList<String> execOutput(String runPath, String encode, String className) throws Exception {
    Runtime rt = Runtime.getRuntime();

    Process proc = rt.exec("java " + className, new String[] {}, new File(runPath));
    InputStream stderr = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(stderr, encode);
    BufferedReader br = new BufferedReader(isr);
    String line = null;//w ww  .  j  a  v  a 2 s  .c  o  m
    ArrayList<String> a = new ArrayList<>();
    while ((line = br.readLine()) != null) {
        System.out.println(line);
        a.add(line);
    }
    return a;
}

From source file:ninja.command.PackageCommand.java

private void packageWar() throws IOException, InterruptedException {
    FileUtils.copyDirectory(new File(project.getBaseDir(), "/src/main/webapp"), packageFolder);

    File classesDir = new File(packageFolder, "WEB-INF/classes");
    FileUtils.copyDirectory(project.getClassesDir(), classesDir);
    // FIXME This is a hack for the views
    FileUtils.copyDirectory(new File(project.getSourceDir(), "views"), new File(classesDir, "views"));
    DepCommand.copyLibs(project, new File(packageFolder, "WEB-INF/lib"));
    // String metainf = "Manifest-Version: 1.0\nArchiver-Version:
    // Nina-cmd\n\n";
    // File metainfFile = new File(packageFolder, "META-INF/MANIFEST.MF");
    // metainfFile.getParentFile().mkdirs();
    // FileUtils.writeStringToFile(metainfFile, metainf);
    String jarName = project.getName() + ".war";
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(String.format("jar -cf ../%s .", jarName), null, packageFolder);
    int result = pr.waitFor();
    if (result == 0)
        info(String.format("War created '%s'.", jarName));
    else/*from w  w  w  .jav a 2 s.c om*/
        info(String.format("Error while creating '%s'.", jarName));
}