List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.docd.purefm.tasks.SearchCommandLineTask.java
@Override protected Void doInBackground(String... params) { final CommandFind command = new CommandFind(mStartDirectory.getAbsolutePath(), params); // NOTE this doesn't use Shell because we can't create a new CommandLineFile from // CommandOutput because executing readlink (which is done in CommandLineFile constructor) // will freeze the whole Shell DataOutputStream os = null;// ww w . j a v a 2s. co m BufferedReader is = null; BufferedReader err = null; Process process = null; try { process = Runtime.getRuntime().exec(mSettings.isSuEnabled() ? "su" : "sh"); os = new DataOutputStream(process.getOutputStream()); is = new BufferedReader(new InputStreamReader(process.getInputStream())); err = new BufferedReader(new InputStreamReader(process.getErrorStream())); os.writeBytes(command.toString()); os.writeBytes("exit\n"); os.flush(); String line; try { while (!isCancelled() && (line = is.readLine()) != null) { this.publishProgress(CommandLineFile.fromLSL(null, line)); } } catch (EOFException e) { //ignore } try { while (!isCancelled() && (line = err.readLine()) != null) { final Matcher denied = DENIED.matcher(line); if (denied.matches()) { this.mDenied.add(denied.group(1)); } } } catch (EOFException e) { //ignore } process.waitFor(); } catch (Exception e) { Log.w("Exception while searching", e.toString()); } finally { IOUtils.closeQuietly(os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(err); if (process != null) { try { process.destroy(); } catch (Exception e) { //ignored } } } return null; }
From source file:com.github.horrorho.inflatabledonkey.util.ProcessManager.java
Optional<byte[]> pipe(Process process, InputStream in) throws IOException, InterruptedException { try (InputStream decoderIn = process.getInputStream(); OutputStream decoderOut = process.getOutputStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); Thread write = new Thread(() -> copy(in, decoderOut)); Thread read = new Thread(() -> copy(decoderIn, out)); write.start();/*from w w w .ja v a 2s . co m*/ read.start(); if (!process.waitFor(timeoutMS, TimeUnit.MILLISECONDS)) { logger.warn("-- pipe() - timed out"); // copy threads will shortly exit on exceptions as their streams are closed. return Optional.empty(); } read.join(timeoutMS); return Optional.of(out.toByteArray()); } finally { if (logger.isWarnEnabled()) { error(process); } } }
From source file:org.eclipse.smila.utils.scriptexecution.UnixScriptExecutor.java
/** * {@inheritDoc}/*from w w w . j av a 2 s .c o m*/ */ public int execute(final File file) throws IOException, InterruptedException { final String shell = System.getenv(SHELL_ENV_NAME); if (shell == null || shell.trim().length() == 0) { throw new RuntimeException("Environment variable '" + SHELL_ENV_NAME + "' is not set"); } final ProcessBuilder processBuilder = new ProcessBuilder(shell); processBuilder.directory(file.getParentFile()); processBuilder.redirectErrorStream(true); final Process shellProcess = processBuilder.start(); InputStream inputStream = null; try { inputStream = new FileInputStream(file); final OutputStream shellProcessOutputStream = shellProcess.getOutputStream(); IOUtils.copy(inputStream, shellProcessOutputStream); shellProcessOutputStream.close(); final int retVal = shellProcess.waitFor(); LogHelper.debug(_log, shellProcess.getInputStream()); return retVal; } finally { IOUtils.closeQuietly(inputStream); } }
From source file:pl.nask.hsn2.service.scdbg.TimedScdbgProcess.java
@Override public Integer call() throws Exception { for (String s : commandLine) { System.out.print(s + " "); }/*from www. ja v a 2 s. c om*/ System.out.println(); Process p = Runtime.getRuntime().exec(commandLine, null, localTmp); try { writer = new PrintWriter(p.getOutputStream()); // have to emit ENTER to make scdbg end processing. writer.println(); writer.flush(); // read as much as possible and buffer since if the process produces too much data it will result with a deadlock. bytes = IOUtils.toByteArray(p.getInputStream()); } catch (IOException e) { throw new ResourceException("Error executing scdbg", e); } finally { IOUtils.closeQuietly(writer); if (p != null) { p.destroy(); } } return p.waitFor(); }
From source file:com.cisco.dvbu.ps.common.util.ScriptExecutor.java
public int executeCommand(String errorFile) { int exitValue = -99; String prefix = "ScriptExecutor::"; String command = ""; try {/*from ww w .j a v a2s . co m*/ // Print out the command and execution directory for (int i = 0; i < scriptArgsList.size(); i++) { command = command + scriptArgsList.get(i) + " "; } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); logger.debug(prefix + "Command: " + CommonUtils.maskCommand(command)); logger.debug(prefix + "Exec Dir: " + execFromDir.toString()); } // Build a new process to execute ProcessBuilder pb = new ProcessBuilder(scriptArgsList); // Setup the environment variables Map<String, String> env = pb.environment(); for (int i = 0; i < envList.size(); i++) { String envVar = envList.get(i).toString(); StringTokenizer st = new StringTokenizer(envVar, "="); if (st.hasMoreTokens()) { String property = st.nextToken(); String propertyVal = ""; try { propertyVal = st.nextToken(); } catch (Exception e) { } env.put(property, propertyVal); if (logger.isDebugEnabled()) { logger.debug(prefix + "Env Var: " + CommonUtils.maskCommand(envVar)); } } } if (logger.isDebugEnabled()) { logger.debug(prefix + "-------------------------------------------------"); } // Setup up the execute from directory File execDir = new File(execFromDir); pb.directory(execDir); if (logger.isDebugEnabled()) { logger.debug(""); logger.debug("ProcessBuilder::pb.command: " + CommonUtils.maskCommand(pb.command().toString())); logger.debug("ProcessBuilder::pb.directory: " + pb.directory().toString()); logger.debug("ProcessBuilder::pb.directory.getAbsolutePath: " + pb.directory().getAbsolutePath()); logger.debug("ProcessBuilder::pb.directory.getCanonicalPath: " + pb.directory().getCanonicalPath()); logger.debug(""); logger.debug("ProcessBuilder::pb.environment: " + CommonUtils.maskCommand(pb.environment().toString())); logger.debug(prefix + "-------------------------------------------------"); logger.debug(""); } // Execute the command Process process = pb.start(); OutputStream stdOutput = process.getOutputStream(); InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream(); inputStreamHandler = new ScriptStreamHandler(inputStream, stdOutput); errorStreamHandler = new ScriptStreamHandler(errorStream); inputStreamHandler.start(); errorStreamHandler.start(); exitValue = process.waitFor(); if (logger.isDebugEnabled()) { logger.debug(prefix + "exitValue for process.waitFor is: " + exitValue); } if (exitValue > 0) { logger.error("Error executing command=" + CommonUtils.maskCommand(command)); logger.error("Error=" + CommonUtils.maskCommand(getStandardErrorFromCommand().toString())); } else { if (logger.isInfoEnabled()) { logger.info("Successfully executed command:\n" + CommonUtils.maskCommand(command)); logger.info("Output:\n" + getStandardOutputFromCommand().toString()); } } } catch (IOException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } catch (InterruptedException e) { CompositeLogger.logException(e, e.getMessage()); throw new CompositeException(e); } return exitValue; }
From source file:org.atilika.kuromoji.server.KuromojiServer.java
private String getViterbiSVG(String dot) { Process process = null; try {/*w ww . j a v a 2 s.co m*/ log.info("Running " + DOT_COMMAND); process = Runtime.getRuntime().exec(DOT_COMMAND); process.getOutputStream().write(dot.getBytes("utf-8")); process.getOutputStream().close(); InputStream input = process.getInputStream(); String svg = new Scanner(input, "utf-8").useDelimiter("\\A").next(); int exitValue = process.exitValue(); log.debug("Read " + svg.getBytes("utf-8").length + " bytes of SVG output"); log.info("Process exited with exit value " + exitValue); return svg; } catch (IOException e) { log.error("Error running process " + process, e.getCause()); return null; } finally { if (process != null) { log.info("Destroying process " + process); process.destroy(); } } }
From source file:org.noroomattheinn.utils.ThreadManager.java
public Process launchExternal(String command, String args, String input, long timeout) { String fullCommand = command + " " + (args == null ? "" : args); try {/*w ww . j a va 2s .co m*/ Process p = Runtime.getRuntime().exec(fullCommand); if (input != null) { IOUtils.copy(IOUtils.toInputStream(input), p.getOutputStream()); p.getOutputStream().close(); } watch(command, p, timeout); // Launch a watchdog thread return p; } catch (IOException ex) { logger.warning("External command (" + fullCommand + ") failed to launch: " + ex); return null; } }
From source file:org.csploit.android.core.System.java
private static void startCoreDaemon() throws SuException, DaemonException { boolean access_granted = false; DataOutputStream writer = null; BufferedReader reader = null; String line;//from ww w.jav a2s. co m int ret = -1; try { Process shell = Runtime.getRuntime().exec("su"); writer = new DataOutputStream(shell.getOutputStream()); String cmd; cmd = String.format("{ echo 'ACCESS GRANTED' >&2; cd '%s' && exec ./start_daemon.sh ;} || exit 1\n", System.getCorePath()); writer.write(cmd.getBytes()); writer.flush(); ret = shell.waitFor(); if (ret != 0) { reader = new BufferedReader(new InputStreamReader(shell.getErrorStream())); while ((line = reader.readLine()) != null) { if (line.equals("ACCESS GRANTED")) { access_granted = true; Logger.debug("'ACCESS GRANTED' found"); } else Logger.warning("STDERR: " + line); } } else access_granted = true; } catch (IOException e) { // command "su" not found or cannot write to it's stdin Logger.error(e.getMessage()); } catch (InterruptedException e) { // interrupted while waiting for shell exit value Logger.error(e.getMessage()); } finally { if (writer != null) try { writer.close(); } catch (IOException ignored) { } if (reader != null) try { reader.close(); } catch (IOException ignored) { } } mKnownIssues.fromFile(String.format("%s/issues", getCorePath())); if (!access_granted) throw new SuException(); if (ret != 0) { File log = new File(System.getCorePath(), "cSploitd.log"); DaemonException daemonException = new DaemonException("core daemon returned " + ret); if (log.exists() && log.canRead()) { ACRAConfiguration conf = ACRA.getConfig(); conf.setApplicationLogFile(log.getAbsolutePath()); ACRA.setConfig(conf); ACRA.getErrorReporter().handleException(daemonException, false); } throw daemonException; } }
From source file:cz.cas.lib.proarc.common.process.AsyncProcess.java
public void kill() { Level level = isDone() ? Level.FINE : Level.WARNING; LOG.log(level, "Kill isDone: " + isDone() + ", " + cmdLine); Process process = refProcess.getAndSet(null); if (process != null) { process.destroy();/*from ww w . j a v a 2s . c o m*/ IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getErrorStream()); IOUtils.closeQuietly(process.getOutputStream()); done.set(true); try { outputConsumer.join(); } catch (InterruptedException ex) { LOG.log(Level.SEVERE, null, ex); } } }
From source file:me.tfeng.toolbox.dust.NodeEngine.java
private void executeCommand(Process process, InputStream inputStream) throws IOException { BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream)); PrintWriter writer = new PrintWriter(process.getOutputStream()); String line = inputReader.readLine(); while (line != null) { writer.println(line);/*from w w w.ja v a2s . c om*/ line = inputReader.readLine(); } writer.println("1"); writer.flush(); readInput(process, "1"); }