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:com.appcel.core.encoder.locator.EncoderLocator.java

@Override
public EncoderExecutor createEncoderExecutor(EncoderExecutorEnum encoderExcutorEnum) {
    EncoderExecutor encoderExcutor = null;

    String os = System.getProperty("os.name").toLowerCase();
    // Windows?/*from w w  w.j  av a2 s .  co  m*/
    boolean isWindows = (os.indexOf("windows") != -1) ? true : false; // Need a chmod?

    //String archexe = encoderExcutorEnum.getValue();

    // Temp dir?
    //      File temp = new File(System.getProperty("java.io.tmpdir"), archexe + myEXEversion);
    //      if (!temp.exists()) {
    //         temp.mkdirs();
    //         temp.deleteOnExit();
    //      }

    // encoder executable export on disk.
    //      String suffix = isWindows ? ".exe" : "";
    //      File exeFile = new File(temp, archexe + suffix);

    //String executableCmdPath = exeFile.getAbsolutePath();

    //      if (!exeFile.exists()) {
    //
    //         copyFile(archexe + suffix, exeFile);
    //      }

    String executableCmdPath = "";
    if (EncoderExecutorEnum.FFMPEGEXECUTOR.equals(encoderExcutorEnum)) {

        executableCmdPath = isWindows ? EncoderConfiguration.getMe().getEncoderFfmpegWinHome()
                : EncoderConfiguration.getMe().getEncoderFfmpegLinuxHome();

        encoderExcutor = new FfmpegEncoderExecutor(executableCmdPath, !isWindows);

    } else if (EncoderExecutorEnum.MENCODEREXECUTOR.equals(encoderExcutorEnum)) {

    } else if (EncoderExecutorEnum.YAMDIEXECUTOR.equals(encoderExcutorEnum)) {

    } else if (EncoderExecutorEnum.QT_FASTSTART.equals(encoderExcutorEnum)) {

        executableCmdPath = isWindows ? EncoderConfiguration.getMe().getEncoderQtFaststartWinHome()
                : EncoderConfiguration.getMe().getEncoderQtFaststartLinuxHome();
        encoderExcutor = new QTFaststartExecutor(executableCmdPath, !isWindows);

    } else {
        throw new EncoderRuntimeException(
                "Illegal The encoder paramter executor error : " + encoderExcutorEnum + " is not support.");
    }

    if (!isWindows) {
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(new String[] { "/bin/chmod", "755", executableCmdPath });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    LOGGER.info("Encoder executor Path ??==========>>> " + executableCmdPath);

    return encoderExcutor;
}

From source file:de.onyxbits.raccoon.ptools.ToolSupport.java

/**
 * Unpack and install tools and drivers//from   ww w  .ja  va  2  s .  c  o m
 * 
 * @param adbzip
 *          zip file containing the tools package
 * @param usbzip
 *          zip file containing the usbdrivers (may be null).
 */
protected void install(File adbzip, File usbzip) throws IOException {
    if (adbzip != null) {
        unzip(adbzip);
    }
    if (usbzip != null) {
        unzip(usbzip);
    }

    try {
        Runtime rt = Runtime.getRuntime();
        if (isWindows()) {
            File inf = new File(new File(binDir, USB), "android_winusb.inf");
            rt.exec("pnputil -i -a " + inf.getAbsolutePath()).waitFor();
        } else {
            rt.exec("chmod +x " + adb.getAbsolutePath()).waitFor();
            rt.exec("chmod +x " + sqlite.getAbsolutePath()).waitFor();
            rt.exec("chmod +x " + fastboot.getAbsolutePath()).waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:de.fau.cs.osr.hddiff.utils.HDDiffTreeVisualizer.java

private void callDot(File inFile) {
    try {//w  w w.j  a v  a  2  s.  co  m
        String outFname = inFile.getName();
        if (outFname.toLowerCase().endsWith(".dot"))
            outFname = outFname.substring(0, outFname.length() - 4);
        outFname += ".png";
        File outFile = new File(inFile.getParentFile(), outFname);

        String[] cmd = new String[] { bin.getPath(), "-Tpng", "-o", outFile.getPath(), inFile.getPath() };

        Runtime rt = Runtime.getRuntime();
        Process pr = rt.exec(cmd);

        int size = 0;
        int maxSize = 2 << 16;
        StringWriter sw = new StringWriter();
        BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

        String line = null;
        while ((line = input.readLine()) != null) {
            size += line.length() + 1;
            if (size < maxSize) {
                sw.append(line);
                sw.append("\n");
            }
        }

        int exitVal = pr.waitFor();
        if (exitVal != 0) {
            System.err.println("Command failed:");
            System.err.println(Arrays.toString(cmd));
            System.err.println("Command output:");
            String cmdOutput = sw.toString();
            System.err.println(cmdOutput);
            if (size != cmdOutput.length())
                System.err.println("WARNING: Command output exceeded buffer size!");
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
    }
}

From source file:org.bonitasoft.connectors.scripting.ComplexShellConnector.java

@Override
protected Process executeShellCommand() throws IOException {
    final Runtime rt = Runtime.getRuntime();
    final String[] commandArray = command.toArray(new String[0]);
    for (int i = 0; i < commandArray.length; i++) {
        LOGGER.warn(i + " : " + commandArray[i]);
    }//www . j  a va 2 s  .  c o  m
    final Process process = rt.exec(commandArray);
    return process;
}

From source file:processing.app.CommandLineTest.java

@Test
public void testCommandLinePreferencesSave() throws Exception {
    Runtime rt = Runtime.getRuntime();
    File prefFile = File.createTempFile("test_pref", ".txt");
    prefFile.deleteOnExit();/*ww  w .  j  ava2s. co  m*/

    Process pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--save-prefs", "--preferences-file",
            prefFile.getAbsolutePath(), "--get-pref", // avoids starting the GUI
    });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--pref", "test_pref=xxx", "--preferences-file",
            prefFile.getAbsolutePath(), });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    PreferencesMap prefs = new PreferencesMap(prefFile);
    assertNull("preference should not be saved", prefs.get("test_pref"));

    pr = rt.exec(new String[] { arduinoPath.getAbsolutePath(), "--pref", "test_pref=xxx", "--preferences-file",
            prefFile.getAbsolutePath(), "--save-prefs", });
    IOUtils.copy(pr.getInputStream(), System.out);
    IOUtils.copy(pr.getErrorStream(), System.out);
    pr.waitFor();
    assertEquals(0, pr.exitValue());

    prefs = new PreferencesMap(prefFile);
    assertEquals("preference should be saved", "xxx", prefs.get("test_pref"));
}

From source file:controllers.ServerController.java

public void addSetting(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("ssh 192.168.1.230:/opt/script/addSetting "
            + request.getParameter("printerName") + " " + request.getParameter("group") + " "
            + request.getParameter("command") + " " + request.getParameter("commandValue"));
}

From source file:fr.inria.oak.paxquery.algebra.operators.BaseLogicalOperator.java

public void draw(String folder, String givenFileName) {
    //System.out.println("BaseLogicalOperator:");
    //System.out.println("\tfolder: "+folder);
    //System.out.println("\tgivenFileName: "+givenFileName);

    StringBuffer sb = new StringBuffer();
    sb.append("digraph  g{\n edge [dir=\"back\"]\n");
    recursiveDotString(sb, 0, 100);/*  w w  w. j ava  2 s.c o m*/
    try {
        if (givenFileName == null) {
            givenFileName = "" + System.currentTimeMillis();
        }
        String pathName = "";
        int lastSlash = givenFileName.lastIndexOf(File.separator);
        if (lastSlash > 0) {
            pathName = givenFileName.substring(0, lastSlash);
            File dir = new File(pathName);
            dir.mkdirs();
        }

        String fileNameDot = new String(folder + File.separator + givenFileName + "-logplan.dot");
        String fileNamePNG = new String(folder + File.separator + givenFileName + "-logplan.png");

        //System.out.println("fileNameDot: "+fileNameDot);
        FileWriter file = new FileWriter(fileNameDot);
        file.write(new String(sb));
        file.write("}\n");
        file.close();
        Runtime r = Runtime.getRuntime();
        String com = new String("dot -Tpng " + fileNameDot + " -o " + fileNamePNG);
        Process p = r.exec(com);
        p.waitFor();
        //System.out.println("Logical plan drawn.");
        logger.debug("Logical plan drawn.");
    } catch (Exception e) {
        logger.error("Exception: ", e);
    }
}

From source file:org.smartfrog.avalanche.client.sf.apps.gt4.gridftp.ConfigureGridFTP.java

public boolean restartXinetd() throws IOException {
    Runtime rt = Runtime.getRuntime();

    String cmd = GFTPConstants.xinetd + " restart";
    Process p = rt.exec(cmd);

    try {//from  w w w.j a  v a  2s  . c om
        if (p.waitFor() != 0) {
            log.error("Failed to restart xinetd");
            return false;
        }
    } catch (InterruptedException ie) {
        log.error(ie);
        return false;
    }
    return true;
}

From source file:cloudworker.Animoto.java

@SuppressWarnings("unchecked")
public void run() {
    //Get queue url   
    GetQueueUrlResult urlResult = sqs.getQueueUrl(responseQName);
    String QueueUrl = urlResult.getQueueUrl();
    JSONObject result = new JSONObject();

    Runtime runtime = Runtime.getRuntime();

    try {/* w w  w.j  a v a  2  s  .c  om*/
        String[] urls = task.split(" ");

        for (String url : urls) {
            //System.out.println(url);
            Process p = runtime.exec("wget " + url);
            p.waitFor();
        }

        Process rename = runtime.exec("./rename.sh");
        rename.waitFor();

        runtime.exec("ffmpeg -f image2 -i img%03d.jpg movie.mpg");

        File movie = new File("movie.mpg");

        S3Service s3 = new S3Service();
        URL url = s3.put(movie.getName(), movie);

        //result.put("task_id", task_id);
        result.put("URL", url.toString());

        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));
        //System.out.println(Thread.currentThread().getName()+" sleep done!");

    } catch (Exception e) {
        //result.put("task_id", task_id);
        result.put("URL", "Failed!");
        sqs.sendMessage(new SendMessageRequest(QueueUrl, result.toString()));

    }
}

