Java Code Examples for org.apache.commons.exec.DefaultExecutor#execute()

The following examples show how to use org.apache.commons.exec.DefaultExecutor#execute() . 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: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 7 votes vote down vote up
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;
}
 
Example 2
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 3
Source File: ProcessExecutor.java    From vespa with Apache License 2.0 6 votes vote down vote up
/**
 * 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()));
}
 
Example 4
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 5
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 6
Source File: Worker.java    From s3-bucket-loader with Apache License 2.0 6 votes vote down vote up
private void runInitOrDestroyCommand(String mode, Properties props) throws Exception {
	// Initialization command and environment vars
	String initCmd 		= 	props.getProperty("worker."+mode+".cmd");
	String initCmdEnv 	= 	props.getProperty("worker."+mode+".cmd.env");
	
	if (initCmd != null) {
		
		Map<String,String> env = null;
		if (initCmdEnv != null) {
			env = Splitter.on(",").withKeyValueSeparator("=").split(initCmdEnv);
		}
		
		// execute it!
		logger.debug("Running "+mode+" command: " + initCmd);
		CommandLine cmdLine = CommandLine.parse(initCmd);
		DefaultExecutor executor = new DefaultExecutor();
		executor.execute(cmdLine, env);
		
	}
}
 
Example 7
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 8
Source File: TestServer.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private int innerExec(String... args)
        throws IOException {
    File p4d = P4ExtFileUtils.extractP4d(outDir, version);
    CommandLine cmdLine = createBaseCmdLine(p4d);
    for (String arg : args) {
        cmdLine.addArgument(arg);
    }
    DefaultExecutor executor = new DefaultExecutor();
    // default - log is pumped to stderr.
    PumpStreamHandler streamHandler = new PumpStreamHandler(status.out, status.log);
    executor.setStreamHandler(streamHandler);
    executor.setProcessDestroyer(processDestroyer);
    return executor.execute(cmdLine);
}
 
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: ExecWorkItemHandler.java    From jbpm-work-items with Apache License 2.0 5 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager manager) {

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String command = (String) workItem.getParameter("Command");
        List<String> arguments = (List<String>) workItem.getParameter("Arguments");

        Map<String, Object> results = new HashMap<>();

        CommandLine commandLine = CommandLine.parse(command);
        if (arguments != null && arguments.size() > 0) {
            commandLine.addArguments(arguments.toArray(new String[0]),
                                     true);
        }

        parsedCommandStr = commandLine.toString();

        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(commandLine);

        results.put(RESULT,
                    outputStream.toString());

        outputStream.close();

        manager.completeWorkItem(workItem.getId(),
                                 results);
    } catch (Throwable t) {
        handleException(t);
    }
}
 
Example 11
Source File: Store.java    From Panako with GNU Affero General Public License v3.0 5 votes vote down vote up
private void extractMetaData(File audioFile){
	Strategy strategy = Strategy.getInstance();
	String identifier = strategy.resolve(file.getAbsolutePath());
	String dir = Config.get(Key.META_DATA_DIRECTORY);
	File metaDataFile = new File(dir,identifier+".json");
	String command = Config.get(Key.META_DATA_COMMAND);
	Map<String,File> map = new HashMap<String,File>();
	map.put("audiofile", audioFile);
	map.put("metadatafile", metaDataFile);
	CommandLine cmdLine = new CommandLine(command);
	cmdLine.addArgument("${audiofile}");
	cmdLine.addArgument("${metadatafile}");
	cmdLine.setSubstitutionMap(map);
	DefaultExecutor executor = new DefaultExecutor();
	//executor.setExitValue(1);
	ExecuteWatchdog watchdog = new ExecuteWatchdog(1000000);
	executor.setWatchdog(watchdog);
	try {
		int exitValue = executor.execute(cmdLine);
		if(exitValue==0){
			System.out.println("Extracted metadata successfully");
		}else{
			System.err.println("Failed to extract metadata for:" + audioFile);
		}
	} catch (IOException e) {
		e.printStackTrace();
	}
	
}
 
Example 12
Source File: YeomanMojo.java    From yeoman-maven-plugin with Apache License 2.0 5 votes vote down vote up
void executeCommand(String command) throws MojoExecutionException {
    try {
        if (isWindows()) {
            command = "cmd /c " + command;
        }
        CommandLine cmdLine = CommandLine.parse(command);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setWorkingDirectory(yeomanProjectDirectory);
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MojoExecutionException("Error during : " + command, e);
    }
}
 
Example 13
Source File: LinuxUtil.java    From SikuliX1 with MIT License 5 votes vote down vote up
@Override
public App get(App app) {
  int pid;
  if (app == null) {
    return app;
  }
  pid = app.getPID();
  if (!app.isClosing() && pid < 0) {
    if (app.getNameGiven() != null && !app.getNameGiven().isEmpty()) {
      pid = findWindowPID(app.getNameGiven(), 0);
      app.setPID(pid);
    }
    return app;
  }
  if (app.isClosing() && pid > -1) {
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outputStream));
    CommandLine command = CommandLine.parse("ps -p " + pid);
    try {
      executor.execute(command);
      app.setPID(pid);
    } catch (Exception e) {
      if (outputStream.toString().split("\\n").length == 1) {
        app.setPID(-1);
        app.setWindow("");
      } else {
        Debug.log(3, "[error] LinuxUtil::executeCommand: %s (%s)", command, e.getMessage());
        logCommandSysout(command.toString(), outputStream);
      }
    }
  }
  return app;
}
 
Example 14
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 15
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
protected int exec(String[] args) 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();
	return executor.execute(cmdLine);
}
 
Example 16
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 17
Source File: AbstractRedisTest.java    From x-pipe with Apache License 2.0 5 votes vote down vote up
protected void executeScript(String file, String... args) throws ExecuteException, IOException {

        URL url = getClass().getClassLoader().getResource(file);
        if (url == null) {
            url = getClass().getClassLoader().getResource("scripts/" + file);
            if (url == null) {
                throw new FileNotFoundException(file);
            }
        }
        DefaultExecutor executor = new DefaultExecutor();
        String command = "sh -v " + url.getFile() + " " + StringUtil.join(" ", args);
        executor.execute(CommandLine.parse(command));
    }
 
Example 18
Source File: ProcPragma.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute() {
	try {
		for (String cmd : cmds) {
			CommandLine cmdLine = CommandLine.parse(cmd);
			DefaultExecutor executor = new DefaultExecutor();
			executor.setStreamHandler(new ProcHandler(cmd));
			executor.execute(cmdLine);
		}
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 19
Source File: PhantomJS.java    From java-phantomjs-wrapper with MIT License 4 votes vote down vote up
/**
 * Execute a script with environment settings, options and a list of arguments.
 *
 * @param script
 *            path of script to execute
 * @param executionEnvironment
 *            the environment to use for script execution
 * @param options
 *            options to execute
 * @param arguments
 *            list of arguments
 * @return the exit code of the script
 * @throws IOException
 *             if cmd execution fails
 */
