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:com.blackducksoftware.tools.scmconnector.integrations.teamfoundation.TeamFoundationConnector.java

private int workspaceExists() {
    CommandLine command = CommandLine.parse(executable);

    command.addArgument("workspaces", false);
    command.addArgument("-server:" + server + "/" + collection, false);
    command.addArgument("-login:" + user + "," + password, false);

    int commandReturnStatus = 1;
    String commandOutput = null;//w w w .j  a v  a2  s. c o m

    try {
        CommandResults results = commandLineExecutor.executeCommandForOutput(log, command,
                new File(getFinalSourceDirectory()));
        commandReturnStatus = results.getStatus();
        commandOutput = results.getOutput();

        if (commandOutput.contains(workspace)) {
            workspaceExists = true;
            log.info("The workspace exists");
        } else {
            workspaceExists = false;
            log.info("The workspace does not exist");
        }

    } catch (Exception e) {

        log.error("Failure executing TF Command: " + command.toString() + "; output: " + commandOutput);
        workspaceExists = false;
    }

    return commandReturnStatus;
}

From source file:hoot.services.nativeinterfaces.CommandRunnerImpl.java

@Override
public CommandResult exec(String[] command) throws IOException {
    logger.debug("Executing the following command: {}", Arrays.toString(command));

    try (OutputStream stdout = new ByteArrayOutputStream(); OutputStream stderr = new ByteArrayOutputStream()) {

        this.stdout = stdout;
        this.stderr = stderr;

        CommandLine cmdLine = new CommandLine(command[0]);
        for (int i = 1; i < command.length; i++) {
            cmdLine.addArgument(command[i], false);
        }/*  w  ww  .  jav a2 s .com*/

        ExecuteStreamHandler executeStreamHandler = new PumpStreamHandler(stdout, stderr);
        DefaultExecutor executor = new DefaultExecutor();
        this.watchDog = new ExecuteWatchdog(ExecuteWatchdog.INFINITE_TIMEOUT);
        executor.setWatchdog(this.watchDog);
        executor.setStreamHandler(executeStreamHandler);

        int exitValue;
        try {
            exitValue = executor.execute(cmdLine);

            if (executor.isFailure(exitValue) && this.watchDog.killedProcess()) {
                // it was killed on purpose by the watchdog
                logger.info("Process for '{}' command was killed!", cmdLine);
            }
        } catch (Exception e) {
            exitValue = -1;
            logger.warn("Error executing: {}", cmdLine, e);
        }

        CommandResult commandResult = new CommandResult(cmdLine.toString(), exitValue, stdout.toString(),
                stderr.toString());

        logger.debug("Finished executing: {}", commandResult);

        return commandResult;
    }
}

From source file:de.torstenwalter.maven.plugins.SQLPlusMojo.java

private void runScriptWithSqlPlus(File file, Map environment)
        throws MojoExecutionException, MojoFailureException {
    checkFileIsReadable(file);// www . ja v a 2s . c  o  m

    CommandLine commandLine = new CommandLine(sqlplus);
    // logon only once, without this sql*plus would prompt for
    // credentials if given ones are not correct
    commandLine.addArgument("-L");
    StringTokenizer stringTokenizer = new StringTokenizer(getConnectionIdentifier());
    while (stringTokenizer.hasMoreTokens()) {
        commandLine.addArgument(stringTokenizer.nextToken());
    }
    commandLine.addArgument("@" + file.getName());
    if (arguments != null) {
        for (Object argument : arguments) {
            if (argument == null) {
                throw new MojoExecutionException("Misconfigured argument, value is null. "
                        + "Set the argument to an empty value if this is the required behaviour.");
            } else {
                commandLine.addArgument(argument.toString());
            }
        }
    }

    getLog().info("Executing command line: " + obfuscateCredentials(commandLine.toString(), getCredentials()));

    Executor exec = new DefaultExecutor();
    exec.setWorkingDirectory(file.getParentFile());
    exec.setStreamHandler(new PumpStreamHandler(System.out, System.err));
    try {
        exec.execute(commandLine, environment);
    } catch (ExecuteException e) {
        throw new MojoExecutionException("program exited with exitCode: " + e.getExitValue());
    } catch (IOException e) {
        throw new MojoExecutionException("Command execution failed.", e);
    }
}

From source file:com.netflix.genie.web.tasks.job.JobCompletionService.java

/**
 * Uploads the job directory to the archive location.
 *
 * @param job The job./*from w  ww .  j a  v a  2 s  .  com*/
 * @throws GenieException if there is any problem
 */
