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

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Stringify operator returns the command line as a string.

Usage

From source file:org.fuin.owndeb.commons.DebUtils.java

private static void execute(final CommandLine cmdLine, final File workingDir, final String errorMsg) {

    LOG.debug("Execute: " + cmdLine.toString());

    final Executor executor = new DefaultExecutor();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final PumpStreamHandler psh = new PumpStreamHandler(bos);
    executor.setStreamHandler(psh);/*from  www. jav a 2 s  .co  m*/
    executor.setWorkingDirectory(workingDir);
    try {
        final int result = executor.execute(cmdLine);
        if (result != 0) {
            logError(asList(bos.toString()));
            throw new RuntimeException("Error # " + result + " / " + errorMsg);
        }
    } catch (final IOException ex) {
        logError(asList(bos.toString()));
        throw new RuntimeException(errorMsg, ex);
    }
}

From source file:org.geoserver.importer.transform.AbstractCommandLinePreTransform.java

protected boolean checkAvailable() throws IOException {
    try {//from ww  w .  j a v a 2 s.c o m
        CommandLine cmd = new CommandLine(getExecutable());
        for (String option : getAvailabilityTestOptions()) {
            cmd.addArgument(option);
        }

        // prepare to run
        DefaultExecutor executor = new DefaultExecutor();

        // grab at least some part of the outputs
        int limit = 16 * 1024;
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            int result = executor.execute(cmd);

            if (result != 0) {
                LOGGER.log(Level.SEVERE, "Failed to execute command " + cmd.toString()
                        + "\nStandard output is:\n" + os.toString() + "\nStandard error is:\n" + es.toString());
                return false;
            }

        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Failure to execute command " + cmd.toString(), e);
            return false;
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Failure to locate executable for class " + this.getClass(), e);
        return false;
    }

    return true;
}

From source file:org.geoserver.importer.transform.AbstractCommandLineTransform.java

@Override
public void apply(ImportTask task, ImportData data) throws Exception {
    boolean inline = isInline();
    File executable = getExecutable();
    File inputFile = getInputFile(data);
    Map<String, File> substitutions = new HashMap<>();
    substitutions.put("input", inputFile);
    File outputDirectory = null;//from  ww  w. j a  v  a  2 s. c  o  m
    File outputFile = null;
    if (!inline) {
        outputDirectory = getOutputDirectory(data);
        outputFile = new File(outputDirectory, inputFile.getName());
        substitutions.put("output", outputFile);
    }

    // setup the options
    CommandLine cmd = new CommandLine(executable);
    cmd.setSubstitutionMap(substitutions);

    setupCommandLine(inline, cmd);

    // prepare to run
    DefaultExecutor executor = new DefaultExecutor();
    // make sure we don't try to execute for too much time
    executor.setWatchdog(new ExecuteWatchdog(DEFAULT_TIMEOUT));

    // grab at least some part of the outputs
    int limit = 16 * 1024;
    try {
        try (OutputStream os = new BoundedOutputStream(new ByteArrayOutputStream(), limit);
                OutputStream es = new BoundedOutputStream(new ByteArrayOutputStream(), limit)) {
            PumpStreamHandler streamHandler = new PumpStreamHandler(os, es);
            executor.setStreamHandler(streamHandler);
            try {
                int result = executor.execute(cmd);

                if (executor.isFailure(result)) {
                    // toString call is routed to ByteArrayOutputStream, which does the right string
                    // conversion
                    throw new IOException(
                            "Failed to execute command " + cmd.toString() + "\nStandard output is:\n"
                                    + os.toString() + "\nStandard error is:\n" + es.toString());
                }
            } catch (Exception e) {
                throw new IOException("Failure to execute command " + cmd.toString() + "\nStandard output is:\n"
                        + os.toString() + "\nStandard error is:\n" + es.toString(), e);
            }
        }

        // if not inline, replace inputs with output
        if (!inline) {
            List<String> names = getReplacementTargetNames(data);
            File inputParent = inputFile.getParentFile();
            for (String name : names) {
                File output = new File(outputDirectory, name);
                File input = new File(inputParent, name);
                if (output.exists()) {
                    // uses atomic rename on *nix, delete and copy on Windows
                    IOUtils.rename(output, input);
                } else if (input.exists()) {
                    input.delete();
                }
            }
        }
    } finally {
        if (outputDirectory != null) {
            FileUtils.deleteQuietly(outputDirectory);
        }
    }
}

From source file:org.grouplens.lenskit.eval.maven.RScriptMojo.java

