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:HelpDemo.java

/**
 * help() -- start a help viewer. On Win32, we use the "start" command. For
 * UNIX, we'll try for Netscape or HotJava in the user's path. For the Mac,
 * not sure what we'll do.//w ww  . j a  va 2 s  .c  om
 */
public void help() throws IOException {

    // A Runtime object has methods for dealing with the OS
    Runtime r = Runtime.getRuntime();
    // A process object tracks one external running process
    Process p;

    // Start Netscape from Java Applications (not Applets though)
    p = r.exec("c:/windows/command/start.exe HelpDemo.htm");

    return;
}

From source file:org.apache.fop.fonts.autodetect.WindowsFontDirFinder.java

/**
 * Attempts to read windir environment variable on windows
 * (disclaimer: This is a bit dirty but seems to work nicely)
 *//* www .  j  a va  2  s  .  c  om*/
private String getWinDir(String osName) throws IOException {
    Process process = null;
    Runtime runtime = Runtime.getRuntime();
    if (osName.startsWith("Windows 9")) {
        process = runtime.exec("command.com /c echo %windir%");
    } else {
        process = runtime.exec("cmd.exe /c echo %windir%");
    }
    InputStreamReader isr = null;
    BufferedReader bufferedReader = null;
    String dir = "";
    try {
        isr = new InputStreamReader(process.getInputStream());
        bufferedReader = new BufferedReader(isr);
        dir = bufferedReader.readLine();
    } finally {
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(isr);
    }
    return dir;
}

From source file:it.sauronsoftware.jave.DefaultFFMPEGLocator.java

/**
 * It builds the default FFMPEGLocator, exporting the ffmpeg executable on a
 * temp file./*from  ww  w .  jav a 2s . c o m*/
 */
public DefaultFFMPEGLocator() {
    // Windows?
    boolean isWindows;
    String os = System.getProperty("os.name").toLowerCase();
    if (os.contains("windows")) {
        isWindows = true;
    } else {
        isWindows = false;
    }

    // Temp dir?
    File temp = new File(System.getProperty("java.io.tmpdir"), "jave-" + myEXEversion);
    if (!temp.exists()) {
        temp.mkdirs();
        temp.deleteOnExit();
    }
    // ffmpeg executable export on disk.
    String suffix = isWindows ? ".exe" : "";
    String arch = System.getProperty("os.arch");

    File exe = new File(temp, "ffmpeg-" + arch + suffix);
    if (!exe.exists()) {
        copyFile("ffmpeg-" + arch + suffix, exe);
    }
    // Need a chmod?
    if (!isWindows) {
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(new String[] { "/bin/chmod", "755", exe.getAbsolutePath() });
        } catch (IOException e) {
            _log.error(e);
        }
    }
    // Ok.
    this.path = exe.getAbsolutePath();
}

From source file:org.cesecore.time.providers.NtpClientParser.java

/**
 * Executes a call to an NTP client and parses the output in order to obtain the offset of the selected trusted time source.
 * /*from ww w  . j  a  v a 2 s.co  m*/
 * @return Double containing the offset of the current selected trusted time source
 */