private boolean processJobDir(final Job job) throws GenieException, IOException {
    log.debug("Got a job finished event. Will process job directory.");
    boolean result = false;
    final Optional<String> oJobId = job.getId();

    // The deletion of dependencies and archiving only happens for job requests which are not Invalid.
    if (oJobId.isPresent()
            && !(this.jobSearchService.getJobStatus(job.getId().get()).equals(JobStatus.INVALID))) {
        final String jobId = oJobId.get();
        final File jobDir = new File(this.baseWorkingDir, jobId);

        if (jobDir.exists()) {
            if (this.deleteDependencies) {
                this.deleteApplicationDependencies(jobId, jobDir);
            }

            final Optional<String> archiveLocation = job.getArchiveLocation();
            if (archiveLocation.isPresent() && !Strings.isNullOrEmpty(archiveLocation.get())) {
                log.debug("Archiving job directory");
                // Create the tar file
                final File localArchiveFile = new File(jobDir, "genie/logs/" + jobId + ".tar.gz");

                final CommandLine commandLine;
                if (this.runAsUserEnabled) {
                    commandLine = new CommandLine("sudo");
                    commandLine.addArgument("tar");
                } else {
                    commandLine = new CommandLine("tar");
                }
                commandLine.addArgument("-c");
                commandLine.addArgument("-z");
                commandLine.addArgument("-f");
                commandLine.addArgument(localArchiveFile.getCanonicalPath());
                commandLine.addArgument("./");

                this.executor.setWorkingDirectory(jobDir);

                log.debug("Archive command : {}", commandLine.toString());
                this.executor.execute(commandLine);

                // Upload the tar file to remote location
                this.genieFileTransferService.putFile(localArchiveFile.getCanonicalPath(),
                        archiveLocation.get());

                // At this point the archive file is successfully uploaded to archive location specified in the job.
                // Now we can delete it from local disk to save space if enabled.
                if (this.deleteArchiveFile) {
                    log.debug("Deleting archive file");
                    try {
                        if (this.runAsUserEnabled) {
                            final CommandLine deleteCommand = new CommandLine("sudo");
                            deleteCommand.addArgument("rm");
                            deleteCommand.addArgument("-f");
                            deleteCommand.addArgument(localArchiveFile.getCanonicalPath());

                            this.executor.setWorkingDirectory(jobDir);
                            log.debug("Delete command: {}", deleteCommand.toString());
                            this.executor.execute(deleteCommand);
                        } else if (!localArchiveFile.delete()) {
                            log.error("Failed to delete archive file for job: {}", jobId);
                            this.archiveFileDeletionFailure.increment();
                        }
                    } catch (final Exception e) {
                        log.error("Failed to delete archive file for job: {}", jobId, e);
                        this.archiveFileDeletionFailure.increment();
                    }
                }
                result = true;
            }
        }
    }
    return result;
}

From source file:fr.fastconnect.factory.tibco.bw.maven.AbstractBWMojo.java

/**
 * This calls a TIBCO binary./*from w  w w. j  a  v a  2  s  .  c  o  m*/
 * 
 * @param binary, the TIBCO binary file to execute
 * @param tras, the TRA files associated with the TIBCO binary
 * @param arguments, command-line arguments
 * @param workingDir, working directory from where the binary is launched
 * @param errorMsg, error message to display in case of a failure
 * @param fork, if true the chiild process will be detached from the caller
 * 
 * @throws IOException
 * @throws MojoExecutionException
 */
