org.apache.commons.exec.Executor.setStreamHandler()方法的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(145)

本文整理了Java中org.apache.commons.exec.Executor.setStreamHandler()方法的一些代码示例,展示了Executor.setStreamHandler()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Executor.setStreamHandler()方法的具体详情如下:
包路径:org.apache.commons.exec.Executor
类名称:Executor
方法名:setStreamHandler

Executor.setStreamHandler介绍

[英]Set a custom the StreamHandler used for providing input and retrieving the output. If you don't provide a proper stream handler the executed process might block when writing to stdout and/or stderr (see java.lang.Process).
[中]设置用于提供输入和检索输出的自定义StreamHandler。如果您没有提供正确的流处理程序,那么在写入stdout和/或stderr时,执行的进程可能会阻塞(请参阅java.lang.process)。

代码示例

代码示例来源:origin: eirslett/frontend-maven-plugin

private int execute(final Logger logger, final OutputStream stdout, final OutputStream stderr)
    throws ProcessExecutionException {
  logger.debug("Executing command line {}", commandLine);
  try {
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(stdout, stderr);
    executor.setStreamHandler(streamHandler);
    int exitValue = executor.execute(commandLine, environment);
    logger.debug("Exit value {}", exitValue);
    return exitValue;
  } catch (ExecuteException e) {
    if (executor.getWatchdog() != null && executor.getWatchdog().killedProcess()) {
      throw new ProcessExecutionException("Process killed after timeout");
    }
    throw new ProcessExecutionException(e);
  } catch (IOException e) {
    throw new ProcessExecutionException(e);
  }
}

代码示例来源:origin: openhab/openhab1-addons

executor.setStreamHandler(streamHandler);
executor.setWatchdog(watchdog);

代码示例来源:origin: BroadleafCommerce/BroadleafCommerce

protected String executeExternalJavaProcess(Class<?> mainClass) throws IOException {
    String classpath = MvelTestUtils.getClassPath();
    
    //See javadoc on MvelOverloadFailureReproduction for description of why we need to execute the test in a new JVM
    CommandLine cmdLine = new CommandLine("java");
    cmdLine.addArgument("-cp");
    cmdLine.addArgument(classpath, true);
    cmdLine.addArgument(mainClass.getName());

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(baos));
    try {
      executor.execute(cmdLine, new HashMap<String, String>());
    } catch (IOException e) {
      throw new IOException(new String(baos.toByteArray()));
    }
    return new String(baos.toByteArray());
  }
}

代码示例来源:origin: com.datastax.cassandra/cassandra-driver-core

closer.register(errStream);
ExecuteStreamHandler streamHandler = new PumpStreamHandler(outStream, errStream);
executor.setStreamHandler(streamHandler);
executor.setWatchdog(watchDog);
int retValue = executor.execute(cli, ENVIRONMENT_MAP);

代码示例来源:origin: com.netflix.genie/genie-web

/**
 * Get an {@link Executor} to use for executing processes from tasks.
 *
 * @return The executor to use
 */
@Bean
public Executor processExecutor() {
  final Executor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(null, null));
  return executor;
}

代码示例来源:origin: org.seleniumhq.selenium/selenium-iphone-driver

private static Executor getOutputIgnoringExecutor() {
  Executor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(null, null));
  return executor;
 }
}

代码示例来源:origin: ro.isdc.wro4j/wro4j-extensions

/**
 * @VisibleForTesting
 */
void doProcess(final InputStream in, final OutputStream out)
  throws IOException {
 final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
 final Executor executor = new DefaultExecutor();
 executor.setStreamHandler(new PumpStreamHandler(out, errorStream, in));
 final int result = executor.execute(CommandLine.parse(NGANN_COMMAND));
 LOG.debug("result={}", result);
 if (result != 0) {
  throw new ExecuteException("Processing failed: " + new String(errorStream.toByteArray()), result);
 }
}

代码示例来源:origin: alexo/wro4j

/**
 * @VisibleForTesting
 */
void doProcess(final InputStream in, final OutputStream out)
  throws ExecuteException, IOException {
 final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
 final Executor executor = new DefaultExecutor();
 executor.setStreamHandler(new PumpStreamHandler(out, errorStream, in));
 final int result = executor.execute(CommandLine.parse(NGMIN_COMMAND));
 LOG.debug("result={}", result);
 if (result != 0) {
  throw new ExecuteException("Processing failed: " + new String(errorStream.toByteArray()), result);
 }
}

代码示例来源:origin: ro.isdc.wro4j/wro4j-extensions

/**
 * @VisibleForTesting
 */
