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.mule.tooling.jubula.cliexecutor.internal.DefaultCliExecutor.java

@Override
public void runAsync(final String commandString, final Callback callback, final String... params) {
    try {/*from www  .j a va 2  s  .c o m*/
        final DefaultExecutor executor = new DefaultExecutor();
        final CommandLine command = CommandLine.parse(commandString);
        command.addArguments(params, true);
        executor.execute(command, new ExecuteResultHandler() {

            @Override
            public void onProcessFailed(final ExecuteException returnCode) {
                callback.failure(returnCode.getExitValue());
            }

            @Override
            public void onProcessComplete(final int returnCode) {
                callback.success(returnCode);
            }
        });
    } catch (final ExecuteException e) {
        throw new RuntimeException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mybatis.generator.ext.api.MeldMergeShellCallback.java

public static boolean exec(String command) {
    CommandLine commandLine = CommandLine.parse(command);
    DefaultExecutor executor = new DefaultExecutor();
    int exitValue = DefaultExecutor.INVALID_EXITVALUE;
    ExecuteWatchdog watchdog = new ExecuteWatchdog(2000);
    executor.setWatchdog(watchdog);// w w  w .ja v  a 2s  . c  om
    try {
        exitValue = executor.execute(commandLine);
    } catch (ExecuteException e) {
        exitValue = e.getExitValue();
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
    System.out.println("Exit :" + exitValue);
    return (exitValue == 0);
}

From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProbe.java

public static boolean testExecutable() {
    CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " --version");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();

    // put a watchdog with a timeout
    ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000);
    executor.setWatchdog(watchdog);/*  w ww  .ja  v  a  2 s .  c o m*/

    try {
        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProbe.java

public static String getVersion() {

    try {//from w  ww . ja va  2s  .c  om
        URL scriptURL = PythonCLIProbe.class.getResource(versionScriptFile);
        File sf = new File(scriptURL.toURI());
        String scriptPath = sf.getAbsolutePath();

        CommandLine commandLine = CommandLine.parse(PythonCLIProcessor.pythonExecutable + " " + scriptPath);

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        Executor executor = new DefaultExecutor();

        // put a watchdog with a timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeout_seconds) * 1000);
        executor.setWatchdog(watchdog);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PumpStreamHandler psh = new PumpStreamHandler(os);
        executor.setStreamHandler(psh);

        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return null;
        }

        return (os.toString());

    } catch (Exception e) {
        return null;
    }
}

From source file:org.n52.movingcode.runtime.processors.python.PythonCLIProcessor.java

public void execute(int timeoutSeconds) throws IllegalArgumentException, RuntimeException, IOException {

    if (!init()) {
        throw new IOException("Could not initialize the processor. Aborting operation.");
    }/* w ww .  j  a  va  2  s  . co  m*/

    // load arguments and parse them to internal data format (--> Strings)
    for (IOParameter item : this.values()) {
        try {
            setValue(item);
        } catch (IOException e) {
            throw new IOException("Could not deal with parameter: " + item.getIdentifier().toString() + "\n"
                    + e.getMessage());
        }
    }

    // create command from parameters and values
    String executable = packageDescriptionDoc.getPackageDescription().getWorkspace().getExecutableLocation();
    if (executable.startsWith("./")) {
        executable = executable.substring(2);
    }

    if (executable.startsWith(".\\")) {
        executable = executable.substring(2);
    }
    executable = "python " + this.clonedWorkspace + File.separator + executable;

    CommandLine cmdLine = buildCommandLine(executable, this.executionValues, this);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);
    executor.setStreamHandler(streamHandler);

    // put a watchdog if required
    if (timeoutSeconds > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(timeoutSeconds) * 1000);
        executor.setWatchdog(watchdog);
    }

    try {
        executor.execute(cmdLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            LOGGER.error("stderr was: " + errorStream.toString());
            LOGGER.error("stdout was: " + outputStream.toString());
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("stdout was:" + outputStream.toString());
                LOGGER.debug("stderr was:" + errorStream.toString());
            }
        }
    } catch (ExecuteException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } catch (InterruptedException e) {
        throw new RuntimeException(
                "Execution was interrupted. Process aborted.\n Message was: " + e.getMessage());
    }

    // update executionData - file data only
    // code below is all about setting the input stream for output media data
    for (ParameterID identifier : this.keySet()) {
        if (this.get(identifier).isMessageOut()) {
            if (this.get(identifier).supportsType(IODataType.MEDIA)) {
                @SuppressWarnings("unchecked")
                List<MediaData> mediaValues = (List<MediaData>) this.get(identifier);
                for (int i = 0; i < mediaValues.size(); i++) {
                    String fileName = this.executionValues.get(identifier)[i];
                    // <-- this is the important line -->
                    mediaValues.get(i).setMediaStream(new FileInputStream(fileName));
                }

            } else {
                // not supported for CLI
            }
        }
    }

}

From source file:org.n52.movingcode.runtime.processors.r.RCLIProbe.java

