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:util.DirUsageUnixUtil.java

/**
 * Uses du command on unix to get dir usage.
 *
 * @param dir // w  w  w  .j ava2s .  com
 * @param file
 * @throws DirException
 * @return String
 */
public String dirUsage(String dir, String file) throws DirException {
    try {
        Runtime runtime = Runtime.getRuntime();
        // It is important to break up the command into a String[] array
        // du -h --total -s
        Process proc = runtime.exec(new String[] { "/usr/bin/du", "-h", "--total", "-s", dir + file });
        InputStream stdin = null;
        int exitVal = proc.waitFor();
        if (exitVal == 0)
            stdin = proc.getInputStream();
        else
            stdin = proc.getErrorStream();
        InputStreamReader isr = new InputStreamReader(stdin);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer output = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            //System.out.println("line = " + line);
            output.append(line);
        }
        return output.toString();
    } catch (Exception e) {
        throw new DirException("Could not get dir usage", e);
    }
}

From source file:org.eclipse.kura.deployment.customizer.upgrade.rp.UpgradeScriptResourceProcessorImpl.java

private void executeScript(File file) throws Exception {
    String path = file.getCanonicalPath();
    String[] cmdarray = { "/bin/bash", path };
    Runtime rt = Runtime.getRuntime();
    Process proc = null;//from  w  ww  .java 2s. c o  m
    try {
        proc = rt.exec(cmdarray);
        if (proc.waitFor() != 0) {
            s_logger.error("Script {} failed with exit value {}", path, proc.exitValue());
        }
        // FIXME: streams must be consumed concurrently
    } catch (Exception e) {
        s_logger.error("Error executing process for script {}", path, e);
        throw e;
    } finally {
        if (proc != null) {
            proc.destroy();
        }
    }
}

From source file:com.web.controller.ToolController.java

@ResponseBody
@RequestMapping(value = "/tool/verifyapk", method = RequestMethod.POST)
public String verifyApk(@RequestParam("apkfile") MultipartFile file) {

    //keytool -list -printcert -jarfile d:\weixin653android980.apk
    //keytool -printcert -file D:\testapp\META-INF\CERT.RSA
    //System.out.println("12345");
    try {// www. j  a  v  a2  s  .c o  m
        OutputStream stream = new FileOutputStream(new File(file.getOriginalFilename()));
        BufferedOutputStream outputStream = new BufferedOutputStream(stream);
        outputStream.write(file.getBytes());
        outputStream.flush();
        outputStream.close();

        Runtime runtime = Runtime.getRuntime();
        String ccString = "keytool -list -printcert -jarfile C:\\Users\\Administrator\\Desktop\\zju1.1.8.2.apk";
        Process p = runtime.exec(ccString);

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

        StringBuilder sb = new StringBuilder();
        while (br.readLine() != null) {
            sb.append(br.readLine() + "<br/>");
        }
        p.destroy();
        p = null;
        return sb.toString();
    } catch (FileNotFoundException fe) {
        return fe.getMessage();
    } catch (IOException ioe) {
        return ioe.getMessage();
    }

}

From source file:net.sourceforge.pmd.cpd.CPDTest.java

/**
 * As java doesn't support symlinks in zip files, maven does not, too.
 * So, we are creating the symlinks manually here before the test.
 * @throws Exception any error//w w w .  j av  a 2  s.c o  m
 */
private void prepareSymLinks() throws Exception {
    if (canTestSymLinks) {
        Runtime runtime = Runtime.getRuntime();
        if (!new File(BASE_TEST_RESOURCE_PATH, "symlink-for-real-file.txt").exists()) {
            runtime.exec(new String[] { "ln", "-s", "real-file.txt",
                    BASE_TEST_RESOURCE_PATH + "symlink-for-real-file.txt" }).waitFor();
        }
        if (!new File(BASE_TEST_RESOURCE_PATH, "this-is-a-broken-sym-link-for-test").exists()) {
            runtime.exec(new String[] { "ln", "-s", "broken-sym-link",
                    BASE_TEST_RESOURCE_PATH + "this-is-a-broken-sym-link-for-test" }).waitFor();
        }
    }
}

From source file:com.orange.clara.cloud.servicedbdumper.acceptance.AcceptanceExternalTest.java

protected boolean isCfCliPluginAvailable() {
    Runtime rt = Runtime.getRuntime();
    Process proc = null;// w w w .  ja v  a  2s  .  c o  m
    try {
        proc = rt.exec(this.dbDumperCli());
        proc.waitFor();
    } catch (IOException | InterruptedException e) {
        return false;
    }
    int exitVal = proc.exitValue();
    return exitVal == 0;
}

From source file:uk.co.modularaudio.util.atomicio.unix.UnixAtomicFileUtilities.java

/**
 * <P>//from w  ww .  j  a  v a  2  s  .c  om
 * Use mv to move the file to its new name. On Unix MV is guaranteed to be
 * atomic (on the same partition).
 * </P>
 * <P>
 * <B>All paths should be ABSOLUTE, and must be on the same partition - and
 * working that out is left to the calling code.</B>
 * </P>
 *
 * @see uk.co.modularaudio.util.atomicio.AtomicFileUtilities#moveFile(String,
 *      String)
 */
