List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
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 ww 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:edu.cmu.cs.diamond.android.Filter.java
public Filter(int resourceId, Context context, String name, String[] args, byte[] blob) throws IOException { Resources r = context.getResources(); String resourceName = r.getResourceEntryName(resourceId); File f = context.getFileStreamPath(resourceName); if (!f.exists()) { InputStream ins = r.openRawResource(resourceId); byte[] buf = IOUtils.toByteArray(ins); FileOutputStream fos = context.openFileOutput(resourceName, Context.MODE_PRIVATE); IOUtils.write(buf, fos);//from w w w.j a v a 2 s. c om context.getFileStreamPath(resourceName).setExecutable(true); fos.close(); } ProcessBuilder pb = new ProcessBuilder(f.getAbsolutePath()); Map<String, String> env = pb.environment(); tempDir = File.createTempFile("filter", null, context.getCacheDir()); tempDir.delete(); // Delete file and create directory. if (!tempDir.mkdir()) { throw new IOException("Unable to create temporary directory."); } env.put("TEMP", tempDir.getAbsolutePath()); env.put("TMPDIR", tempDir.getAbsolutePath()); proc = pb.start(); is = proc.getInputStream(); os = proc.getOutputStream(); sendInt(1); sendString(name); sendStringArray(args); sendBinary(blob); while (this.getNextToken().tag != TagEnum.INIT) ; Log.d(TAG, "Filter initialized."); }
From source file:postenergy.PostEnergy.java
private void initUI() { /* Definitions */ JPanel panel = new JPanel(); getContentPane().add(panel);//from w w w. j a va 2 s . c o m panel.setLayout(null); /* Basic elements */ JButton getBatteryInfo = new JButton("Get Battery Info"); getBatteryInfo.setBounds(0, 60, 180, 30); getBatteryInfo.setToolTipText("Get Battery Info"); getBatteryInfo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.out.println("getBatteryInfo button pressed!"); ProcessBuilder pbs = new ProcessBuilder("/Users/thomas/Development/script.sh"); try { Process p = pbs.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder builder = new StringBuilder(); String line = null; try { while ((line = br.readLine()) != null) { builder.append(line); builder.append(System.getProperty("line.separator")); } } catch (IOException ex) { Logger.getLogger(PostEnergy.class.getName()).log(Level.SEVERE, null, ex); } String result = builder.toString(); System.out.println("Result: " + result); // Send as POST request String[] paramNames = new String[] { "t", "h" }; String[] paramVals = new String[] { result, result + 100 }; PostHttpClient("mindass", paramNames, paramVals); } catch (IOException ex) { System.out.println("Error with the processbuilder!"); Logger.getLogger(PostEnergy.class.getName()).log(Level.SEVERE, null, ex); } } }); panel.add(getBatteryInfo); JButton sendPost = new JButton("Send Post"); sendPost.setBounds(0, 30, 180, 30); sendPost.setToolTipText("Send Post"); sendPost.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.out.println("sendPost button pressed!"); PostHttpClient("mindass", new String[] { "t", "h" }, new String[] { "23", "44" }); } }); panel.add(sendPost); JButton quitButton = new JButton("Quit"); quitButton.setBounds(0, 0, 80, 30); quitButton.setToolTipText("Quit iPower"); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.out.println("Quit button pressed!"); System.exit(0); } }); panel.add(quitButton); /* Set init */ setTitle("iPower"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); }
From source file:com.thoughtworks.go.util.ProcessManager.java
public ProcessWrapper createProcess(String[] commandLine, String commandLineForDisplay, File workingDir, Map<String, String> envMap, EnvironmentVariableContext environmentVariableContext, ConsoleOutputStreamConsumer consumer, String processTag, String encoding, String errorPrefix) { ProcessBuilder processBuilder = new ProcessBuilder(commandLine); if (LOG.isDebugEnabled()) { LOG.debug("Executing: " + commandLineForDisplay); }/*from w ww. j a v a 2s. c o m*/ if (workingDir != null) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("[Command Line] Using working directory %s to start the process.", workingDir.getAbsolutePath())); } processBuilder.directory(workingDir); } environmentVariableContext.setupRuntimeEnvironment(processBuilder.environment(), consumer); processBuilder.environment().putAll(envMap); Process process = startProcess(processBuilder, commandLineForDisplay); ProcessWrapper processWrapper = new ProcessWrapper(process, processTag, commandLineForDisplay, consumer, encoding, errorPrefix); processMap.putIfAbsent(process, processWrapper); return processWrapper; }
From source file:com.consol.citrus.admin.service.executor.AbstractExecuteCommand.java
public ProcessBuilder getProcessBuilder() { validateWorkingDirectory(workingDirectory); List<String> commands = new ArrayList<String>(); if (SystemUtils.IS_OS_UNIX) { commands.add(BASH);/*from www.ja va2 s . c o m*/ commands.add(BASH_OPTION_C); } else { commands.add(CMD); commands.add(CMD_OPTION_C); } commands.add(buildCommand()); ProcessBuilder pb = new ProcessBuilder(commands); pb.directory(workingDirectory); LOG.debug("Process builder commands: " + commands); return pb; }
From source file:dk.deck.remoteconsole.proxy.LocalExecutor.java
public void execute(String command, String[] arguments, final PrintStream out, final PrintStream error) throws IOException, InterruptedException { List<String> args = new ArrayList<String>(); args.add(command);// w w w . ja v a2s .c o m args.addAll(Arrays.asList(arguments)); ProcessBuilder builder = new ProcessBuilder(args); // Map<String, String> env = builder.environment(); // System.out.println("Env:"); // for (Map.Entry<String, String> entry : env.entrySet()) { // System.out.println(entry.getKey() + "=" + entry.getValue()); // } final Process p = builder.start(); Runnable copyOutput = new Runnable() { @Override public void run() { try { IOUtils.copyLarge(p.getInputStream(), out); } catch (IOException ex) { ex.printStackTrace(); } } }; Runnable copyError = new Runnable() { @Override public void run() { try { IOUtils.copyLarge(p.getErrorStream(), error); } catch (IOException ex) { ex.printStackTrace(); } } }; new Thread(copyOutput).start(); new Thread(copyError).start(); int exitValue = p.waitFor(); if (exitValue != 0) { throw new IllegalStateException("Exit value for dump was " + exitValue); } }
From source file:com.photon.phresco.plugins.xcode.CodeValidation.java
public void execute() throws MojoExecutionException { try {//from w w w .j a v a 2 s . c o m ProcessBuilder pb = new ProcessBuilder(check); // Include errors in output pb.redirectErrorStream(true); List<String> commands = pb.command(); commands.add("-o"); commands.add("make"); commands.add("xcodebuild"); commands.add("-scheme"); commands.add(scheme); commands.add("-project"); commands.add(xcodeProject); commands.add("build"); getLog().info("List of commands" + pb.command()); // pb.command().add("install"); pb.directory(new File(basedir)); Process child = pb.start(); // Consume subprocess output and write to stdout for debugging InputStream is = new BufferedInputStream(child.getInputStream()); int singleByte = 0; while ((singleByte = is.read()) != -1) { // output.write(buffer, 0, bytesRead); System.out.write(singleByte); } child.waitFor(); int exitValue = child.exitValue(); getLog().info("Exit Value: " + exitValue); if (exitValue != 0) { throw new MojoExecutionException("Compilation error occured. Resolve the error(s) and try again!"); } } catch (IOException e) { getLog().error("An IOException occured."); throw new MojoExecutionException("An IOException occured", e); } catch (InterruptedException e) { getLog().error("The clean process was been interrupted."); throw new MojoExecutionException("The clean process was been interrupted", e); } createreport(); }
From source file:org.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java
public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) { String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" ")); LOGGER.info("==================="); LOGGER.info("Command to invoke: {}", lineToRun); ProcessBuilder processBuilder = new ProcessBuilder(command); updateEnvOfProcessBuilder(processBuilder.environment(), properties); if (workingDir != null) { processBuilder.directory(new File(workingDir)); }/* www .ja va 2 s. c om*/ processBuilder.redirectErrorStream(true); StringBuilder processOutput = new StringBuilder(); Process process; BufferedReader stdout = null; try { process = processBuilder.start(); stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = stdout.readLine()) != null) { LOGGER.debug(":::::: " + line); processOutput.append(line); processOutput.append('\n'); } try { process.waitFor(); } catch (InterruptedException e) { LOGGER.error("Command '" + lineToRun + "' interrupted.", e); } } catch (IOException e) { LOGGER.error("Problem executing external process.", e); return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e); } finally { closeReader(stdout); } ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(), processOutput.toString(), null); LOGGER.info("Exit value: {}", result.getExitCode()); LOGGER.info("==================="); return result; }
From source file:net.sf.mavenjython.test.PythonTestMojo.java
public void execute() throws MojoExecutionException { // all we have to do is to run nose on the source directory List<String> l = new ArrayList<String>(); if (program.equals("nose")) { l.add("nosetests.bat"); l.add("--failure-detail"); l.add("--verbose"); } else {/* www .j a v a 2s . c om*/ l.add(program); } ProcessBuilder pb = new ProcessBuilder(l); pb.directory(testOutputDirectory); pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath()); final Process p; getLog().info("starting python tests"); getLog().info("executing " + pb.command()); getLog().info("in directory " + testOutputDirectory); getLog().info("and also including " + outputDirectory); try { p = pb.start(); } catch (IOException e) { throw new MojoExecutionException( "Python tests execution failed. Provide the executable '" + program + "' in the path", e); } copyIO(p.getInputStream(), System.out); copyIO(p.getErrorStream(), System.err); copyIO(System.in, p.getOutputStream()); try { if (p.waitFor() != 0) { throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue()); } else { getLog().info("Python tests (" + program + ") succeeded."); } } catch (InterruptedException e) { throw new MojoExecutionException("Python tests were interrupted", e); } }
From source file:io.hakbot.providers.shell.ShellProvider.java
public boolean process(Job job) { try (InputStream inputStream = process.getInputStream(); InputStream errorStream = process.getErrorStream()) { final ProcessBuilder pb = new ProcessBuilder(command.split(" ")); process = pb.start();// www.j a v a 2s.c om final int exitCode = process.waitFor(); final byte[] stdout = IOUtils.toByteArray(inputStream); final byte[] stderr = IOUtils.toByteArray(errorStream); if (LOGGER.isDebugEnabled()) { LOGGER.debug("STDOUT:"); LOGGER.debug(new String(stdout)); LOGGER.debug("STDERR:"); LOGGER.debug(new String(stderr)); } if (exitCode == 0) { addArtifact(job, JobArtifact.Type.PROVIDER_RESULT, JobArtifact.MimeType.PLAIN_TEXT.value(), stdout, "Console-STDOUT-" + job.getUuid() + ".txt"); } else { if (stdout.length == 0) { addArtifact(job, JobArtifact.Type.PROVIDER_RESULT, JobArtifact.MimeType.PLAIN_TEXT.value(), stderr, "Console-STDERR-" + job.getUuid() + ".txt"); } else { addArtifact(job, JobArtifact.Type.PROVIDER_RESULT, JobArtifact.MimeType.PLAIN_TEXT.value(), stdout, "Console-STDOUT-" + job.getUuid() + ".txt"); } throw new JobException(exitCode); } return true; } catch (IOException | InterruptedException e) { addProcessingMessage(job, "Could not execute job."); addProcessingMessage(job, e.getMessage()); } catch (JobException e) { addProcessingMessage(job, "Job terminated abnormally. Exit code: " + e.getExitCode()); addProcessingMessage(job, e.getMessage()); } return false; }