List of usage examples for org.apache.commons.exec PumpStreamHandler PumpStreamHandler
public PumpStreamHandler(final OutputStream out, final OutputStream err, final InputStream input)
PumpStreamHandler
. From source file:org.codehaus.mojo.exec.ExecMojo.java
protected int executeCommandLine(Executor exec, CommandLine commandLine, Map<String, String> enviro, OutputStream out, OutputStream err) throws ExecuteException, IOException { // note: don't use BufferedOutputStream here since it delays the outputs MEXEC-138 PumpStreamHandler psh = new PumpStreamHandler(out, err, System.in); return executeCommandLine(exec, commandLine, enviro, psh); }
From source file:org.evosuite.utils.ProcessLauncher.java
public int launchNewProcess(File baseDir, String cmdString, int timeout) throws IOException, ProcessTimeoutException { DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog timeoutWatchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(timeoutWatchdog); PumpStreamHandler streamHandler = new PumpStreamHandler(this.outAndErr, this.outAndErr, this.input); executor.setStreamHandler(streamHandler); if (baseDir != null) { executor.setWorkingDirectory(baseDir); }// w w w . ja v a 2 s . c o m int exitValue; try { logger.debug("About to execute command " + cmdString); exitValue = executor.execute(CommandLine.parse(cmdString)); if (executor.isFailure(exitValue) && timeoutWatchdog.killedProcess()) { // it was killed on purpose by the watchdog logger.debug("A timeout occured while executing a process"); logger.debug("The command is " + cmdString); throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString); } return exitValue; } catch (ExecuteException e) { if (timeoutWatchdog.killedProcess()) { logger.debug("A timeout occured while executing a process"); logger.debug("The command is " + cmdString); throw new ProcessTimeoutException("A timeout occurred while executing command " + cmdString); } else { throw e; } } }
From source file:org.fornax.toolsupport.sculptor.maven.plugin.GeneratorMojo.java
/** * Executes the commandline running the Eclipse MWE2 launcher and returns * the commandlines exit value.// ww w . j a v a 2 s .c o m * * @param changedFiles * list of files from <code>checkFileSets</code> which are * modified since last generator execution or <code>null</code> * if code generation is enforced */ protected List<File> executeGenerator(Set<String> changedFiles) throws MojoExecutionException { List<File> createdFiles = null; // Build executor for projects base directory ScanningMavenLogOutputStream stdout = getStdoutStream(); ScanningMavenLogOutputStream stderr = getStderrStream(); Executor exec = getExecutor(); exec.setWorkingDirectory(project.getBasedir()); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); // Execute commandline and check return code try { int exitValue = exec.execute(getGeneratorCommandLine(changedFiles)); // Check exit value and output streams for errors if (exitValue == 0 && stdout.getErrorCount() == 0 && stderr.getLineCount() == 0) { // Return list of created files createdFiles = stdout.getCreatedFiles(); } } catch (ExecuteException e) { // ignore } catch (IOException e) { // ignore } return createdFiles; }
From source file:org.fornax.toolsupport.sculptor.maven.plugin.GraphvizMojo.java
/** * Executes the command line tool <code>dot</code>. * //from w w w.ja va 2 s .co m * @param dotFiles * list of dot files from the * {@link AbstractSculptorMojo#statusFile} */ protected boolean executeDot(Set<String> dotFiles) throws MojoExecutionException { // Build executor for projects base directory MavenLogOutputStream stdout = getStdoutStream(); MavenLogOutputStream stderr = getStderrStream(); Executor exec = getExecutor(); exec.setWorkingDirectory(project.getBasedir()); exec.setStreamHandler(new PumpStreamHandler(stdout, stderr, System.in)); // Execute commandline and check return code try { int exitValue = exec.execute(getDotCommandLine(dotFiles)); if (exitValue == 0 && stdout.getErrorCount() == 0) { return true; } } catch (ExecuteException e) { // ignore } catch (IOException e) { // ignore } return false; }
From source file:org.kualigan.maven.plugins.api.DefaultPrototypeHelper.java
protected int executeCommandLine(final String... args) throws ExecuteException, IOException { final Executor exec = new DefaultExecutor(); final Map enviro = new HashMap(); try {/*from w ww . j av a2 s . c o m*/ final Properties systemEnvVars = CommandLineUtils.getSystemEnvVars(); enviro.putAll(systemEnvVars); } catch (IOException x) { getCaller().getLog().error("Could not assign default system enviroment variables.", x); } final File workingDirectory = new File(System.getProperty("java.io.tmpdir")); final org.apache.commons.exec.CommandLine commandLine = new org.apache.commons.exec.CommandLine(args[0]); for (int i = 1; i < args.length; i++) { commandLine.addArgument(args[i]); } exec.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in)); exec.setWorkingDirectory(workingDirectory); return exec.execute(commandLine, enviro); }
From source file:org.ng200.openolympus.cerberus.compilers.FPCCompiler.java
@Override public void compile(final List<Path> inputFiles, final Path outputFile, final Map<String, Object> additionalParameters) throws CompilationException { FPCCompiler.logger.debug("Compiling {} to {} using FPC", inputFiles, outputFile); final CommandLine commandLine = new CommandLine("ppcx64"); commandLine.setSubstitutionMap(additionalParameters); this.arguments.forEach((arg) -> commandLine.addArgument(arg)); commandLine.addArgument("-o" + outputFile.toAbsolutePath().toString()); // Set // outuput/*from ww w. j av a 2s . co m*/ // file commandLine.addArgument("-l-"); commandLine.addArgument("-v0"); inputFiles.forEach((file) -> commandLine .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add // input // files FPCCompiler.logger.debug("Running FPC with arguments: {}", commandLine.toString()); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(errorStream, null, null)); executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to // compile int result; try { result = executor.execute(commandLine); } catch (final IOException e) { FPCCompiler.logger.error("Could not execute FPC: {}", e); throw new CompilationException("Could not execute FPC", e); } switch (result) { case 0: return; case 1: try { final String errorString = errorStream.toString("UTF-8"); final Pattern pattern = Pattern.compile( "^(" + inputFiles.stream().map(file -> Pattern.quote(file.getFileName().toString())) .collect(Collectors.joining("|")) + ")", Pattern.MULTILINE); FPCCompiler.logger.debug("Compilation error: {}", errorString); throw new CompilerError("fpc.wrote.stdout", errorString); } catch (final UnsupportedEncodingException e) { throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e); } } }
From source file:org.ng200.openolympus.cerberus.compilers.GNUCompiler.java
@Override public void compile(final List<Path> inputFiles, final Path outputFile, final Map<String, Object> additionalParameters) throws CompilationException { GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile); final CommandLine commandLine = new CommandLine("g++"); commandLine.setSubstitutionMap(additionalParameters); this.arguments.forEach((arg) -> commandLine.addArgument(arg)); commandLine.addArgument("-w"); // Prohibit warnings because they screw // up error detection commandLine.addArgument("-o"); commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file inputFiles.forEach((file) -> commandLine .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add // input/* w w w . j a v a2s . c om*/ // files GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments())); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null)); executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to // compile int result; try { result = executor.execute(commandLine); } catch (final IOException e) { GNUCompiler.logger.error("Could not execute GCC: {}", e); throw new CompilationException("Could not execute GCC", e); } switch (result) { case 0: return; case 1: try { String errorString = errorStream.toString(StandardCharsets.UTF_8.name()); final Pattern pattern = Pattern.compile( "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString())) .collect(Collectors.joining("|")) + "):", Pattern.MULTILINE); errorString = pattern.matcher(errorString).replaceAll(""); GNUCompiler.logger.debug("Compilation error: {}", errorString); throw new CompilerError("gcc.wrote.stderr", errorString); } catch (final UnsupportedEncodingException e) { throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e); } } }
From source file:org.ng200.openolympus.cerberus.compilers.JavaCompiler.java
@Override public void compile(final List<Path> inputFiles, final Path outputFile, final Map<String, Object> additionalParameters) throws CompilationException, IOException { FileAccess.createDirectories(outputFile); final CommandLine commandLine = new CommandLine("javac"); commandLine.setSubstitutionMap(additionalParameters); this.arguments.forEach((arg) -> commandLine.addArgument(arg)); commandLine.addArgument("-d"); commandLine.addArgument(outputFile.toAbsolutePath().toString()); commandLine.addArgument("-nowarn"); // Prohibit warnings because they // screw/*from w ww.j a va 2 s .c o m*/ // up error detection inputFiles.forEach((file) -> commandLine .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add // input // files JavaCompiler.logger.info("Running javac with arguments: {}", Arrays.asList(commandLine.getArguments())); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(new int[] { 0, 1 }); final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null)); executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to // compile int result; try { result = executor.execute(commandLine); } catch (final IOException e) { JavaCompiler.logger.error("Could not execute javac: {}", e); throw new CompilationException("Could not execute javac", e); } switch (result) { case 0: return; case 1: try { String errorString = errorStream.toString("UTF-8"); final Pattern pattern = Pattern.compile( "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString())) .collect(Collectors.joining("|")) + "):", Pattern.MULTILINE); errorString = pattern.matcher(errorString).replaceAll(""); JavaCompiler.logger.debug("Compilation error: {}", errorString); throw new CompilerError("javac.wrote.stderr", errorString); } catch (final UnsupportedEncodingException e) { throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e); } } }
From source file:org.ng200.openolympus.cerberus.executors.JavaExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { final Path chrootRoot = this.storage.getPath().resolve("chroot"); final Path chrootedProgram = chrootRoot.resolve(program.getFileName().toString()); FileAccess.createDirectories(chrootedProgram); FileAccess.copyDirectory(program, chrootedProgram, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES); final Path outOfMemoryFile = chrootRoot.resolve("outOfMemory"); final Path policyFile = this.storage.getPath().resolve("olymp.policy"); try (Stream<Path> paths = FileAccess.walkPaths(storage.getPath())) { paths.forEach(path -> {/*from w w w .j a v a 2 s.c o m*/ try { Files.setPosixFilePermissions(path, new HashSet<PosixFilePermission>( Lists.from(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, PosixFilePermission.OTHERS_EXECUTE, PosixFilePermission.OTHERS_READ))); } catch (Exception e) { throw new RuntimeException(e); } }); } this.buildPolicy(chrootRoot, policyFile); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument("--security=0"); commandLine.addArgument("--jail=/"); commandLine.addArgument("--"); commandLine.addArgument("/usr/bin/java"); commandLine.addArgument("-classpath"); commandLine.addArgument(chrootedProgram.toAbsolutePath().toString()); commandLine.addArgument("-Djava.security.manager"); commandLine.addArgument("-Djava.security.policy=" + policyFile.toAbsolutePath().toString()); commandLine.addArgument("-Xmx" + this.getMemoryLimit()); commandLine.addArgument("-Xms" + this.getMemoryLimit()); commandLine.addArgument(MessageFormat.format("-XX:OnOutOfMemoryError=touch {0}; echo \"\" > {0}", outOfMemoryFile.toAbsolutePath().toString()), false); commandLine.addArgument("Main"); final DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(20000)); // 20 seconds for the // sandbox to // complete executor.setWorkingDirectory(chrootRoot.toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); try { executor.execute(commandLine); } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } final ExecutionResult readOlrunnerVerdict = this.readOlrunnerVerdict(chrootRoot.resolve("verdict.txt")); if (FileAccess.exists(outOfMemoryFile)) { readOlrunnerVerdict.setResultType(ExecutionResultType.MEMORY_LIMIT); } readOlrunnerVerdict.setMemoryPeak(this.getMemoryLimit()); return readOlrunnerVerdict; }
From source file:org.ng200.openolympus.cerberus.executors.SandboxedExecutor.java
@Override public ExecutionResult execute(final Path program) throws IOException { SandboxedExecutor.logger.debug("Copying program into jail"); final Path chrootedProgram = this.storage.getPath().resolve("chroot") .resolve(program.getFileName().toString()); chrootedProgram.getParent().toFile().mkdirs(); FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES); final CommandLine commandLine = new CommandLine("sudo"); commandLine.addArgument("olympus_watchdog"); this.setUpOlrunnerLimits(commandLine); commandLine.addArgument(MessageFormat.format("--jail={0}", this.storage.getPath().resolve("chroot").toAbsolutePath().toString())); commandLine.addArgument("--"); commandLine/* w w w . j av a 2 s . c om*/ .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString()); final DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the // sandbox to // complete executor.setWorkingDirectory(this.storage.getPath().toFile()); executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream)); SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString()); try { executor.execute(commandLine); } catch (final ExecuteException e) { SandboxedExecutor.logger.info("Execution failed: {}", e); throw e; } catch (final IOException e) { if (!e.getMessage().toLowerCase().equals("stream closed")) { throw e; } } return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt")); }