From source file:org.jwebsocket.plugins.tts.SpeakAloudProvider.java

@Override
public byte[] generateAudioFromString(String aText, String aGender, String aSpeaker, String aFormat) {
    synchronized (this) {
        byte[] lResult = null;
        Process lProcess = null;/* w  ww  .  j a  va  2s . c om*/
        try {
            String lUUID = "speak"; // UUID.randomUUID().toString();
            String lTextFN = mTextPath + lUUID + ".txt";

            mLog.debug("Executing '" + mExePath + " " + lTextFN + "'...");

            // write text from client into text file of server harddisk
            File lTextFile = new File(lTextFN);
            FileUtils.writeStringToFile(lTextFile, aText, "Cp1252");

            // call conversion tool with appropriate arguments
            Runtime lRT = Runtime.getRuntime();
            // pass the text file to be converted.
            String[] lCmd = { mExePath, lTextFN };
            lProcess = lRT.exec(lCmd);

            InputStream lIS = lProcess.getInputStream();
            InputStreamReader lISR = new InputStreamReader(lIS);
            BufferedReader lBR = new BufferedReader(lISR);
            String lLine;
            while ((lLine = lBR.readLine()) != null) {
                //                  System.out.println(lLine);
            }
            // wait until process has performed completely
            if (lProcess.waitFor() != 0) {
                mLog.error("Converter exited with value " + lProcess.exitValue());
            } else {
                mLog.info("Audiostream successfully generated!");
            }
            String lAudioFN = mTextPath + lUUID + ".MP3";
            File lAudioFile = new File(lAudioFN);
            lResult = FileUtils.readFileToByteArray(lAudioFile);

            FileUtils.deleteQuietly(lTextFile);
            FileUtils.deleteQuietly(lAudioFile);

        } catch (Exception lEx) {
            mLog.error(Logging.getSimpleExceptionMessage(lEx, "performing TTS conversion"));
        } finally {
            if (null != lProcess) {
                lProcess.destroy();
            }
        }
        return lResult;
    }
}