List of usage examples for org.apache.commons.exec DefaultExecutor setStreamHandler
public void setStreamHandler(final ExecuteStreamHandler streamHandler)
From source file:org.mail.bridge.FolderMonitor.java
public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) { if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles)) return;// w w w . j a va2 s . c om LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { CommandLine cmd = CommandLine.parse(config.getInboxScript()); for (File file : inboxFiles) cmd.addArgument(file.getName(), true); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(out)); executor.setWatchdog(new ExecuteWatchdog(SCRIPT_TIMEOUT)); Map<String, String> environment = EnvironmentUtils.getProcEnvironment(); environment.putAll(config.asEnvironmentMap()); executor.setWorkingDirectory(new File(System.getProperty("user.dir"))); executor.execute(cmd, environment); LOG.info("Script '{}' successfully finished", config.getInboxScript()); LOG.debug("Script output:\n{}", out.toString()); } catch (ExecuteException e) { LOG.error(e.getMessage(), e); LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString()); int c = config.getInboxScriptStopCode(); if (c != 0 && c == e.getExitValue()) postMessage(new Main.StopMessage( String.format("Script '%s' exited with code %d that is configured as stop code", config.getInboxScript(), c))); } catch (IOException e) { LOG.error(e.getMessage(), e); LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString()); } }
From source file:org.moe.cli.utils.Utils.java
public static String[] execute(File dir, String command, Map<String, String> environment) { Map<String, String> current = null; try {/* w w w. j a va 2s .c om*/ current = EnvironmentUtils.getProcEnvironment(); } catch (IOException e1) { e1.printStackTrace(); } if (environment != null && current != null) { current.putAll(environment); } CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(dir); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); PumpStreamHandler stHandler = new PumpStreamHandler(stdout, stderr); executor.setStreamHandler(stHandler); int exitValue = Executor.INVALID_EXITVALUE; try { exitValue = executor.execute(cmdLine, current); } catch (IOException e) { } return new String[] { stdout.toString(), executor.isFailure(exitValue) ? stderr.toString() : null }; }
From source file:org.ms123.common.management.ManagementServiceImpl.java
private int exec(String line, ByteArrayOutputStream outputStream, ByteArrayOutputStream outputErr, int[] exitValues) throws Exception { CommandLine cmdLine = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValues(exitValues);//from w w w . ja v a 2s . c o m PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, outputErr); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(cmdLine); return exitValue; }
From source file:org.mule.test.infrastructure.process.Controller.java
private int executeSyncCommand(String command, String[] args, Map<Object, Object> newEnv, int timeout) throws MuleControllerException { CommandLine commandLine = new CommandLine(muleBin); commandLine.addArgument(command);// www .ja va 2 s . c om commandLine.addArguments(args); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog); executor.setStreamHandler(new PumpStreamHandler()); return doExecution(executor, commandLine, newEnv); }
From source file:org.mule.test.infrastructure.process.MuleUtils.java
public static int executeCommand(String command, String... envVars) throws IOException { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); Map<String, String> env = addEnvProperties(envVars); ExecuteWatchdog watchDog = new ExecuteWatchdog(TIMEOUT); executor.setWatchdog(watchDog);/*from ww w . ja v a2 s . com*/ executor.setStreamHandler(new PumpStreamHandler()); int result = executor.execute(cmdLine, env); if (executor.isFailure(result)) { if (watchDog.killedProcess()) { throw new RuntimeException("Reached timeout while running: " + cmdLine); } throw new RuntimeException("Process failed with return code [" + result + "]: " + cmdLine); } return result; }
From source file:org.mule.test.infrastructure.process.UnixController.java
@Override public int getProcessId() { Map<Object, Object> newEnv = this.copyEnvironmentVariables(); DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout); executor.setWatchdog(watchdog);//from w w w. j a va 2 s.c om ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); if (this.doExecution(executor, new CommandLine(this.muleBin).addArgument("status"), newEnv) == 0) { Matcher matcher = STATUS_PATTERN.matcher(outputStream.toString()); if (matcher.find()) { return Integer.parseInt(matcher.group(1)); } else { throw new MuleControllerException("bin/mule status didn't return the expected pattern: " + STATUS); } } else { throw new MuleControllerException("Mule ESB is not running"); } }
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//w w w.j ava 2 s.c o 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/*from w w w .j a v a 2s . c o m*/ // 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 v a 2 s .co 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 -> {// w w w. j a va2 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; }