private static boolean testExecutable() {
    CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
    Executor executor = new DefaultExecutor();

    // put a watchdog with a timeout
    ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000);
    executor.setWatchdog(watchdog);//from  w  w  w  . ja  v a  2  s. c om

    try {
        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return false;
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.n52.movingcode.runtime.processors.r.RCLIProbe.java

private static String getVersion() {
    try {//  w  w w  . j  a v a 2  s. c  om
        CommandLine commandLine = CommandLine.parse(RCLIProcessor.rExecutable + " " + VERSION_CALL);

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        Executor executor = new DefaultExecutor();

        // put a watchdog with a timeout
        ExecuteWatchdog watchdog = new ExecuteWatchdog(new Long(TIMEOUT_SECONDS) * 1000);
        executor.setWatchdog(watchdog);

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PumpStreamHandler psh = new PumpStreamHandler(os);
        executor.setStreamHandler(psh);

        executor.execute(commandLine, resultHandler);
        resultHandler.waitFor();
        int exitVal = resultHandler.getExitValue();
        if (exitVal != 0) {
            return null;
        }

        String osString = os.toString();

        String versionString = osString.substring(osString.lastIndexOf(": ") + 2);
        versionString = versionString.substring(0, versionString.indexOf('\n'));

        return (versionString);
    } catch (Exception e) {
        LOGGER.error("Could not get version string.", e);
        return null;
    }
}

From source file:org.nanoko.coffee.mill.mojos.reporting.JsDocMojo.java

private void generateJSDOC() throws MavenReportException {
    if (skipJSDOC) {
        getLog().info("JSDoc report generation skipped");
        return;//  w ww . j  ava 2  s . com
    }

    File jsdocExec = ExecUtils.findExecutableInPath("jsdoc");
    if (jsdocExec == null) {
        getLog().error("Cannot build jsdoc report - jsdoc not in the system path, the report is ignored.");
        return;
    } else {
        getLog().info("Invoking jsdoc : " + jsdocExec.getAbsolutePath());
        getLog().info("Output directory : " + getOutputDirectory());
    }

    File out = new File(getOutputDirectory());
    out.mkdirs();

    CommandLine cmdLine = CommandLine.parse(jsdocExec.getAbsolutePath());

    // Destination
    cmdLine.addArgument("--destination");
    cmdLine.addArgument(out.getAbsolutePath());

    if (jsdocIncludePrivate) {
        cmdLine.addArgument("--private");
    }

    File input = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".js");
    if (!input.exists()) {
        throw new MavenReportException("Cannot find the project's artifact : " + input.getAbsolutePath());
    }
    cmdLine.addArgument(input.getAbsolutePath());

    DefaultExecutor executor = new DefaultExecutor();

    executor.setWorkingDirectory(project.getBasedir());
    executor.setExitValue(0);
    try {
        getLog().info("Executing " + cmdLine.toString());
        executor.execute(cmdLine);
    } catch (IOException e) {
        throw new MavenReportException("Error during jsdoc report generation", e);
    }

}

From source file:org.nanoko.coffee.mill.processors.JpegTranProcessor.java

private void optimize(File file) throws ProcessorException {
    File dir = file.getParentFile();

    // Build command line
    CommandLine cmdLine = CommandLine.parse(jpegTranExec.getAbsolutePath());

    if (verbose) {
        cmdLine.addArgument("-verbose");
    }/*  w w  w .j  a  v a  2 s .c  o  m*/

    cmdLine.addArgument("-copy");
    cmdLine.addArgument("none");

    cmdLine.addArgument("-optimize");

    cmdLine.addArgument("-outfile");
    cmdLine.addArgument("out.jpeg");

    cmdLine.addArgument(file.getName());

    DefaultExecutor executor = new DefaultExecutor();

    executor.setWorkingDirectory(dir);
    executor.setExitValue(0);
    try {
        getLog().info("Executing " + cmdLine.toString());
        executor.execute(cmdLine);

        // Overwrite the original file
        File out = new File(dir, "out.jpeg");
        if (out.exists()) {
            FileUtils.copyFile(new File(dir, "out.jpeg"), file);
        } else {
            throw new IOException("Output file not found : " + out.getAbsolutePath());
        }

        getLog().info(file.getName() + " optimized");
    } catch (IOException e) {
        throw new ProcessorException("Error during JPG optimization of " + file.getAbsolutePath(), e);
    }
}

From source file:org.nanoko.coffee.mill.processors.OptiPNGProcessor.java

private void optimize(File file) throws ProcessorException {
    File dir = file.getParentFile();

    // Build command line
    CommandLine cmdLine = CommandLine.parse(optiPNGExec.getAbsolutePath());
    cmdLine.addArgument(file.getName());

    if (verbose) {
        cmdLine.addArgument("-v");
    }/*from w  ww.  j  a  va 2 s  .  co  m*/

    cmdLine.addArgument("-o" + level);

    DefaultExecutor executor = new DefaultExecutor();

    executor.setWorkingDirectory(dir);
    executor.setExitValue(0);
    try {
        getLog().info("Executing " + cmdLine.toString());
        executor.execute(cmdLine);
        getLog().info(file.getName() + " optimized");
    } catch (IOException e) {
        throw new ProcessorException("Error during PNG optimization of " + file.getAbsolutePath(), e);
    }
}