本文整理汇总了Java中org.zeroturnaround.exec.ProcessExecutor类的典型用法代码示例。如果您正苦于以下问题:Java ProcessExecutor类的具体用法?Java ProcessExecutor怎么用?Java ProcessExecutor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
ProcessExecutor类属于org.zeroturnaround.exec包,在下文中一共展示了ProcessExecutor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: execute
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
/**
* Executes this command.
* @param timeout The allowed timeout
* @param unit A time unit
* @return This command
* @throws TimeoutException See {@link ProcessExecutor#execute()}
* @throws InvalidExitValueException See {@link ProcessExecutor#execute()}
* @throws IOException See {@link ProcessExecutor#execute()}
* @throws InterruptedException See {@link ProcessExecutor#execute()}
*/
public Command execute(long timeout, TimeUnit unit)
throws TimeoutException, InvalidExitValueException, IOException,
InterruptedException {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
final int exitCode = new ProcessExecutor()
.environment(System.getenv())
.directory(this.directory)
.command(this.parts)
.timeout(timeout, unit)
.redirectOutput(outputStream)
.redirectError(errorStream)
.readOutput(true)
.stopper((process) -> {
process.destroyForcibly();
})
.execute()
.getExitValue();
this.result = new Result(
exitCode,
outputStream,
errorStream
);
return this;
}
示例2: login2
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Ignore
public void login2() throws Exception {
List<String> commands = new ArrayList<>();
commands.add("ssh");
// commands.add("-t");
// commands.add ("-o StrictHostKeyChecking=no");
commands.add("[email protected]");
ByteArrayOutputStream out = new ByteArrayOutputStream();
ProcessResult result1 = new ProcessExecutor(commands).readOutput(true).redirectOutput(out)
.redirectInput(new ReaderInputStream(new StringReader("@n$ible.\\r\\n"))).execute();
System.out.println(result1.outputString());
// out.write("@n$ible.".getBytes());
result1.getOutput().getLines().forEach(i -> System.out.println(i));
// ProcessResult result2=new ProcessExecutor("ls -lrt").readOutput(true).execute();
}
示例3: execute
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Override
public void execute(final String[] arguments, final File directory) {
LOGGER.info(String.format("Execute maven at '%s': %s", directory, Arrays.toString(arguments)));
try {
final List<String> argumentsAsList = Lists.newArrayList(Arrays.asList(arguments));
argumentsAsList.add(0, getMavenCommand());
if (LOGGER.isDebugEnabled()) {
argumentsAsList.add("-e");
}
new ProcessExecutor() //
.command(argumentsAsList) //
.directory(directory) //
.redirectOutput(Slf4jStream.of(LOGGER).asDebug()) //
.redirectError(Slf4jStream.of(LOGGER).asError()) //
.execute();
} catch (final Exception exception) {
throw new MavenExecutionException(exception);
}
}
示例4: setUp
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
EmbeddedRabbitMqConfig embeddedRabbitMqConfig = new EmbeddedRabbitMqConfig.Builder()
.extractionFolder(tempFolder.getRoot())
.processExecutorFactory(factory)
.build();
this.processExecutor = Mockito.mock(ProcessExecutor.class, new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
if (invocationOnMock.getMethod().getName().equals("start")){
return startedProcess;
}
return invocationOnMock.getMock();
}
});
when(factory.createInstance()).thenReturn(processExecutor);
rabbitMqPlugins = new RabbitMqPlugins(embeddedRabbitMqConfig);
String appFolder = PredefinedVersion.LATEST.getExtractionFolder();
File executableFilesFolder = tempFolder.newFolder(appFolder, RabbitMqCommand.BINARIES_FOLDER);
executableFile = new File(executableFilesFolder, "rabbitmq-plugins" + RabbitMqCommand.getCommandExtension());
assertTrue("Fake executable file couldn't be created!", executableFile.createNewFile());
}
示例5: setUp
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Before
public void setUp() throws Exception {
version = PredefinedVersion.LATEST;
configBuilder = new EmbeddedRabbitMqConfig.Builder()
.extractionFolder(tempFolder.getRoot())
.version(this.version)
.processExecutorFactory(this.factory);
command = RandomStringUtils.randomAlphabetic(10);
this.processExecutor = Mockito.mock(ProcessExecutor.class, new Answer() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
if (invocationOnMock.getMethod().getName().equals("start")){
return startedProcess;
}
return invocationOnMock.getMock();
}
});
when(factory.createInstance()).thenReturn(processExecutor);
String appFolder = version.getExtractionFolder();
File executableFilesFolder = tempFolder.newFolder(appFolder, RabbitMqCommand.BINARIES_FOLDER);
executableFile = new File(executableFilesFolder, command + RabbitMqCommand.getCommandExtension());
assertTrue("Fake executable file couldn't be created!", executableFile.createNewFile());
}
示例6: taskkill
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
/**
* Sends the destroy signal to this process.
*
* @param forceful <code>true</code> if this process should be destroyed forcefully.
* @return <code>true</code> if this process got the signal, <code>false</code> if the process was not found (any more).
*
* @throws IOException on IO error.
* @throws InterruptedException if interrupted.
*/
public boolean taskkill(boolean forceful) throws IOException, InterruptedException {
try {
new ProcessExecutor()
.commandSplit(String.format("taskkill%s%s /PID %d", includeChildren ? " /T" : "", forceful ? " /F" : "", pid))
.redirectOutput(Slf4jStream.ofCaller().asDebug()).exitValueNormal().executeNoTimeout();
return true;
}
catch (InvalidExitValueException e) {
if (e.getExitValue() == EXIT_CODE_COULD_NOT_BE_TERMINATED) {
// Process could be either alive or not, if it's not alive we don't want to throw an exception
if (isAlive()) {
throw e; // process is still alive
}
return false; // process is stopped but but not because of us
}
if (e.getExitValue() == EXIT_CODE_NO_SUCH_PROCESS) {
return false;
}
throw e;
}
}
示例7: isAlive
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
public boolean isAlive() throws IOException, InterruptedException {
try {
new ProcessExecutor()
.commandSplit(String.format("kill -0 %d", pid)).readOutput(true)
.redirectOutput(Slf4jStream.ofCaller().asTrace())
.setMessageLogger(MessageLoggers.TRACE)
.exitValueNormal()
.executeNoTimeout();
return true;
}
catch (InvalidExitValueException e) {
if (isNoSuchProcess(e)) {
return false;
}
throw e;
}
}
示例8: loadAgent
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
private static void loadAgent(final File tempAgentJar, final String pid) throws Exception {
if (DynamicInstrumentationReflections.isBeforeJava9()) {
DynamicInstrumentationLoadAgentMain.loadAgent(pid, tempAgentJar.getAbsolutePath());
} else {
//-Djdk.attach.allowAttachSelf https://www.bountysource.com/issues/45231289-self-attach-fails-on-jdk9
//workaround this limitation by attaching from a new process
final File loadAgentJar = createTempJar(DynamicInstrumentationLoadAgentMain.class, false);
final String javaExecutable = getJavaHome() + File.separator + "bin" + File.separator + "java";
final List<String> command = new ArrayList<String>();
command.add(javaExecutable);
command.add("-classpath");
command.add(loadAgentJar.getAbsolutePath()); //tools.jar not needed since java9
command.add(DynamicInstrumentationLoadAgentMain.class.getName());
command.add(pid);
command.add(tempAgentJar.getAbsolutePath());
new ProcessExecutor().command(command)
.destroyOnExit()
.exitValueNormal()
.redirectOutput(Slf4jStream.of(DynamicInstrumentationLoader.class).asInfo())
.redirectError(Slf4jStream.of(DynamicInstrumentationLoader.class).asWarn())
.execute();
}
}
示例9: runShellCommand
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
/**
* Run a shell command synchronously.
*
* @param command command to run and arguments
* @return the stdout output of the command
*/
public static String runShellCommand(String... command) {
String joinedCommand = String.join(" ", command);
LOGGER.debug("Executing shell command: `{}`", joinedCommand);
try {
ProcessResult result;
result = new ProcessExecutor()
.command(command)
.readOutput(true)
.exitValueNormal()
.execute();
return result.outputUTF8().trim();
} catch (IOException | InterruptedException | TimeoutException | InvalidExitValueException e) {
throw new ShellCommandException("Exception when executing " + joinedCommand, e);
}
}
示例10: main
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
static public void main(String[] args) throws Exception {
// use one-time use temporary directory
File catExeFile = JNE.findExecutable("cat", "prime-cat");
if (catExeFile == null) {
logger.error("Unable to find executable!");
System.exit(1);
}
logger.info("java version: " + System.getProperty("java.version"));
logger.info("java home: " + System.getProperty("java.home"));
logger.info("using exe: " + catExeFile.getAbsolutePath());
// use "cat" to print out an expected file
File expectedTxtFile = new File(JneDemo.class.getResource("/test.txt").toURI());
File actualTxtFile = new File("target", "actual.txt");
int exitValue
= new ProcessExecutor()
.command(catExeFile.getAbsolutePath(), expectedTxtFile.getAbsolutePath())
.execute()
.getExitValue();
logger.info("exit value: {}", exitValue);
}
示例11: createProcessExecutor
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
/**
* Method description
*
*
* @return
*/
private ProcessExecutor createProcessExecutor()
{
logger.debug("create process executor for {}", command);
//J-
ProcessExecutor executor = new ProcessExecutor(command)
.directory(workDirectory)
.redirectErrorStream(true)
.exitValueNormal();
//J+
if (environment != null)
{
executor = executor.environment(environment);
}
return executor;
}
示例12: testDataIsFlushedToProcessWithANonEndingInputStream
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Test
public void testDataIsFlushedToProcessWithANonEndingInputStream() throws Exception {
String str = "Tere Minu Uus vihik " + System.nanoTime();
// Setup InputStream that will block on a read()
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ProcessExecutor exec = new ProcessExecutor("java", "-cp", "target/test-classes", PrintInputToOutput.class.getName());
exec.redirectInput(pis).redirectOutput(baos);
StartedProcess startedProcess = exec.start();
pos.write(str.getBytes());
pos.write("\n\n\n".getBytes()); // PrintInputToOutput processes at most 3 lines
// Assert that we don't get a TimeoutException
startedProcess.getFuture().get(5, TimeUnit.SECONDS);
Assert.assertEquals(str, baos.toString());
}
示例13: testRedirectInput
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Test
public void testRedirectInput() throws Exception {
String binTrue;
if (SystemUtils.IS_OS_LINUX) {
binTrue = "/bin/true";
}
else if (SystemUtils.IS_OS_MAC_OSX) {
binTrue = "/usr/bin/true";
}
else {
Assume.assumeTrue("Unsupported OS " + SystemUtils.OS_NAME, false);
return; // Skip this test
}
// We need to put something in the buffer
ByteArrayInputStream bais = new ByteArrayInputStream("foo".getBytes());
ProcessExecutor exec = new ProcessExecutor().command(binTrue);
// Test that we don't get IOException: Stream closed
int exit = exec.redirectInput(bais).readOutput(true).execute().getExitValue();
log.debug("Exit: {}", exit);
}
示例14: testProcessExecutorCommand
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Test
public void testProcessExecutorCommand() throws Exception {
// Use timeout in case we get stuck
List<String> args = new ArrayList<String>() {
{
add("java");
add("-cp");
add("target/test-classes");
add(HelloWorld.class.getName());
}
};
ProcessExecutor exec = new ProcessExecutor();
exec.command(args);
ProcessResult result = exec.readOutput(true).execute();
Assert.assertEquals("Hello world!", result.outputUTF8());
}
示例15: testProcessExecutorSetDirectory
import org.zeroturnaround.exec.ProcessExecutor; //导入依赖的package包/类
@Test
public void testProcessExecutorSetDirectory() throws Exception {
// Use timeout in case we get stuck
List<String> args = new ArrayList<String>() {
{
add("java");
add("-cp");
add("test-classes");
add(HelloWorld.class.getName());
}
};
ProcessExecutor exec = new ProcessExecutor().directory(new File("target"));
exec.command(args);
ProcessResult result = exec.readOutput(true).execute();
Assert.assertEquals("Hello world!", result.outputUTF8());
}