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.nanoko.coffee.mill.mojos.reporting.JsDocMojo.java

private void generateJSDOC() throws MavenReportException {
    if (skipJSDOC) {
        getLog().info("JSDoc report generation skipped");
        return;//w  w  w. j  av  a 2 s. c  o m
    }

    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");
    }/*  ww w  .  java 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  . ja v a  2s .  c o 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);
    }
}

From source file:org.nanoko.coffeemill.mojos.processresources.OptiJpegMojo.java

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

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

    if (verbose) {
        cmdLine.addArgument("-verbose");
    }//w  w  w.j ava  2  s.  c  om

    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");

        getLog().info("output jpeg file : " + out.getAbsolutePath());
        if (out.exists()) {
            FileUtils.copyFile(out, file);
            FileUtils.deleteQuietly(out);
        } else {
            throw new IOException("Output file not found : " + out.getAbsolutePath());
        }

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

From source file:org.nanoko.coffeemill.mojos.processresources.OptiPngMojo.java

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

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

    if (verbose) {
        cmdLine.addArgument("-v");
    }// ww  w .  jav  a  2  s  . c om

    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 WatchingException("Error during PNG optimization of " + file.getAbsolutePath(), e);
    }
}

From source file:org.nanoko.playframework.mojo.Play2StartMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("start");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);// w ww  .j a v  a 2s.c om
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

From source file:org.nanoko.playframework.mojo.Play2StopMojo.java

public void execute() throws MojoExecutionException {

    String line = getPlay2().getAbsolutePath();

    CommandLine cmdLine = CommandLine.parse(line);
    cmdLine.addArguments(getPlay2SystemPropertiesArguments(), false);
    cmdLine.addArgument("stop");
    System.out.println(cmdLine.toString());
    DefaultExecutor executor = new DefaultExecutor();

    // As where not linked to a project, we can't set the working directory.
    // So it will use the directory where mvn was launched.

    executor.setExitValue(0);/*ww  w .  j  av  a 2s .c  om*/
    try {
        executor.execute(cmdLine, getEnvironment());
    } catch (IOException e) {
        // Ignore.
    }
}

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  .ja  v  a 2  s .c  o m
    // 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.executors.SandboxedExecutor.java

@Override
public ExecutionResult execute(final Path program) throws IOException {
    SandboxedExecutor.logger.debug("Copying program into jail");
    final Path chrootedProgram = this.storage.getPath().resolve("chroot")
            .resolve(program.getFileName().toString());
    chrootedProgram.getParent().toFile().mkdirs();
    FileAccess.copy(program, chrootedProgram, StandardCopyOption.COPY_ATTRIBUTES);

    final CommandLine commandLine = new CommandLine("sudo");
    commandLine.addArgument("olympus_watchdog");

    this.setUpOlrunnerLimits(commandLine);

    commandLine.addArgument(MessageFormat.format("--jail={0}",
            this.storage.getPath().resolve("chroot").toAbsolutePath().toString()));

    commandLine.addArgument("--");
    commandLine/*from w w  w.  ja va 2 s.com*/
            .addArgument("/" + this.storage.getPath().resolve("chroot").relativize(chrootedProgram).toString());

    final DefaultExecutor executor = new DefaultExecutor();

    executor.setExitValue(0);

    executor.setWatchdog(new ExecuteWatchdog(60000)); // 60 seconds for the
    // sandbox to
    // complete

    executor.setWorkingDirectory(this.storage.getPath().toFile());

    executor.setStreamHandler(new PumpStreamHandler(this.outputStream, this.errorStream, this.inputStream));

    SandboxedExecutor.logger.debug("Executing in sandbox: {}", commandLine.toString());
    try {
        executor.execute(commandLine);
    } catch (final ExecuteException e) {
        SandboxedExecutor.logger.info("Execution failed: {}", e);
        throw e;
    } catch (final IOException e) {
        if (!e.getMessage().toLowerCase().equals("stream closed")) {
            throw e;
        }
    }

    return this.readOlrunnerVerdict(this.storage.getPath().resolve("verdict.txt"));
}

From source file:org.nuxeo.webpage.archiver.WebpageToBlob.java

protected Blob buildCommandLineAndRun(String inCommandLine, CmdParameters inParams, String inFileName,
        boolean inUseAllParams) throws IOException, CommandNotAvailable, NuxeoException {

    // Create a temp. File handled by Nuxeo
    Blob resultPdf = Blobs.createBlobWithExtension(".pdf");

    // Build the full, resolved command line
    String resolvedParameterString = CommandLineParameters.buildParameterString(inCommandLine,
            inParams.getParameter(CommandLineParameters.COOKIE_JAR),
            inParams.getParameter(CommandLineParameters.URL), resultPdf.getFile().getAbsolutePath());

    // Mainly during test, we may have uncjecked parameters (safe because everything is hard-coded server side)
    if (inUseAllParams) {
        if (!Framework.isTestModeSet()) {
            throw new NuxeoException("A call to buildCommandLineAndRun(..., true) is for test only.");
        }//from   ww  w .j a  v a2  s  .  co m
        Map<String, ParameterValue> allParams = inParams.getParameters();
        String key, value;
        for (Entry<String, ParameterValue> entry : allParams.entrySet()) {
            key = entry.getKey();
            value = entry.getValue().getValue();
            if (!CommandLineParameters.isHandledParameter(key)) {
                resolvedParameterString = StringUtils.replace(resolvedParameterString, "#{" + key + "}", value);
            }
        }
    }

    // Get the exact command line and build the line
    CommandLineDescriptor desc = CommandLineExecutorComponent.getCommandDescriptor(inCommandLine);
    String line = desc.getCommand() + " " + resolvedParameterString;

    // Run the thing
    Exception exception = null;

    CommandLine cmdLine = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ExecuteWatchdog watchdog = new ExecuteWatchdog(timeout);
    // We don't want a check on exit values, because a PDF can still be created with errors
    // (can't get a font, ...)
    executor.setExitValues(null);
    executor.setWatchdog(watchdog);
    int exitValue = 0;
    try {
        exitValue = executor.execute(cmdLine);
    } catch (IOException e) {
        exception = e;
    }

    // Even if we had no error catched, we must check if the pdf is valid.
    // Exit value may be 1, or non zero while the pdf was created. But maybe
    // a font could not be correctly rendered, etc. Let's check if we have
    // something in the pdf and it looks valid
    if (!pdfLooksValid(resultPdf.getFile())) {
        resultPdf = null;
        String msg = "Failed to execute the command line [" + cmdLine.toString()
                + " ]. No valid PDF generated. exitValue: " + exitValue;

        if (exitValue == 143) { // On Linux: Timeout, wkhtmltopdf was SIGTERM
            msg += " (time out reached. The timeout was " + timeout + "ms)";
        }
        if (exception == null) {
            throw new NuxeoException(msg);
        } else {
            throw new NuxeoException(msg, exception);
        }
    }

    resultPdf.setMimeType("application/pdf");
    String url = inParams.getParameter(CommandLineParameters.URL);
    // Url parameter can be blank (hard coded url in the command line XML for example)
    if (StringUtils.isBlank(inFileName) && StringUtils.isNotBlank(url)) {
        try {
            URL urlObj = new URL(url);
            inFileName = StringUtils.replace(urlObj.getHost(), ".", "-") + ".pdf";
        } finally {
            // Nothing. Default name has been set by nuxeo
        }
    }
    if (StringUtils.isNotBlank(inFileName)) {
        resultPdf.setFilename(inFileName);
    }

    return resultPdf;
}