當前位置: 首頁>>代碼示例>>Java>>正文


Java DefaultExecutor.execute方法代碼示例

本文整理匯總了Java中org.apache.commons.exec.DefaultExecutor.execute方法的典型用法代碼示例。如果您正苦於以下問題:Java DefaultExecutor.execute方法的具體用法?Java DefaultExecutor.execute怎麽用?Java DefaultExecutor.execute使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.commons.exec.DefaultExecutor的用法示例。


在下文中一共展示了DefaultExecutor.execute方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: runMavenCommand

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
@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);
}
 
開發者ID:nodevops,項目名稱:confd-maven-plugin,代碼行數:27,代碼來源:MavenRunnerStepdefs.java

示例2: triggerThreadDump

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
private void triggerThreadDump() {
    String kill = findBinary("kill");
    
    if (kill != null) {
        for (final Integer pid : getOpenNMSProcesses()) {
            LogUtils.debugf(this, "pid = " + pid);
            CommandLine command = CommandLine.parse(kill + " -3 " + pid.toString());
            try {
                LogUtils.tracef(this, "running '%s'", command.toString());
                DefaultExecutor executor = new DefaultExecutor();
                executor.setWatchdog(new ExecuteWatchdog(5000));
                int exitValue = executor.execute(command);
                LogUtils.tracef(this, "finished '%s'", command.toString());
                if (exitValue != 0) {
                    LogUtils.warnf(this, "'%s' exited non-zero: %d", command.toString(), exitValue);
                }
            } catch (final Exception e) {
                LogUtils.warnf(this, e, "Unable to run kill -3 on '%s': you might need to run system-report as root.", pid.toString());
            }
        }
    }
}
 
開發者ID:qoswork,項目名稱:opennmszh,代碼行數:23,代碼來源:ThreadReportPlugin.java

示例3: execToFile

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
/**
 * 日誌文件輸出方式
 *
 * 優點:支持將目標數據實時輸出到指定日誌文件中去
 * 缺點:
 *      標準輸出和錯誤輸出優先級固定,可能和腳本中順序不一致
 *      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;
}
 
開發者ID:mmwhd,項目名稱:stage-job,代碼行數:37,代碼來源:ScriptUtil.java

示例4: startJekyllCI

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:adessoAG,項目名稱:jekyll2cms,代碼行數:28,代碼來源:JekyllService.java

示例5: compile

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
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.");
    }
}
 
開發者ID:justice-oj,項目名稱:dispatcher,代碼行數:34,代碼來源:JavaWorker.java

示例6: compile

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
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.");
    }
}
 
開發者ID:justice-oj,項目名稱:dispatcher,代碼行數:27,代碼來源:CLikeWorker.java

示例7: exec

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:xtianus,項目名稱:yadaframework,代碼行數:28,代碼來源:YadaUtil.java

示例8: execute

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
  if (!Files.isExecutable(file)) {
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    Files.setPosixFilePermissions(file, perms);
  }

  ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
  CommandLine cmd = new CommandLine(file.toFile());
  cmd.addArguments(args);
  DefaultExecutor exec = new DefaultExecutor();
  exec.setWatchdog(watchdog);
  exec.setStreamHandler(createStreamHandler());
  exec.setExitValues(null);
  if (workingDir != null) {
    exec.setWorkingDirectory(workingDir.toFile());
  }
  in.close();
  LOG.info("Executing: {}", cmd.toString());
  Map<String, String> env = new HashMap<>(System.getenv());
  env.putAll(addEnv);
  return exec.execute(cmd, env);
}
 
開發者ID:SonarSource,項目名稱:sonarlint-cli,代碼行數:25,代碼來源:CommandExecutor.java

示例9: handle

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
@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);
  }
}
 
開發者ID:creactiviti,項目名稱:piper,代碼行數:20,代碼來源:Mediainfo.java

示例10: handle

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
@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);
  }
}
 
開發者ID:creactiviti,項目名稱:piper,代碼行數:21,代碼來源:Ffmpeg.java

示例11: handle

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
@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);
  }
}
 
開發者ID:creactiviti,項目名稱:piper,代碼行數:27,代碼來源:Ffprobe.java

示例12: runCancelJob

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
            TaskEvent taskEvent = (TaskEvent) message.taskEvent;
            String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), message.jobId);
            String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), message.jobId);
            Worker.Result result = new Worker.Result(-9, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, message);
            getSender().tell(new Worker.WorkFailed(result), getSelf());
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}
 
開發者ID:Abiy,項目名稱:distGatling,代碼行數:22,代碼來源:JarExecutor.java

示例13: runCancelJob

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}
 
開發者ID:Abiy,項目名稱:distGatling,代碼行數:17,代碼來源:ScriptExecutor.java

示例14: exec

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
void exec(String action, File dir, CommandLine cmdLine) {
    String label = action + ": " + cmdLine;
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(dir);
        Map<String, String> environment = EnvironmentUtils.getProcEnvironment();
        environment.put("PATH", environment.get("PATH") + ":" + new File(frontendDirectory, "node").getAbsolutePath());
        int exitValue = executor.execute(cmdLine, environment);
        if (exitValue == 0) {
            getLog().info(label + ": OK");
        } else {
            throw new MojoExecutionException("EXEC FAILURE: " + label);
        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        throw new IllegalStateException("EXEC FAILURE: " + label, e);
    }
}
 
開發者ID:spirylics,項目名稱:web2app,代碼行數:20,代碼來源:Web2AppMojo.java

示例15: execute

import org.apache.commons.exec.DefaultExecutor; //導入方法依賴的package包/類
/**
 * Executes the given command synchronously.
 *
 * @param command The command to execute.
 * @param processInput Input provided to the process.
 * @return The result of the execution, or empty if the process does not terminate within the timeout set for this executor.
 * @throws IOException if the process execution failed.
 */
public Optional<ProcessResult> execute(String command, String processInput) throws IOException {
    ByteArrayOutputStream processErr = new ByteArrayOutputStream();
    ByteArrayOutputStream processOut = new ByteArrayOutputStream();

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(createStreamHandler(processOut, processErr, processInput));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(TimeUnit.SECONDS.toMillis(timeoutSeconds));
    executor.setWatchdog(watchDog);
    executor.setExitValues(successExitCodes);

    int exitCode;
    try {
        exitCode = executor.execute(CommandLine.parse(command));
    } catch (ExecuteException e) {
        exitCode = e.getExitValue();
    }
    return (watchDog.killedProcess()) ?
            Optional.empty() : Optional.of(new ProcessResult(exitCode, processOut.toString(), processErr.toString()));
}
 
開發者ID:vespa-engine,項目名稱:vespa,代碼行數:28,代碼來源:ProcessExecutor.java


注:本文中的org.apache.commons.exec.DefaultExecutor.execute方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。