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:de.huberlin.wbi.hiway.am.HiWay.java

/**
 * If the debug flag is set, dump out contents of current working directory and the environment to stdout for debugging.
 *///  w  ww .j  a va 2  s . com
private static void dumpOutDebugInfo() {
    System.out.println("Dump debug output");
    Map<String, String> envs = System.getenv();
    for (Map.Entry<String, String> env : envs.entrySet()) {
        System.out.println("System env: key=" + env.getKey() + ", val=" + env.getValue());
    }

    String cmd = "ls -al";
    Runtime run = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = run.exec(cmd);
        pr.waitFor();

        try (BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()))) {
            String line = "";
            while ((line = buf.readLine()) != null) {
                System.out.println("System CWD content: " + line);
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:nl.nn.adapterframework.util.Misc.java

public static Properties getEnvironmentVariables() throws IOException {
    Properties props = new Properties();

    try {/* w w  w .j a  v  a  2  s . com*/
        Method getenvs = System.class.getMethod("getenv", (java.lang.Class[]) null);
        Map env = (Map) getenvs.invoke(null, (java.lang.Object[]) null);
        for (Iterator it = env.keySet().iterator(); it.hasNext();) {
            String key = (String) it.next();
            String value = (String) env.get(key);
            props.setProperty(key, value);
        }
    } catch (NoSuchMethodException e) {
        log.debug("Caught NoSuchMethodException, just not on JDK 1.5: " + e.getMessage());
    } catch (IllegalAccessException e) {
        log.debug("Caught IllegalAccessException, using JDK 1.4 method", e);
    } catch (InvocationTargetException e) {
        log.debug("Caught InvocationTargetException, using JDK 1.4 method", e);
    }

    if (props.size() == 0) {
        BufferedReader br = null;
        Process p = null;
        Runtime r = Runtime.getRuntime();
        String OS = System.getProperty("os.name").toLowerCase();
        if (OS.indexOf("windows 9") > -1) {
            p = r.exec("command.com /c set");
        } else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 20") > -1)
                || (OS.indexOf("windows xp") > -1)) {
            p = r.exec("cmd.exe /c set");
        } else {
            //assume Unix
            p = r.exec("env");
        }
        //         props.load(p.getInputStream()); // this does not work, due to potential malformed escape sequences
        br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = br.readLine()) != null) {
            int idx = line.indexOf('=');
            if (idx >= 0) {
                String key = line.substring(0, idx);
                String value = line.substring(idx + 1);
                props.setProperty(key, value);
            }
        }
    }

    return props;
}

From source file:org.mybatis.generator.ext.api.MeldMergeShellCallback.java

@Override
public String mergeJavaFile(String newFileSource, String existingFileFullPath, String[] javadocTags,
        String fileEncoding) throws ShellException {
    try {//w  w w  .j  av  a 2  s.  c om
        File existingFile = new File(existingFileFullPath);
        File directory = existingFile.getParentFile();

        File tmpFile = GenUtil.getUniqueFileName(directory, existingFile.getName());
        writeFile(tmpFile, newFileSource, "UTF-8");
        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec("meld " + existingFileFullPath + " " + tmpFile.getAbsolutePath());
        int exitVal = proc.waitFor();
        System.out.println("Process exitValue: " + exitVal);

        org.apache.commons.io.FileUtils.deleteQuietly(tmpFile);
        return org.apache.commons.io.FileUtils.readFileToString(existingFile);
    } catch (Exception ex) {
        return null;
    }
}

From source file:fm.last.irccat.Scripter.java

