List of usage examples for java.lang Process getOutputStream
public abstract OutputStream getOutputStream();
From source file:com.almunt.jgcaap.systemupdater.MainActivity.java
public void RebootRecovery(boolean update) { AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this); builder1.setTitle("Recovery Reboot"); if (update)//from w w w .j a v a 2 s. co m builder1.setMessage( "Would you like to reboot into recovery now to complete update?\nClear ORS will delete the OpenRecoveryScript to stop TWRP from automatically installing any files."); else builder1.setMessage("Would you like to reboot into recovery now.\n" + "Clear ORS will delete the current OpenRecoveryScript and stop any automatic update installations in TWRP"); builder1.setCancelable(true); builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); outputStream.writeBytes("reboot recovery\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); } catch (IOException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } } }); builder1.setNeutralButton("Clear ORS", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { Process su = Runtime.getRuntime().exec("su"); DataOutputStream outputStream = new DataOutputStream(su.getOutputStream()); outputStream.writeBytes("cd /cache/recovery/\n"); outputStream.flush(); outputStream.writeBytes("rm openrecoveryscript\n"); outputStream.flush(); outputStream.writeBytes("exit\n"); outputStream.flush(); su.waitFor(); Toast.makeText(MainActivity.this, "OpenRecoveryScript file was cleared", Toast.LENGTH_LONG) .show(); } catch (IOException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { Toast.makeText(MainActivity.this, "Error No Root Access detected", Toast.LENGTH_LONG).show(); } } }); builder1.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); if (update) builder1.setNegativeButton("Reboot Later", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alert11 = builder1.create(); alert11.show(); }
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java
public ProcessOutput execute(String[] command, Map<String, String> envMap) { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null; ProcessOutput processOutput = null;/*from w ww.j av a 2s. c om*/ try { processBuilder.environment().putAll(envMap); process = processBuilder.start(); int returnCode = process.waitFor(); List outputStream = IOUtils.readLines(process.getInputStream()); List errorStream = IOUtils.readLines(process.getErrorStream()); processOutput = new ProcessOutput(returnCode, outputStream, errorStream); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (process != null) { closeQuietly(process.getInputStream()); closeQuietly(process.getErrorStream()); closeQuietly(process.getOutputStream()); process.destroy(); } } return processOutput; }
From source file:com.thoughtworks.go.util.ProcessWrapper.java
ProcessWrapper(Process process, ProcessTag processTag, String command, ConsoleOutputStreamConsumer consumer, String encoding, String errorPrefix) { this.process = process; this.processTag = processTag; this.command = command; this.startTime = System.currentTimeMillis(); this.processOutputStream = StreamPumper.pump(process.getInputStream(), new OutputConsumer(consumer), "", encoding);/* www. j a v a2s . c om*/ this.processErrorStream = StreamPumper.pump(process.getErrorStream(), new ErrorConsumer(consumer), errorPrefix, encoding); this.processInputStream = new PrintWriter(new OutputStreamWriter(process.getOutputStream())); }
From source file:org.neo4j.io.pagecache.impl.SingleFilePageSwapperTest.java
@Test(expected = FileLockException.class) public void creatingSwapperForExternallyLockedFileMustThrow() throws Exception { assumeFalse("No file locking on Windows", SystemUtils.IS_OS_WINDOWS); // no file locking on Windows. PageSwapperFactory factory = swapperFactory(); DefaultFileSystemAbstraction fs = new DefaultFileSystemAbstraction(); factory.setFileSystemAbstraction(fs); File file = testDir.file("file"); fs.create(file).close();/*from ww w .j a v a 2 s . com*/ ProcessBuilder pb = new ProcessBuilder(ProcessUtil.getJavaExecutable().toString(), "-cp", ProcessUtil.getClassPath(), LockThisFileProgram.class.getCanonicalName(), file.getAbsolutePath()); File wd = new File("target/test-classes").getAbsoluteFile(); pb.directory(wd); Process process = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); assertThat(reader.readLine(), is(LockThisFileProgram.LOCKED_OUTPUT)); try { createSwapper(factory, file, 4, NO_CALLBACK, true); } finally { process.getOutputStream().write(0); process.getOutputStream().flush(); process.waitFor(); } }
From source file:de.uni_koblenz.jgralab.utilities.tg2dot.Tg2Dot.java
public void pipeToGraphViz(GraphVizProgram prog) throws IOException { String executionString = String.format("%s%s -T%s -o%s", prog.path, prog.layouter, prog.outputFormat, outputName);//from w w w . j av a 2s . c o m final Process process = Runtime.getRuntime().exec(executionString); new Thread() { @Override public void run() { PrintStream ps = new PrintStream(process.getOutputStream()); convert(ps); ps.flush(); ps.close(); }; }.start(); try { int retVal = process.waitFor(); if (retVal != 0) { throw new RuntimeException("GraphViz process failed! Error code = " + retVal); } } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:com.anrisoftware.globalpom.exec.core.DefaultProcessTask.java
@SuppressWarnings("unchecked") private List<Future<?>> createProcessStreams(Process process) { if (output == null) { this.outputStream = new ByteArrayOutputStream(); this.output = commandOutputFactory.create(outputStream); }//from w w w . ja v a 2 s. co m if (error == null) { this.errorStream = new ByteArrayOutputStream(); this.error = commandErrorFactory.create(errorStream); } if (input == null) { byte[] bytes = "".getBytes(); InputStream stream = new ByteArrayInputStream(bytes); this.input = commandInputFactory.create(stream); } input.setOutput(process.getOutputStream()); output.setInput(process.getInputStream()); error.setInput(process.getErrorStream()); return new ArrayList<Future<?>>( asList(threads.submit(input), threads.submit(output), threads.submit(error))); }
From source file:com.asakusafw.testdriver.DefaultJobExecutor.java
private int runCommand(List<String> commandLine, Map<String, String> environmentVariables) throws IOException { LOG.info(MessageFormat.format(Messages.getString("DefaultJobExecutor.infoEchoCommandLine"), //$NON-NLS-1$ toCommandLineString(commandLine))); ProcessBuilder builder = new ProcessBuilder(commandLine); builder.redirectErrorStream(true);/*from w ww . j av a 2 s . co m*/ builder.environment().putAll(environmentVariables); File hadoopCommand = configurations.getHadoopCommand(); if (hadoopCommand != null) { builder.environment().put("HADOOP_CMD", hadoopCommand.getAbsolutePath()); //$NON-NLS-1$ } builder.directory(new File(System.getProperty("user.home", "."))); //$NON-NLS-1$ //$NON-NLS-2$ int exitCode; Process process = builder.start(); try (InputStream is = process.getInputStream()) { InputStreamThread it = new InputStreamThread(is); it.start(); exitCode = process.waitFor(); it.join(); } catch (InterruptedException e) { throw new IOException( MessageFormat.format(Messages.getString("DefaultJobExecutor.errorExecutionInterrupted"), //$NON-NLS-1$ toCommandLineString(commandLine)), e); } finally { process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } return exitCode; }
From source file:org.ensembl.healthcheck.util.StreamGobbler.java
private static int waitForProcess(Thread outputGobbler, Thread errorGobbler, boolean discard, Process proc) { // kick them off errorGobbler.start();//from w ww . ja v a2s . c o m outputGobbler.start(); // return exit status try { // get the exit status of the command once finished // int exit = proc.waitFor(); // now wait for the output and error to be read with a suitable // timeout // outputGobbler.join(TIMEOUT); errorGobbler.join(TIMEOUT); return exit; } catch (InterruptedException e) { // While the Process is running, the Thread is in the state // called "WAITING". If an interrupt has been requested and caught // within the thread, reinterrupting is requested. // // See // http://download.oracle.com/javase/1,5.0/docs/guide/misc/threadPrimitiveDeprecation.html // chapter // Section "How do I stop a thread that waits for long periods (e.g., for input)?" // for more details on this. // Thread.currentThread().interrupt(); return -1; } finally { // to make sure the all streams are closed to avoid open file handles // IOUtils.closeQuietly(proc.getErrorStream()); IOUtils.closeQuietly(proc.getInputStream()); IOUtils.closeQuietly(proc.getOutputStream()); // Otherwise we will be waiting for the process to terminate on // its own instead of interrupting as the user has requested. // proc.destroy(); } }
From source file:io.stallion.utils.ProcessHelper.java
public CommandResult run() { String cmdString = String.join(" ", args); System.out.printf("----- Execute command: %s ----\n", cmdString); ProcessBuilder pb = new ProcessBuilder(args); if (!empty(directory)) { pb.directory(new File(directory)); }//from w w w . j av a 2 s . c o m Map<String, String> env = pb.environment(); CommandResult commandResult = new CommandResult(); Process p = null; try { if (showDotsWhileWaiting == null) { showDotsWhileWaiting = !inheritIO; } if (inheritIO) { p = pb.inheritIO().start(); } else { p = pb.start(); } BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!empty(input)) { Log.info("Writing input to pipe {0}", input); IOUtils.write(input, p.getOutputStream(), UTF8); p.getOutputStream().flush(); } while (p.isAlive()) { p.waitFor(1000, TimeUnit.MILLISECONDS); if (showDotsWhileWaiting == true) { System.out.printf("."); } } commandResult.setErr(IOUtils.toString(err)); commandResult.setOut(IOUtils.toString(out)); commandResult.setCode(p.exitValue()); if (commandResult.succeeded()) { info("\n---- Command execution completed ----\n"); } else { Log.warn("Command failed with error code: " + commandResult.getCode()); } } catch (IOException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(999); commandResult.setEx(e); } catch (InterruptedException e) { Log.exception(e, "Error running command: " + cmdString); commandResult.setCode(998); commandResult.setEx(e); } Log.fine( "\n\n----Start shell command result----:\nCommand: {0}\nexitCode: {1}\n----------STDOUT---------\n{2}\n\n----------STDERR--------\n{3}\n\n----end shell command result----\n", cmdString, commandResult.getCode(), commandResult.getOut(), commandResult.getErr()); return commandResult; }
From source file:com.thoughtworks.go.agent.AgentProcessParentImpl.java
public int run(String launcherVersion, String launcherMd5, ServerUrlGenerator urlGenerator, Map<String, String> env, Map context) { int exitValue = 0; LOG.info("Agent is version: {}", CurrentGoCDVersion.getInstance().fullVersion()); String command[] = new String[] {}; try {/*from w w w. j av a2s. c o m*/ AgentBootstrapperArgs bootstrapperArgs = AgentBootstrapperArgs.fromProperties(context); File rootCertFile = bootstrapperArgs.getRootCertFile(); SslVerificationMode sslVerificationMode = SslVerificationMode .valueOf(bootstrapperArgs.getSslMode().name()); ServerBinaryDownloader agentDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile, sslVerificationMode); agentDownloader.downloadIfNecessary(DownloadableFile.AGENT); ServerBinaryDownloader pluginZipDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile, sslVerificationMode); pluginZipDownloader.downloadIfNecessary(DownloadableFile.AGENT_PLUGINS); ServerBinaryDownloader tfsImplDownloader = new ServerBinaryDownloader(urlGenerator, rootCertFile, sslVerificationMode); tfsImplDownloader.downloadIfNecessary(DownloadableFile.TFS_IMPL); command = agentInvocationCommand(agentDownloader.getMd5(), launcherMd5, pluginZipDownloader.getMd5(), tfsImplDownloader.getMd5(), env, context, agentDownloader.getExtraProperties()); LOG.info("Launching Agent with command: {}", join(command, " ")); Process agent = invoke(command); // The next lines prevent the child process from blocking on Windows AgentOutputAppender agentOutputAppenderForStdErr = new AgentOutputAppender(GO_AGENT_STDERR_LOG); AgentOutputAppender agentOutputAppenderForStdOut = new AgentOutputAppender(GO_AGENT_STDOUT_LOG); if (new SystemEnvironment().consoleOutToStdout()) { agentOutputAppenderForStdErr.writeTo(AgentOutputAppender.Outstream.STDERR); agentOutputAppenderForStdOut.writeTo(AgentOutputAppender.Outstream.STDOUT); } agent.getOutputStream().close(); AgentConsoleLogThread stdErrThd = new AgentConsoleLogThread(agent.getErrorStream(), agentOutputAppenderForStdErr); stdErrThd.start(); AgentConsoleLogThread stdOutThd = new AgentConsoleLogThread(agent.getInputStream(), agentOutputAppenderForStdOut); stdOutThd.start(); Shutdown shutdownHook = new Shutdown(agent); Runtime.getRuntime().addShutdownHook(shutdownHook); try { exitValue = agent.waitFor(); } catch (InterruptedException ie) { LOG.error("Agent was interrupted. Terminating agent and respawning. {}", ie.toString()); agent.destroy(); } finally { removeShutdownHook(shutdownHook); stdErrThd.stopAndJoin(); stdOutThd.stopAndJoin(); } } catch (Exception e) { LOG.error("Exception while executing command: {} - {}", join(command, " "), e.toString()); exitValue = EXCEPTION_OCCURRED; } return exitValue; }