Java Code Examples for org.apache.commons.exec.DefaultExecuteResultHandler#waitFor()

The following examples show how to use org.apache.commons.exec.DefaultExecuteResultHandler#waitFor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CommonsExecAsyncInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
private static CompletableFuture<AbstractSpan<?>> asyncProcessHasTransactionContext() throws Exception {
    final CompletableFuture<AbstractSpan<?>> future = new CompletableFuture<>();
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler() {

        // note: calling super is required otherwise process termination is not detected and waits forever

        @Override
        public void onProcessComplete(int exitValue) {
            super.onProcessComplete(exitValue);
            if (exitValue == 0) {
                future.complete(tracer.getActive());
            } else {
                future.completeExceptionally(new IllegalStateException("Exit value is not 0: " + exitValue));
            }
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            super.onProcessFailed(e);
            future.completeExceptionally(e);
        }
    };

    new DefaultExecutor().execute(new CommandLine(getJavaBinaryPath()).addArgument("-version"), handler);
    handler.waitFor();

    assertThat(future.isCompletedExceptionally())
        .describedAs("async process should have properly executed")
        .isFalse();

    return future;
}
 
Example 2
Source File: CommonsExecOsCommandOperations.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
private Future<CommandResult> executeCommand(String command, File executionDirectory, boolean silent)
		throws IOException {

	StringWriter writer = new StringWriter();
	DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

	try (WriterOutputStream outputStream = new WriterOutputStream(writer)) {

		String outerCommand = "/bin/bash -lc";

		CommandLine outer = CommandLine.parse(outerCommand);
		outer.addArgument(command, false);

		DefaultExecutor executor = new DefaultExecutor();
		executor.setWorkingDirectory(executionDirectory);
		executor.setStreamHandler(new PumpStreamHandler(silent ? outputStream : System.out, null));
		executor.execute(outer, ENVIRONMENT, resultHandler);

		resultHandler.waitFor();

	} catch (InterruptedException e) {
		throw new IllegalStateException(e);
	}

	return new AsyncResult<CommandResult>(
			new CommandResult(resultHandler.getExitValue(), writer.toString(), resultHandler.getException()));
}
 
Example 3
Source File: SolrCLI.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
protected Map<String,Object> startSolr(File solrHomeDir,
                                       boolean cloudMode,
                                       CommandLine cli,
                                       int port,
                                       String zkHost,
                                       int maxWaitSecs)
    throws Exception
{

  String extraArgs = readExtraArgs(cli.getArgs());

  String host = cli.getOptionValue('h');
  String memory = cli.getOptionValue('m');

  String hostArg = (host != null && !"localhost".equals(host)) ? " -h "+host : "";
  String zkHostArg = (zkHost != null) ? " -z "+zkHost : "";
  String memArg = (memory != null) ? " -m "+memory : "";
  String cloudModeArg = cloudMode ? "-cloud " : "";
  String forceArg = cli.hasOption("force") ? " -force" : "";

  String addlOpts = cli.getOptionValue('a');
  String addlOptsArg = (addlOpts != null) ? " -a \""+addlOpts+"\"" : "";

  File cwd = new File(System.getProperty("user.dir"));
  File binDir = (new File(script)).getParentFile();

  boolean isWindows = (OS.isFamilyDOS() || OS.isFamilyWin9x() || OS.isFamilyWindows());
  String callScript = (!isWindows && cwd.equals(binDir.getParentFile())) ? "bin/solr" : script;

  String cwdPath = cwd.getAbsolutePath();
  String solrHome = solrHomeDir.getAbsolutePath();

  // don't display a huge path for solr home if it is relative to the cwd
  if (!isWindows && cwdPath.length() > 1 && solrHome.startsWith(cwdPath))
    solrHome = solrHome.substring(cwdPath.length()+1);

  String startCmd =
      String.format(Locale.ROOT, "\"%s\" start %s -p %d -s \"%s\" %s %s %s %s %s %s",
          callScript, cloudModeArg, port, solrHome, hostArg, zkHostArg, memArg, forceArg, extraArgs, addlOptsArg);
  startCmd = startCmd.replaceAll("\\s+", " ").trim(); // for pretty printing

  echo("\nStarting up Solr on port " + port + " using command:");
  echo(startCmd + "\n");

  String solrUrl =
      String.format(Locale.ROOT, "%s://%s:%d/solr", urlScheme, (host != null ? host : "localhost"), port);

  Map<String,Object> nodeStatus = checkPortConflict(solrUrl, solrHomeDir, port, cli);
  if (nodeStatus != null)
    return nodeStatus; // the server they are trying to start is already running

  int code = 0;
  if (isWindows) {
    // On Windows, the execution doesn't return, so we have to execute async
    // and when calling the script, it seems to be inheriting the environment that launched this app
    // so we have to prune out env vars that may cause issues
    Map<String,String> startEnv = new HashMap<>();
    Map<String,String> procEnv = EnvironmentUtils.getProcEnvironment();
    if (procEnv != null) {
      for (Map.Entry<String, String> entry : procEnv.entrySet()) {
        String envVar = entry.getKey();
        String envVarVal = entry.getValue();
        if (envVarVal != null && !"EXAMPLE".equals(envVar) && !envVar.startsWith("SOLR_")) {
          startEnv.put(envVar, envVarVal);
        }
      }
    }
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
    executor.execute(org.apache.commons.exec.CommandLine.parse(startCmd), startEnv, handler);

    // wait for execution.
    try {
      handler.waitFor(3000);
    } catch (InterruptedException ie) {
      // safe to ignore ...
      Thread.interrupted();
    }
    if (handler.hasResult() && handler.getExitValue() != 0) {
      throw new Exception("Failed to start Solr using command: "+startCmd+" Exception : "+handler.getException());
    }
  } else {
    try {
      code = executor.execute(org.apache.commons.exec.CommandLine.parse(startCmd));
    } catch(ExecuteException e){
      throw new Exception("Failed to start Solr using command: "+startCmd+" Exception : "+ e);
    }
  }
  if (code != 0)
    throw new Exception("Failed to start Solr using command: "+startCmd);

  return getNodeStatus(solrUrl, maxWaitSecs);
}