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

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

Introduction

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

Prototype

public CommandLine(final CommandLine other) 

Source Link

Document

Copy constructor.

Usage

From source file:org.kgi.mybatis.scala.generator.GenerateDaoMojo.java

public void execute() throws MojoExecutionException {
    String scaladocParamFileName = project.getBuild().getOutputDirectory() + File.separator + "myb-doclet.txt";

    try {//from  w  ww.ja  v a 2 s.  c  o  m
        File f = outputDirectory;
        getLog().info("writing generated files to directory:" + outputDirectory.getAbsolutePath());
        if (!f.exists()) {
            f.mkdirs();
        }

        File sourcesDir = new File(project.getBasedir(), "src" + File.separator + "main");
        getLog().info("sources located in:" + sourcesDir.getAbsolutePath());
        Collection<File> sourceFiles = FileUtils.listFiles(sourcesDir, new String[] { "scala", "java" }, true);

        PrintWriter scaladocParamFileWriter = new PrintWriter(new FileWriter(scaladocParamFileName));
        scaladocParamFileWriter.println("-d");
        scaladocParamFileWriter.println("src");
        scaladocParamFileWriter.println("-doc-generator");
        scaladocParamFileWriter.println("org.kgi.mybatis.scala.generator.doclet.MyBatisMappingDoclet");
        for (File sourceFile : sourceFiles) {
            scaladocParamFileWriter.println(sourceFile.getAbsolutePath());
        }
        scaladocParamFileWriter.flush();
        scaladocParamFileWriter.close();

        DependencyNode depTree = dependencyGraphBuilder.buildDependencyGraph(project, new ArtifactFilter() {
            public boolean include(Artifact artifact) {
                return "jar".equals(artifact.getType());
            }
        });

        List deps = collectDependencies(depTree);

        Iterator depIterator = deps.iterator();
        StringBuilder cpBuilder = new StringBuilder();
        String docletPath = null;

        while (depIterator.hasNext()) {
            Artifact dep = (Artifact) depIterator.next();

            String path = System.getProperty("user.home") + File.separator + ".m2" + File.separator
                    + "repository" + File.separator + dep.getGroupId().replace('.', File.separatorChar)
                    + File.separator + dep.getArtifactId() + File.separator + dep.getVersion() + File.separator
                    + dep.getArtifactId() + "-" + dep.getVersion() + "." + dep.getType();
            if (cpBuilder.length() > 0) {
                cpBuilder.append(File.pathSeparator);
            }
            cpBuilder.append(path);
            if ("mybatis-scala-gen-doclet".equals(dep.getArtifactId())) {
                docletPath = path;
            }
        }
        CommandLine cmdl = new CommandLine("scaladoc");
        cmdl.addArgument("-Dmyb-gen-destination=" + outputDirectory.getAbsolutePath());
        cmdl.addArgument("-Dmyb-gen-destination-package=" + destinationPackage);
        cmdl.addArgument("-classpath");
        cmdl.addArgument(cpBuilder.toString());
        cmdl.addArgument("-toolcp");
        cmdl.addArgument(docletPath);
        cmdl.addArgument("@" + scaladocParamFileName);

        getLog().info("generation command:\n" + cmdl.toString());
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValue(0);
        executor.execute(cmdl);
    } catch (Exception e) {
        getLog().error(e);
        throw new MojoExecutionException("Problems generating DAO sources" + scaladocParamFileName);
    }
}