public void run() {
    try {//from  w ww .  jav a2s .c o  m
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime
                .exec(new String[] { bot.getCmdScript(), nick + " " + channel + " " + returnName + " " + cmd });
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line;
        int i = 0;
        while ((line = br.readLine()) != null) {
            bot.sendMsg(returnName, line);
            if (++i == bot.getCmdMaxResponseLines()) {
                bot.sendMsg(returnName, "<truncated, too many lines>");
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:nl.prowareness.jenkins.testgrid.utils.DockerClientSetupTest.java

private Runtime getRuntimeStub(int retCode, String message) throws IOException, InterruptedException {
    Runtime runtime = mock(Runtime.class);
    Process process = mock(Process.class);
    when(runtime.exec(any(String.class))).thenReturn(process);
    when(process.waitFor()).thenReturn(retCode);
    when(process.getErrorStream()).thenReturn(IOUtils.toInputStream(message));
    return runtime;
}

From source file:com.excella.deploy.agent.core.UnixShellCommand.java

/**
 * {@inheritDoc}//from  w ww  .  ja v  a 2  s . co m
 */
public String execute(String argument) throws FailedCommandException {
    String line = "";
    StringBuffer buffer = new StringBuffer();
    String command = getJBossHome() + "/bin/appdeploy.sh " + argument + " 2>/dev/null";
    InputStreamReader inputStream = null;
    BufferedReader input = null;

    log.info("Running an RSM Deployment using the following command: " + command);
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        int exitValue = process.waitFor();
        inputStream = new InputStreamReader(process.getInputStream());
        input = new BufferedReader(inputStream);
        while ((line = input.readLine()) != null) {
            log.debug("> " + line);
            buffer.append(line);
            buffer.append("<br/>");
        }

        log.info("RSM Deployment Kicked off.  Exited with [" + exitValue + "]");
    } catch (Exception e) {
        throw new FailedCommandException("Unable to execute the command.", e);
    } finally {
        close(inputStream);
        close(input);
    }
    return buffer.toString();
}

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

@Test
@SuppressWarnings("unchecked")
public void executeCommandTestDealingWithIoException() throws IOException, InterruptedException {
    shellCommandUtils.logger = Mockito.mock(Logger.class);

    Runtime runtimeMock = configureAndGetRuntimeMock();
    Mockito.when(runtimeMock.exec(command)).thenThrow(IOException.class);

    String commandOutput = shellCommandUtils.executeCommand(command);

    executeChecksForExceptionTests(commandOutput, IOException.class);
}

From source file:ape.TouchCommand.java

public boolean runImpl(String[] args) {
    System.out.println("Going to touch /tmp/foo.tst");

    Runtime rt = Runtime.getRuntime();
    Process p;//from  w  w w . j a v  a 2s . c  om
    try {
        p = rt.exec("touch /tmp/foo.tst");
        p.waitFor();
        p = rt.exec("ls /tmp");
        p.waitFor();
        return writeSTDOut(p);
    } catch (IOException e) {
        System.out.println("IOException caught in executing command.");
        e.printStackTrace();
        return false;
    } catch (InterruptedException e) {
        System.out.println("The process for the 'ls /tmp' command was interrupted.");
        e.printStackTrace();
        return false;
    }
}

From source file:es.tid.fiware.rss.service.CdrsManagerTest.java

/**
 * Test runCdrToDB method./*from  w  w  w . j  a va  2s.  c  om*/
 */
@Test
public void runCdrToDB() throws IOException, InterruptedException {
    Process p = Mockito.mock(Process.class);
    Runtime runtime = Mockito.mock(Runtime.class);
    Mockito.when(runtime.exec(Matchers.any(String.class))).thenReturn(p);
    ReflectionTestUtils.setField(cdrsManager, "runtime", runtime);
    InputStream inputStream = new ByteArrayInputStream("OK".getBytes());
    Mockito.when(p.getInputStream()).thenReturn(inputStream);
    Mockito.when(p.waitFor()).thenReturn(0);
    String result = cdrsManager.runCdrToDB();
    Assert.assertNull(result);
    // Error
    inputStream = new ByteArrayInputStream("ERROR".getBytes());
    Mockito.when(p.getInputStream()).thenReturn(inputStream);
    Mockito.when(p.waitFor()).thenReturn(-1);
    result = cdrsManager.runCdrToDB();
    Assert.assertEquals("ERROR", result);
}

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

@Test
@SuppressWarnings("unchecked")
public void executeCommandTestDealingWithInterruptedException() throws IOException, InterruptedException {
    shellCommandUtils.logger = Mockito.mock(Logger.class);

    Process processMock = Mockito.mock(Process.class);
    Runtime runtimeMock = configureAndGetRuntimeMock();
    Mockito.when(runtimeMock.exec(command)).thenReturn(processMock);
    Mockito.when(processMock.waitFor()).thenThrow(InterruptedException.class);

    String commandOutput = shellCommandUtils.executeCommand(command);

    Mockito.verify(processMock).waitFor();
    executeChecksForExceptionTests(commandOutput, InterruptedException.class);
}