org.zeroturnaround.exec.ProcessResult Java Examples
The following examples show how to use
org.zeroturnaround.exec.ProcessResult.
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: ProjectCommandExecutorTests.java From spring-cloud-release-tools with Apache License 2.0 | 6 votes |
@Test public void should_throw_exception_when_process_exits_with_invalid_code() { ReleaserProperties properties = new ReleaserProperties(); properties.getBash().setBuildCommand("exit 1"); properties.setWorkingDir(tmpFile("/builder/unresolved").getPath()); ProjectCommandExecutor builder = new ProjectCommandExecutor() { @Override ReleaserProcessExecutor executor(String workingDir) { return new ReleaserProcessExecutor(properties.getWorkingDir()) { @Override ProcessResult doExecute(ProcessExecutor processExecutor) throws IOException, InterruptedException, TimeoutException { return new ProcessResult(1, null); } }; } }; thenThrownBy(() -> builder.build(properties, original(), new ProjectVersion("foo", "1.0.0.BUILD-SNAPSHOT"))).hasMessageContaining( "The process has exited with exit code [1]"); }
Example #2
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 6 votes |
@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()); }
Example #3
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 6 votes |
@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()); }
Example #4
Source File: CommandLine.java From testcontainers-java with MIT License | 6 votes |
/** * 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 = 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); } }
Example #5
Source File: RabbitMqPluginsTest.java From embedded-rabbitmq with Apache License 2.0 | 6 votes |
@Test public void testExecutionError() throws Exception { futureResult = mock(Future.class); result = mock(ProcessResult.class); when(startedProcess.getFuture()) .thenReturn(futureResult); TimeoutException timeoutException = new TimeoutException("Fake timeout"); when(futureResult.get(anyLong(), any(TimeUnit.class))) .thenThrow(timeoutException); expectedException.expect(instanceOf(RabbitMqCommandException.class)); expectedException.expectMessage("rabbitmq-plugins list"); expectedException.expectCause(sameInstance(timeoutException)); rabbitMqPlugins.groupedList(); }
Example #6
Source File: RabbitMqPluginsTest.java From embedded-rabbitmq with Apache License 2.0 | 6 votes |
@Test public void testUnexpectedExitCode() throws Exception { futureResult = mock(Future.class); result = mock(ProcessResult.class); when(startedProcess.getFuture()) .thenReturn(futureResult); when(futureResult.get(anyLong(), any(TimeUnit.class))) .thenReturn(result); int exitCode = new Random().nextInt(10) + 1; when(result.getExitValue()) .thenReturn(exitCode); expectedException.expect(instanceOf(RabbitMqCommandException.class)); expectedException.expectMessage("exit code: " + exitCode); rabbitMqPlugins.groupedList(); }
Example #7
Source File: ShutdownHelper.java From embedded-rabbitmq with Apache License 2.0 | 6 votes |
private void confirmShutdown() throws ShutDownException { int exitValue; try { ProcessResult rabbitMqProcessResult = rabbitMqProcess.get(timeoutDuration, TimeUnit.MILLISECONDS); exitValue = rabbitMqProcessResult.getExitValue(); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new ShutDownException("Error while waiting " + timeoutDuration + " " + timeoutUnit + "for " + "RabbitMQ Server to shut down", e); } if (exitValue == 0) { LOGGER.debug("RabbitMQ Server stopped successfully."); } else { LOGGER.warn("RabbitMQ Server stopped with exit value: " + exitValue); } }
Example #8
Source File: GolangGetMojo.java From mvn-golang with Apache License 2.0 | 6 votes |
@Override protected boolean doesNeedOneMoreAttempt(@Nonnull final ProcessResult processResult, @Nonnull final String consoleOut, @Nonnull final String consoleErr) throws IOException, MojoExecutionException { boolean result = false; if (processResult.getExitValue() != 0) { final Matcher matcher = PATTERN_NO_SUBMODULE_MAPPING_FOUND_IN_GIT.matcher(consoleErr); if (matcher.find()) { final List<String> packagesWithDetectedGitCacheErrors = extractProblemPackagesFromErrorLog(consoleErr); if (!packagesWithDetectedGitCacheErrors.isEmpty()) { if (this.autofixGitCache) { getLog().warn("Trying to fix the detected git cache errors automatically.."); result = tryToFixGitCacheErrorsForPackages(packagesWithDetectedGitCacheErrors); } else { for (final String s : packagesWithDetectedGitCacheErrors) { getLog().error(String.format("Detected Git cache error for package '%s', can be fixed with 'git rm -r --cached .'", s)); } } } } } return result; }
Example #9
Source File: DockerComposeRuntime.java From carnotzet with Apache License 2.0 | 6 votes |
@Override public ExecResult exec(String serviceName, int timeout, TimeUnit timeoutUnit, String... command) { Container container = getContainer(serviceName); List<String> fullCommand = new ArrayList<>(Arrays.asList("docker", "exec", container.getId())); fullCommand.addAll(Arrays.asList(command)); try { ProcessResult pr = new ProcessExecutor() .command(fullCommand) .readOutput(true) .timeout(timeout, timeoutUnit) .execute(); return new ExecResult(pr.getExitValue(), pr.getOutput().getUTF8()); } catch (IOException | InterruptedException | TimeoutException e) { throw new RuntimeException("Failed to execute " + Arrays.toString(command) + " in container [" + serviceName + "]", e); } }
Example #10
Source File: DefaultCommandRunner.java From carnotzet with Apache License 2.0 | 6 votes |
public String runCommandAndCaptureOutput(File directoryForRunning, String... command) { log.debug("Running command [{}]", Joiner.on(" ").join(command)); ProcessExecutor pe = new ProcessExecutor() .command(command) .redirectErrorStream(true) .directory(directoryForRunning) .readOutput(true); try { ProcessResult processResult = pe.execute(); String output = processResult.outputUTF8().trim(); if (processResult.getExitValue() != 0) { throw new RuntimeException("External command [" + Joiner.on(" ").join(command) + "] exited with [" + processResult.getExitValue() + "], output: " + output); } return output; } catch (InterruptedException | IOException | TimeoutException e) { throw new RuntimeException(e); } }
Example #11
Source File: RabbitMqPlugins.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
/** * Executes the {@code rabbitmq-plugins list} command * * @return a Map where the key is the plugin name and the value is the full plugin details parsed from the output. * * @throws RabbitMqCommandException if the command cannot be executed, it doesn't * {@link EmbeddedRabbitMqConfig.Builder#defaultRabbitMqCtlTimeoutInMillis(long) * finish in time} or exits unexpectedly * @see #groupedList() */ public Map<String, Plugin> list() { String[] args = {LIST_COMMAND}; String executionErrorMessage = String.format("Error executing: %s %s", COMMAND, LIST_COMMAND); String unexpectedExitCodeMessage = "Listing of plugins failed with exit code: "; ProcessResult processResult = getProcessResult(args, executionErrorMessage, unexpectedExitCodeMessage); List<Plugin> plugins = parseListOutput(processResult); Map<String, Plugin> result = mapPluginsByName(plugins); return result; }
Example #12
Source File: GolangGetMojo.java From mvn-golang with Apache License 2.0 | 5 votes |
private boolean processCustomScriptCallForPackage(@Nonnull final String packageName, @Nonnull final File rootCvsFolder, @Nonnull final CustomScript script) { final List<String> command = new ArrayList<>(); command.add(script.path); if (script.options != null) { command.addAll(Arrays.asList(script.options)); } if (getLog().isDebugEnabled()) { getLog().debug("CLI : " + command); getLog().debug("Package name : " + packageName); getLog().debug("Root CVS folder : " + rootCvsFolder); } getLog().warn(String.format("Starting script in VCS folder [%s] : %s", packageName, StringUtils.join(command.toArray(), ' '))); final ProcessExecutor processExecutor = new ProcessExecutor(command.toArray(new String[0])); processExecutor .exitValueAny() .directory(rootCvsFolder) .environment("MVNGO_CVS_BRANCH", GetUtils.ensureNonNull(this.branch, "")) .environment("MVNGO_CVS_TAG", GetUtils.ensureNonNull(this.tag, "")) .environment("MVNGO_CVS_REVISION", GetUtils.ensureNonNull(this.revision, "")) .environment("MVNGO_CVS_PACKAGE", packageName) .redirectError(System.err) .redirectOutput(System.out); boolean result = false; try { final ProcessResult process = processExecutor.executeNoTimeout(); final int exitValue = process.getExitValue(); result = script.ignoreFail || exitValue == 0; } catch (IOException | InterruptedException | InvalidExitValueException ex) { getLog().error("Error in proces custom script", ex); } return result; }
Example #13
Source File: RabbitMqPlugins.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
private ProcessResult getProcessResult(String[] args, String executionErrorMessage, String unexpectedExitCodeMessage) { ProcessResult processResult; try { Future<ProcessResult> startedProcess = execute(args); processResult = startedProcess.get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException | ExecutionException | TimeoutException e) { throw new RabbitMqCommandException(executionErrorMessage, e); } int exitValue = processResult.getExitValue(); if (exitValue != 0) { throw new RabbitMqCommandException(unexpectedExitCodeMessage + exitValue); } return processResult; }
Example #14
Source File: RabbitMqServer.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
private Future<ProcessResult> execute(String... arguments) throws RabbitMqCommandException { return new RabbitMqCommand(config, COMMAND, arguments) .writeOutputTo(outputStream) .listenToEvents(listener) .call() .getFuture(); }
Example #15
Source File: LoggingProcessListener.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
@Override public void afterFinish(Process process, ProcessResult result) { assert executor != null; // "beforeStart()" must be called previously try { executor.checkExitValue(result); logger.debug("Process finished (exit code: {}).", result.getExitValue()); } catch (InvalidExitValueException e) { logger.error("Process finished with unexpected exit code: {}.", result.getExitValue()); } }
Example #16
Source File: RabbitMqPluginsTest.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void testListParsing() throws Exception { futureResult = mock(Future.class); result = mock(ProcessResult.class); when(startedProcess.getFuture()) .thenReturn(futureResult); when(futureResult.get(anyLong(), any(TimeUnit.class))) .thenReturn(result); when(result.getExitValue()) .thenReturn(0); processOutput = mock(ProcessOutput.class); when(result.getOutput()) .thenReturn(processOutput); List<String> output = Arrays.asList( " Configured: E = explicitly enabled; e = implicitly enabled ", " | Status: * = running on rabbit@rivera-mbp ", " |/ ", "[e*] amqp_client 3.5.7 ", "[ ] cowboy 0.5.0-rmq3.5.7-git4b93c2d", "[e*] mochiweb 2.7.0-rmq3.5.7-git680dba8", "[ ] rabbitmq_amqp1_0 3.5.7 ", "[E*] rabbitmq_management 3.5.7 ", "[e*] rabbitmq_management_agent 3.5.7 " ); when(processOutput.getLinesAsUTF8()) .thenReturn(output); Map<Plugin.State, Set<Plugin>> groupedPlugins = rabbitMqPlugins.groupedList(); assertThat(groupedPlugins.get(Plugin.State.RUNNING).size(), equalTo(4)); assertThat(groupedPlugins.get(Plugin.State.ENABLED_EXPLICITLY).size(), equalTo(1)); assertThat(groupedPlugins.get(Plugin.State.ENABLED_IMPLICITLY).size(), equalTo(3)); assertThat(groupedPlugins.get(Plugin.State.NOT_ENABLED).size(), equalTo(2)); assertThat(groupedPlugins.get(Plugin.State.NOT_RUNNING).size(), equalTo(2)); }
Example #17
Source File: LoggingProcessListenerTest.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void expectedExitValueDoesNotLogError() throws Exception { processExecutor.exitValue(0); loggingProcessListener.afterFinish(null, new ProcessResult(0, null)); ArgumentCaptor<String> msgCaptor = ArgumentCaptor.forClass(String.class); verify(logger).debug(msgCaptor.capture(), Matchers.any()); assertThat(msgCaptor.getValue().toLowerCase(), containsString("process finished")); verify(logger, never()).error(anyString(), anyString()); }
Example #18
Source File: LoggingProcessListenerTest.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
@Test public void expectedExitValueDoesLogError() throws Exception { String command = RandomStringUtils.randomAlphabetic(5); ProcessExecutor processExecutor = new ProcessExecutor(command).exitValue(0); LoggingProcessListener loggingProcessListener = new LoggingProcessListener(logger); loggingProcessListener.beforeStart(processExecutor); loggingProcessListener.afterFinish(null, new ProcessResult(1, null)); ArgumentCaptor<String> msg = ArgumentCaptor.forClass(String.class); verify(logger).error(msg.capture(), anyString()); assertThat(msg.getValue(), containsString("unexpected exit code")); }
Example #19
Source File: MySQLBackupProcessor.java From gocd with Apache License 2.0 | 5 votes |
@Override public void backup(File targetDir, DataSource dataSource, DbProperties dbProperties) throws InterruptedException, TimeoutException, IOException { ProcessResult processResult = createProcessExecutor(targetDir, dbProperties).execute(); if (processResult.getExitValue() == 0) { log.info("MySQL backup finished successfully."); } else { log.warn("There was an error backing up the database using `mysqldump`. The `mysqldump` process exited with status code {}.", processResult.getExitValue()); throw new RuntimeException("There was an error backing up the database using `mysqldump`. The `mysqldump` process exited with status code " + processResult.getExitValue() + ". Please see the server logs for more errors"); } }
Example #20
Source File: PostgresqlBackupProcessor.java From gocd with Apache License 2.0 | 5 votes |
@Override public void backup(File targetDir, DataSource dataSource, DbProperties dbProperties) throws Exception { ProcessResult processResult = createProcessExecutor(targetDir, dbProperties).execute(); if (processResult.getExitValue() == 0) { log.info("PostgreSQL backup finished successfully."); } else { log.warn("There was an error backing up the database using `pg_dump`. The `pg_dump` process exited with status code {}.", processResult.getExitValue()); throw new RuntimeException("There was an error backing up the database using `pg_dump`. The `pg_dump` process exited with status code " + processResult.getExitValue() + ". Please see the server logs for more errors."); } }
Example #21
Source File: ProcessListenerThrowTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Override public void afterFinish(Process process, ProcessResult result) { super.afterFinish(process, result); if (result.getOutput().getString().contains("java version")) { throw new InvalidOutputException("Test", result); } }
Example #22
Source File: ProcessListenerSuccessTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Test public void testJavaVersion() throws Exception { ProcessListenerImpl listener = new ProcessListenerImpl(); ProcessResult result = new ProcessExecutor("java", "-version").addListener(listener).execute(); int exit = result.getExitValue(); Assert.assertEquals(0, exit); Assert.assertNotNull(listener.executor); Assert.assertNotNull(listener.process); Assert.assertNotNull(listener.result); Assert.assertEquals(result, listener.result); }
Example #23
Source File: ProcessListenerSuccessTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Override public void afterFinish(Process process, ProcessResult result) { Assert.assertNotNull(process); Assert.assertNotNull(result); Assert.assertNotNull(this.executor); Assert.assertNotNull(this.process); Assert.assertNull(this.result); Assert.assertEquals(this.process, process); this.result = result; }
Example #24
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Test public void testJavaVersionOutputTwice() throws Exception { ProcessExecutor executor = new ProcessExecutor().command("java", "-version").readOutput(true); ProcessResult result = executor.execute(); String str = result.outputUTF8(); Assert.assertFalse(StringUtils.isEmpty(str)); Assert.assertEquals(str, executor.execute().outputUTF8()); }
Example #25
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Test public void testJavaVersionLogInfoAndOutput() throws Exception { // Just expect no errors - don't check the log file itself ProcessResult result = new ProcessExecutor().command("java", "-version").redirectOutput(Slf4jStream.of("testJavaVersionLogInfoAndOutput").asInfo()).readOutput(true).execute(); String str = result.outputUTF8(); Assert.assertFalse(StringUtils.isEmpty(str)); }
Example #26
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Test public void testJavaVersionLogInfoAndOutputFuture() throws Exception { // Just expect no errors - don't check the log file itself ProcessResult result = new ProcessExecutor().command("java", "-version").redirectOutput(Slf4jStream.of("testJavaVersionLogInfoAndOutputFuture").asInfo()).readOutput(true).start().getFuture().get(); String str = result.outputUTF8(); Assert.assertFalse(StringUtils.isEmpty(str)); }
Example #27
Source File: ProcessExecutorMainTest.java From zt-exec with Apache License 2.0 | 5 votes |
@Test public void testProcessExecutorListInit() 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(args); ProcessResult result = exec.readOutput(true).execute(); Assert.assertEquals("Hello world!", result.outputUTF8()); }
Example #28
Source File: ErlangShell.java From embedded-rabbitmq with Apache License 2.0 | 5 votes |
/** * @return a String representing the Erlang version, such as {@code "18.2.1"} * @throws ErlangShellException if the Erlang command can't be executed or if it exits unexpectedly. */ public String getErlangVersion() throws ErlangShellException { String erlangShell = UNIX_ERL_COMMAND; Logger processOutputLogger = LoggerFactory.getLogger( String.format(LOGGER_TEMPLATE, this.getClass().getName(), erlangShell)); Slf4jStream stream = Slf4jStream.of(processOutputLogger); final ProcessExecutor processExecutor = config.getProcessExecutorFactory().createInstance() .command(erlangShell, "-noshell", "-eval", "erlang:display(erlang:system_info(otp_release)), halt().") .timeout(config.getErlangCheckTimeoutInMillis(), TimeUnit.MILLISECONDS) .redirectError(stream.as(Level.WARN)) .destroyOnExit() .readOutput(true); try { ProcessResult processResult = processExecutor.execute(); int exitValue = processResult.getExitValue(); if (exitValue == 0) { return processResult.outputUTF8().trim().replaceAll("[\"\\\\n]", ""); // "18.2.1\n" -> "18.2.1" } else { throw new ErlangShellException("Erlang exited with status " + exitValue); } } catch (IOException | InterruptedException | TimeoutException e) { throw new ErlangShellException("Exception executing Erlang shell command", e); } }
Example #29
Source File: ExecStoreTest.java From mxisd with GNU Affero General Public License v3.0 | 5 votes |
protected ProcessResult make(int exitCode, Supplier<String> supplier) { return new ProcessResult(exitCode, null) { @Override public String outputUTF8() { return supplier.get(); } }; }
Example #30
Source File: AbstractRepo.java From mvn-golang with Apache License 2.0 | 5 votes |
public int execute(@Nullable String customCommand, @Nonnull final Log logger, @Nonnull final File cvsFolder, @Nonnull @MustNotContainNull final String... args) { final List<String> cli = new ArrayList<>(); cli.add(GetUtils.findFirstNonNull(customCommand, this.command)); cli.addAll(Arrays.asList(args)); if (logger.isDebugEnabled()) { logger.debug("Executing repo command : " + cli); } final ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final ProcessExecutor executor = new ProcessExecutor(cli); int result = -1; try { final ProcessResult processResult = executor.directory(cvsFolder).redirectError(errorStream).redirectOutput(outStream).executeNoTimeout(); result = processResult.getExitValue(); if (logger.isDebugEnabled()) { logger.debug("Exec.out........................................."); logger.debug(new String(errorStream.toByteArray(), Charset.defaultCharset())); logger.debug("................................................."); } if (result != 0) { logger.error(new String(errorStream.toByteArray(), Charset.defaultCharset())); } } catch (IOException | InterruptedException | InvalidExitValueException ex) { if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } logger.error("Unexpected error", ex); } return result; }