From source file:org.kitodo.imagemanagement.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine//from  w w w.  ja  v  a2s  .  c  o  m
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * KitodoConfig.getIntParameter(ParameterImageManagement.TIMEOUT_SEC, DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = KitodoConfig.getParameter(ParameterImageManagement.SSH_HOST);
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.kitodo.imagemanagementmodule.ConvertRunner.java

/**
 * Executes the ImageMagick command using Apache Commons Exec.
 *
 * @param commandLine//from w w w  . j a v a  2 s .c o  m
 *            command line to execute
 * @throws IOException
 *             if I/O fails
 */
void run(IMOperation commandLine) throws IOException {
    Executor executor = new DefaultExecutor();

    OutputStream outAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(outAndErr));

    long timeoutMillis = 1000
            * Config.getIntParameter("ImageManagementModule.timeoutSec", DEFAULT_TIMEOUT_MINS);
    executor.setWatchdog(new ExecuteWatchdog(timeoutMillis));

    CommandLine command;
    try {
        String sshHosts = Config.getParameter("ImageManagementModule.sshHosts");
        command = new CommandLine("ssh");
        String[] hosts = sshHosts.split(",");
        String host = hosts[RANDOMNESS_GENERATOR.nextInt(hosts.length)];
        command.addArgument(host, false);
        command.addArgument(convertCommand + ' ' + commandLine.toString(), false);
    } catch (NoSuchElementException e) {
        logger.trace("SSH not configured.", e);
        command = new CommandLine(convertCommand);
        command.addArguments(commandLine.toString());
    }

    try {
        logger.debug("Executing: {}", command);
        logger.trace("Timeout: {} mins", timeoutMillis / 60000d);
        executor.execute(command);
        logger.debug("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
    } catch (IOException | RuntimeException e) {
        logger.error("Command output:{}{}", System.lineSeparator(), outAndErr.toString());
        throw e;
    }
}

From source file:org.lucidj.launcher.Launcher.java

private void launch(String[] args) {
    System.out.println("Exec: " + java_exe);

    CommandLine cmdline = new CommandLine(java_exe);

    //----------//from w w w .  j a  v a  2s.  c  om
    // JVM args
    //----------

    cmdline.addArgument("-server");
    cmdline.addArgument("-Xms128M");
    cmdline.addArgument("-Xmx1024M");
    cmdline.addArgument("-XX:+UnlockDiagnosticVMOptions");
    cmdline.addArgument("-XX:+UnsyncloadClass");
    cmdline.addArgument("-Djava.awt.headless=true");
    cmdline.addArgument("-Dcom.sun.management.jmxremote");

    //-----------
    // Classpath
    //-----------

    List<String> path_elements = new ArrayList<>();

    String classpath_extra = karaf_properties.getProperty(".classpath.extra");

    if (classpath_extra != null) {
        // TODO: HANDLE COMPOUND classpath_extra; HANDLE MULTIPLE .classpath.*
        // Get all exported classpath files
        File[] file_list = new File(classpath_extra).listFiles();

        // And add to classpath if found
        if (file_list != null) {
            for (int i = 0; i < file_list.length; i++) {
                if (file_list[i].isFile() && file_list[i].getName().toLowerCase().endsWith(".jar")) {
                    path_elements.add(file_list[i].getAbsolutePath());
                }
            }
        }
    }

    cmdline.addArgument("-classpath");
    cmdline.addArgument(string_join(path_separator, path_elements), false);

    //-------------
    // LucidJ args
    //-------------

    addArgument(cmdline, "system.home", System.getProperty("system.home"));
    addArgument(cmdline, "system.conf", System.getProperty("system.conf"));
    addArgument(cmdline, "system.bootstrap", System.getProperty("system.bootstrap"));
    addArgument(cmdline, "system.deploy", System.getProperty("system.deploy"));

    // Copy the parsed properties to command line
    for (String key : karaf_properties.stringPropertyNames()) {
        if (!key.startsWith(".")) {
            addArgument(cmdline, key, karaf_properties.getProperty(key));
        }
    }

    if (System.getProperty("user.conf") != null) {
        addArgument(cmdline, "user.conf", System.getProperty("user.conf"));
    }

    // Class to exec
    cmdline.addArgument(main_class);

    // Add class arguments
    if (args != null) {
        for (String arg : args) {
            cmdline.addArgument(arg);
        }
    }

    //------------------
    // Ready to launch!
    //------------------

    if (verbose) {
        String[] argv = cmdline.toStrings();

        for (int i = 0; i < argv.length; i++) {
            System.out.println("argv[" + i + "] = '" + argv[i] + "'");
        }
    }

    launch_cmdline(cmdline);
}

From source file:org.lucidj.launcher.Launcher.java

public boolean launch_gui() {
    try {/*from  w  w  w.  j  a  va  2  s .c  om*/
        CommandLine cmdline = new CommandLine(java_exe);
        cmdline.addArgument("-jar");
        cmdline.addArgument(System.getProperty("app.launcher.jar"));
        launch_cmdline(cmdline);
        return (true);
    } catch (Exception ignore) {
    }
    ;

    return (false);
}

From source file:org.moneta.DropwizardContractTest.java

@BeforeClass
public static void setUpBeforeClass() throws Exception {
    System.out.println("Java Temp Dir: " + System.getProperty("java.io.tmpdir"));

    executor = new DefaultExecutor();
    resultHandler = new DefaultExecuteResultHandler();
    String javaHome = System.getProperty("java.home");
    String userDir = System.getProperty("user.dir");

    executor.setStreamHandler(new PumpStreamHandler(System.out));
    watchdog = new ExecuteWatchdog(10000);
    executor.setWatchdog(watchdog);/*ww w .j ava  2 s. c o  m*/
    executor.execute(new CommandLine(
            javaHome + SystemUtils.FILE_SEPARATOR + "bin" + SystemUtils.FILE_SEPARATOR + "java.exe")
                    .addArgument("-version"));
    executor.execute(
            new CommandLine(
                    javaHome + SystemUtils.FILE_SEPARATOR + "bin" + SystemUtils.FILE_SEPARATOR + "java.exe")
                            .addArgument("-jar")
                            .addArgument(userDir + "/../moneta-dropwizard/target/moneta-dropwizard-"
                                    + ContractTestSuite.getProjectVersion() + ".jar")
                            .addArgument("server").addArgument(
                                    "src/main/resources/dropwizard/moneta-dropwizard.yaml"),
            resultHandler);
    Thread.sleep(3000);
    System.out.println("Test sequence starting....");
}

From source file:org.mule.test.infrastructure.process.Controller.java

private int executeSyncCommand(String command, String[] args, Map<Object, Object> newEnv, int timeout)
        throws MuleControllerException {
    CommandLine commandLine = new CommandLine(muleBin);
    commandLine.addArgument(command);/* www  .j ava2  s .c  o m*/
    commandLine.addArguments(args);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);
    executor.setStreamHandler(new PumpStreamHandler());
    return doExecution(executor, commandLine, newEnv);
}