void doProcess(final InputStream in, final OutputStream out)
  throws ExecuteException, IOException {
 final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
 final Executor executor = new DefaultExecutor();
 executor.setStreamHandler(new PumpStreamHandler(out, errorStream, in));
 final int result = executor.execute(CommandLine.parse(NGMIN_COMMAND));
 LOG.debug("result={}", result);
 if (result != 0) {
  throw new ExecuteException("Processing failed: " + new String(errorStream.toByteArray()), result);
 }
}

代码示例来源:origin: org.seleniumhq.selenium/selenium-iphone-driver

public void launch() {
 Executor executor = new DefaultExecutor();
 executor.setStreamHandler(new PumpStreamHandler(createOutputStream()));
 try {
  exitCode = executor.execute(commandLine);
 } catch (IOException e) {
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: org.seleniumhq.selenium/selenium-iphone-driver

public void shutdown() {
 try {
  File scriptFile = File.createTempFile("iWebDriver.kill.", ".script");
  FileWriter writer = new FileWriter(scriptFile);
  writer.write("ps ax | grep 'iPhone Simulator' | grep -v grep | awk '{print $1}' | xargs kill");
  writer.flush();
  writer.close();
  FileHandler.makeExecutable(scriptFile);
  CommandLine killCommandLine = CommandLine.parse(scriptFile.getAbsolutePath());
  Executor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(null, null));
  getOutputIgnoringExecutor().execute(killCommandLine);
 } catch (Exception ignored) {
 }
 // Wait until the process really quits (nothing is bound to port 3001)
 // TODO something other than Thread.sleep
 // client = new HttpClientFactory().getHttpClient();
 try {
   Thread.sleep(5000);
 } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
 }
 exitCode = null;
}

代码示例来源:origin: com.addc.mojo/addc-mojo

/**
   * Execute the sub-process
   *
   * @param executor
   *            The executor to use
   * @param cmdLine
   *            The command line to execute
   * @param streamHandler
   *            The stream handler to use
   * @throws MojoExecutionException
   *             If the process execution fails
   */
  protected void executeTarget(Executor executor, CommandLine cmdLine, PumpStreamHandler streamHandler)
      throws MojoExecutionException {
    executor.setStreamHandler(streamHandler);
    try {
      executor.execute(cmdLine);
    } catch (IOException e) {
      getLog().error("Failed to run " + cmdLine.getExecutable(), e);
      throw new MojoExecutionException("Failed to run " + cmdLine.getExecutable(), e);
    }
  }
}

代码示例来源:origin: nidi3/graphviz-java

public void execute(CommandLine cmd, @Nullable File workingDirectory) throws InterruptedException, IOException {
    LOG.info("executing command {}", cmd.toString());

    final ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    final Executor executor = new org.apache.commons.exec.DefaultExecutor();

    executor.setWatchdog(watchdog);
    if (workingDirectory != null) {
      executor.setWorkingDirectory(workingDirectory);
    }
    LOG.debug("workdir: {}", executor.getWorkingDirectory());

    final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ByteArrayOutputStream err = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(out, err));
    executor.execute(cmd, resultHandler);
    resultHandler.waitFor();

    final int exitCode = resultHandler.getExitValue();
    if (out.size() > 0) {
      LOG.info(out.toString());
    }
    if (exitCode != 0) {
      throw new IOException(err.size() == 0 ? "command '" + cmd + "' didn't succeed" : err.toString());
    }
  }
}

代码示例来源:origin: ru.yandex.qatools.camelot/camelot-utils

/**
 * Run Jetty in separate fork at http://localhost:{@link #port}/{@link #contextPath}. Use {@link #webAppDirectory}
 * as web application context war.
 *
 * @throws Exception if can't start Jetty server.
 */
protected void runForked() throws Exception { //NOSONAR
  String commandLine = createCommandLine();
  logger.info(String.format("Executing 'java %s'", commandLine));
  CommandLine cmdLine = CommandLine.parse(commandLine);
  Executor executor = CamelotRunnerUtils.createExecutor();
  DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
  executor.setStreamHandler(createStreamHandler());
  if (waitFor) { // shutdown process if we were killed while waiting for it
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
  }
  executor.execute(cmdLine, resultHandler);
  if (waitFor) {
    logger.info("Waiting until process is finished...");
    resultHandler.waitFor();
  } else {
    logger.info("Waiting until camelot is deployed...");
    while (!release) {
      sleep(2000);
    }
    logger.info(String.format(" ==== Camelot is STARTED at http://localhost:%s%s ==== ", port, contextPath));
  }
}

代码示例来源:origin: com.github.becausetesting/commons