protected int launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir,
        String errorMsg, boolean fork, boolean synchronous) throws IOException, MojoExecutionException {
    Integer result = 0;

    if (tras == null) { // no value specified as Mojo parameter, we use the .tra in the same directory as the binary
        String traPathFileName = binary.getAbsolutePath();
        traPathFileName = FilenameUtils.removeExtension(traPathFileName);
        traPathFileName += ".tra";
        tras = new ArrayList<File>();
        tras.add(new File(traPathFileName));
    }

    HashMap<File, File> trasMap = new HashMap<File, File>();
    for (File tra : tras) {
        // copy of ".tra" file in the working directory
        File tmpTRAFile = new File(directory, tra.getName());
        trasMap.put(tra, tmpTRAFile);
        copyFile(tra, tmpTRAFile);
    }

    for (File tra : trasMap.keySet()) {
        if (trasMap.containsKey(tibcoDesignerTRAPath)
                && ((tibcoBuildEARUseDesignerTRA && tra == tibcoBuildEARTRAPath)
                        || (tibcoBuildLibraryUseDesignerTRA && tra == tibcoBuildLibraryTRAPath))) {
            if (tras.size() > 1) {
                ReplaceRegExp replaceRegExp = new ReplaceRegExp();
                replaceRegExp.setFile(trasMap.get(tra));
                replaceRegExp.setMatch("tibco.include.tra (.*/designer.tra)");
                replaceRegExp.setReplace(
                        "tibco.include.tra " + trasMap.get(tibcoDesignerTRAPath).toString().replace('\\', '/'));
                replaceRegExp.setByLine(true);

                replaceRegExp.execute();
            }
        }

        if (tra == tibcoBuildEARTRAPath || tra == tibcoDesignerTRAPath || tra == tibcoBWEngineTRAPath) { // FIXME: should check more properly
            // append user.home at the end to force the use of custom Designer5.prefs
            PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(trasMap.get(tra), true)));
            out.println("");
            out.println("java.property.user.home=" + directory.getAbsolutePath().replace("\\", "/"));
            out.close();
        }
    }

    CommandLine cmdLine = new CommandLine(binary);

    for (String argument : arguments) {
        cmdLine.addArgument(argument);
    }
    getLog().debug("launchTIBCOBinary command line : " + cmdLine.toString());
    getLog().debug("working dir : " + workingDir);

    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(workingDir);

    if (timeOut > 0) {
        ExecuteWatchdog watchdog = new ExecuteWatchdog(timeOut * 1000);
        executor.setWatchdog(watchdog);
    }

    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());

    ByteArrayOutputStream stdOutAndErr = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdOutAndErr));

    if (fork) {
        CommandLauncher commandLauncher = CommandLauncherFactory.createVMLauncher();
        commandLauncher.exec(cmdLine, null, workingDir);
    } else {
        try {
            if (synchronous) {
                result = executor.execute(cmdLine);
            } else {
                executor.execute(cmdLine, new DefaultExecuteResultHandler());
            }
        } catch (ExecuteException e) {
            // TODO : grer erreurs des excutables (ventuellement parser les erreurs classiques)
            getLog().info(cmdLine.toString());
            getLog().info(stdOutAndErr.toString());
            getLog().info(result.toString());
            throw new MojoExecutionException(errorMsg, e);
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }

    return result;
}

From source file:it.drwolf.ridire.index.cwb.CWBPatternSearcher.java