@Override
public boolean moveFile(final String fromPath, final String toPath) throws IOException {
    boolean retVal = false;

    final File fromFile = new File(fromPath);
    final File toFile = new File(toPath);
    if (fromFile.getParentFile().getPath().equals(toFile.getParentFile().getPath())) {
        // Do java rename which is atomic if parent dirs are the same
        retVal = fromFile.renameTo(toFile);
    } else {

        if (fromPath == null || fromPath.equals("")) {
            final String msg = "AtomicFileUtilities does not support a NULL fromPath for copy.";
            log.error(msg);
            throw new IOException(msg);
        }

        if (toPath == null || toPath.equals("")) {
            final String msg = "AtomicFileUtilities does not support a NULL toPath for copy.";
            log.error(msg);
            throw new IOException(msg);
        }

        final String cmdArray[] = new String[3];
        cmdArray[0] = mvLocation;
        cmdArray[1] = fromPath;
        cmdArray[2] = toPath;

        // Simple system call. Or at least it would be simple, if we knew
        // where
        // the binary lives _all_ the time.
        final Runtime runtime = Runtime.getRuntime();
        final Process executor = runtime.exec(cmdArray);
        try {
            executor.waitFor();
            final int exitValue = executor.exitValue();

            if (exitValue != 0) {
                throw new IOException("Bad return value from UNIX " + mvLocation + ": " + exitValue);
            } else {
                retVal = true;
            }
        } catch (final InterruptedException ie) {
            final String errMsg = "Error waiting for mv child process to complete: " + ie.toString();
            log.error(errMsg);
            throw new IOException(errMsg);
        }
    }
    return retVal;
}

From source file:org.mifos.test.framework.util.DbUnitDataImportExport.java

private void dumpSql(String fileName) {
    // execute mysqldump and provide a reasonable error message if
    // mysqldump isn't found on the $PATH.

    System.out.print("dumping sql to: " + fileName + " ... ");

    try {/*from w  w w  . j  a va2  s.  co  m*/
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("mysqldump --password=" + password + " --user=" + user + " --result-file="
                + fileName + " " + databaseName);
        int exitVal = proc.waitFor();

        if (exitVal == 0) {
            System.out.println("done!");
        } else {
            System.err.println("ERROR: Wrong username, password and/or database name!");
        }
    } catch (IOException ioe) {
        System.err.println("ERROR: " + ioe.getMessage());

        System.err.println(
                "Please make sure that \"mysqldump\" is in your PATH.\nSee http://www.mifos.org/developers/install-mifos/install-windows#add-required-environment-variables for an example %Path on Windows.\nOn linux, run \"which mysqldump\" to find out which directory mysqldump is in, and add it to PATH.");
    } catch (InterruptedException ie) {
        System.err.println("ERROR (interruption): " + ie.getLocalizedMessage());
    }
}

From source file:camera.Camera.java

private void snapshot() {
    //      System.out.println("shot...");
    try {/*from ww  w  .java  2s.  c  om*/
        Runtime rt = Runtime.getRuntime();
        Process p;

        //            p = rt.exec("raspistill -n --nopreview -t 2000 -w 400 -h 300 -e jpg -o -");
        p = rt.exec("raspistill -n --nopreview -t 2000 -w 400 -h 300 -ex sports  -q 100 -e jpg -o -");

        Thread.sleep(2000); // sonst werden die bilder nicht sicher bereitgestellt
        byte[] currentImage = IOUtils.toByteArray(p.getInputStream());
        //System.out.println(currentImage.length + "   " + new Date());
        sendBild(currentImage);
        /*
                
         OutputStream out = null;
                
         try {
         out = new BufferedOutputStream(new FileOutputStream("/home/root/bilf.jpg"));
         out.write(currentImage);
         } finally {
         if (out != null) {
         out.close();
         }
         }
         */
        //client.disconnect();
        //client.close();
    } catch (Exception ex) {
        log.error(ex);
    }

}

From source file:br.com.autonomiccs.autonomic.plugin.common.utils.ShellCommandUtilsTest.java

@Test
public void executeCommandTest() throws IOException, InterruptedException {
    Process processMock = Mockito.mock(Process.class);
    Runtime runtimeMock = configureAndGetRuntimeMock();

    String commandOutput = "TEST";
    InputStream input = IOUtils.toInputStream(commandOutput, "utf-8");

    Mockito.when(runtimeMock.exec(command)).thenReturn(processMock);
    Mockito.when(processMock.waitFor()).thenReturn(1);
    Mockito.when(processMock.getInputStream()).thenReturn(input);

    String response = shellCommandUtils.executeCommand(command);
    Assert.assertEquals(commandOutput, response);
    Mockito.verify(processMock).waitFor();
}

From source file:uk.co.modularaudio.util.pooling.forkexec.ChildProcessExecutor.java

public ChildProcessExecutor(final String[] cmdArray) throws IOException {
    // log.debug("CPE Constructor called.");
    final Runtime runtime = Runtime.getRuntime();
    boolean wasError = false;
    try {//from   w ww  .  j  a va 2s .  co m
        this.process = runtime.exec(cmdArray);
    } catch (final SecurityException se) {
        log.warn("Caught se");
    } catch (final NullPointerException npe) {
        log.warn("Caught npe");
    } catch (final IOException ioe) {
        log.warn("Caught ioe");
    } catch (final Exception e) {
        log.warn("Caught e");
        wasError = true;
    }

    if (this.process == null) {
        wasError = true;
    }

    if (wasError) {
        throw new IOException("Unable to create child process " + cmdArray[0]);

    }
    inputStream = process.getInputStream();
    outputStream = process.getOutputStream();
    errorStream = process.getErrorStream();
}