Example usage for org.apache.commons.exec ExecuteException getMessage

List of usage examples for org.apache.commons.exec ExecuteException getMessage

Introduction

In this page you can find the example usage for org.apache.commons.exec ExecuteException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.apache.zeppelin.submarine.SubmarineJobTest.java

@Test
public void defaultExecutorTest() throws IOException {
    DefaultExecutor executor = new DefaultExecutor();
    CommandLine cmdLine = CommandLine.parse(shell);

    URL urlTemplate = Resources.getResource(DEFAULT_EXECUTOR_TEST);

    cmdLine.addArgument(urlTemplate.getFile(), false);

    Map<String, String> env = new HashMap<>();
    env.put("CLASSPATH", "`$HADOOP_HDFS_HOME/bin/hadoop classpath --glob`");
    env.put("EVN", "test");

    AtomicBoolean cmdLineRunning = new AtomicBoolean(true);
    StringBuffer sbLogOutput = new StringBuffer();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override/*from  w  w w  .  j  a va2s  .c o  m*/
        protected void processLine(String line, int level) {
            //LOGGER.info(line);
            sbLogOutput.append(line + "\n");
        }
    }));

    executor.execute(cmdLine, env, new DefaultExecuteResultHandler() {
        @Override
        public void onProcessComplete(int exitValue) {
            cmdLineRunning.set(false);
        }

        @Override
        public void onProcessFailed(ExecuteException e) {
            cmdLineRunning.set(false);
            LOGGER.error(e.getMessage());
        }
    });
    int loopCount = 100;
    while ((loopCount-- > 0) && cmdLineRunning.get()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    LOGGER.info(sbLogOutput.toString());
}

From source file:org.cloudifysource.shell.commands.TestRecipe.java

/**
 * Execute a command line in with a given map of environment settings. The execution outupt is filtered unless
 * verbose is set to true./*  ww  w .  j ava2  s  .  c  om*/
 *
 * @param cmdLine
 *            The command to execute
 * @param env
 *            Environment settings available for the command execution
 * @return the command's execution exit code, or -2 if the command failed to execute
 */
private int executeRecipe(final CommandLine cmdLine, final Map<Object, Object> env) {
    final DefaultExecutor executor = new DefaultExecutor();

    // The watchdog will terminate the process if it does not end within the
    // specified timeout
    final int externalProcessTimeout = (this.timeout + EXTERNAL_PROCESS_WATCHDOG_ADDITIONAL_TIMEOUT) * 1000;
    final ExecuteWatchdog watchdog = new TestRecipeWatchdog(externalProcessTimeout);
    executor.setWatchdog(watchdog);

    executor.setExitValue(0);
    int result = -1;

    PipedInputStream in = null;
    PipedOutputStream out = null;
    BufferedReader reader = null;
    try {
        in = new PipedInputStream();
        out = new PipedOutputStream(in);
        reader = new BufferedReader(new InputStreamReader(in));

        final Thread thread = new Thread(new FilteredOutputHandler(reader, this.verbose));
        thread.setDaemon(true);
        thread.start();

        final PumpStreamHandler psh = new PumpStreamHandler(out, out);
        executor.setStreamHandler(psh);
        result = executor.execute(cmdLine, env);
    } catch (final ExecuteException e) {
        logger.log(Level.SEVERE, "A problem was encountered while executing the recipe: " + e.getMessage(), e);
    } catch (final IOException e) {
        logger.log(Level.SEVERE,
                "An IO Exception was encountered while executing the recipe: " + e.getMessage(), e);
        result = UNEXPECTED_ERROR_EXIT_CODE;
    }

    return result;
}

From source file:org.excalibur.service.manager.NodeManager.java