private Integer getCQPQueryResultsSize(File queryFile, String cqpSizeQuery)
        throws ExecuteException, IOException {
    EnvironmentUtils.addVariableToEnvironment(EnvironmentUtils.getProcEnvironment(), "LC_ALL=C");
    Executor executor = new DefaultExecutor();
    File tempSize = File.createTempFile("ridireSZ", ".size");
    File tempSh = File.createTempFile("ridireSH", ".sh");
    CommandLine commandLine = new CommandLine(this.cqpExecutable);
    commandLine.addArgument("-f").addArgument(queryFile.getAbsolutePath()).addArgument("-D")
            .addArgument(this.cqpCorpusName).addArgument("-r").addArgument(this.cqpRegistry);
    String commLineString = commandLine.toString() + " > " + tempSize.getAbsolutePath();
    FileUtils.writeStringToFile(tempSh, commLineString);
    tempSh.setExecutable(true);//from   w w  w.j  a va  2 s  .  com
    executor = new DefaultExecutor();
    executor.setExitValue(0);
    ExecuteWatchdog watchdog = new ExecuteWatchdog(CWBPatternSearcher.TIMEOUT);
    executor.setWatchdog(watchdog);
    commandLine = new CommandLine(tempSh.getAbsolutePath());
    executor.execute(commandLine);
    Integer size = 0;
    List<String> lines = FileUtils.readLines(tempSize);
    if (lines.size() > 0) {
        size = Integer.parseInt(lines.get(0).trim());
    }
    FileUtils.deleteQuietly(tempSh);
    FileUtils.deleteQuietly(tempSize);
    return size;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);/*from w  ww .  ja  va 2  s  .  c  om*/
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured kindlegen executable
        logger.info("Kindlegen will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Kindlegen will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());
    cmdLine.addArgument("-c0");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter stdoutWriter = new StringWriter();
    StringWriter stderrWriter = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8"));
    WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8"));

    ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream);
    executor.setStreamHandler(kindlegenStreamHandler);

    logger.debug("Launching kindlegen:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Kindlegen failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Kindlegen execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"kindlegen\"")) {
                logger.error("Kindlegen could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("Kindlegen's execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    try {
        String stderrOutput = stderrWriter.getBuffer().toString();
        stderrWriter.close();
        if (stderrOutput.isEmpty() == false) {
            logger.error("Kindlegen logged some errors:");
            logger.error(stderrOutput);
        }
    } catch (IOException e) {
        logger.error("Error closing kindlegen's stderr buffer");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += stdoutWriter.getBuffer().toString();
        stdoutWriter.close();

    } catch (IOException e) {
        logger.error("Error closing kindlegen's stdout buffer:");
        logger.error(e.getMessage(), e);
    }

    logger.debug("Kindlegen output: \n" + output);

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    logger.debug("Moving Kindlegen output file: " + mobiFilename);

    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);
    return tempMobiFilepath.toFile();
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {//from   w w w  .  j a v a  2 s  . co  m
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(pandocStreamHandler);

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Pandoc execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();

            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

From source file:io.takari.maven.testing.executor.ForkedLauncher.java

public int run(String[] cliArgs, Map<String, String> envVars, File multiModuleProjectDirectory,
        File workingDirectory, File logFile) throws IOException, LauncherException {
    String javaHome;/*  w w w  .j  a va  2s .co  m*/
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        javaHome = System.getProperty("java.home");
    } else {
        javaHome = envVars.get("JAVA_HOME");
    }

    File executable = new File(javaHome, Os.isFamily(Os.FAMILY_WINDOWS) ? "bin/javaw.exe" : "bin/java");

    CommandLine cli = new CommandLine(executable);
    cli.addArgument("-classpath").addArgument(classworldsJar.getAbsolutePath());
    cli.addArgument("-Dclassworlds.conf=" + new File(mavenHome, "bin/m2.conf").getAbsolutePath());
    cli.addArgument("-Dmaven.home=" + mavenHome.getAbsolutePath());
    cli.addArgument("-Dmaven.multiModuleProjectDirectory=" + multiModuleProjectDirectory.getAbsolutePath());
    cli.addArgument("org.codehaus.plexus.classworlds.launcher.Launcher");

    cli.addArguments(args.toArray(new String[args.size()]));
    if (extensions != null && !extensions.isEmpty()) {
        cli.addArgument("-Dmaven.ext.class.path=" + toPath(extensions));
    }

    cli.addArguments(cliArgs);

    Map<String, String> env = new HashMap<>();
    if (mavenHome != null) {
        env.put("M2_HOME", mavenHome.getAbsolutePath());
    }
    if (envVars != null) {
        env.putAll(envVars);
    }
    if (envVars == null || envVars.get("JAVA_HOME") == null) {
        env.put("JAVA_HOME", System.getProperty("java.home"));
    }

    DefaultExecutor executor = new DefaultExecutor();
    executor.setProcessDestroyer(new ShutdownHookProcessDestroyer());
    executor.setWorkingDirectory(workingDirectory.getAbsoluteFile());

    try (OutputStream log = new FileOutputStream(logFile)) {
        PrintStream out = new PrintStream(log);
        out.format("Maven Executor implementation: %s\n", getClass().getName());
        out.format("Maven home: %s\n", mavenHome);
        out.format("Build work directory: %s\n", workingDirectory);
        out.format("Environment: %s\n", env);
        out.format("Command line: %s\n\n", cli.toString());
        out.flush();

        PumpStreamHandler streamHandler = new PumpStreamHandler(log);
        executor.setStreamHandler(streamHandler);
        return executor.execute(cli, env); // this throws ExecuteException if process return code != 0
    } catch (ExecuteException e) {
        throw new LauncherException("Failed to run Maven: " + e.getMessage() + "\n" + cli, e);
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);//from  w  ww.  j  a v a 2s. com
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured calibre ebook-convert executable
        logger.info("Calibre ebook-convert will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Calibre ebook-convert will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);

    logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString());
    cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString());

    // Output will be in format "KF8" only, old format does not allow external CSS files
    cmdLine.addArgument("--mobi-file-type=new");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(calibreStreamHandler);

    logger.debug("Launching calibres ebook-convert:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("calibres ebook-convert failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("calibre ebook-converts execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) {
                logger.error("calibres ebook-convert could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("calibre ebook-converts execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading calibre ebook-converts output from buffer:");
        logger.error(e.getMessage(), e);

    }

    logger.debug("Calibre ebook-convert output: \n" + output);

    return tempMobiFilepath.toFile();
}