public TrustedTime getTrustedTime() {

    Process proc = null;
    TrustedTime trustedTime = null;
    try {
        Runtime runtime = Runtime.getRuntime();
        proc = runtime.exec(this.ntpClientCommand);

        @SuppressWarnings("unchecked")
        List<String> lines = IOUtils.readLines(proc.getInputStream());

        trustedTime = parseOffset(lines);
    } catch (Exception e) {
        log.error("Error parsing NTP output", e);
        trustedTime = new TrustedTime();
    } finally {
        if (proc != null) {
            IOUtils.closeQuietly(proc.getInputStream());
            IOUtils.closeQuietly(proc.getErrorStream());
            IOUtils.closeQuietly(proc.getOutputStream());
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(trustedTime.toString());
    }

    return trustedTime;
}

From source file:org.apache.hadoop.hdfs.ManualSyncTester.java

private Process runChild(String dataPath, String progressPath) throws Exception {
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec(new String[] { "java", "-cp", System.getProperty("java.class.path"),
            "org.apache.hadoop.hdfs.ManualSyncTester$Child", dataPath, progressPath });
    new Pumper(p.getInputStream(), System.out).start();
    new Pumper(p.getErrorStream(), System.err).start();
    return p;/* ww w .j  ava2 s . c o  m*/
}

From source file:org.hobbit.spatiotemporalbenchmark.platformConnection.systems.LogMapSystemAdapter.java

public void linkingController(String source, String target) throws IOException {
    resultsFile = new File("./datasets/LimesSystemAdapterResults/mappings."
            + SesameUtils.parseRdfFormat(dataFormat).getDefaultFileExtension());

    LOGGER.info("Started LogMap Controller.. ");
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("java -jar ./lib/logmap2_standalone.jar " + "MATCHER file:" + source + " " + "file:"
            + target + " " + "" + resultsFile.getAbsolutePath() + " true");

    //-Xms512m -Xmx1152m
    //an treksei allakse kai to memory tis java stin entoli

    File[] files = new File("file.getName()").listFiles();
    //If this pathname does not denote a directory, then listFiles() returns null. 

    for (File file : files) {
        if (file.isFile()) {
            LOGGER.info("Logmap - Results file.getName() " + file.getName());

            BufferedReader br = new BufferedReader(
                    new FileReader("./datasets/LogMapSystemAdapterResults/" + file.getName()));
            String line = null;/*from   w w  w .  ja  va2  s . com*/
            while ((line = br.readLine()) != null) {
                LOGGER.info("-> " + line);
            }
        }
    }
    LOGGER.info("LogMap Controller finished..");
}

From source file:org.magicbeans.project.setupVisualPanel1.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    URL dlLoc;/* www.  ja  v  a2s .  c  om*/
    String url = jTextField1.getText();
    char lastChar = url.charAt(url.length() - 1);
    if (lastChar == '\\' || lastChar == '/') {
        url = url.substring(0, url.length() - 2);
    }
    try {
        dlLoc = new URL(url);
        String installerDir = jTextField2.getText();
        File toFile = new File(installerDir);
        if (toFile.exists()) {
            if (toFile.isDirectory()) {
                String installerPath = jTextField2.getText() + "/miktexinstaller.exe";
                toFile = new File(installerPath);
                try {
                    FileUtils.copyURLToFile(dlLoc, toFile);
                    Runtime rt = Runtime.getRuntime();
                    Process pr = rt.exec(installerPath + " -d " + installerDir);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
        }
    } catch (MalformedURLException ex) {
        Exceptions.printStackTrace(ex);
    }

}

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

public static void exportServiceDefCJSIDL(com.u2d.generated.ServiceDef serviceDef, File outputFile) {
    lastServiceDefExportPath = outputFile.getParentFile();

    com.u2d.app.Context.getInstance().getViewMechanism().message("Exporting ServiceDef... ");

    org.jts.jsidl.binding.ServiceDef sd = org.jts.gui.jmatterToJAXB.ServiceDef.convert(serviceDef);
    RemoveJSIDLPlus.removeJSIDLPlus(sd);
    if (hasDependencies(sd)) {
        com.u2d.app.Context.getInstance().getViewMechanism().message(
                "ServiceDef Conversion Failed!  Dependencies detected, but not included.\n This should be done using a service set. ");

        JOptionPane.showMessageDialog(GUI.getFrame(),
                "ServiceDef Conversion Failed!\n" + "Dependencies detected, but not included.\n"
                        + "Try exporting a service set that includes all dependencies.");
        return;/*  ww  w .  ja  va2 s . co  m*/
    }
    try {
        java.util.List<File> files = new ArrayList<File>();
        File tmpfolder = org.jts.gui.importCJSIDL.Import.createTempDir();
        File tmpfile = null;
        try {
            tmpfile = serializeJAXB(sd, tmpfolder.getCanonicalPath());
            files.add(tmpfile);
        } catch (FileNotFoundException ex) {
            System.out.println(
                    "Failed to create a temp file used during conversion: " + tmpfile.getCanonicalPath());
        }

        // convertFromJSIDL tmpfile.getCanonicalPath() outputFile.getCanonicalPath()
        // this could be done instead of the following try/catch, but an antlr lib version conflict gets in the way
        //            Conversion conv = new Conversion();
        //            conv.convertFromJSIDL(tmpfile.getCanonicalPath(), outputFile.getCanonicalPath());
        try {
            System.out.println("Initiating Conversion process 'convertFromJSIDL'");
            java.lang.Runtime rt = java.lang.Runtime.getRuntime();
            String execStr = ("java " + classpath
                    + " org.jts.eclipse.conversion.cjsidl.Conversion \"convertFromJSIDL\" \""
                    + tmpfile.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.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();

            System.out.println("Process exited with code = " + p.exitValue());
            if (!errors.isEmpty()) {
                Logger.getLogger(Export.class.getName()).log(Level.SEVERE, errors);
                JOptionPane.showMessageDialog(GUI.getFrame(), errors, "CJSIDL Export Error",
                        JOptionPane.ERROR_MESSAGE);
            }

        } catch (IOException ex) {
            Logger.getLogger(Export.class.getName()).log(Level.SEVERE, null, ex);
        }

        com.u2d.app.Context.getInstance().getViewMechanism().message("ServiceDef Export Complete!  ");
    } 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);
    }
}

From source file:it.sauronsoftware.jave.FFMPEGExecutor.java

/**
 * Executes the ffmpeg process with the previous given arguments.
 * /*from   w  w w .j ava2  s  . co  m*/
 * @throws IOException
 *             If the process call fails.
 */
public void execute() throws IOException {
    int argsSize = args.size();
    String[] cmd = new String[argsSize + 1];
    cmd[0] = ffmpegExecutablePath;
    for (int i = 0; i < argsSize; i++) {
        cmd[i + 1] = args.get(i);
    }
    if (_log.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        for (String c : cmd) {
            sb.append(c);
            sb.append(' ');
        }
        _log.debug("About to execute " + sb.toString());
    }
    Runtime runtime = Runtime.getRuntime();
    ffmpeg = runtime.exec(cmd);
    ffmpegKiller = new ProcessKiller(ffmpeg);
    runtime.addShutdownHook(ffmpegKiller);
    inputStream = ffmpeg.getInputStream();
    outputStream = ffmpeg.getOutputStream();
    errorStream = ffmpeg.getErrorStream();
}

From source file:de.rrze.idmone.utils.jidgen.filter.ShellCmdFilter.java

public String apply(String id) {
    String cmd = this.cmdTemplate.replace("%s", id);

    logger.trace("Executing command: " + cmd);

    Runtime run = Runtime.getRuntime();
    try {//from  www .j a  va 2 s  .c  o m
        Process proc = run.exec(cmd);

        /*      BufferedWriter commandLine = new BufferedWriter(
                    new OutputStreamWriter(proc.getOutputStream())
              );
              commandLine.write(cmd);
              commandLine.flush();
        */
        // read stdout and log it to the debug level
        BufferedReader stdOut = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        String stdOutput = "";
        while ((stdOutput = stdOut.readLine()) != null) {
            logger.debug("STDOUT: " + stdOutput);
        }
        stdOut.close();

        // read stderr and log it to the error level
        BufferedReader stdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
        String errOutput = "";
        while ((errOutput = stdErr.readLine()) != null) {
            logger.error("STDERR: " + errOutput);
        }
        stdErr.close();

        int exitCode = proc.waitFor();
        proc.destroy();

        if (exitCode == 0) {
            logger.trace("Filtered!");
            return null;
        } else {
            return id;
        }

    } catch (IOException e) {
        logger.fatal(e.toString());
        System.exit(120);
    } catch (InterruptedException e) {
        logger.fatal(e.toString());
        System.exit(121);
    }

    return null;
}