public void execute(final ApplicationExecutionRequest request) throws ExecuteException, IOException {
    final long start = nanoTime();
    final long timeS = currentTimeMillis();

    request.setOwner(this.userService_.createIfDoesNotExist(request.getOwner(), request.getKeyPairs()));

    new Worker().execute(request.getApplication(), new ExecuteResultHandler() {
        @Override/*from  w ww  .j  a  v a 2s . com*/
        public void onProcessFailed(ExecuteException e) {
            onComplete(e, e.getExitValue());
        }

        @Override
        public void onProcessComplete(int exitValue) {
            onComplete(null, exitValue);
        }

        private void onComplete(ExecuteException failure, int exitValue) {
            final long elapsedTime = nanoTime() - start;
            final long elapsedTimeM = currentTimeMillis() - timeS;
            String failureReason = Strings.nullToEmpty(failure != null ? failure.getMessage() : null);

            LOG.info(
                    "Completed the execution of the task: [{}] in [{}/{} seconds] of job: [{}], manager: [{}], "
                            + " with exitValue: [{}] from requestId: [{}], failure reason: [{}]",
                    request.getApplication().getId(), MILLISECONDS.toSeconds(elapsedTimeM),
                    NANOSECONDS.toSeconds(elapsedTime), request.getJobId(), request.getManager().getName(),
                    exitValue, request.getId(), failureReason);

            Client client = ClientBuilder.newClient().register(ObjectMapperProvider.class)
                    .register(JacksonFeature.class);
            WebTarget target = client.target(String.format("http://%s:%s/application",
                    request.getManager().getConfiguration().getPublicIpAddress(), 8080));

            String output = Base64
                    .encodeBase64String(compress(readLinesQuietly(request.getApplication().getOuputFile())));

            ApplicationExecutionResult result = new ApplicationExecutionResult();
            result.setApplication(request.getApplication()).setId(request.getId()).setJobId(request.getJobId())
                    .setUser(request.getOwner()).setElapsedTime(elapsedTime).setElapsedTimeMillis(elapsedTimeM)
                    .setFailureReason(failureReason).setReplyId(request.getId()).setExitValue(exitValue)
                    .setWorker(request.getWorker()).setOutput(output);

            target.path("reply").request(APPLICATION_XML_TYPE)
                    .post(Entity.entity(result, APPLICATION_XML_TYPE));
        }
    });
}

From source file:org.fuin.kickstart4j.ErrorDialog.java

/**
 * Constructor with stream, exception and exit code.
 * /*from   w  w  w  .ja v a 2  s  . c  o  m*/
 * @param errStream
 *            Error stream filled by <code>Executor</code>.
 * @param executeException
 *            Exception from <code>onProcessFailed(..)</code> method.
 * @param exitCode
 *            Code for <code>System.exit(..)</code>.
 */
private ErrorDialog(final ByteArrayOutputStream errStream, final ExecuteException executeException,
        final int exitCode) {
    Utils4J.checkNotNull("errStream", errStream);
    Utils4J.checkNotNull("executeException", executeException);
    final String msg = errStream.toString();
    if (msg.length() == 0) {
        message = executeException.getMessage();
    } else {
        message = msg;
    }
    this.exitCode = exitCode;
}

From source file:org.jahia.services.templates.SourceControlFactory.java

/**
 * Sets the executables for various SCM providers.
 * /*from   ww w .j ava  2  s .com*/
 * @param sourceControlExecutables
 *            a map with paths to SCM executables by SCM type
 */
public void setSourceControlExecutables(Map<String, String> sourceControlExecutables) {
    this.sourceControlExecutables = new HashMap<String, String>();
    for (Map.Entry<String, String> entry : sourceControlExecutables.entrySet()) {
        try {
            DefaultExecutor executor = new DefaultExecutor();
            executor.setStreamHandler(
                    new PumpStreamHandler(new StringOutputStream(), new StringOutputStream()));
            executor.execute(new CommandLine(entry.getValue()), System.getenv());
        } catch (ExecuteException e) {
            // ignore this one as the command always returns error code 1
        } catch (IOException e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to execute the " + entry.getKey() + " SCM executable: " + entry.getValue()
                        + ". The SCM provider will be disabled. Cause: " + e.getMessage(), e);
            } else {
                logger.info("Cannot find a valid " + entry.getKey() + " SCM executable at: " + entry.getValue()
                        + ". The SCM provider will be skipped.");
            }
            continue;
        }
        this.sourceControlExecutables.put(entry.getKey(), entry.getValue());
    }
}

From source file:org.jboss.tools.windup.runtime.WindupRmiClient.java

