Java Code Examples for org.zeroturnaround.exec.ProcessResult#getExitValue()
The following examples show how to use
org.zeroturnaround.exec.ProcessResult#getExitValue() .
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: 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 2
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 3
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 4
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 5
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 6
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; }
Example 7
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 8
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 9
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 10
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 11
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 12
Source File: AbstractGolangMojo.java From mvn-golang with Apache License 2.0 | 4 votes |
protected boolean doMainBusiness(@Nullable final ProxySettings proxySettings, final int maxAttempts) throws InterruptedException, MojoFailureException, MojoExecutionException, IOException { int iterations = 0; boolean error = false; while (!Thread.currentThread().isInterrupted()) { final ProcessExecutor executor = prepareExecutor(proxySettings); if (executor == null) { logOptionally("The Mojo should not be executed"); break; } final ProcessResult result = executor.executeNoTimeout(); final int resultCode = result.getExitValue(); error = resultCode != 0 && !isIgnoreErrorExitCode(); iterations++; final String outLog = extractOutAsString(); final String errLog = extractErrorOutAsString(); if (getLog().isDebugEnabled()) { getLog().debug("OUT_LOG: " + outLog); getLog().debug("ERR_LOG: " + errLog); } this.processConsoleOut(resultCode, outLog, errLog); printLogs(error || isEnforcePrintOutput() || (this.isVerbose() && this.isCommandSupportVerbose()), error, outLog, errLog); if (doesNeedOneMoreAttempt(result, outLog, errLog)) { if (iterations > maxAttempts) { throw new MojoExecutionException("Too many iterations detected, may be some loop and bug at mojo " + this.getClass().getName()); } getLog().warn("Make one more attempt..."); } else { if (!isIgnoreErrorExitCode()) { assertProcessResult(result); } break; } } return error; }
Example 13
Source File: AbstractGolangMojo.java From mvn-golang with Apache License 2.0 | 4 votes |
private void assertProcessResult(@Nonnull final ProcessResult result) throws MojoFailureException { final int code = result.getExitValue(); if (code != 0) { throw new MojoFailureException("Process exit code : " + code); } }