@Override
public void execute() throws MojoExecutionException {
    getLog().info("The analysis directory is " + analysisDir);
    getLog().info("The analysisScript is " + analysisScript);
    getLog().info("The R executable is " + rscriptExecutable);

    // Copy the script file into the working directory.  We could just execute
    // it from its original location, but it will be easier for our users to 
    // have the copy from the src directory next to its results in target.
    File scriptFile = new File(analysisScript);
    File scriptCopy = new File(analysisDir, scriptFile.getName());
    try {/*from   w  w  w .j a v a 2  s  . c  om*/
        if (!scriptFile.getCanonicalPath().equals(scriptCopy.getCanonicalPath())) {
            copyFile(scriptFile, scriptCopy);
        }
    } catch (IOException e1) {
        throw new MojoExecutionException("Unable to copy scriptFile " + scriptFile.getAbsolutePath()
                + " into working directory " + scriptCopy.getAbsolutePath());
    }

    // Generate the command line for executing R.
    final CommandLine command = new CommandLine(rscriptExecutable).addArgument(scriptCopy.getAbsolutePath(),
            false);
    getLog().debug("command: " + command);

    // Execute the command line, in the working directory.
    final DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(new File(analysisDir));
    try {
        if (executor.execute(command) != 0) {
            throw new MojoExecutionException("Error code returned for: " + command.toString());
        }
    } catch (ExecuteException e) {
        throw new MojoExecutionException("Error executing command: " + command.toString(), e);
    } catch (IOException e) {
        throw new MojoExecutionException("IO Exception while executing command: " + command.toString(), e);
    }
}

From source file:org.jahia.modules.dm.thumbnails.video.impl.VideoThumbnailServiceImpl.java

public boolean generateThumbnail(File videoFile, File outputFile, int offsetSeconds, String size)
        throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("FFmpeg service is not enabled." + " Skip converting file {}", videoFile);

        return false;
    }/*ww w .  j  a  va2  s. co  m*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(videoFile, outputFile, String.valueOf(offsetSeconds),
            StringUtils.defaultIfEmpty(size, "320x240"));

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting thumbnail generation command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(null, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (exitValue > 0 && err.getLength() > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && err.getLength() > 0) {
            logger.debug(err.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Generating thumbnail {} from {} done (exit code: {}) in {} ms",
                new Object[] { outputFile, videoFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.modules.dm.viewer.impl.PDF2SWFConverterService.java

public boolean convert(File inputPdfFile, File outputSwfFile) throws DocumentOperationException {
    if (!isEnabled()) {
        logger.info("pdf2swf conversion service is not enabled." + " Skip converting file {}", inputPdfFile);

        return false;
    }/*from  ww  w.j  av a 2 s  . c om*/

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(inputPdfFile, outputSwfFile);

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting conversion command: {}", cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream();
    StringOutputStream err = new StringOutputStream();
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (Exception e) {
        throw new DocumentOperationException(e);
    } finally {
        if (err.getLength() > 0) {
            logger.error("Conversion process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled() && out.getLength() > 0) {
            logger.debug(out.toString());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Conversion from {} to {} done (exit code: {}) in {} ms",
                new Object[] { inputPdfFile, outputSwfFile, exitValue, (System.currentTimeMillis() - timer) });
    }

    return exitValue == 0;
}

From source file:org.jahia.modules.docviewer.PDF2SWFConverterService.java

/**
 * Converts the provided PDF input file into specified SWF output file.
 * //from  w  w w  . j  av  a 2s . co  m
 * @param inputFile
 *            the source file
 * @param outputFile
 *            the output file descriptor to store converted content into
 * @throws Exception
 *             in case of a conversion error
 */
public void convert(File inputFile, File outputFile) throws Exception {
    if (!isEnabled()) {
        logger.info("pdf2swf conversion service is not enabled." + " Skip converting file {}", inputFile);
        return;

    }

    long timer = System.currentTimeMillis();

    CommandLine cmd = getConvertCommandLine(inputFile, outputFile);

    if (logger.isDebugEnabled()) {
        logger.debug("Execuiting conversion command: {}", cmd.toString());
    }

    int exitValue = new DefaultExecutor().execute(cmd);

    if (logger.isDebugEnabled()) {
        logger.debug("Conversion from {} to {} done (exit code: {}) in {} ms",
                new Object[] { inputFile, outputFile, exitValue, (System.currentTimeMillis() - timer) });
    }
}

From source file:org.jahia.utils.ProcessHelper.java