From source file:org.mule.test.infrastructure.process.UnixController.java

@Override
public int getProcessId() {
    Map<Object, Object> newEnv = this.copyEnvironmentVariables();
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    executor.setWatchdog(watchdog);//www  . j a  v a  2 s.c om
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    if (this.doExecution(executor, new CommandLine(this.muleBin).addArgument("status"), newEnv) == 0) {
        Matcher matcher = STATUS_PATTERN.matcher(outputStream.toString());
        if (matcher.find()) {
            return Integer.parseInt(matcher.group(1));
        } else {
            throw new MuleControllerException("bin/mule status didn't return the expected pattern: " + STATUS);
        }
    } else {
        throw new MuleControllerException("Mule ESB is not running");
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.FPCCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    FPCCompiler.logger.debug("Compiling {} to {} using FPC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("ppcx64");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-o" + outputFile.toAbsolutePath().toString()); // Set
    // outuput//from  w w w .  j  a  v  a 2 s . c  om
    // file
    commandLine.addArgument("-l-");
    commandLine.addArgument("-v0");
    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input
    // files

    FPCCompiler.logger.debug("Running FPC with arguments: {}", commandLine.toString());

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(errorStream, null, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        FPCCompiler.logger.error("Could not execute FPC: {}", e);
        throw new CompilationException("Could not execute FPC", e);
    }
    switch (result) {
    case 0:
        return;
    case 1:
        try {
            final String errorString = errorStream.toString("UTF-8");

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.getFileName().toString()))
                            .collect(Collectors.joining("|")) + ")",
                    Pattern.MULTILINE);

            FPCCompiler.logger.debug("Compilation error: {}", errorString);

            throw new CompilerError("fpc.wrote.stdout", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:org.ng200.openolympus.cerberus.compilers.GNUCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("g++");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-w"); // Prohibit warnings because they screw
    // up error detection

    commandLine.addArgument("-o");
    commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input//from  w  w  w.  j  a va2  s  . c o  m
    // files

    GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        GNUCompiler.logger.error("Could not execute GCC: {}", e);
        throw new CompilationException("Could not execute GCC", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString(StandardCharsets.UTF_8.name());

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            GNUCompiler.logger.debug("Compilation error: {}", errorString);
            throw new CompilerError("gcc.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}