Example usage for org.apache.commons.exec DefaultExecutor DefaultExecutor

List of usage examples for org.apache.commons.exec DefaultExecutor DefaultExecutor

Introduction

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

Prototype

public DefaultExecutor() 

Source Link

Document

Default constructor creating a default PumpStreamHandler and sets the working directory of the subprocess to the current working directory.

Usage

From source file:org.zanata.sync.jobs.utils.ProcessUtils.java

public static List<String> runNativeCommand(Path workingDir, long timeoutInMilli, String... commands) {
    Preconditions.checkArgument(commands != null && commands.length > 0, "You must provide commands to run");

    CommandLine commandLine = CommandLine.parse(commands[0]);
    ImmutableList<String> args = ImmutableList.copyOf(commands).subList(1, commands.length);
    for (String arg : args) {
        commandLine.addArgument(arg);//from   w ww .  j  ava2  s .  c o  m
    }

    Executor executor = new DefaultExecutor();

    ImmutableList.Builder<String> output = ImmutableList.builder();
    executor.setStreamHandler(new PumpStreamHandler(new LogOutputStream() {
        @Override
        protected void processLine(String line, int logLevel) {
            log.info(line);
            output.add(line);
        }
    }));
    ExecuteWatchdog watchDog = new ExecuteWatchdog(timeoutInMilli);
    executor.setWatchdog(watchDog);
    executor.setWorkingDirectory(workingDir.toFile());
    executor.setProcessDestroyer(PROCESS_DESTROYER);

    try {
        int exitCode = executor.execute(commandLine);
        if (Execute.isFailure(exitCode) && watchDog.killedProcess()) {
            // it was killed on purpose by the watchdog
            log.error("process {} taking too long to run and killed by watchdog", commandLine);
        }
    } catch (IOException e) {
        log.error("error running:{}", commandLine);
        throw Throwables.propagate(e);
    }

    return output.build();
}

From source file:pl.net.ptak.InstallShieldBuildMojo.java

/**
 * Verifies that configuration is satisfied to bild the project and builds it.
 * /*from w  w w  .j  a va 2  s .  c o  m*/
 * @throws MojoExecutionException when plugin is misconfigured
 * @throws MojoFailureException when plugin execution result was other than expected
 * @see org.apache.maven.plugin.AbstractMojo#execute()
 */
public void execute() throws MojoExecutionException, MojoFailureException {

    if (!OS.isFamilyWindows()) {
        throw new MojoExecutionException("This plugin is for Windows systems only");
    }

    if (!installshieldOutputDirectory.exists()) {
        installshieldOutputDirectory.mkdirs();
    }

    if (installshieldProjectFile == null || !installshieldProjectFile.exists()) {
        if (failWhenNoInstallshieldFile) {
            getLog().error(String.format("IS Project File available: %b", installshieldProjectFile.exists()));
            throw new MojoFailureException("InstallShield project file not found");
        } else {
            getLog().info("IS Project File not found. IS build skipped");
        }
    } else {

        String canonicalProjectFilePath = resolveCanonicalPath(installshieldProjectFile);

        getLog().info(String.format("About to build file %s", canonicalProjectFilePath));

        String canonicalOutputDirectoryPath = resolveCanonicalPath(installshieldOutputDirectory);

        getLog().info(String.format("Output will be placed in %s", canonicalOutputDirectoryPath));

        CommandLine installshieldCommandLine = new CommandLine(installshieldExecutable);

        addCmdLnArguments(installshieldCommandLine, "-p", canonicalProjectFilePath);
        addCmdLnArguments(installshieldCommandLine, "-b", canonicalOutputDirectoryPath);
        if (usePomVersion && null != version && !version.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-y", version);

        }

        if (null != productConfiguration && !productConfiguration.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-a", productConfiguration);
        }

        if (null != productRelease && !productRelease.isEmpty()) {
            addCmdLnArguments(installshieldCommandLine, "-r", productRelease);
        }

        if (null != properties && !properties.isEmpty()) {
            for (Entry<String, String> entry : properties.entrySet()) {
                addCmdLnArguments(installshieldCommandLine, "-z",
                        String.format("%s=%s", entry.getKey(), entry.getValue()));
            }
        }

        if (null != pathVariables && !pathVariables.isEmpty()) {
            for (Entry<String, String> entry : pathVariables.entrySet()) {
                addCmdLnArguments(installshieldCommandLine, "-l",
                        String.format("%s=%s", entry.getKey(), entry.getValue()));
            }
        }

        Executor exec = new DefaultExecutor();

        getLog().debug(
                String.format("IS Build Command to be executed: %s", installshieldCommandLine.toString()));

        try {
            int exitCode = exec.execute(installshieldCommandLine);
            getLog().debug(String.format("IS build exit code: %d", exitCode));
            if (exitCode != 0) {
                throw new MojoFailureException("Failed to build IS project");
            }
        } catch (IOException e) {
            String errorMessage = "Failed to execute InstallShield build";
            getLog().error(errorMessage);
            getLog().debug("Details to failure: ", e);
            throw new MojoFailureException(errorMessage);
        }
    }

}

