RuntimeCommandExec { public static synchronized String exec(String command) throws RuntimeCommandException { try { Process p = getOSSpecificProcess(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); StringBuilder result = new StringBuilder(); String line; while ((line = stdInput.readLine()) != null) { result.append(line); } boolean hasError = false; while ((line = stdError.readLine()) != null) { result.append(line); hasError = true; } try { int niceExit = p.waitFor(); if (niceExit != 0) hasError = true; } catch (InterruptedException e) { } if (hasError) { throw new RuntimeCommandException(result.toString()); } return result.toString(); } catch (IOException e) { throw new RuntimeCommandException(e); } } private  RuntimeCommandExec(); static synchronized String exec(String command);  }
@Test public void testExecSuccess() throws Exception { String command = "pwd"; String value = RuntimeCommandExec.exec(command); assert new File(value).isDirectory(); }
@Test public void testExecError() throws Exception { String command = "pw"; try { String value = RuntimeCommandExec.exec(command); assert !(new File(value).isDirectory()); } catch (RuntimeCommandException e) { assert e.getMessage().contains("not found"); } command = "cat /noFileShouldBeWithThatName"; try { String value = RuntimeCommandExec.exec(command); assert !(new File(value).isDirectory()); } catch (RuntimeCommandException e) { assert e.getMessage().equals("cat: /noFileShouldBeWithThatName: No such file or directory"); } }
@Test public void testExec() throws Exception { String command = "echo in > " + temp.getAbsolutePath(); RuntimeCommandExec.exec(command); command = "cat " + temp.getAbsolutePath(); String value = RuntimeCommandExec.exec(command); assert value.equals("in"); }