@Override public Long call() throws Exception { Executor executor = new DefaultExecutor(); executor.setProcessDestroyer(new ShutdownHookProcessDestroyer()); ExecuteWatchdog watchDog = new ExecuteWatchdog(watchdogTimeout); executor.setWatchdog(watchDog); executor.setStreamHandler(new PumpStreamHandler(new MyLogOutputStream(handler, true), new MyLogOutputStream(handler, false))); Long exitValue; try { exitValue = new Long(executor.execute(commandline)); } catch (ExecuteException e) { exitValue = new Long(e.getExitValue()); } if (watchDog.killedProcess()) { exitValue = WATCHDOG_EXIST_VALUE; } return exitValue; }
@When("I run maven with args: (.*)") public void runMavenCommand(List<String> mvnArgs) throws IOException { this.mvnArgs.addAll(mvnArgs); System.out.println("Launching Maven with args <" + Joiner.on(" ").join(mvnArgs) + ">"); CommandLine cmdLine = new CommandLine(getCommandLine()); for (String mvnArg : mvnArgs) { cmdLine.addArgument(mvnArg); } if (confdForCucumberLocation != null) { cmdLine.addArgument("-Dcucumber.confd.binary.path=" + confdForCucumberLocation); } DefaultExecutor executor = new DefaultExecutor(); if (projectRootAsFile != null) { executor.setWorkingDirectory(projectRootAsFile); } executor.setExitValue(expectedExitCode); executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() { @Override protected void processLine(String line, int level) { System.out.println(line); executorOutput.add(line); } })); exitCode = executor.execute(cmdLine, environment); fullOutput = Joiner.on(LINE_SEPARATOR).join(executorOutput); }
/** * 日志文件输出方式 * * 优点:支持将目标数据实时输出到指定日志文件中去 * 缺点: * 标准输出和错误输出优先级固定,可能和脚本中顺序不一致 * Java无法实时获取 * * @param command * @param scriptFile * @param logFile * @param params * @return * @throws IOException */ public static int execToFile(String command, String scriptFile, String logFile, String... params) throws IOException { // 标准输出:print (null if watchdog timeout) // 错误输出:logging + 异常 (still exists if watchdog timeout) // 标准输入 FileOutputStream fileOutputStream = new FileOutputStream(logFile, true); PumpStreamHandler streamHandler = new PumpStreamHandler(fileOutputStream, fileOutputStream, null); // command CommandLine commandline = new CommandLine(command); commandline.addArgument(scriptFile); if (params!=null && params.length>0) { commandline.addArguments(params); } // exec DefaultExecutor exec = new DefaultExecutor(); exec.setExitValues(null); exec.setStreamHandler(streamHandler); int exitValue = exec.execute(commandline); // exit code: 0=success, 1=error return exitValue; }
/** * Starts the jekyll build process (jekyll build --incremental) * @return true, if jekyll build was successful */ public boolean startJekyllCI() { int exitValue = -1; String line = JEKYLL_PATH; ByteArrayOutputStream jekyllBuildOutput = new ByteArrayOutputStream(); CommandLine cmdLine = CommandLine.parse(line); cmdLine.addArgument(JEKYLL_OPTION_BUILD); cmdLine.addArgument(JEKYLL_OPTION_INCR); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(new File(LOCAL_REPO_PATH)); PumpStreamHandler streamHandler = new PumpStreamHandler(jekyllBuildOutput); executor.setStreamHandler(streamHandler); try { LOGGER.info("Starting jekyll build"); exitValue = executor.execute(cmdLine); LOGGER.info("Jekyll build command executed"); } catch (IOException e) { LOGGER.error("Error while executing jekyll build. Error message: {}", e.getMessage()); e.printStackTrace(); return false; } printJekyllStatus(exitValue, jekyllBuildOutput.toString()); return true; }
public static void main(String[] args) throws Exception { String cmd = "/tmp/test.sh"; CommandLine cmdLine = CommandLine.parse("/bin/bash " + cmd); ByteArrayOutputStream stdout = new ByteArrayOutputStream(); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr); psh.setStopTimeout(TIMEOUT_FIVE_MINUTES); ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT_TEN_MINUTES); // timeout in milliseconds Executor executor = new DefaultExecutor(); executor.setExitValue(0); executor.setStreamHandler(psh); executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine, Collections.emptyMap()); System.out.println(exitValue); }
public static List<Failure> runH2Spec(File targetDirectory, int port, final int timeout, final int maxHeaderLength, final Set<String> excludeSpecs) throws IOException { File reportsDirectory = new File(targetDirectory, "reports"); if (!reportsDirectory.exists()) { reportsDirectory.mkdir(); } File junitFile = new File(reportsDirectory, "TEST-h2spec.xml"); File h2spec = getH2SpecFile(targetDirectory); Executor exec = new DefaultExecutor(); PumpStreamHandler psh = new PumpStreamHandler(System.out, System.err, System.in); exec.setStreamHandler(psh); exec.setExitValues(new int[]{0, 1}); psh.start(); if (exec.execute(buildCommandLine(h2spec, port, junitFile, timeout, maxHeaderLength)) != 0) { return parseReports(reportsDirectory, excludeSpecs); } psh.stop(); return Collections.emptyList(); }
public void compile(String cwd, Submission submission) throws RuntimeException { CommandLine cmd = new CommandLine(compiler); cmd.addArgument("-basedir=" + cwd); cmd.addArgument("-compiler=" + realCompiler); cmd.addArgument("-filename=" + fileName + "." + suffix); cmd.addArgument("-timeout=" + watchdogTimeout); cmd.addArgument("-std=" + std); logger.info(cmd.toString()); ByteArrayOutputStream stderr = new ByteArrayOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(null, stderr, null)); try { executor.execute(cmd); if (stderr.toString().length() > 0) { submission.setStatus(Submission.STATUS_CE); submission.setError("Compile error"); logger.warn(stderr.toString()); throw new RuntimeException("Sandbox Aborted."); } logger.info("Compile OK"); } catch (IOException e) { logger.warn("Compile error:\t" + e.getMessage()); throw new RuntimeException("An Error Occurred."); } }
/** * Esegue un comando di shell * @param command comando * @param args lista di argomenti (ogni elemento puo' contenere spazi), puo' essere null * @param outputStream ByteArrayOutputStream che conterrà l'output del comando * @return the error message (will be empty for a return code >0), or null if there was no error */ public String exec(String command, List<String> args, ByteArrayOutputStream outputStream) { int exitValue=1; try { CommandLine commandLine = new CommandLine(command); if (args!=null) { for (String arg : args) { commandLine.addArgument(arg, false); // Don't handle quoting } } DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); log.debug("Executing shell command: {}", commandLine); exitValue = executor.execute(commandLine); } catch (Exception e) { log.error("Failed to execute shell command: " + command + " " + args, e); return e.getMessage(); } return exitValue>0?"":null; }
@Override public Map<String,Object> handle (Task aTask) throws Exception { CommandLine cmd = new CommandLine ("mediainfo"); cmd.addArgument(aTask.getRequiredString("input")); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return parse(FileUtils.readFileToString(tempFile)); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
@Override public Object handle(Task aTask) throws Exception { List<String> options = aTask.getList("options", String.class); CommandLine cmd = new CommandLine ("ffmpeg"); options.forEach(o->cmd.addArgument(o)); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); int exitValue = exec.execute(cmd); return exitValue!=0?FileUtils.readFileToString(tempFile):cmd.toString(); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
@Override public Map<String,Object> handle(Task aTask) throws Exception { CommandLine cmd = new CommandLine ("ffprobe"); cmd.addArgument("-v") .addArgument("quiet") .addArgument("-print_format") .addArgument("json") .addArgument("-show_error") .addArgument("-show_format") .addArgument("-show_streams") .addArgument(aTask.getRequiredString("input")); log.debug("{}",cmd); DefaultExecutor exec = new DefaultExecutor(); File tempFile = File.createTempFile("log", null); try (PrintStream stream = new PrintStream(tempFile);) { exec.setStreamHandler(new PumpStreamHandler(stream)); exec.execute(cmd); return parse(FileUtils.readFileToString(tempFile)); } catch (ExecuteException e) { throw new ExecuteException(e.getMessage(),e.getExitValue(), new RuntimeException(FileUtils.readFileToString(tempFile))); } finally { FileUtils.deleteQuietly(tempFile); } }
public static ExecResult setupSudoCredentials(String password) { ExecCommand execCommand = new ExecCommand("sudo"); execCommand.addArgument("--validate", false); execCommand.addArgument("--stdin", false); Executor executor = new DefaultExecutor(); executor.setWorkingDirectory(execCommand.getWorkingDirectory()); executor.setExitValues(execCommand.getExitValues()); ExecOutputStream execOutputStream = new ExecOutputStream(); executor.setStreamHandler(new PumpStreamHandler(execOutputStream, execOutputStream, new ExecInputStream(password))); try { executor.execute(execCommand); } catch (IOException e) { return new ExecResult(execOutputStream.getOutput(), e); } return new ExecResult(execOutputStream.getOutput()); }
@Deprecated public static ExecResult execCommand(CommandLine commandLine, File workDir, int[] exitValues, boolean routeToCapture, boolean routeToStdout) { Executor executor = new DefaultExecutor(); if (workDir != null) { executor.setWorkingDirectory(workDir); } if (exitValues != null) { executor.setExitValues(exitValues); } ExecOutputStream execOutputStream = new ExecOutputStream(routeToCapture, routeToStdout); PumpStreamHandler streamHandler = new PumpStreamHandler(execOutputStream); executor.setStreamHandler(streamHandler); try { executor.execute(commandLine); } catch (IOException e) { return new ExecResult(false, execOutputStream.getOutput(), e); } return new ExecResult(true, execOutputStream.getOutput(), null); }
private String execToString(File model, File properties) throws ExecuteException, IOException { String command; String prism = (System.getProperty("os.name").contains("Windows"))? "prism.bat" : "prism"; if (mConverter.isBoundedNet()) { command = mPrismPath + " " + model.getAbsolutePath() + " " + properties.getAbsolutePath() + " -exportstates " + mFilesPath+mStatesFileName; } else { command = mPrismPath + " " + model.getAbsolutePath() + " " + properties.getAbsolutePath() + " -ex"; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream); //Workbench.consoleMessage("Executing: " + command); exec.setStreamHandler(streamHandler); System.out.println("Executing "+command); exec.execute(commandline); System.out.println("ID-Mapping: "+TransitionToIDMapper.getMapping()); return(outputStream.toString()); }
@BeforeClass public static void setUpBeforeClass() throws Exception { System.out.println("Java Temp Dir: " +System.getProperty("java.io.tmpdir")); executor = new DefaultExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(10000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-" + ContractTestSuite.getProjectVersion() + ".jar") .addArgument("server") .addArgument("src/main/resources/dropwizard/moneta-dropwizard.yaml"), resultHandler); Thread.sleep(3000); System.out.println("Test sequence starting...."); }
public void run() { try { executor = new DaemonExecutor(); resultHandler = new DefaultExecuteResultHandler(); String javaHome = System.getProperty("java.home"); String userDir = System.getProperty("user.dir"); executor.setStreamHandler(new PumpStreamHandler(System.out)); watchdog = new ExecuteWatchdog(15000); executor.setWatchdog(watchdog); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe").addArgument("-version")); executor.execute(new CommandLine(javaHome + SystemUtils.FILE_SEPARATOR + "bin"+ SystemUtils.FILE_SEPARATOR+"java.exe") .addArgument("-jar") .addArgument(userDir + "/../moneta-springboot/target/moneta-springboot-" + ContractTestSuite.getProjectVersion() + ".jar")); } catch (Exception e) { e.printStackTrace(); } }
/** * Run a short living engine command where we expect a process failure as the engine invokes <code>System.exit(-1)</code>. * @param statusCmd * @return the output of the engine command. */ private String executeSynch(CommandLine statusCmd) { String engineOutput = null; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, System.err); Executor executor = createEngineExecutor(); executor.setStreamHandler(streamHandler); executor.setExitValue(-1); try { executor.execute(statusCmd); } catch (IOException ex) { // expected! } finally { engineOutput = outputStream.toString(); IOUtils.closeQuietly(outputStream); } return engineOutput; }
/** * Verify if dot can be started and print out the version to stdout. * * @return True if "dot -V" ran successfully, false otherwise * * @throws IOException If running dot fails. */ public static boolean checkDot() throws IOException { // call graphviz-dot via commons-exec CommandLine cmdLine = new CommandLine(DOT_EXE); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); executor.setExitValue(0); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); int exitValue = executor.execute(cmdLine); if(exitValue != 0) { System.err.println("Could not run '" + DOT_EXE + "', had exit value: " + exitValue + "!"); return false; } return true; }
@Test public void testCommonsCodecsConflicts() throws IOException, VerificationException { SetupContent setupContent = new SetupContent().invoke(); String shadedJar = setupContent.getShadedJar(); String issue24POM = setupContent.getIssue24POM(); String issue24TestFile = setupContent.getIssue24TestFile(); File cwdFile = setupContent.getCwdFile(); String line = String.format("java -jar %s -v -p %s %s %s", shadedJar, issue24POM, issue24TestFile, StringUtils.join(new String[] {cwdFile.getAbsolutePath(), "testCommonsCodecsConflicts.html"}, File.separator)); CommandLine command = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(out, err)); executor.execute(command); }
@Test public void shouldNotOverwriteInputFile() throws IOException, VerificationException { SetupContent setupContent = new SetupContent().invoke(); String shadedJar = setupContent.getShadedJar(); String issue24POM = setupContent.getIssue24POM(); String issue24TestFile = setupContent.getIssue24TestFile(); File specFile = new File(issue24TestFile); File specBackupFile = new File(issue24TestFile + ".orig"); FileUtils.copyFile(specFile, specBackupFile); String line = String.format("java -jar %s -v -p %s %s", shadedJar, issue24POM, issue24TestFile); CommandLine command = CommandLine.parse(line); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(specFile.getParentFile()); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); executor.setStreamHandler(new PumpStreamHandler(out, err)); executor.execute(command); assertTrue("The specification should not be overriden by the output", FileUtils.contentEquals(specFile,specBackupFile)); }
public int getVersion() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = new CommandLine(p4d); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); int version = 0; for (String line : outputStream.toString().split("\\n")) { if (line.startsWith("Rev. P4D")) { Pattern p = Pattern.compile("\\d{4}\\.\\d{1}"); Matcher m = p.matcher(line); while (m.find()) { String found = m.group(); found = found.replace(".", ""); // strip "." version = Integer.parseInt(found); } } } logger.info("P4D Version: " + version); return version; }
@SuppressWarnings("rawtypes") public static void execAsync(String display, CommandLine commandline) throws ShellCommandException { log.debug("executing async command: " + commandline); DefaultExecutor exec = new DefaultExecutor(); ExecuteResultHandler handler = new DefaultExecuteResultHandler(); PumpStreamHandler streamHandler = new PumpStreamHandler( new PritingLogOutputStream()); exec.setStreamHandler(streamHandler); try { if (display == null || display.isEmpty()) { exec.execute(commandline, handler); } else { Map env = EnvironmentUtils.getProcEnvironment(); EnvironmentUtils.addVariableToEnvironment(env, "DISPLAY=:" + display); exec.execute(commandline, env, handler); } } catch (Exception e) { throw new ShellCommandException( "An error occured while executing shell command: " + commandline, e); } }
protected void startTranscode() { try { logger.info("Starting transcode"); notifyObservers(SessionEvent.PRESTART, null); this.outstream = new TranscodeSessionOutputStream(this); this.resultHandler = new TranscodeSessionResultHandler(this.watchdog, this); this.executor.setWorkingDirectory(new File(this.workingDirectoryPath)); this.executor.setStreamHandler(new PumpStreamHandler(this.outstream)); this.executor.setProcessDestroyer(new TranscodeSessionDestroyer(this)); this.executor.setWatchdog(this.watchdog); this.executor.setExitValue(0); this.executor.execute(this.cmdLine, this.resultHandler); } catch (Exception e) { logger.info("Error starting process " + e.getMessage()); } }
public static int executeCommand(String command,ExecuteWatchdog watchdog) { CommandLine cmdLine = CommandLine.parse(command); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out,System.err, null)); executor.setExitValues(new int[]{0, 1}); if(watchdog != null){ executor.setWatchdog(watchdog); } int exitValue = 0; try { exitValue = executor.execute(cmdLine); } catch (IOException e) { exitValue = 1; log.error("error executing command", e); } return exitValue; }
@Override protected final void executeGoal() throws MojoExecutionException { init(); LOG.info("command={}", command); LOG.info("arguments={}", Arrays.toString(arguments)); final CommandLine cmdLine = createCommandLine(); final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); final DaemonExecutor executor = new DaemonExecutor(); try { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PumpStreamHandler psh = new PumpStreamHandler(bos); executor.setStreamHandler(psh); executor.setWorkingDirectory(getEventStoreDir()); executor.execute(cmdLine, resultHandler); final List<String> messages = waitForHttpServer(resultHandler, bos); logDebug(messages); final String pid = extractPid(messages); LOG.info("Event store process ID: {}", pid); writePid(pid); } catch (final IOException ex) { throw new MojoExecutionException( "Error executing the command line: " + cmdLine, ex); } }
private CmdResultHandler runAsync(String command, CmdResultHandler resultHandler, boolean shouldClone) throws IOException, IOException, IOException, IOException { CmdResultHandler handler = shouldClone ? resultHandler.clone() : resultHandler; PumpStreamHandler streamHandler = handler.getStreamHandler(this); Executor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); // String[] arguments = CommandLine.parse(command).toStrings(); // CommandLine cmdLine = new CommandLine(arguments[0]); // for (int i = 1; i < arguments.length; i++) { // cmdLine.addArgument(command, true); // } CommandLine cmdLine = CommandLine.parse(command); executor.execute(cmdLine, getEnvironment(), handler.delegate); return handler; }
static public CommandLineResult runCommand(String command, boolean throwException) throws SakuliException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); CommandLineResult result = new CommandLineResult(); try { DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(outputStream, error)); int exitCode = executor.execute(CommandLine.parse(command)); result.setExitCode(exitCode); result.setOutput(error.toString() + outputStream.toString()); } catch (Exception e) { if (throwException) { throw new SakuliException(e, String.format("Error during execution of command '%s': %s", command, error.toString())); } result.setExitCode(resolveExitCode(e.getMessage())); result.setOutput(e.getMessage()); } return result; }
@Override protected void doRebuild() throws DevShellRebuildException { System.out.println( "Reload!" ); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream output = new ByteArrayOutputStream(); executor.setStreamHandler( new PumpStreamHandler( output ) ); try { int exitValue = executor.execute( cmdLine ); if( exitValue != 0 ) { throw new DevShellRebuildException( new MavenExecutionException( "Maven exited with a non-zero status: " + exitValue, pom ) ); } } catch( Exception ex ) { throw new DevShellRebuildException( ex, output.toString() ); } }
public int unload(String loadedInputPath) throws Exception { String unloaderDir = platformConfig.getUnloaderPath(); commandLine = new CommandLine(Paths.get(unloaderDir).toFile()); commandLine.addArgument("--graph-name"); commandLine.addArgument(formattedGraph.getName()); commandLine.addArgument("--output-path"); commandLine.addArgument(loadedInputPath); String commandString = StringUtils.toString(commandLine.toStrings(), " "); LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString)); Executor executor = new DefaultExecutor(); executor.setStreamHandler(new PumpStreamHandler(System.out, System.err)); executor.setExitValue(0); return executor.execute(commandLine); }
public static void launchContrailServer(int port) throws Exception { try { DefaultExecutor exec = new DefaultExecutor(); int exitValues[] = {1}; exec.setExitValues(exitValues); String workingDir = System.getProperty("user.dir"); String path = workingDir + "/../../config/api-server/tests/"; File f = new File(path); exec.setWorkingDirectory(f); exec.setStreamHandler(new PumpStreamHandler(new ByteArrayOutputStream())); CommandLine cmd = buildServerLaunchCmd(port); ExecuteResultHandler handler = null; exec.execute(cmd, handler); /* sleep 5 seconds for server to get started */ Thread.sleep(5000); } catch (Exception e) { s_logger.debug(e); String cause = e.getMessage(); if (cause.equals("python: not found")) System.out.println("No python interpreter found."); throw e; } }
public int getVersion() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine cmdLine = new CommandLine(p4d); cmdLine.addArgument("-V"); DefaultExecutor executor = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(cmdLine); int version = 0; for (String line : outputStream.toString(Charset.forName("UTF-8")).split("\\n")) { if (line.startsWith("Rev. P4D")) { Pattern p = Pattern.compile("\\d{4}\\.\\d{1}"); Matcher m = p.matcher(line); while (m.find()) { String found = m.group(); found = found.replace(".", ""); // strip "." version = Integer.parseInt(found); } } } logger.info("P4D Version: " + version); return version; }
public static ExecuteWatchdog execASync(String line, File workDir, Map<String, String> environment, OutputStream output, ExecuteResultHandler erh, long timeout) throws IOException { if (environment != null) { Map<String, String> sysenv = System.getenv(); for (String key : sysenv.keySet()) { boolean contains = false; for (String k : environment.keySet()) { if (k.equalsIgnoreCase(key)) { contains = true; break; } } if (!contains) environment.put(key, sysenv.get(key)); } } DefaultExecutor executor = new DefaultExecutor(); if (workDir != null) executor.setWorkingDirectory(workDir); PumpStreamHandler sh = new PumpStreamHandler(output, output, null); executor.setStreamHandler(sh); ExecuteWatchdog watchdog = new ProcessTreeWatchDog(timeout); executor.setWatchdog(watchdog); executor.execute(CommandLine.parse(line), environment, erh); return watchdog; }
public static ExecuteWatchdog execASync(String line, File workDir, Map<String, String> environment, OutputStream output, ExecuteResultHandler erh, long timeout, Logger log) throws IOException { if (environment != null) { Map<String, String> sysenv = System.getenv(); for (String key : sysenv.keySet()) { boolean contains = false; for (String k : environment.keySet()) { if (k.equalsIgnoreCase(key)) { contains = true; break; } } if (!contains) environment.put(key, sysenv.get(key)); } } DefaultExecutor executor = new DefaultExecutor(); if (workDir != null) executor.setWorkingDirectory(workDir); PumpStreamHandler sh = new PumpStreamHandler(output, output, null); executor.setStreamHandler(sh); ExecuteWatchdog watchdog = new ProcessTreeWatchDog(timeout, log); executor.setWatchdog(watchdog); executor.execute(CommandLine.parse(line), environment, erh); return watchdog; }
public void processFile(File file) throws IOException { CommandLine cmdLine = new CommandLine(executable); cmdLine.addArguments(arguments); Map<String, Object> map = new HashMap<>(); map.put(SubstitutionHelper.FILE, file); cmdLine.setSubstitutionMap(map); DefaultExecutor executor = new DefaultExecutor(); // executor.setExitValue(1); // NotifierLogOutputStream outputLog = new NotifierLogOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(logOutputStream); executor.setStreamHandler(psh); // ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); // executor.setWatchdog(watchdog); int exitValue = executor.execute(cmdLine); }
public CommandResult execute(CommandLine commandLine, File workingDirectory, OutputStream outputStream) { CommandResult commandResult = new CommandResult(); try { // create executor for command DefaultExecutor executor = new DefaultExecutor(); // set working directory if (workingDirectory != null) { executor.setWorkingDirectory(workingDirectory); } // set possible exit values executor.setExitValues(IntStream.range(0, 255).toArray()); // create output stream for command ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); TeeOutputStream teeOutputStream = new TeeOutputStream(outputStream, byteArrayOutputStream); PumpStreamHandler streamHandler = new PumpStreamHandler(teeOutputStream); executor.setStreamHandler(streamHandler); // execute command int exitValue = executor.execute(commandLine); // fill command result commandResult.setOutput(byteArrayOutputStream.toString()); commandResult.setSuccess(exitValue == 0 ? true : false); } catch(IOException e) { LOG.error(e.getMessage(), e); } return commandResult; }
public String execToString(String command) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CommandLine commandline = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); exec.execute(commandline); return (outputStream.toString()); }
public void compile(String cwd, Submission submission) throws RuntimeException { ByteArrayOutputStream stderr = new ByteArrayOutputStream(); ExecuteWatchdog watchdog = new ExecuteWatchdog(watchdogTimeout); DefaultExecutor executor = new DefaultExecutor(); executor.setWorkingDirectory(new File(cwd)); executor.setStreamHandler(new PumpStreamHandler(null, stderr, null)); executor.setWatchdog(watchdog); CommandLine cmd = new CommandLine(javac); cmd.addArgument("-J-Duser.language=en"); // force using English cmd.addArgument("-classpath"); cmd.addArgument(cwd); cmd.addArgument(fileName + ".java"); logger.info("Compiler cmd:\t" + cmd.toString()); try { executor.execute(cmd); logger.info("Compile OK"); } catch (IOException e) { if (watchdog.killedProcess()) { submission.setStatus(Submission.STATUS_CE); submission.setError("Compile Time Exceeded"); logger.warn("Compile Time Exceeded:\t" + e.getMessage()); } else { submission.setStatus(Submission.STATUS_CE); submission.setError("Compile error"); logger.warn("Compile error:\t" + e.getMessage()); } logger.warn(stderr.toString()); throw new RuntimeException("Compile Aborted."); } }
private String execute(List<String> subCommands) throws IOException { CommandLine cmd = new CommandLine("calendar-cli.py"); cmd.addArgument("--caldav-url"); cmd.addArgument(caldavURL); cmd.addArgument("--caldav-user"); cmd.addArgument(caldavUser); cmd.addArgument("--caldav-pass"); cmd.addArgument(caldavPassword); cmd.addArgument("--calendar-url"); cmd.addArgument(calendarURL); for(String subCommand : subCommands) { cmd.addArgument(subCommand); } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DefaultExecutor exec = new DefaultExecutor(); final PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); exec.setStreamHandler(streamHandler); try { doExecute(cmd, exec); }catch(IOException e) { log.error("Error on executing calendar-cli.py.\nCommand: {}\nOutput: {}", cmd.toString(), outputStream.toString()); throw e; } return outputStream.toString(); }
private ExecuteStreamHandler createStreamHandler() throws IOException { out = new ByteArrayOutputStream(); err = new ByteArrayOutputStream(); PipedOutputStream outPiped = new PipedOutputStream(); InputStream inPiped = new PipedInputStream(outPiped); in = outPiped; TeeOutputStream teeOut = new TeeOutputStream(out, System.out); TeeOutputStream teeErr = new TeeOutputStream(err, System.err); return new PumpStreamHandler(teeOut, teeErr, inPiped); }