From source file:processing.app.debug.Compiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 */// ww w .j a v  a  2  s.  com
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, Compiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(_("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(_("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:processing.app.debug.OldCompiler.java

/**
 * Either succeeds or throws a RunnerException fit for public consumption.
 *//*from   ww w .  j  ava2 s. c  o m*/
private void execAsynchronously(String[] command) throws RunnerException {

    // eliminate any empty array entries
    List<String> stringList = new ArrayList<String>();
    for (String string : command) {
        string = string.trim();
        if (string.length() != 0)
            stringList.add(string);
    }
    command = stringList.toArray(new String[stringList.size()]);
    if (command.length == 0)
        return;

    if (verbose) {
        for (String c : command)
            System.out.print(c + " ");
        System.out.println();
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler() {

        @Override
        protected Thread createPump(InputStream is, OutputStream os, boolean closeWhenExhausted) {
            final Thread result = new Thread(new MyStreamPumper(is, OldCompiler.this));
            result.setDaemon(true);
            return result;

        }
    });

    CommandLine commandLine = new DoubleQuotedArgumentsOnWindowsCommandLine(command[0]);
    for (int i = 1; i < command.length; i++) {
        commandLine.addArgument(command[i], false);
    }

    int result;
    executor.setExitValues(null);
    try {
        result = executor.execute(commandLine);
    } catch (IOException e) {
        RunnerException re = new RunnerException(e.getMessage());
        re.hideStackTrace();
        throw re;
    }
    executor.setExitValues(new int[0]);

    // an error was queued up by message(), barf this back to compile(),
    // which will barf it back to Editor. if you're having trouble
    // discerning the imagery, consider how cows regurgitate their food
    // to digest it, and the fact that they have five stomaches.
    //
    //System.out.println("throwing up " + exception);
    if (exception != null)
        throw exception;

    if (result > 1) {
        // a failure in the tool (e.g. unable to locate a sub-executable)
        System.err.println(I18n.format(tr("{0} returned {1}"), command[0], result));
    }

    if (result != 0) {
        RunnerException re = new RunnerException(tr("Error compiling."));
        re.hideStackTrace();
        throw re;
    }
}

From source file:processing.app.macosx.Platform.java

private void discoverRealOsArch() throws IOException {
    CommandLine uname = CommandLine.parse("uname -m");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Executor executor = new DefaultExecutor();
    executor.setStreamHandler(new PumpStreamHandler(baos, null));
    executor.execute(uname);//from  w  ww.  j  a v a 2  s.  co  m
    osArch = StringUtils.trim(new String(baos.toByteArray()));
}

From source file:ro.cosu.vampires.client.executors.fork.ForkModule.java

@Provides
private org.apache.commons.exec.Executor provideExecutor() {
    return new DefaultExecutor();
}

From source file:ro.cosu.vampires.server.resources.local.LocalResourceModule.java

@Provides
private Executor provideExecutor() {
    return new DefaultExecutor();
}

From source file:sce.ProcessExecutor.java

public String executeProcess(String[] processParameters) throws JobExecutionException {
    try {/*  ww w.java 2s .  com*/
        //Command to be executed
        CommandLine command = new CommandLine(processParameters[0]);

        String[] params = new String[processParameters.length - 1];
        for (int i = 0; i < processParameters.length - 1; i++) {
            params[i] = processParameters[i + 1];
        }

        //Adding its arguments
        command.addArguments(params);

        //set timeout in seconds
        ExecuteWatchdog watchDog = new ExecuteWatchdog(
                this.timeout == 0 ? ExecuteWatchdog.INFINITE_TIMEOUT : this.timeout * 1000);
        this.watchdog = watchDog;

        //Result Handler for executing the process in a Asynch way
        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        //MyResultHandler resultHandler = new MyResultHandler();

        //Using Std out for the output/error stream
        //ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        //This is used to end the process when the JVM exits
        ShutdownHookProcessDestroyer processDestroyer = new ShutdownHookProcessDestroyer();

        //Our main command executor
        DefaultExecutor executor = new DefaultExecutor();

        //Setting the properties
        executor.setStreamHandler(new PumpStreamHandler(null, null));
        executor.setWatchdog(watchDog);
        //executor.setExitValue(1); // this has to be set if the java code contains System.exit(1) to avoid a FAILED status

        //Setting the working directory
        //Use of recursion along with the ls makes this a long running process
        //executor.setWorkingDirectory(new File("/home"));
        executor.setProcessDestroyer(processDestroyer);

        //if set, use the java environment variables when running the command
        if (!this.environment.equals("")) {
            Map<String, String> procEnv = EnvironmentUtils.getProcEnvironment();
            EnvironmentUtils.addVariableToEnvironment(procEnv, this.environment);
            //Executing the command
            executor.execute(command, procEnv, resultHandler);
        } else {
            //Executing the command
            executor.execute(command, resultHandler);
        }

        //The below section depends on your need
        //Anything after this will be executed only when the command completes the execution
        resultHandler.waitFor();

        /*int exitValue = resultHandler.getExitValue();
         System.out.println(exitValue);
         if (executor.isFailure(exitValue)) {
         System.out.println("Execution failed");
         } else {
         System.out.println("Execution Successful");
         }
         System.out.println(outputStream.toString());*/
        //return outputStream.toString();
        if (watchdog.killedProcess()) {
            throw new JobExecutionException("Job Interrupted", new InterruptedException());
        }
        if (executor.isFailure(resultHandler.getExitValue())) {
            ExecuteException ex = resultHandler.getException();
            throw new JobExecutionException(ex.getMessage(), ex);
        }
        return "1";
    } catch (ExecuteException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    } catch (IOException | InterruptedException | JobExecutionException ex) {
        throw new JobExecutionException(ex.getMessage(), ex);
    }
}

From source file:uk.org.sappho.applications.transcript.service.registry.vcs.CommandExecuter.java

public String execute(Command command, File directory) throws TranscriptException {

    try {//from  ww  w . j a v  a 2  s.co  m
        if (logger.isLoggable(Level.INFO)) {
            logger.info(command.getSafeCommand());
        }
        DefaultExecutor executor = new DefaultExecutor();
        DefaultExecuteResultHandler commandResultsHandler = new DefaultExecuteResultHandler();
        ByteArrayOutputStream commandOutputStream = new ByteArrayOutputStream();
        ByteArrayOutputStream commandErrorStream = new ByteArrayOutputStream();
        PumpStreamHandler pumpStreamHandler = new PumpStreamHandler(commandOutputStream, commandErrorStream);
        executor.setWatchdog(new ExecuteWatchdog(60000));
        executor.setStreamHandler(pumpStreamHandler);
        executor.setWorkingDirectory(directory);
        executor.execute(command.getCommandLine(), commandResultsHandler);
        commandResultsHandler.waitFor();
        if (commandResultsHandler.getExitValue() != 0) {
            throw new TranscriptException(commandErrorStream.toString());
        }
        return commandOutputStream.toString();
    } catch (Throwable throwable) {
        if (logger.isLoggable(Level.WARNING)) {
            logger.warning(throwable.getMessage());
        }
        throw new TranscriptException("Unable to execute system command: " + command.getSafeCommand(),
                throwable);
    }
}

From source file:util.Utility.java

/**
 * command line execution/*from ww  w  .  java  2s. c  o  m*/
 * 
 * @param line command line
 * @return output string of running this command line
 */
public static String exec(String line) {

    //String line = "wc -l " + "/home/hathitrust/solr/ToVM_Solr_related/test/apache-tomcat-6.0.35/bin/proxy_logs/logfile";

    CommandLine command = CommandLine.parse(line);

    DefaultExecutor executor = new DefaultExecutor();

    //int exitValue = executor.execute(command);

    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    PumpStreamHandler pump_stream_handler = new PumpStreamHandler(stdout);

    executor.setStreamHandler(pump_stream_handler);

    int exitValue = 0;
    try {
        exitValue = executor.execute(command);
    } catch (ExecuteException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // System.out.println(exitValue);

    // System.out.println(stdout.toString());

    return stdout.toString();

}