List of usage examples for java.lang ProcessBuilder ProcessBuilder
public ProcessBuilder(String... command)
From source file:bboss.org.artofsolving.jodconverter.process.LinuxProcessManager.java
private List<String> execute(String... args) throws IOException { String[] command;//from ww w . j av a 2s .c o m if (runAsArgs != null) { command = new String[runAsArgs.length + args.length]; System.arraycopy(runAsArgs, 0, command, 0, runAsArgs.length); System.arraycopy(args, 0, command, runAsArgs.length, args.length); } else { command = args; } Process process = new ProcessBuilder(command).start(); @SuppressWarnings("unchecked") List<String> lines = IOUtils.readLines(process.getInputStream()); return lines; }
From source file:de.uni_potsdam.hpi.asg.common.io.Invoker.java
private ProcessReturn invoke(String[] cmd, List<String> params, File folder, int timeout) { List<String> command = new ArrayList<String>(); command.addAll(Arrays.asList(cmd)); command.addAll(params);/*from w w w. j av a2 s.c o m*/ ProcessReturn retVal = new ProcessReturn(Arrays.asList(cmd), params); Process process = null; try { logger.debug("Exec command: " + command.toString()); //System.out.println(timeout + ": " + command.toString()); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(folder); builder.environment(); // bugfix setting env in test-mode (why this works? i dont know..) process = builder.start(); Thread timeoutThread = null; if (timeout > 0) { timeoutThread = new Thread(new Timeout(Thread.currentThread(), timeout)); timeoutThread.setName("Timout for " + command.toString()); timeoutThread.start(); } IOStreamReader ioreader = new IOStreamReader(process); Thread streamThread = new Thread(ioreader); streamThread.setName("StreamReader for " + command.toString()); streamThread.start(); process.waitFor(); streamThread.join(); if (timeoutThread != null) { timeoutThread.interrupt(); } String out = ioreader.getResult(); //System.out.println(out); if (out == null) { //System.out.println("out = null"); retVal.setStatus(Status.noio); } retVal.setCode(process.exitValue()); retVal.setStream(out); retVal.setStatus(Status.ok); } catch (InterruptedException e) { process.destroy(); retVal.setTimeout(timeout); retVal.setStatus(Status.timeout); } catch (IOException e) { logger.error(e.getLocalizedMessage()); retVal.setStatus(Status.ioexception); } return retVal; }
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. */// www .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:io.jmnarloch.cd.go.plugin.sbt.SbtTaskExecutor.java
/** * Builds the SBT process to be executed * * @param environment the build environment * @param config the build configuration * @return the SBT process//from w ww . j a v a2 s . co m */ private ProcessBuilder buildSbtProcess(ExecutionContext environment, ExecutionConfiguration config) { final Map<String, String> env = environment.getEnvironmentVariables(); final List<String> command = parse(config, env); logger.debug("Executing command: " + command); final ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); builder.directory(new File(environment.getWorkingDirectory())); return builder; }
From source file:azkaban.jobExecutor.utils.process.AzkabanProcess.java
/** * Execute this process, blocking until it has completed. *//*from ww w .j a v a2s . c o m*/ public void run() throws IOException { if (this.isStarted() || this.isComplete()) { throw new IllegalStateException("The process can only be used once."); } ProcessBuilder builder = new ProcessBuilder(cmd); builder.directory(new File(workingDir)); builder.environment().putAll(env); builder.redirectErrorStream(true); this.process = builder.start(); try { this.processId = processId(process); if (processId == 0) { logger.debug("Spawned thread with unknown process id"); } else { logger.debug("Spawned thread with process id " + processId); } this.startupLatch.countDown(); LogGobbler outputGobbler = new LogGobbler(new InputStreamReader(process.getInputStream()), logger, Level.INFO, 30); LogGobbler errorGobbler = new LogGobbler(new InputStreamReader(process.getErrorStream()), logger, Level.ERROR, 30); outputGobbler.start(); errorGobbler.start(); int exitCode = -1; try { exitCode = process.waitFor(); } catch (InterruptedException e) { logger.info("Process interrupted. Exit code is " + exitCode, e); } completeLatch.countDown(); // try to wait for everything to get logged out before exiting outputGobbler.awaitCompletion(5000); errorGobbler.awaitCompletion(5000); if (exitCode != 0) { String output = new StringBuilder().append("Stdout:\n").append(outputGobbler.getRecentLog()) .append("\n\n").append("Stderr:\n").append(errorGobbler.getRecentLog()).append("\n") .toString(); throw new ProcessFailureException(exitCode, output); } } finally { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:edu.illinois.cs.cogcomp.CompileMojo.java
public void execute() throws MojoExecutionException { dFlag = FileUtils.getPlatformIndependentFilePath(dFlag); gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag); sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag); classpath.add(dFlag);// w w w . j a va 2 s . co m classpath.add(gspFlag); String newpath = StringUtils.join(classpath, File.pathSeparator); // If these directories don't exist, make them. new File(dFlag).mkdirs(); new File(gspFlag).mkdirs(); for (String lbjInputFile : lbjavaInputFileList) { if (StringUtils.isEmpty(lbjInputFile)) { // making the optional-compile-parameter happy. continue; } getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main..."); lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile); try { String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile }; ProcessBuilder pr = new ProcessBuilder(args); pr.inheritIO(); Process p = pr.start(); p.waitFor(); } catch (Exception e) { e.printStackTrace(); System.out.println("Yeah, an error."); } } }
From source file:edu.illinois.cs.cogcomp.GenerateMojo.java
public void execute() throws MojoExecutionException { dFlag = FileUtils.getPlatformIndependentFilePath(dFlag); gspFlag = FileUtils.getPlatformIndependentFilePath(gspFlag); sourcepathFlag = FileUtils.getPlatformIndependentFilePath(sourcepathFlag); classpath.add(dFlag);/*w ww.j a va2 s . c om*/ classpath.add(gspFlag); String newpath = StringUtils.join(classpath, File.pathSeparator); // If these directories don't exist, make them. new File(dFlag).mkdirs(); new File(gspFlag).mkdirs(); for (String lbjInputFile : lbjavaInputFileList) { if (StringUtils.isEmpty(lbjInputFile)) { // making the optional-compile-step parameter happy. continue; } getLog().info("Calling Java edu.illinois.cs.cogcomp.lbjava.Main..."); lbjInputFile = FileUtils.getPlatformIndependentFilePath(lbjInputFile); try { String[] args = new String[] { "java", "-cp", newpath, "edu.illinois.cs.cogcomp.lbjava.Main", "-c", "-d", dFlag, "-gsp", gspFlag, "-sourcepath", sourcepathFlag, lbjInputFile }; ProcessBuilder pr = new ProcessBuilder(args); pr.inheritIO(); Process p = pr.start(); p.waitFor(); } catch (Exception e) { e.printStackTrace(); System.out.println("Yeah, an error."); } } }
From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java
@Override public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName, List<String> compilerFlags) throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException { // First we build the command to invoke the compiler. This consists of // the compiler executable, the path of the // file to compile and compiler flags. So for example we call: List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags); // Now we build a launchable process from the given parameters and set // the working directory. Process compilerProcess = null; try {// w w w . ja va 2 s .c o m ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation); // make sure the compiler stays in its directory. if (Files.isDirectory(pathToProgramFile)) { compilerProcessBuilder.directory(pathToProgramFile.toFile()); } else { compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile()); } compilerProcess = compilerProcessBuilder.start(); } catch (IOException e) { // If we cannot call the compiler we return a CompilerOutput // initialized with false, false, indicating // that the compiler wasn't invoked properly and that there was no // clean Compile. CompilerOutput compilerInvokeError = new CompilerOutput(); compilerInvokeError.setClean(false); compilerInvokeError.setCompilerInvoked(false); LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH"); return compilerInvokeError; } // Now we read compiler output. If everything is ok gcc reports // nothing at all. InputStream compilerOutputStream = compilerProcess.getErrorStream(); InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream); BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader); String line; CompilerOutput compilerOutput = new CompilerOutput(); compilerOutput.setCompilerInvoked(true); List<String> compilerOutputLines = new LinkedList<>(); try { while ((line = compilerOutputBuffer.readLine()) != null) { compilerOutputLines.add(line); } compilerOutputStream.close(); compilerStreamReader.close(); compilerOutputBuffer.close(); compilerProcess.destroy(); } catch (IOException e) { // Reading might go wrong here if gcc should unexpectedly terminate LOGGER.severe("Error while reading from compiler stream."); compilerOutput.setClean(false); compilerOutput.setCompileStreamBroken(true); return compilerOutput; } if (compilerOutputLines.size() == 0) { compilerOutput.setClean(true); } compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput); // delete all .o and .exe files // these are output files generated by gcc which we won't need // anymore File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles(); for (File candidateFile : candidateToplevelFiles) { if (!candidateFile.isDirectory()) { String extension = FilenameUtils.getExtension(candidateFile.toString()); if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) { // We only pass the filename, since gcc will be // confined to the dir the file is located in. candidateFile.delete(); } } } return compilerOutput; }
From source file:com.act.utils.ProcessRunner.java
/** * Run's a child process using the specified command and arguments, timing out after a specified number of seconds * if the process does not terminate on its own in that time. * @param command The process to run./*w w w . j a va 2s . c om*/ * @param args The arguments to pass to that process. * @param timeoutInSeconds A timeout to impose on the child process; an InterruptedException is likely to occur * when the child process times out. * @return The exit code of the child process. * @throws InterruptedException * @throws IOException */ public static int runProcess(String command, List<String> args, Long timeoutInSeconds) throws InterruptedException, IOException { /* The ProcessBuilder doesn't differentiate the command from its arguments, but we do in our API to ensure the user * doesn't just pass us a single string command, which invokes the shell and can cause all sorts of bugs and * security issues. */ List<String> commandAndArgs = new ArrayList<String>(args.size() + 1) { { add(command); addAll(args); } }; ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs); LOGGER.info("Running child process: %s", StringUtils.join(commandAndArgs, " ")); Process p = processBuilder.start(); // Log whatever the child writes. new StreamLogger(p.getInputStream(), l -> LOGGER.info("[child STDOUT]: %s", l)).run(); new StreamLogger(p.getErrorStream(), l -> LOGGER.warn("[child STDERR]: %s", l)).run(); // Wait for the child process to exit, timing out if it takes to long to finish. if (timeoutInSeconds != null) { p.waitFor(timeoutInSeconds, TimeUnit.SECONDS); } else { p.waitFor(); } // 0 is the default success exit code in *nix land. if (p.exitValue() != 0) { LOGGER.error("Child process exited with non-zero status code: %d", p.exitValue()); } return p.exitValue(); }
From source file:com.bekwam.resignator.commands.KeytoolCommand.java
public List<KeystoreEntry> findKeystoreEntries(String keytoolExec, String keystore, String storepass) throws CommandExecutionException { List<KeystoreEntry> entries = new ArrayList<>(); Preconditions.checkNotNull(keytoolExec); Preconditions.checkNotNull(keystore); Preconditions.checkNotNull(storepass); File outputFile = null;//from w w w .j a v a2s . c o m try { String[] cmdAndArgs = { keytoolExec, "-keystore", keystore, "-storepass", storepass, "-list" }; File resignatorDir = new File(System.getProperty("user.home"), ".resignator"); String outputFileName = OUTPUTFILE_PREFIX + StringUtils.lowerCase(RandomStringUtils.randomAlphabetic(12)) + OUTPUTFILE_SUFFIX; outputFile = new File(resignatorDir, outputFileName); ProcessBuilder pb = new ProcessBuilder(cmdAndArgs); pb.redirectErrorStream(false); pb.redirectOutput(outputFile); Process p = pb.start(); boolean exitted = p.waitFor(TIMEOUT_SECS, TimeUnit.SECONDS); if (exitted) { if (p.exitValue() == 0) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(outputFile))); entries.addAll(parseKeystoreEntries(br)); br.close(); } else { String firstLine = ""; if (outputFile != null && outputFile.exists()) { BufferedReader br = new BufferedReader(new FileReader(outputFile)); firstLine = br.readLine(); br.close(); } if (logger.isErrorEnabled()) { logger.error("error running exec={}; firstLine={}", keytoolExec, firstLine); } throw new CommandExecutionException( "Command '" + keytoolExec + "' failed to run" + newLine + firstLine); } } else { if (logger.isErrorEnabled()) { logger.error("command '" + keytoolExec + "' timed out"); } throw new CommandExecutionException("Command '" + keytoolExec + "' timed out"); } } catch (Exception exc) { // includes interrupted exception if (logger.isErrorEnabled()) { logger.error("error running keytool", exc); } throw new CommandExecutionException("Error running keytool command" + newLine + exc.getMessage()); } finally { if (outputFile != null) { outputFile.delete(); } } return entries; }