public void startWindup(final IProgressMonitor monitor, String jreHome) {
    logInfo("Begin start RHAMT."); //$NON-NLS-1$
    monitor.worked(1);//from  w  w w  .java 2 s.c om

    String windupExecutable = WindupRuntimePlugin.computeWindupExecutable();

    if (windupExecutable == null) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not specified."); //$NON-NLS-1$
        return;
    }

    boolean executable = new File(windupExecutable).setExecutable(true);
    if (!executable) {
        WindupRuntimePlugin.logErrorMessage("rhamt-cli not executable."); //$NON-NLS-1$
        return;
    }

    CommandLine cmdLine = CommandLine.parse(windupExecutable);

    Map<String, String> env = Maps.newHashMap();
    for (Map.Entry<String, String> entry : System.getenv().entrySet()) {
        env.put(entry.getKey(), entry.getValue());
    }
    if (!jreHome.trim().isEmpty()) {
        env.put(JAVA_HOME, jreHome);
    }

    logInfo("Using " + JAVA_HOME + " - " + jreHome);

    cmdLine.addArgument("--startServer"); //$NON-NLS-1$
    cmdLine.addArgument(String.valueOf(getRmiPort()));
    watchdog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
    ExecuteResultHandler handler = new ExecuteResultHandler() {
        @Override
        public void onProcessFailed(ExecuteException e) {
            logInfo("The RHAMT process failed:"); //$NON-NLS-1$
            logInfo(e.getMessage()); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }

        @Override
        public void onProcessComplete(int exitValue) {
            logInfo("The RHAMT process has completed."); //$NON-NLS-1$
            executionBuilder = null;
            notifyServerChanged();
        }
    };
    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            logInfo("Message from RHAMT executor: " + line); //$NON-NLS-1$
            monitor.worked(1);
        }
    }));
    executor.setWatchdog(watchdog);
    executor.setExitValue(1);
    monitor.worked(1);
    try {
        logInfo("Starting RHAMT in server mode..."); //$NON-NLS-1$
        logInfo("Command-line: " + cmdLine); //$NON-NLS-1$
        executor.execute(cmdLine, env, handler);
    } catch (IOException e) {
        WindupRuntimePlugin.log(e);
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void stageInputFile(FilePaths files, EngineData output) {
    Path stagePath = FileUtils.getParent(files.stagedInputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {//from   ww w .j av  a  2 s  .  c om
        FileUtils.createDirectories(stagePath);

        CommandLine cmdLine = new CommandLine("cp");
        cmdLine.addArgument(files.inputFile.toString());
        cmdLine.addArgument(files.stagedInputFile.toString());

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

        executor.execute(cmdLine);
        System.out.printf("%s service: input file '%s' copied to '%s'%n", NAME, files.inputFile, stagePath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void removeStagedInputFile(FilePaths files, EngineData output) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {//ww  w  .ja va  2 s.c o m
        CommandLine cmdLine = new CommandLine("rm");
        cmdLine.addArgument(files.stagedInputFile.toString());

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

        executor.execute(cmdLine);
        System.out.printf("%s service: staged input file %s removed%n", NAME, files.stagedInputFile);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.jlab.clara.std.services.DataManager.java

private void saveOutputFile(FilePaths files, EngineData output) {
    Path outputPath = FileUtils.getParent(files.outputFile);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {/*from  w  w w.ja  va2  s.com*/
        FileUtils.createDirectories(outputPath);

        CommandLine cmdLine = new CommandLine("mv");

        //            cmdLine.addArgument(files.stagedOutputFile.toString());
        //            cmdLine.addArgument(files.outputFile.toString());

        //             modified 09.12.18. Stage back multiple output files. vg
        Files.list(directoryPaths.stagePath).forEach(name -> {
            name.startsWith(files.stagedOutputFile.toString());
            cmdLine.addArgument(name.toString());
        });
        cmdLine.addArgument(outputPath.toString());
        //                                                                  vg

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

        executor.execute(cmdLine);
        System.out.printf("%s service: output file '%s' saved to '%s'%n", NAME, files.stagedOutputFile,
                outputPath);
        returnFilePaths(output, files);

    } catch (ExecuteException e) {
        ServiceUtils.setError(output, "could not complete request: " + outputStream.toString().trim());
    } catch (IOException e) {
        ServiceUtils.setError(output, "could not complete request: " + e.getMessage());
    }
}

From source file:org.mail.bridge.FolderMonitor.java

public synchronized void runScriptAgainstReceivedFiles(List<File> inboxFiles) {
    if (config.getInboxScript().isEmpty() || Utils.isEmpty(inboxFiles))
        return;/*from  w  w  w .  j  ava  2 s . c o m*/
    LOG.debug("Run script '{}' against files {}", config.getInboxScript(), inboxFiles);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        CommandLine cmd = CommandLine.parse(config.getInboxScript());
        for (File file : inboxFiles)
            cmd.addArgument(file.getName(), true);
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out));
        executor.setWatchdog(new ExecuteWatchdog(SCRIPT_TIMEOUT));
        Map<String, String> environment = EnvironmentUtils.getProcEnvironment();
        environment.putAll(config.asEnvironmentMap());
        executor.setWorkingDirectory(new File(System.getProperty("user.dir")));
        executor.execute(cmd, environment);
        LOG.info("Script '{}' successfully finished", config.getInboxScript());
        LOG.debug("Script output:\n{}", out.toString());
    } catch (ExecuteException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
        int c = config.getInboxScriptStopCode();
        if (c != 0 && c == e.getExitValue())
            postMessage(new Main.StopMessage(
                    String.format("Script '%s' exited with code %d that is configured as stop code",
                            config.getInboxScript(), c)));
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        LOG.error("\nScript '{}' output:\n{}", config.getInboxScript(), out.toString());
    }
}