List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:Main.java
private static byte[] ExecuteCommand(String command, Boolean useroot, boolean forcenew) throws Exception { Process p; DataOutputStream stdin;//from www . jav a2 s.c om InputStream stdout; ByteArrayOutputStream baos; int read; byte[] buffer; /* * If for any reason the command does not print anything we are stuck forever. * Make sure that we print SOMETHING ALWAYS! */ command = "RESULT=$(" + command + "); if [[ $RESULT == '' ]]; then echo '#null#';else echo $RESULT;fi\n"; p = getProcess(useroot, forcenew); stdin = new DataOutputStream(p.getOutputStream()); stdout = p.getInputStream(); buffer = new byte[BUFF_LEN]; baos = new ByteArrayOutputStream(); stdin.writeBytes(command); while (true) { read = stdout.read(buffer); baos.write(buffer, 0, read); if (read < BUFF_LEN) { //we have read everything break; } } if (forcenew) { stdin.writeBytes("exit\n"); stdin.flush(); stdin.close(); } //p.waitFor(); return baos.toByteArray(); }
From source file:org.rapidcontext.app.plugin.cmdline.CmdLineExecProcedure.java
/** * Waits for the specified process to terminate, reading its * standard output and error streams meanwhile. * * @param process the process to monitor * @param cx the procedure call context * * @return the data object with the process output results * * @throws IOException if the stream reading failed *//*from w w w . jav a2s . co m*/ private static Dict waitFor(Process process, CallContext cx) throws IOException { StringBuffer output = new StringBuffer(); StringBuffer error = new StringBuffer(); InputStream isOut = process.getInputStream(); InputStream isErr = process.getErrorStream(); byte[] buffer = new byte[4096]; int exitValue = 0; process.getOutputStream().close(); while (true) { if (cx.isInterrupted()) { // TODO: isOut.close(); // TODO: isErr.close(); process.destroy(); throw new IOException("procedure call interrupted"); } try { readStream(isOut, buffer, output); readStream(isErr, buffer, error); log(cx, error); exitValue = process.exitValue(); break; } catch (IllegalThreadStateException e) { try { Thread.sleep(50); } catch (InterruptedException ignore) { // Ignore this exception } } } Dict res = new Dict(); res.setInt("exitValue", exitValue); res.set("output", output); return res; }
From source file:org.opf_labs.utils.ProcessRunnerImpl.java
@SuppressWarnings("resource") private static void feedProcess(final Process process, final InputStream input) { if (input == null) { // No complaints here - null just means no input return;/*w w w . j a va 2 s . c o m*/ } final OutputStream pIn = process.getOutputStream(); final InputStream given = input; Thread t = new Thread() { @Override public void run() { try { OutputStream writer = null; try { writer = new BufferedOutputStream(pIn); int c; while ((c = given.read()) != -1) { writer.write(c); } } finally { if (writer != null) { writer.close(); } pIn.close(); } } catch (IOException e) { // This seems ugly throw new RuntimeException("Couldn't write input to " + "process.", e); } } }; Thread.UncaughtExceptionHandler u = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(final Thread thread, final Throwable e) { // Might not be the prettiest solution... } }; t.setUncaughtExceptionHandler(u); t.start(); try { pIn.close(); } catch (IOException excep) { // Nothing to do } }
From source file:nl.b3p.catalog.arcgis.ArcObjectsSynchronizerForker.java
public static Document synchronize(ServletContext context, /* HttpServletResponse response,*/ String dataset, String type, String sdeConnectionString, String metadata) throws Exception { String workingDir = context.getRealPath("/WEB-INF"); String cp = buildClasspath(context); String mainClass = ArcObjectsSynchronizerMain.class.getName(); List<String> args = new ArrayList<String>(); args.addAll(Arrays.asList("java", "-classpath", cp, mainClass, "-type", type, "-dataset", dataset)); if (metadata != null && !"".equals(metadata)) { args.add("-stdin"); }// ww w .java 2s . c om if ("sde".equals(type)) { if (sdeConnectionString == null) { throw new IllegalArgumentException("SDE connection string is required"); } args.add("-sde"); args.add(sdeConnectionString); } final StringWriter output = new StringWriter(); final StringWriter errors = new StringWriter(); // response.getWriter(); errors.write(String.format("Werkdirectory: %s\nUitvoeren synchronizer proces: %s\n\n", workingDir, StringUtils.join(args, ' '))); //errors.flush(); int result; try { Process p = Runtime.getRuntime().exec(args.toArray(new String[] {}), null, new File(workingDir)); final BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream())); final BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream())); if (metadata != null && !"".equals(metadata)) { try { p.getOutputStream().write(metadata.getBytes("UTF-8")); p.getOutputStream().flush(); p.getOutputStream().close(); } catch (Exception e) { errors.write("Fout tijdens schrijven metadata XML met alle elementen naar stdin: " + e.getClass() + ": " + e.getMessage() + "\n"); } } // Threads vereist omdat streams blocken en pas verder gaan nadat je uit // de andere stream hebt gelezen Thread stderrReader = new Thread() { @Override public void run() { String line; try { while ((line = stderr.readLine()) != null) { errors.write(line + "\r\n"); //errors.flush(); } stderr.close(); } catch (Exception e) { throw new Error(e); } } }; Thread stdoutReader = new Thread() { @Override public void run() { String line; try { while ((line = stdout.readLine()) != null) { output.write(line + "\r\n"); } stdout.close(); } catch (Exception e) { throw new Error(e); } } }; stderrReader.start(); stdoutReader.start(); result = p.waitFor(); stderrReader.join(); stdoutReader.join(); errors.write("Resultaat: " + (result == 0 ? "succesvol gesynchroniseerd" : "fout opgetreden") + "\n\n"); } catch (Exception e) { throw new Exception( "Fout tijdens aanroepen extern proces voor synchroniseren, output: \n" + errors.toString(), e); } if (log.isDebugEnabled()) { log.debug("Synchroniseren via apart proces succesvol; output: " + errors.toString()); } if (result == 0) { return DocumentHelper.getMetadataDocument(output.toString()); } else { throw new Exception("Synchroniseren via apart process geeft error code " + result + "; output: \n" + errors.toString()); } }
From source file:org.spring.data.gemfire.AbstractGemFireIntegrationTest.java
protected static OutputStream startSpringGemFireServer(final long waitTimeout, final String... springConfigLocations) throws IOException { String serverId = DATE_FORMAT.format(Calendar.getInstance().getTime()); File serverWorkingDirectory = FileSystemUtils.createFile("server-".concat(serverId)); Assert.isTrue(FileSystemUtils.createDirectory(serverWorkingDirectory), String.format( "Failed to create working directory (%1$s) in which the Spring-based GemFire Server will run!", serverWorkingDirectory));//from www.j av a2 s . co m String[] serverCommandLine = buildServerCommandLine(springConfigLocations); System.out.printf("Starting Spring GemFire Server in (%1$s)...%n", serverWorkingDirectory); Process serverProcess = ProcessUtils.startProcess(serverCommandLine, serverWorkingDirectory); readProcessStream(serverId, "ERROR", serverProcess.getErrorStream()); readProcessStream(serverId, "OUT", serverProcess.getInputStream()); ProcessUtils.registerProcessShutdownHook(serverProcess, "Spring GemFire Server", serverWorkingDirectory); waitOnServer(waitTimeout, serverProcess, serverWorkingDirectory); return serverProcess.getOutputStream(); }
From source file:org.opencastproject.util.IoSupport.java
/** * Closes the processes input, output and error streams. * * @param process//from w w w . j a v a 2 s .co m * the process * @return <code>true</code> if the streams were closed */ public static boolean closeQuietly(final Process process) { if (process != null) { try { if (process.getErrorStream() != null) process.getErrorStream().close(); if (process.getInputStream() != null) process.getInputStream().close(); if (process.getOutputStream() != null) process.getOutputStream().close(); return true; } catch (Throwable t) { logger.trace("Error closing process streams: " + t.getMessage()); } } return false; }
From source file:org.midonet.util.process.ProcessHelper.java
public static RunnerConfiguration newProcess(final String commandLine) { return new RunnerConfiguration() { DrainTarget drainTarget;//w ww . j a v a 2 s . c o m String procCommandLine = commandLine; Map<String, String> envVars = new HashMap<>(); EnumSet<OutputStreams> streamsToLog = EnumSet.allOf(OutputStreams.class); final List<Runnable> exitHandlers = new ArrayList<>(1); @Override public RunnerConfiguration logOutput(Logger log, String marker, OutputStreams... streams) { streamsToLog.clear(); if (streams.length == 0) { streamsToLog = EnumSet.of(OutputStreams.StdOutput); } else { streamsToLog = EnumSet.noneOf(OutputStreams.class); Collections.addAll(streamsToLog, streams); } drainTarget = DrainTargets.slf4jTarget(log, marker); return this; } public RunnerConfiguration setDrainTarget(DrainTarget drainTarget) { this.drainTarget = drainTarget; return this; } @Override public RunnerConfiguration setEnvVariables(Map<String, String> vars) { this.envVars.putAll(vars); return this; } @Override public RunnerConfiguration setEnvVariable(String var, String value) { this.envVars.put(var, value); return this; } @Override public RunnerConfiguration addExitHandler(Runnable handler) { synchronized (exitHandlers) { exitHandlers.add(handler); } return this; } @Override public int runAndWait() { Process p = createProcess(true); String processName = procCommandLine; try { if (p != null) { p.waitFor(); IOUtils.closeQuietly(p.getInputStream()); IOUtils.closeQuietly(p.getErrorStream()); IOUtils.closeQuietly(p.getOutputStream()); if (p.exitValue() == 0) { log.trace("Process \"{}\" exited with code: {}", processName, p.exitValue()); } else { log.debug("Process \"{}\" exited with non zero code: {}", processName, p.exitValue()); } return p.exitValue(); } } catch (InterruptedException e) { log.error(String.format("Error while launching command: \"%s\"", processName), e); } return -1; } public Process run() { return createProcess(false); } @Override public RunnerConfiguration withSudo() { procCommandLine = "sudo " + procCommandLine; return this; } private Process createProcess(boolean wait) { try { final Process process = launchProcess(); if (drainTarget == null) { drainTarget = DrainTargets.noneTarget(); } Runnable exitHandler = new Runnable() { @Override public void run() { try { process.waitFor(); } catch (InterruptedException e) { } synchronized (exitHandlers) { for (Runnable handler : exitHandlers) { handler.run(); } } } }; ProcessOutputDrainer outputDrainer; if (streamsToLog.contains(OutputStreams.StdError)) { outputDrainer = new ProcessOutputDrainer(process, true); } else { outputDrainer = new ProcessOutputDrainer(process); } outputDrainer.drainOutput(drainTarget, wait, exitHandler); return process; } catch (IOException e) { log.error("Error while executing command: \"{}\"", commandLine, e); } return null; } private Process launchProcess() throws IOException { if (envVars.isEmpty()) { return Runtime.getRuntime().exec(procCommandLine); } else { List<String> param = new ArrayList<>(); for (Map.Entry<String, String> var : envVars.entrySet()) { param.add(var.getKey() + "=" + var.getValue()); } return Runtime.getRuntime().exec(procCommandLine, param.toArray(new String[param.size()])); } } }; }
From source file:com.wakatime.intellij.plugin.WakaTime.java
private static void sendHeartbeat(final Heartbeat heartbeat, final ArrayList<Heartbeat> extraHeartbeats) { final String[] cmds = buildCliCommand(heartbeat, extraHeartbeats); log.debug("Executing CLI: " + Arrays.toString(obfuscateKey(cmds))); try {//from w w w . ja v a2 s.c o m Process proc = Runtime.getRuntime().exec(cmds); if (extraHeartbeats.size() > 0) { String json = toJSON(extraHeartbeats); log.debug(json); try { BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())); stdin.write(json); stdin.write("\n"); try { stdin.flush(); stdin.close(); } catch (IOException e) { /* ignored because wakatime-cli closes pipe after receiving \n */ } } catch (IOException e) { log.warn(e); } } if (WakaTime.DEBUG) { BufferedReader stdout = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); proc.waitFor(); String s; while ((s = stdout.readLine()) != null) { log.debug(s); } while ((s = stderr.readLine()) != null) { log.debug(s); } log.debug("Command finished with return value: " + proc.exitValue()); } } catch (Exception e) { log.warn(e); } }
From source file:SystemKit.java
/** * Returns the first line of the result of a shell command. * Taken from UUID./*from ww w .ja v a 2 s .c o m*/ * * @param commands the commands to run * @return the first line of the command * @throws IOException * * @since 3.3.3 */ static String getFirstLineOfCommand(String[] commands) throws IOException { Process p = null; BufferedReader reader = null; try { p = Runtime.getRuntime().exec(commands); reader = new BufferedReader(new InputStreamReader(p.getInputStream()), 128); return reader.readLine(); } finally { if (p != null) { if (reader != null) { try { reader.close(); } catch (IOException ex) { } } try { p.getErrorStream().close(); } catch (IOException ex) { } try { p.getOutputStream().close(); } catch (IOException ex) { } p.destroy(); } } }
From source file:org.apache.pig.shock.SSHSocketImplFactory.java
private static void lsTest(SSHSocketImplFactory fac) throws JSchException, IOException { Process p = fac.ssh("ls"); byte b[] = new byte[1024]; final InputStream es = p.getErrorStream(); new Thread() { @Override//from w w w . j a va 2 s .com public void run() { try { while (es.available() > 0) { es.read(); } } catch (Exception e) { } } }.start(); p.getOutputStream().close(); InputStream is = p.getInputStream(); int rc; while ((rc = is.read(b)) > 0) { System.out.write(b, 0, rc); } }