org.apache.commons.exec.DefaultExecutor Java Examples

The following examples show how to use org.apache.commons.exec.DefaultExecutor. 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: SubmarineShellInterpreter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void createSecureConfiguration() throws InterpreterException {
  Properties properties = getProperties();
  CommandLine cmdLine = CommandLine.parse(shell);
  cmdLine.addArgument("-c", false);
  String kinitCommand = String.format("kinit -k -t %s %s",
      properties.getProperty(SUBMARINE_HADOOP_KEYTAB),
      properties.getProperty(SUBMARINE_HADOOP_PRINCIPAL));
  cmdLine.addArgument(kinitCommand, false);
  DefaultExecutor executor = new DefaultExecutor();
  try {
    executor.execute(cmdLine);
  } catch (Exception e) {
    LOGGER.error("Unable to run kinit for zeppelin user " + kinitCommand, e);
    throw new InterpreterException(e);
  }
}
 
Example #3
Source File: Session.java    From poor-man-transcoder with GNU General Public License v2.0 6 votes vote down vote up
private Session(Builder builder) 
{
	Session.id++;
	
	this.config = builder.config;
	this.source = builder.input;
	this.cmdLine = builder.cmdLine;	
	this.cleanUpOnExit = builder.cleanUpOnExit;
	this.setOutputs(builder.outputs);
	this.executor = new DefaultExecutor();
	
	// set this locally not globally -|
	this.workingDirectoryPath = (builder.workingDirectoryPath == null || builder.workingDirectoryPath == "")?Globals.getEnv(Globals.Vars.WORKING_DIRECTORY):builder.workingDirectoryPath;
	
	this.executonTimeout = ExecuteWatchdog.INFINITE_TIMEOUT;
	this.watchdog = new ExecuteWatchdog(executonTimeout);
	this.observers = new ArrayList<ISessionObserver>();
	
	
	logger.info("Command :" + this.cmdLine.toString());
}
 
Example #4
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 #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: 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 #7
Source File: __platform-name__Loader.java    From ldbc_graphalytics with Apache License 2.0 6 votes vote down vote up
public int unload(String loadedInputPath) throws Exception {
	String unloaderDir = platformConfig.getUnloaderPath();
	commandLine = new CommandLine(Paths.get(unloaderDir).toFile());

	commandLine.addArgument("--graph-name");
	commandLine.addArgument(formattedGraph.getName());

	commandLine.addArgument("--output-path");
	commandLine.addArgument(loadedInputPath);

	String commandString = StringUtils.toString(commandLine.toStrings(), " ");
	LOG.info(String.format("Execute graph unloader with command-line: [%s]", commandString));

	Executor executor = new DefaultExecutor();
	executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
	executor.setExitValue(0);

	return executor.execute(commandLine);
}
 
Example #8
Source File: AbstractCppcheckCommand.java    From cppcheclipse with Apache License 2.0 6 votes vote down vote up
public AbstractCppcheckCommand(IConsole console, String[] defaultArguments,
		long timeout, String binaryPath) {

	this.binaryPath = binaryPath;
	this.console = console;
	this.defaultArguments = defaultArguments;
	
	executor = new DefaultExecutor();

	// all modes of operation returns 0 when no error occured,
	executor.setExitValue(0);

	watchdog = new ExecuteWatchdog(timeout);
	executor.setWatchdog(watchdog);

	out = new ByteArrayOutputStream();
	err = new ByteArrayOutputStream();

	processStdOut = new LineFilterOutputStream(new TeeOutputStream(out,
			console.getConsoleOutputStream(false)), DEFAULT_CHARSET);
	processStdErr = new LineFilterOutputStream(new TeeOutputStream(err,
			console.getConsoleOutputStream(true)), DEFAULT_CHARSET);
	
}
 
Example #9
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 #10
Source File: Ffprobe.java    From piper with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String,Object> handle(TaskExecution 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);
  }
}
 
