当前位置: 首页>>代码示例>>Java>>正文


Java DefaultExecutor.setWatchdog方法代码示例

本文整理汇总了Java中org.apache.commons.exec.DefaultExecutor.setWatchdog方法的典型用法代码示例。如果您正苦于以下问题:Java DefaultExecutor.setWatchdog方法的具体用法?Java DefaultExecutor.setWatchdog怎么用?Java DefaultExecutor.setWatchdog使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.commons.exec.DefaultExecutor的用法示例。


在下文中一共展示了DefaultExecutor.setWatchdog方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: triggerThreadDump

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
private void triggerThreadDump() {
    String kill = findBinary("kill");
    
    if (kill != null) {
        for (final Integer pid : getOpenNMSProcesses()) {
            LogUtils.debugf(this, "pid = " + pid);
            CommandLine command = CommandLine.parse(kill + " -3 " + pid.toString());
            try {
                LogUtils.tracef(this, "running '%s'", command.toString());
                DefaultExecutor executor = new DefaultExecutor();
                executor.setWatchdog(new ExecuteWatchdog(5000));
                int exitValue = executor.execute(command);
                LogUtils.tracef(this, "finished '%s'", command.toString());
                if (exitValue != 0) {
                    LogUtils.warnf(this, "'%s' exited non-zero: %d", command.toString(), exitValue);
                }
            } catch (final Exception e) {
                LogUtils.warnf(this, e, "Unable to run kill -3 on '%s': you might need to run system-report as root.", pid.toString());
            }
        }
    }
}
 
开发者ID:qoswork,项目名称:opennmszh,代码行数:23,代码来源:ThreadReportPlugin.java

示例2: compile

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
public void compile(String cwd, Submission submission) throws RuntimeException {
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(watchdogTimeout);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(cwd));
    executor.setStreamHandler(new PumpStreamHandler(null, stderr, null));
    executor.setWatchdog(watchdog);

    CommandLine cmd = new CommandLine(javac);
    cmd.addArgument("-J-Duser.language=en");  // force using English
    cmd.addArgument("-classpath");
    cmd.addArgument(cwd);
    cmd.addArgument(fileName + ".java");
    logger.info("Compiler cmd:\t" + cmd.toString());

    try {
        executor.execute(cmd);
        logger.info("Compile OK");
    } catch (IOException e) {
        if (watchdog.killedProcess()) {
            submission.setStatus(Submission.STATUS_CE);
            submission.setError("Compile Time Exceeded");
            logger.warn("Compile Time Exceeded:\t" + e.getMessage());
        } else {
            submission.setStatus(Submission.STATUS_CE);
            submission.setError("Compile error");
            logger.warn("Compile error:\t" + e.getMessage());
        }
        logger.warn(stderr.toString());
        throw new RuntimeException("Compile Aborted.");
    }
}
 
开发者ID:justice-oj,项目名称:dispatcher,代码行数:34,代码来源:JavaWorker.java

示例3: execute

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
public int execute(String[] args, @Nullable Path workingDir, Map<String, String> addEnv) throws IOException {
  if (!Files.isExecutable(file)) {
    Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    Files.setPosixFilePermissions(file, perms);
  }

  ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
  CommandLine cmd = new CommandLine(file.toFile());
  cmd.addArguments(args);
  DefaultExecutor exec = new DefaultExecutor();
  exec.setWatchdog(watchdog);
  exec.setStreamHandler(createStreamHandler());
  exec.setExitValues(null);
  if (workingDir != null) {
    exec.setWorkingDirectory(workingDir.toFile());
  }
  in.close();
  LOG.info("Executing: {}", cmd.toString());
  Map<String, String> env = new HashMap<>(System.getenv());
  env.putAll(addEnv);
  return exec.execute(cmd, env);
}
 
开发者ID:SonarSource,项目名称:sonarlint-cli,代码行数:25,代码来源:CommandExecutor.java

示例4: runCancelJob

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
            TaskEvent taskEvent = (TaskEvent) message.taskEvent;
            String outPath = agentConfig.getJob().getOutPath(taskEvent.getJobName(), message.jobId);
            String errPath = agentConfig.getJob().getErrorPath(taskEvent.getJobName(), message.jobId);
            Worker.Result result = new Worker.Result(-9, agentConfig.getUrl(errPath), agentConfig.getUrl(outPath), null, message);
            getSender().tell(new Worker.WorkFailed(result), getSelf());
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}
 