/**
 * Executes the external process using the provided command, arguments (optional), parameter substitution map to expand variables in the
 * command or arguments in form of <code>${variable}<code> (optional) and a working directory (optional).
 * Buffers for process output and error stream can be provided.
 * //  ww  w .  j ava2  s  . c  om
 * @param command
 *            the command to be executed
 * @param arguments
 *            optional arguments for the command
 * @param parameterSubstitutionMap
 *            optional values for variables to be expanded
 * @param workingDir
 *            optional working directory for the process to be started from
 * @param resultOut
 *            the buffer to write the process execution output into (optional)
 * @param resultErr
 *            the buffer to write the process execution error into (optional)
 * @return the execution status
 * @return redirectOutputs if set to <code>true</code> the output of the execution will be also redirected to standard system out and
 *         the error to error out
 * @throws JahiaRuntimeException
 *             in case the process execution failed
 */
public static int execute(String command, String arguments[], Map<String, Object> parameterSubstitutionMap,
        File workingDir, StringBuilder resultOut, StringBuilder resultErr, boolean redirectOutputs)
        throws JahiaRuntimeException {

    long timer = System.currentTimeMillis();

    CommandLine cmd = new CommandLine(command);

    if (arguments != null && arguments.length > 0) {
        cmd.addArguments(arguments, false);
    }

    if (parameterSubstitutionMap != null && !parameterSubstitutionMap.isEmpty()) {
        cmd.setSubstitutionMap(parameterSubstitutionMap);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Executing command: {}", cmd.toString());
    } else if (redirectOutputs) {
        logger.info("Executing command: ");
        logger.info(cmd.toString());
    }

    int exitValue = 0;

    StringOutputStream out = new StringOutputStream(redirectOutputs ? System.out : null);
    StringOutputStream err = new StringOutputStream(redirectOutputs ? System.err : null);
    try {
        DefaultExecutor executor = new DefaultExecutor();
        executor.setStreamHandler(new PumpStreamHandler(out, err));
        if (workingDir != null) {
            if (workingDir.exists() || workingDir.mkdirs()) {
                executor.setWorkingDirectory(workingDir);
            }
        }
        exitValue = executor.execute(cmd, System.getenv());
    } catch (ExecuteException ee) {
        return ee.getExitValue();
    } catch (Exception e) {
        throw new JahiaRuntimeException(e);
    } finally {
        if (resultErr != null) {
            resultErr.append(err.toString());
        }
        if (resultOut != null) {
            resultOut.append(out.toString());
        }
        if (exitValue > 0) {
            logger.error("External process finished with error. Cause: {}", err.toString());
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Execution took {} ms and finished with status {} and output {}",
                    new Object[] { (System.currentTimeMillis() - timer), exitValue, out.toString() });
        }
    }

    return exitValue;
}

From source file:org.jboss.jdocbook.translate.PoSynchronizerImpl.java

private void updateTranslation(File template, File translation, Locale translationLocale) {
    if (!template.exists()) {
        log.trace("skipping PO updates; POT file did not exist : {0}", template);
        return;/*from  ww w .  j  av  a 2s  .  co m*/
    }

    if (translation.lastModified() >= template.lastModified()) {
        log.trace("skipping PO updates; up-to-date : {0}", translation);
        return;
    }

    final String translationLocaleString = componentRegistry.toLanguageString(translationLocale);

    CommandLine commandLine;
    if (translation.exists()) {
        commandLine = CommandLine.parse("msgmerge");
        commandLine.addArgument("--quiet");
        commandLine.addArgument("--update");
        commandLine.addArgument("--backup=none");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
    } else {
        if (!translation.getParentFile().exists()) {
            boolean created = translation.getParentFile().mkdirs();
            if (!created) {
                log.info("Unable to create PO directory {}", translation.getParentFile().getAbsolutePath());
            }
        }
        commandLine = CommandLine.parse("msginit");
        commandLine.addArgument("--no-translator");
        commandLine.addArgument("--locale=" + translationLocaleString);
        commandLine.addArgument("-i");
        commandLine.addArgument(FileUtils.resolveFullPathName(template));
        commandLine.addArgument("-o");
        commandLine.addArgument(FileUtils.resolveFullPathName(translation));
    }

    log.info("po-synch -> " + commandLine.toString());

    DefaultExecutor executor = new DefaultExecutor();
    try {
        executor.execute(commandLine);
    } catch (IOException e) {
        throw new JDocBookProcessException(
                "Error synchronizing PO file [" + template.getName() + "] for " + translationLocaleString, e);
    }
}

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 {/* w w  w.  j  av  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);
    }
}