public static PhantomJSExecutionResponse exec(final InputStream script, final Map<String, String> executionEnvironment, final PhantomJSOptions options, final CommandLineArgument... arguments) throws IOException {
    if (!PhantomJSSetup.isInitialized()) {
        throw new IllegalStateException("Unable to find and execute PhantomJS binaries");
    }

    if (script == null) {
        throw new IllegalArgumentException("Script is a required argument");
    }

    // the path where the script will be copied to
    final String renderId = getRenderId();
    final Path scriptPath = PhantomJSConstants.TEMP_SCRIPT_DIR.resolve(PhantomJSConstants.SCRIPT_PREFIX + renderId);

    // create the parent directory
    Files.createDirectories(PhantomJSConstants.TEMP_SCRIPT_DIR);

    // copy the script to the path
    Files.copy(script, scriptPath);

    // start building the phantomjs binary call
    final CommandLine cmd = new CommandLine(PhantomJSSetup.getPhantomJsBinary());
    final Map<String, Object> args = new HashMap<>();
    cmd.setSubstitutionMap(args);

    // add options to the phantomjs call
    if (options != null) {
        options.apply(cmd, args);
    }

    // then script
    args.put("_script_path", scriptPath.toFile());
    cmd.addArgument("${_script_path}");

    // then any additional arguments
    if (arguments != null) {
        for (final CommandLineArgument arg : arguments) {
            if (arg != null) {
                arg.apply(cmd, args);
            }
        }
    }

    logger.info("Running command: [{}]", cmd);

    final InfoLoggerOutputStream stdOutLogger = new InfoLoggerOutputStream();
    final ErrorLoggerOutputStream stdErrLogger = new ErrorLoggerOutputStream();

    final DefaultExecutor de = new DefaultExecutor();
    de.setStreamHandler(new PumpStreamHandler(stdOutLogger, stdErrLogger));

    int code;
    try {
        if(executionEnvironment != null && !executionEnvironment.isEmpty()) {
            code = de.execute(cmd, executionEnvironment);
        } else {
            code = de.execute(cmd);
        }
    } catch (final ExecuteException exe) {
        code = exe.getExitValue();
    }

    // remove the script after running it
    Files.deleteIfExists(scriptPath);

    logger.info("Execution Completed");

    return new PhantomJSExecutionResponse(code, stdOutLogger.getMessageContents(), stdErrLogger.getMessageContents());
}
 
Example 20
Source File: NPM.java    From wisdom with Apache License 2.0 4 votes vote down vote up
/**
 * Executes the current NPM using the given binary file.
 *
 * @param binary the program to run
 * @param args   the arguments
 * @return the execution exit status
 * @throws MojoExecutionException if the execution failed
 */
public int execute(File binary, String... args) throws MojoExecutionException {
    File destination = getNPMDirectory();
    if (!destination.isDirectory()) {
        throw new IllegalStateException("NPM " + this.npmName + " not installed");
    }

    CommandLine cmdLine = new CommandLine(node.getNodeExecutable());

    if (binary == null) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary is 'null'.");
    }

    if (!binary.isFile()) {
        throw new IllegalStateException("Cannot execute NPM " + this.npmName + " - the given binary does not " +
                "exist: " + binary.getAbsoluteFile() + ".");
    }

    // NPM is launched using the main file.
    cmdLine.addArgument(binary.getAbsolutePath(), false);
    for (String arg : args) {
        cmdLine.addArgument(arg, this.handleQuoting);
    }

    DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    errorStreamFromLastExecution = new LoggedOutputStream(log, true, true);
    outputStreamFromLastExecution = new LoggedOutputStream(log, false, registerOutputStream);

    PumpStreamHandler streamHandler = new PumpStreamHandler(
            outputStreamFromLastExecution,
            errorStreamFromLastExecution);

    executor.setStreamHandler(streamHandler);
    executor.setWorkingDirectory(node.getWorkDir());
    log.info("Executing " + cmdLine.toString() + " from " + executor.getWorkingDirectory().getAbsolutePath());

    try {
        return executor.execute(cmdLine, extendEnvironmentWithNodeInPath(node));
    } catch (IOException e) {
        throw new MojoExecutionException("Error during the execution of the NPM " + npmName, e);
    }

}