开发者ID:Abiy,项目名称:distGatling,代码行数:22,代码来源:JarExecutor.java

示例5: runCancelJob

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
private void runCancelJob(Master.Job message) {
    if (getAbortStatus(message.abortUrl, message.trackingId)) {
        CommandLine cmdLine = new CommandLine("/bin/bash");
        cmdLine.addArgument(agentConfig.getJob().getJobArtifact("cancel"));
        cmdLine.addArgument(message.jobId);
        DefaultExecutor killExecutor = new DefaultExecutor();
        ExecuteWatchdog watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        killExecutor.setWatchdog(watchdog);
        try {
            log.info("Cancel command: {}", cmdLine);
            killExecutor.execute(cmdLine);
        } catch (IOException e) {
            log.error(e, "Error cancelling job");
        }
    }
}
 
开发者ID:Abiy,项目名称:distGatling,代码行数:17,代码来源:ScriptExecutor.java

示例6: execute

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
/**
 * 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()));
}
 
开发者ID:vespa-engine,项目名称:vespa,代码行数:28,代码来源:ProcessExecutor.java

示例7: setUpBeforeClass

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
@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....");
}
 
开发者ID:Derek-Ashmore,项目名称:moneta,代码行数:24,代码来源:DropwizardContractTest.java

示例8: checkDot

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
/**
 * Verify if dot can be started and print out the version to stdout.
 *
 * @return True if "dot -V" ran successfully, false otherwise
 *
 * @throws IOException If running dot fails.
 */
public static boolean checkDot() throws IOException {
	// call graphviz-dot via commons-exec
	CommandLine cmdLine = new CommandLine(DOT_EXE);
	cmdLine.addArgument("-V");
	DefaultExecutor executor = new DefaultExecutor();
	executor.setExitValue(0);
	ExecuteWatchdog watchdog = new ExecuteWatchdog(60000);
	executor.setWatchdog(watchdog);
	executor.setStreamHandler(new PumpStreamHandler(System.out, System.err));
	int exitValue = executor.execute(cmdLine);
	if(exitValue != 0) {
		System.err.println("Could not run '" + DOT_EXE + "', had exit value: " + exitValue + "!");
		return false;
	}

	return true;
}
 
开发者ID:centic9,项目名称:commons-dost,代码行数:25,代码来源:DotUtils.java

示例9: AbstractCppcheckCommand

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
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);
	
}
 
开发者ID:kwin,项目名称:cppcheclipse,代码行数:25,代码来源:AbstractCppcheckCommand.java

示例10: executeCommand

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
public static int executeCommand(String command,ExecuteWatchdog watchdog) {
	CommandLine cmdLine = CommandLine.parse(command);
	DefaultExecutor executor = new DefaultExecutor();
	executor.setStreamHandler(new PumpStreamHandler(System.out,System.err, null));
	executor.setExitValues(new int[]{0, 1});
	if(watchdog != null){
		executor.setWatchdog(watchdog);
	}
	int exitValue = 0;
	try {
		exitValue = executor.execute(cmdLine);
	} catch (IOException e) {
		exitValue = 1;
		log.error("error executing command", e);
	}
	return exitValue;
}
 
开发者ID:mohitsoni,项目名称:compose-executor,代码行数:18,代码来源:ProcessUtils.java

示例11: execASync

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
public static ExecuteWatchdog execASync(String line, File workDir, Map<String, String> environment, OutputStream output, ExecuteResultHandler erh,
		long timeout) throws IOException {
	if (environment != null) {
		Map<String, String> sysenv = System.getenv();
		for (String key : sysenv.keySet()) {
			boolean contains = false;
			for (String k : environment.keySet()) {
				if (k.equalsIgnoreCase(key)) {
					contains = true;
					break;
				}
			}
			if (!contains)
				environment.put(key, sysenv.get(key));
		}
	}
	DefaultExecutor executor = new DefaultExecutor();
	if (workDir != null)
		executor.setWorkingDirectory(workDir);
	PumpStreamHandler sh = new PumpStreamHandler(output, output, null);
	executor.setStreamHandler(sh);
	ExecuteWatchdog watchdog = new ProcessTreeWatchDog(timeout);
	executor.setWatchdog(watchdog);
	executor.execute(CommandLine.parse(line), environment, erh);
	return watchdog;
}
 
开发者ID:slimsymphony,项目名称:testgrid,代码行数:27,代码来源:CommonUtils.java

示例12: extractMetaData

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
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();
	}
	
}
 