Example #11
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 #12
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 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 #13
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 #14
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 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 #15
Source File: GeneratorRunner.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public static int run(final GeneratorConfig gc, final ExecutionConfig ec) throws IOException, InterruptedException {
	final File configFile = File.createTempFile("trainbenchmark-generator-", ".conf");
	final String configPath = configFile.getAbsolutePath();
	gc.saveToFile(configPath);

	final String projectName = String.format("trainbenchmark-generator-%s", gc.getProjectName());
	final String jarPath = String.format("../%s/build/libs/%s-1.0.0-SNAPSHOT-fat.jar", projectName, projectName);
	final String javaCommand = String.format("java -Xms%s -Xmx%s -server -jar %s %s", ec.getXms(), ec.getXmx(),
			jarPath, configPath);

	final CommandLine cmdLine = CommandLine.parse(javaCommand);
	final DefaultExecutor executor = new DefaultExecutor();
	try {
		final int exitValue = executor.execute(cmdLine);
		System.out.println();
		return exitValue;
	} catch (final ExecuteException e) {
		e.printStackTrace(System.out);
		return e.getExitValue();
	}
}
 
Example #16
Source File: ProcessLauncher.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void launch() {
  DefaultExecutor executor = new DefaultExecutor();
  executor.setStreamHandler(new PumpStreamHandler(processOutput));
  this.watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
  executor.setWatchdog(watchdog);
  try {
    executor.execute(commandLine, envs, this);
    transition(State.LAUNCHED);
    LOGGER.info("Process is launched: {}", commandLine);
  } catch (IOException e) {
    this.processOutput.stopCatchLaunchOutput();
    LOGGER.error("Fail to launch process: " + commandLine, e);
    transition(State.TERMINATED);
    errorMessage = e.getMessage();
  }
}
 
Example #17
Source File: JavaPythonInteropUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenPythonScript_whenPythonProcessExecuted_thenSuccess() throws ExecuteException, IOException {
    String line = "python " + resolvePythonScriptPath("hello.py");
    CommandLine cmdLine = CommandLine.parse(line);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(streamHandler);

    int exitCode = executor.execute(cmdLine);
    assertEquals("No errors should be detected", 0, exitCode);
    assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", outputStream.toString()
        .trim());
}
 
Example #18
Source File: BotRunner.java    From 2018-TowerDefence with MIT License 6 votes vote down vote up
protected String RunSimpleCommandLineCommand(String line, int expectedExitValue) throws IOException, TimeoutException {
    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    File bot = new File(this.getBotDirectory());
    executor.setWorkingDirectory(bot);
    executor.setExitValue(expectedExitValue);

    ExecuteWatchdog watchdog = new ExecuteWatchdog(this.timeoutInMilliseconds);
    executor.setWatchdog(watchdog);

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

    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        if (watchdog.killedProcess()) {
            throw new TimeoutException("Bot process timed out after " + this.timeoutInMilliseconds + "ms of inactivity");
        } else {
            throw e;
        }
    }

    return outputStream.toString();
}
 
Example #19
Source File: DockerCompose.java    From football-events with MIT License 6 votes vote down vote up
private String execProcess(String command) {
    logger.debug(command);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    CommandLine commandline = CommandLine.parse(command);
    DefaultExecutor exec = new DefaultExecutor();
    exec.setStreamHandler(new PumpStreamHandler(outputStream));
    int exitCode;

    try {
        exitCode = exec.execute(commandline);
    } catch (IOException e) {
        throw new RuntimeException("Unable to execute " + command + ": " + outputStream, e);
    }
    if (exitCode != 0) {
        throw new RuntimeException(command + " exited with code " + exitCode + ", " + outputStream);
    }
    String output = outputStream.toString();
    logger.debug(System.lineSeparator() + output);
    return output;
}
 
Example #20
Source File: JavaFXJLinkMojo.java    From javafx-maven-plugin with Apache License 2.0 6 votes vote down vote up
private boolean isJLinkVersion13orHigher(String jlinkExePath) {
    CommandLine versionCommandLine = new CommandLine(jlinkExePath)
            .addArgument("--version");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int resultCode = -1;

    try {
        resultCode = executeCommandLine(new DefaultExecutor(), versionCommandLine, null, baos, System.err);
    } catch (IOException e) {
        if (getLog().isDebugEnabled()) {
            getLog().error("Error getting JLink version", e);
        }
    }

    if (resultCode != 0) {
        getLog().error("Unable to get JLink version");
        getLog().error("Result of " + versionCommandLine + " execution is: '" + resultCode + "'");
        return false;
    }

    String versionStr = new String(baos.toByteArray());
    return JLINK_VERSION_PATTERN.matcher(versionStr).lookingAt();
}
 