/**
 * Execute a command on the operating system using Apache Commons Exec. This
 * function runs asynchronously and dumps both stderr and stdout streams to
 * a temp file.
 *
 * @param commandLine
 *            The command to be executed.
 * @param outputStreamHandler
 *            An output stream to dump the process stderr and stdout to it.
 */
public static void runCommandUsingApacheExec(CommandLine commandLine, OutputStream outputStreamHandler) {
  try {
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamHandler);
    logger.info("commandLine: " + commandLine.toString());
    Executor process = new DefaultExecutor();
    process.setExitValue(0);
    process.setStreamHandler(streamHandler);
    process.execute(commandLine, resultHandler);
    // resultHandler.waitFor();
  } catch (Exception ex) {
    logger.error("An exception was thrown.", ex);
  }
}

代码示例来源:origin: com.github.becauseQA/becauseQA-utils

/**
 * Execute a command on the operating system using Apache Commons Exec. This
 * function runs asynchronously and dumps both stderr and stdout streams to
 * a temp file.
 *
 * @param commandLine
 *            The command to be executed.
 * @param outputStreamHandler
 *            An output stream to dump the process stderr and stdout to it.
 */
public static void runCommandUsingApacheExec(CommandLine commandLine, OutputStream outputStreamHandler) {
  try {
    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStreamHandler);
    logger.info("commandLine: " + commandLine.toString());
    Executor process = new DefaultExecutor();
    process.setExitValue(0);
    process.setStreamHandler(streamHandler);
    process.execute(commandLine, resultHandler);
    // resultHandler.waitFor();
  } catch (Exception ex) {
    logger.error("An exception was thrown.", ex);
  }
}

代码示例来源:origin: jFastCGI/jfastcgi

pe.setWatchdog(new ExecuteWatchdog(60000));
processExecutor.setStreamHandler(new ExecuteStreamHandler() {

代码示例来源:origin: com.hotels/shunting-yard-replicator

public void run(Context context) {
 try (OutputStream out = outStream(context); OutputStream err = errStream(context)) {
  CommandLine cli = CommandLine
    .parse(String.format("%s/%s", getProcEnvironment().get(CIRCUS_TRAIN_HOME_ENV_VAR), CIRCUS_TRAIN_HOME_SCRIPT));
  cli.addArgument("--config=" + context.getConfigLocation());
  if (!StringUtils.isEmpty(context.getCircusTrainConfigLocation())) {
   cli.addArgument("--config=" + context.getCircusTrainConfigLocation());
  }
  Executor executor = new DefaultExecutor();
  executor.setWorkingDirectory(new File(context.getWorkspace()));
  executor.setStreamHandler(new PumpStreamHandler(out, err));
  log.debug("Executing {} with environment {}", cli, getProcEnvironment());
  int returnValue = executor.execute(cli, getProcEnvironment());
  log.debug("Command exited with value {} ", returnValue);
  if (returnValue != 0) {
   throw new CircusTrainException("Circus Train exited with error value " + returnValue);
  }
 } catch (Throwable e) {
  log.error("Unable to execute Circus Train", e);
 }
}

代码示例来源:origin: net.jangaroo/jangaroo-maven-plugin

private static void internalExecute(CommandLine cmdLine, OutputStream outputStream, File workingDirectory) throws IOException {
 Executor executor = getExecutor();
 ExecuteWatchdog watchdog = getExecuteWatchdog();
 executor.setWatchdog(watchdog);
 if (workingDirectory != null) {
  executor.setWorkingDirectory(workingDirectory);
 }
 // set allowed exit values (0 is actually the default)
 executor.setExitValue(0);
 PumpStreamHandler psh = new PumpStreamHandler(outputStream);
 executor.setStreamHandler(psh);
 executor.execute(cmdLine);
 if (watchdog.killedProcess()) {
  throw new ExecuteException(String.format("Watchdog killed Sencha Cmd process after %s ms.", MAX_EXECUTION_TIME), 0);
 }
}

代码示例来源:origin: danielflower/app-runner

private static Executor createExecutor(LineConsumer consoleLogHandler, CommandLine command, File projectRoot, ExecuteWatchdog watchDog) {
  Executor executor = new DefaultExecutor();
  executor.setWorkingDirectory(projectRoot);
  executor.setWatchdog(watchDog);
  executor.setStreamHandler(new PumpStreamHandler(new WriterOutputStream(new WriterToOutputBridge(consoleLogHandler))));
  consoleLogHandler.consumeLine(fullPath(executor.getWorkingDirectory()) + "> " + String.join(" ", command.toStrings()) + LINE_SEPARATOR);
  return executor;
}

相关文章