org.apache.commons.exec.DefaultExecuteResultHandler Java Examples

The following examples show how to use org.apache.commons.exec.DefaultExecuteResultHandler. 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: DropwizardContractTest.java    From moneta with Apache License 2.0 6 votes vote down vote up
@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....");
}
 
Example #2
Source File: SpringBootContractTest.java    From moneta with Apache License 2.0 6 votes vote down vote up
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();
	}
	
}
 
Example #3
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-C0");
	cmdLine.addArgument("-r");
	cmdLine.addArgument(formatPath(p4root.getAbsolutePath()));
	for (String arg : args) {
		cmdLine.addArgument(arg);
	}

	logger.debug("EXEC: " + cmdLine.toString());

	DefaultExecutor executor = new DefaultExecutor();
	if (block) {
		executor.execute(cmdLine, environment);
	} else {
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		executor.execute(cmdLine, environment, resultHandler);
	}
}
 
Example #4
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
	CommandLine cmdLine = new CommandLine(p4d);
	cmdLine.addArgument("-C0");
	cmdLine.addArgument("-r");
	cmdLine.addArgument(formatPath(p4root.getAbsolutePath()));
	for (String arg : args) {
		cmdLine.addArgument(arg);
	}

	logger.debug("EXEC: " + cmdLine.toString());

	DefaultExecutor executor = new DefaultExecutor();
	if (block) {
		executor.execute(cmdLine, environment);
	} else {
		DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
		executor.execute(cmdLine, environment, resultHandler);
	}
}
 
Example #5
Source File: TestServer.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
protected void exec(String[] args, boolean block, HashMap<String, String> environment) throws Exception {
    File p4d = P4ExtFileUtils.extractP4d(outDir, version);
    CommandLine cmdLine = new CommandLine(p4d);
    cmdLine.addArgument("-C0");
    cmdLine.addArgument("-r");
    cmdLine.addArgument(outDir.getAbsolutePath());
    for (String arg : args) {
        cmdLine.addArgument(arg);
    }

    DefaultExecutor executor = new DefaultExecutor();
    if (block) {
        executor.execute(cmdLine, environment);
    } else {
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        executor.execute(cmdLine, environment, resultHandler);
    }
}
 
Example #6
Source File: LocalLbAdapter.java    From Baragon with Apache License 2.0 6 votes vote down vote up
private int executeWithTimeout(CommandLine command, int timeout) throws LbAdapterExecuteException, IOException {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(baos));
  DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

  // Start async and do our own time limiting instead of using a watchdog to avoid https://issues.apache.org/jira/browse/EXEC-62
  try {
    long start = System.currentTimeMillis();
    executor.execute(command, resultHandler);
    while (System.currentTimeMillis() - start < timeout && !resultHandler.hasResult()) {
      Thread.sleep(50);
    }
    if (resultHandler.hasResult()) {
      if (resultHandler.getException() != null) {
        throw resultHandler.getException();
      }
      return resultHandler.getExitValue();
    } else {
      CompletableFuture.runAsync(() -> executor.getWatchdog().destroyProcess(), destroyProcessExecutor);
      throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), command.toString());
    }
  } catch (ExecuteException|InterruptedException e) {
    throw new LbAdapterExecuteException(baos.toString(Charsets.UTF_8.name()), e, command.toString());
  }
}
 
Example #7
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 #8
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 #9
Source File: KuduLocal.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void executeAsyncAndWatch(final CommandLine command)
    throws ExecuteException, IOException {
  LOGGER.info("Running async: {}", command.toString());
  final ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  final DefaultExecutor executor = new DefaultExecutor();
  executor.setWatchdog(watchdog);
  executor.setWorkingDirectory(kuduLocalDir);
  watchdogs.add(watchdog);
  // Using a result handler makes the local instance run async
  executor.execute(command, new DefaultExecuteResultHandler());
}
 
Example #10
Source File: DynamoDBLocal.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Using apache commons exec for cmd line execution
 *
 * @param command
 * @return exitCode
 * @throws ExecuteException
 * @throws IOException
 * @throws InterruptedException
 */
private void startDynamoLocal() throws ExecuteException, IOException, InterruptedException {
  // java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar
  // -sharedDb
  final CommandLine cmdLine = new CommandLine("java");

  cmdLine.addArgument("-Djava.library.path=" + dynLocalDir + "/DynamoDBLocal_lib");
  cmdLine.addArgument("-jar");
  cmdLine.addArgument(dynLocalDir + "/DynamoDBLocal.jar");
  cmdLine.addArgument("-sharedDb");
  cmdLine.addArgument("-inMemory");
  cmdLine.addArgument("-port");
  cmdLine.addArgument(Integer.toString(port));
  System.setProperty("aws.accessKeyId", "dummy");
  System.setProperty("aws.secretKey", "dummy");

  // Using a result handler makes the emulator run async
  final DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

  // watchdog shuts down the emulator, later
  watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  final Executor executor = new DefaultExecutor();
  executor.setWatchdog(watchdog);
  executor.execute(cmdLine, resultHandler);

  // we need to wait here for a bit, in case the emulator needs to update
  // itself
  Thread.sleep(EMULATOR_SPINUP_DELAY_MS);
}
 
Example #11
Source File: IngestionUtils.java    From Explorer with Apache License 2.0 5 votes vote down vote up
public static DefaultExecuteResultHandler executeBash(String command) throws IOException {
    CommandLine cmdLine = CommandLine.parse("bash");
    cmdLine.addArgument("-c", false);
    cmdLine.addArgument(command, false);

    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStreamAgentStart = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStreamAgentStart));
    DefaultExecuteResultHandler handler = new DefaultExecuteResultHandler();
    executor.execute(cmdLine, handler);

    return handler;
}
 
Example #12
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);
}