Example #21
Source File: Crawlergo.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object start() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    WebsocketOutputStream outputStream = new WebsocketOutputStream(byteArrayOutputStream,getSession());
    String url = param.get("url").toString();
    int maxtab = Integer.parseInt(param.get("maxtab").toString());
    String mode = param.get("mode").toString();
    String proxy = param.get("proxy").toString();
    crawlergoInner.executor();
    crawlergoInner.addUrl(url);
    CrawlergoInner.GlobalOption option = crawlergoInner.option();
    option.maxCrawledCount(maxtab);
    option.filterMode(mode);
    if (StringUtils.isNotEmpty(proxy)){
        option.pushProxy(proxy);
    }else {
        option.pushProxy("");
    }
    CommandLine commandLine = crawlergoInner.buildCommandLine();
    crawlergoInner.setOutputStream(outputStream);
    crawlergoInner.setSync(false);
    DefaultExecutor run = crawlergoInner.run(commandLine);
    return "";
}
 
Example #22
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 #23
Source File: ShellInterpreter.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public void createSecureConfiguration() throws InterpreterException {
  Properties properties = getProperties();
  CommandLine cmdLine = CommandLine.parse(shell);
  cmdLine.addArgument("-c", false);
  String kinitCommand = String.format("kinit -k -t %s %s",
      properties.getProperty("zeppelin.shell.keytab.location"),
      properties.getProperty("zeppelin.shell.principal"));
  cmdLine.addArgument(kinitCommand, false);
  DefaultExecutor executor = new DefaultExecutor();
  try {
    executor.execute(cmdLine);
  } catch (Exception e) {
    LOGGER.error("Unable to run kinit for zeppelin user " + kinitCommand, e);
    throw new InterpreterException(e);
  }
}
 
Example #24
Source File: SimpleTestServer.java    From p4ic4idea with Apache License 2.0 6 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 #25
Source File: ProcessExecClient.java    From Quicksql with MIT License 6 votes vote down vote up
/**
 * Start a new process to execute.
 *
 * @return log or result output stream
 */
public OutputStream exec() {
    CommandLine commandLine = CommandLine.parse(submit());
    commandLine.addArguments(arguments());
    LOGGER.debug("CommandLine is " + commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(System.out));
    try {
        executor.execute(commandLine);
    } catch (Exception ex) {
        ex.printStackTrace();
        LOGGER.error("Process executing failed!! Caused by: " + ex.getMessage());
        throw new RuntimeException(ex);
    }

    return System.out;
}
 
Example #26
Source File: ScriptUtil.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 日志文件输出方式
 *
 * 优点:支持将目标数据实时输出到指定日志文件中去
 * 缺点:
 *      标准输出和错误输出优先级固定,可能和脚本中顺序不一致
 *      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)
    // 标准输入
    try (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;
    }
}
 
Example #27
Source File: __platform-name__Job.java    From ldbc_graphalytics with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the platform job with the pre-defined parameters.
 *
 * @return the exit code
 * @throws IOException if the platform failed to run
 */
public int execute() throws Exception {
	String executableDir = platformConfig.getExecutablePath();
	commandLine = new CommandLine(Paths.get(executableDir).toFile());

	// List of benchmark parameters.
	String jobId = getJobId();
	String logDir = getLogPath();

	// List of dataset parameters.
	String inputPath = getInputPath();
	String outputPath = getOutputPath();

	// List of platform parameters.
	int numMachines = platformConfig.getNumMachines();
	int numThreads = platformConfig.getNumThreads();
	String homeDir = platformConfig.getHomePath();

	appendBenchmarkParameters(jobId, logDir);
	appendAlgorithmParameters();
	appendDatasetParameters(inputPath, outputPath);
	appendPlatformConfigurations(homeDir, numMachines, numThreads);

	String commandString = StringUtils.toString(commandLine.toStrings(), " ");
	LOG.info(String.format("Execute benchmark job with command-line: [%s]", commandString));

	Executor executor = new DefaultExecutor();
	executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
	executor.setExitValue(0);
	return executor.execute(commandLine);
}
 
Example #28
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 #29
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 #30
Source File: ReportGenerate.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected void runUnsafe() throws Exception {
    validateResultsDirectories();
    CommandLine commandLine = createCommandLine();
    new DefaultExecutor().execute(commandLine);
    LOGGER.info("Report successfully generated to the directory <{}>. " +
            "Use `allure report open` command to show the report.", getReportDirectoryPath());
}