开发者ID:JorenSix,项目名称:Panako,代码行数:30,代码来源:Store.java

示例13: executeProcess

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
/**
 * Creates a process and logs the output
 */
public void executeProcess(String[] cmd, String logKey, ProcessResult result,
    Map<String, String> additionalEnvVars, File workingDir) {

  Map<String, String> env = getEnvVars(cmd, additionalEnvVars);
  logger.info(format("%s Cmd: %s, Additional Env Vars: %s", logKey,
      String.join(" ", cmd), additionalEnvVars));

  try {
    CommandLine cmdLine = new CommandLine(cmd[0]);
    // add rest of cmd string[] as arguments
    for (int i = 1; i < cmd.length; i++) {
      // needs the quote handling=false or else doesn't work
      // http://www.techques.com/question/1-5080109/How-to-execute--bin-sh-with-commons-exec?
      cmdLine.addArgument(cmd[i], false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValue(0);
    executor.setWatchdog(new ExecuteWatchdog(timeoutInSeconds * 1000));
    executor.setStreamHandler(new OutputHandler(logger, logKey, result));
    if (workingDir != null) {
      executor.setWorkingDirectory(workingDir);
    }
    result.setResultCode(executor.execute(cmdLine, env));

    // set fault to last error if fault map is empty
    if (result.getResultCode() != 0 && result.getFaultMap().keySet().size() < 1) {
      result.getFaultMap().put("ERROR", result.getLastError());
    }

  } catch (ExecuteException ee) {
    logger.error(logKey + ee);
    result.setResultCode(ee.getExitValue());
  } catch (IOException e) {
    logger.error(e);
    result.setResultCode(1);
  }

}
 
开发者ID:oneops,项目名称:oneops,代码行数:42,代码来源:ProcessRunner.java

示例14: prepareDefaultExecutor

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
protected DefaultExecutor prepareDefaultExecutor(ExecCommand execCommand) {
    DefaultExecutor executor = new ExecDefaultExecutor();
    executor.setExitValues(null);

    if (execCommand.getWorkingDir() != null) {
        executor.setWorkingDirectory(new File(execCommand.getWorkingDir()).getAbsoluteFile());
    }
    if (execCommand.getTimeout() != ExecEndpoint.NO_TIMEOUT) {
        executor.setWatchdog(new ExecuteWatchdog(execCommand.getTimeout()));
    }
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    return executor;
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:14,代码来源:DefaultExecCommandExecutor.java

示例15: generateThumbnailWithImageMagickConvert

import org.apache.commons.exec.DefaultExecutor; //导入方法依赖的package包/类
private void generateThumbnailWithImageMagickConvert(File source, File destination, ImageThumbnailFormat thumbnailFormat)
		throws ImageThumbnailGenerationException {
	try {
		CommandLine commandLine = new CommandLine(imageMagickConvertBinary);
		commandLine.addArgument("-auto-orient");
		commandLine.addArgument("-thumbnail");
		if (thumbnailFormat.isAllowEnlarge()) {
			commandLine.addArgument("${width}x${height}");
		} else {
			commandLine.addArgument("${width}x${height}>");
		}
		commandLine.addArgument("-quality");
			commandLine.addArgument("${quality}");
		commandLine.addArgument("${originalFilePath}");
		commandLine.addArgument("${targetFilePath}");
		
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("width", String.valueOf(thumbnailFormat.getWidth()));
		parameters.put("height", String.valueOf(thumbnailFormat.getHeight()));
		parameters.put("quality", String.valueOf(thumbnailFormat.getQuality()));
		parameters.put("originalFilePath", source.getAbsolutePath());
		parameters.put("targetFilePath", destination.getAbsolutePath());
		
		commandLine.setSubstitutionMap(parameters);
		
		DefaultExecutor executor = new DefaultExecutor();
		ExecuteWatchdog watchdog = new ExecuteWatchdog(IMAGE_MAGICK_CONVERT_TIMEOUT);
		executor.setWatchdog(watchdog);
		executor.execute(commandLine);
	} catch (RuntimeException | IOException e) {
		throw new ImageThumbnailGenerationException(String.format("Unable to generate a thumbnail for file %1$s",
				source.getAbsolutePath()), e);
	}
}
 
开发者ID:openwide-java,项目名称:owsi-core-parent,代码行数:35,代码来源:ImageServiceImpl.java


注:本文中的org.apache.commons.exec.DefaultExecutor.setWatchdog方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。