List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.searchbox.framework.web.SystemController.java
/** * Utility function to execute a function *//*w w w. java2 s . co m*/ private static String execute(String cmd) { DataInputStream in = null; Process process = null; try { process = Runtime.getRuntime().exec(cmd); in = new DataInputStream(process.getInputStream()); // use default charset from locale here, because the command invoked // also uses the default locale: return IOUtils.toString(new InputStreamReader(in, Charset.defaultCharset())); } catch (Exception ex) { // ignore - log.warn("Error executing command", ex); return "(error executing: " + cmd + ")"; } finally { if (process != null) { IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getErrorStream()); } } }
From source file:de.ub0r.android.wifibarcode.WifiBarcodeActivity.java
/** * Run command as root./*from www. ja v a 2s. c om*/ * * @param command command * @return true, if command was successfully executed */ private static boolean runAsRoot(final String command) { Log.i(TAG, "running command as root: ", command); try { Runtime r = Runtime.getRuntime(); Process p = r.exec("su"); DataOutputStream d = new DataOutputStream(p.getOutputStream()); d.writeBytes(command); d.writeBytes("\nexit\n"); d.flush(); int retval = p.waitFor(); Log.i(TAG, "done"); return (retval == 0); } catch (Exception e) { Log.e(TAG, "runAsRoot", e); return false; } }
From source file:com.tc.process.Exec.java
@SuppressWarnings("resource") public static Result execute(final Process process, String cmd[], String outputLog, byte[] input, File workingDir, final long timeout) throws Exception { final AtomicBoolean processFinished = new AtomicBoolean(); if (timeout > 0) { Thread timeoutThread = new Thread() { @Override//from w w w. ja va 2 s . com public void run() { ThreadUtil.reallySleep(timeout); if (!processFinished.get()) { process.destroy(); } } }; timeoutThread.start(); } Thread inputThread = new InputPumper(input == null ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog != null) { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } else { stderr = new StreamCollector(process.getErrorStream()); stdout = new StreamCollector(process.getInputStream()); stderr.start(); stdout.start(); } inputThread.start(); final int exitCode = process.waitFor(); processFinished.set(true); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } return new Result(cmd, outString, errString, exitCode); } finally { closeQuietly(fileOutput); } }
From source file:mitm.common.util.ProcessUtils.java
/** * Helper method that executes the given cmd and returns the output. The process will be destroyed * if the process takes longer to execute than the timeout. *//*from w w w .j a va 2 s . c o m*/ public static void executeCommand(List<String> cmd, long timeout, InputStream input, OutputStream output) throws IOException { Check.notNull(cmd, "cmd"); if (cmd.size() == 0) { throw new IOException("Process is missing."); } /* * Used for reporting */ String name = StringUtils.join(cmd, ","); /* * Watchdog that will be used to destroy the process on a timeout */ TaskScheduler watchdog = new TaskScheduler(ProcessUtils.class.getCanonicalName() + "#" + name); try { ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); /* * Task that will destroy the process on a timeout */ Task processWatchdogTask = new DestroyProcessTimeoutTask(process, watchdog.getName()); watchdog.addTask(processWatchdogTask, timeout); /* * Task that will interrup the current thread on a timeout */ Task threadInterruptTimeoutTask = new ThreadInterruptTimeoutTask(Thread.currentThread(), watchdog.getName()); watchdog.addTask(threadInterruptTimeoutTask, timeout); /* * Send the input to the standard input of the process */ if (input != null) { IOUtils.copy(input, process.getOutputStream()); IOUtils.closeQuietly(process.getOutputStream()); } /* * Get the standard output from the process */ if (output != null) { IOUtils.copy(process.getInputStream(), output); } int exitValue; try { exitValue = process.waitFor(); } catch (InterruptedException e) { throw new IOException("Error executing [" + name + "]", e); } if (exitValue != 0) { throw new ProcessException("Error executing [" + name + "]. exit value: " + exitValue, exitValue); } } finally { /* * Need to cancel any pending tasks */ watchdog.cancel(); } }
From source file:com.noshufou.android.su.util.Util.java
public static ArrayList<String> run(String shell, String[] commands) { ArrayList<String> output = new ArrayList<String>(); try {// w ww. j ava2s . c om Process process = Runtime.getRuntime().exec(shell); BufferedOutputStream shellInput = new BufferedOutputStream(process.getOutputStream()); BufferedReader shellOutput = new BufferedReader(new InputStreamReader(process.getInputStream())); for (String command : commands) { Log.i(TAG, "command: " + command); shellInput.write((command + " 2>&1\n").getBytes()); } shellInput.write("exit\n".getBytes()); shellInput.flush(); String line; while ((line = shellOutput.readLine()) != null) { Log.d(TAG, "command output: " + line); output.add(line); } process.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return output; }
From source file:opennlp.fieldspring.tr.util.IOUtil.java
/** * Run a command with the option of waiting for it to finish. * * @param cmd The string containing the command to execute * @param wait True if the caller should wait for this thread to * finish before continuing, false otherwise. *//* w ww. ja v a 2 s . co m*/ public static void runCommand(String cmd, boolean wait) { try { System.out.println("Running command: " + cmd); Process proc = Runtime.getRuntime().exec(cmd); // This needs to be done, otherwise some processes fill up // some Java buffer and make it so the spawned process // doesn't complete. BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line = null; while ((line = br.readLine()) != null) { // while (br.readLine() != null) { // just eat up the inputstream // Use this if you want to see the output from running // the command. System.out.println(line); } if (wait) { try { proc.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } proc.getInputStream().close(); proc.getOutputStream().close(); proc.getErrorStream().close(); } catch (IOException e) { System.out.println("Unable to run command: " + cmd); } }
From source file:org.fusesource.meshkeeper.distribution.provisioner.embedded.Execute.java
/** * Close the streams belonging to the given Process. * @param process the <code>Process</code>. */// www . j av a2 s . c om public static void closeStreams(Process process) { close(process.getInputStream()); close(process.getOutputStream()); close(process.getErrorStream()); }
From source file:org.artofsolving.jodconverter.process.AbstractProcessManager.java
/** * Execute the specified command and return the output. * /*from ww w .java 2 s . c o m*/ * @param command * a string array containing the program and its arguments. * @return the execution output. * @throws IOException * if an I/O error occurs. */ protected List<String> execute(String... command) throws IOException { Process process = new ProcessBuilder(command).start(); process.getOutputStream().close(); // don't wait for stdin List<String> lines = IOUtils.readLines(process.getInputStream(), "UTF-8"); try { process.waitFor(); } catch (InterruptedException interruptedEx) { // sorry for the interruption } return lines; }
From source file:com.noshufou.android.su.util.Util.java
public static VersionInfo getSuVersionInfo() { VersionInfo info = new VersionInfo(); Process process = null; String inLine = null;// www . j av a2 s.co m try { process = Runtime.getRuntime().exec("sh"); DataOutputStream os = new DataOutputStream(process.getOutputStream()); BufferedReader is = new BufferedReader( new InputStreamReader(new DataInputStream(process.getInputStream())), 64); os.writeBytes("su -v\n"); // We have to hold up the thread to make sure that we're ready to read // the stream, using increments of 5ms makes it return as quick as // possible, and limiting to 1000ms makes sure that it doesn't hang for // too long if there's a problem. for (int i = 0; i < 400; i++) { if (is.ready()) { break; } try { Thread.sleep(5); } catch (InterruptedException e) { Log.w(TAG, "Sleep timer got interrupted..."); } } if (is.ready()) { inLine = is.readLine(); if (inLine != null) { info.version = inLine; } } else { // If 'su -v' isn't supported, neither is 'su -V'. return legacy info os.writeBytes("exit\n"); info.version = "legacy"; info.versionCode = 0; return info; } os.writeBytes("su -v\n"); // We have to hold up the thread to make sure that we're ready to read // the stream, using increments of 5ms makes it return as quick as // possible, and limiting to 1000ms makes sure that it doesn't hang for // too long if there's a problem. for (int i = 0; i < 400; i++) { if (is.ready()) { break; } try { Thread.sleep(5); } catch (InterruptedException e) { Log.w(TAG, "Sleep timer got interrupted..."); } } if (is.ready()) { inLine = is.readLine(); if (inLine != null && Integer.parseInt(inLine.substring(0, 1)) > 2) { inLine = null; os.writeBytes("su -V\n"); inLine = is.readLine(); if (inLine != null) { info.versionCode = Integer.parseInt(inLine); } } else { info.versionCode = 0; } } else { os.writeBytes("exit\n"); } } catch (IOException e) { Log.e(TAG, "Problems reading current version.", e); } finally { if (process != null) { process.destroy(); } } return info; }
From source file:edu.brandeis.ggen.GGenCommand.java
public String generateGraphviz() throws GGenException { ProcessBuilder pb = new ProcessBuilder(); List<String> command = new LinkedList<>(); command.add(GGEN_PATH);//from w ww . j a v a2 s. c o m Arrays.stream(args.split(" ")).forEach(command::add); try { Process p = pb.command(command).start(); if (this.input != null) p.getOutputStream().write(this.input.generateGraphviz().getBytes()); p.getOutputStream().close(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(p.getInputStream(), bos); return new String(bos.toByteArray()); } catch (IOException e) { throw new GGenException( "Could not launch the ggen command. Check that the GGenCommand.GGEN_PATH static variable is correctly set for your system. Message: " + e.getMessage()); } }