Example usage for org.apache.commons.exec DefaultExecuteResultHandler getException

List of usage examples for org.apache.commons.exec DefaultExecuteResultHandler getException

Introduction

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

Prototype

public ExecuteException getException() 

Source Link

Document

Get the exception causing the process execution to fail.

Usage

From source file:com.anrisoftware.mongoose.buildins.execbuildin.ExecBuildin.java

private void waitForCommand() throws InterruptedException, CommandException {
    if (handler instanceof DefaultExecuteResultHandler) {
        DefaultExecuteResultHandler h = (DefaultExecuteResultHandler) handler;
        h.waitFor();/*  w  w  w .j  a  v a2 s  .  c  o m*/
        ExecuteException ex = h.getException();
        if (ex != null) {
            throw log.errorCommand(this, ex);
        }
    }
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private void generateThumbnailsWithoutDuration(final String videoFilePath)
        throws IOException, InterruptedException {
    final CommandLine command = getFFmpegCreateThumbnailCommand(videoFilePath, getThumbnailFilePath(), null,
            THUMBNAIL_COUNT);//from   ww  w  .  j  ava  2 s.  co m
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(command, 15, null);

    resultHandler.waitFor();

    if (resultHandler.getException() != null) {
        throw resultHandler.getException();
    }
}

From source file:ddf.content.plugin.video.VideoThumbnailPlugin.java

private byte[] createGifFromThumbnailFiles() throws IOException, InterruptedException {
    final DefaultExecuteResultHandler resultHandler = executeFFmpeg(getFFmpegCreateAnimatedGifCommand(), 3,
            null);/*from w w w.j a  va2s. c  o m*/

    resultHandler.waitFor();

    if (resultHandler.getException() == null) {
        return FileUtils.readFileToByteArray(new File(getGifFilePath()));
    } else {
        throw resultHandler.getException();
    }
}

From source file:edu.emory.cci.aiw.neo4jetl.Neo4jHome.java

private void controlServer(String command) throws IOException, InterruptedException, CommandFailedException {
    LOGGER.debug("Executing neo4j command {}...", command);
    CommandLine serverControlCommand = new CommandLine(new File(this.home, SERVER_CONTROL_COMMAND));
    serverControlCommand.addArgument("${command}");
    Map<String, String> map = new HashMap<>();
    map.put("command", command);
    serverControlCommand.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);/* www . j  av a 2 s. c o  m*/
    executor.setWatchdog(watchdog);
    executor.execute(serverControlCommand, resultHandler);
    LOGGER.debug("Neo4j command {} is completed, checking exit value...", command);
    resultHandler.waitFor();
    int exitValue = resultHandler.getExitValue();
    if (exitValue != 0) {
        ExecuteException exception = resultHandler.getException();
        throw new CommandFailedException(exitValue, "Neo4j command '" + command + "' failed", exception);
    }
    LOGGER.debug("Neo4j command {} was successful", command);
}

From source file:com.stratio.ingestion.IngestionInterpreter.java

@Override
public InterpreterResult interpret(String st) {

    if (ingestionHome.isEmpty()) {
        open();/*www . j av  a 2 s  .com*/
        if (ingestionHome.isEmpty()) {
            return new InterpreterResult(InterpreterResult.Code.ERROR,
                    "%text Ingestion is not installed correctly. " + "INGESTION_HOME Is not set");
        }
    }

    IngestionSyntaxParser parser = new IngestionSyntaxParser();
    IngestionParserResult parserResult = null;
    try {
        parserResult = parser.parse(st);
    } catch (IngestionParserException e) {
        return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
    }

    StringBuilder shellCommand = new StringBuilder();
    StringBuilder interpreterResult = new StringBuilder();
    String bashResult;
    interpreterResult.append("%text ");

    switch (parserResult.getCommand()) {
    case AGENT_START:

        try {
            IngestionAgent agentStart = parserResult.getAgent();
            String agentName = agentStart.getName();
            String agentFilepath = agentStart.getFilepath();
            int agentPort = agentStart.getPort();

            logger.info("Ingestion interpreter @ agent start $INGESTION_HOME -> " + ingestionHome);
            logger.info("Ingestion interpreter @ agent start agent filepath -> " + agentFilepath);
            logger.info("Ingestion interpreter @ agent start agent name -> " + agentName);
            logger.info("Ingestion interpreter @ agent start agent port -> " + agentPort);

            shellCommand.append("exec \"").append(ingestionHome).append("/bin/flume-ng\" agent --conf ")
                    .append(ingestionHome).append("/conf --conf-file ").append(agentFilepath).append(" --name ")
                    .append(agentName).append(" -Dflume.monitoring.type=http -Dflume.monitoring.port=")
                    .append(String.valueOf(agentPort)).append("> /dev/null & ");

            logger.info("Ingestion interpreter @ agent start command -> " + shellCommand.toString());
            DefaultExecuteResultHandler handler = IngestionUtils.executeBash(shellCommand.toString());
            long initTime = System.currentTimeMillis();
            while (!handler.hasResult()) {
                if (System.currentTimeMillis() > (initTime + CMD_TIMEOUT)) {
                    handler.onProcessComplete(999);
                }
            }
            if (handler.getException() != null) {
                return new InterpreterResult(InterpreterResult.Code.ERROR,
                        "%text " + handler.getExitValue() + " " + handler.getException().getMessage());
            }
            bashResult = "Agent started";
            return new InterpreterResult(InterpreterResult.Code.SUCCESS, bashResult);
        } catch (IOException e) {
            return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
        }
    case AGENT_STOP:
        try {
            IngestionAgent agentStop = parserResult.getAgent();
            shellCommand.append("ps auxww | grep flume | grep ").append(agentStop.getPort())
                    .append("| awk '{ print $2 }' | xargs kill -15 ");
            IngestionUtils.executeBash(shellCommand.toString());
            return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                    interpreterResult.append("Agent " + "apparently stopped ").toString());

        } catch (IOException e) {
            if (e.getMessage().contains("143")) { //after kill a process always 143 exit code
                return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                        interpreterResult.append("Agent " + "apparently stopped ").toString());
            } else {
                return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
            }
        }
    case CHANNELS_STATUS:
        try {
            String json = IngestionUtils.getAgentStatus(parserResult.getAgent().getPort());
            if (json.length() > 3) {
                Map<String, String> channelsStatus = IngestionUtils.getChannelsStatus(json);
                String channelStatusResult = "";
                for (String channel : channelsStatus.keySet()) {
                    channelStatusResult += "Channel ".concat(channel).concat(": ")
                            .concat(channelsStatus.get(channel)).concat("\n");
                }
                return new InterpreterResult(InterpreterResult.Code.SUCCESS, "%text " + channelStatusResult);
            }
        } catch (IOException e) {
            return new InterpreterResult(InterpreterResult.Code.ERROR, "%text " + e.getMessage());
        }
        break;
    case LIST_PROPERTIES:
        List<String> files = new ArrayList<>();
        StringBuilder listResult = new StringBuilder();
        IngestionUtils.getIngestionPropertiesFiles(files, ingestionHome);
        if (!files.isEmpty()) {
            for (String file : files) {
                listResult.append(file).append("\n");
            }
            return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                    "%text ".concat(listResult.toString()));
        }
        return new InterpreterResult(InterpreterResult.Code.ERROR, "%text No .properties files found");
    case HELP:
        return new InterpreterResult(InterpreterResult.Code.SUCCESS,
                interpreterResult.append(IngestionUtils.help()).toString());
    }

    return new InterpreterResult(InterpreterResult.Code.ERROR,
            "%text Ingestion command not recognized, type help" + " for more info");
}

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);//ww w.  jav  a 2s  .  c o m
    }

    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();
}

From source file:beans.ServerBootstrapperImpl.java

private void createNewMachine(ServerNode serverNode) {
    File cloudFolder = null;//from   w w  w .ja v a 2  s . com
    ComputeServiceContext jCloudsContext = null;
    try {
        // no existing management machine - create new server
        String project = serverNode.getProject();
        String secretKey = serverNode.getSecretKey();
        String apiKey = serverNode.getKey();
        logger.info("Creating cloud folder with specific user credentials. Project: [{}], api key: [{}]",
                project, apiKey);
        jCloudsContext = CloudifyUtils.createJcloudsContext(project, apiKey, secretKey);
        cloudFolder = CloudifyUtils.createCloudFolder(project, apiKey, secretKey, jCloudsContext);
        logger.info("cloud folder is at [{}]", cloudFolder);

        logger.info("Creating security group for user.");
        CloudifyUtils.createCloudifySecurityGroup(jCloudsContext);

        //Command line for bootstrapping remote cloud.
        CommandLine cmdLine = new CommandLine(conf.server.cloudBootstrap.remoteBootstrap.getAbsoluteFile());
        cmdLine.addArgument(cloudFolder.getName());

        DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
        ProcExecutor bootstrapExecutor = executorFactory.getBootstrapExecutor(serverNode);

        logger.info("Executing command line: " + cmdLine);
        bootstrapExecutor.execute(cmdLine, ApplicationContext.get().conf().server.environment.getEnvironment(),
                resultHandler);
        logger.info("waiting for output");
        resultHandler.waitFor();
        logger.info("finished waiting , exit value is [{}]", resultHandler.getExitValue());

        String output = Utils.getOrDefault(Utils.getCachedOutput(serverNode), "");
        if (resultHandler.getException() != null) {
            logger.info("we have exceptions, checking for known issues");
            if (output.contains("found existing management machines")) {
                logger.info(
                        "found 'found existing management machines' - issuing cloudify already exists message");
                throw new ServerException(Messages.get("cloudify.already.exists"));
            }
            logger.info("Command execution ended with errors: {}", output);
            throw new RuntimeException("Failed to bootstrap cloudify machine: " + output,
                    resultHandler.getException());
        }

        logger.info("finished handling errors, extracting IP");
        String publicIp = Utils.extractIpFromBootstrapOutput(output);
        if (StringUtils.isEmpty(publicIp)) {
            logger.warn("No public ip address found in bootstrap output. " + output);
            throw new RuntimeException("Bootstrap failed. No IP address found in bootstrap output." + output,
                    resultHandler.getException());
        }
        logger.info("ip is [{}], saving to serverNode", publicIp);

        String privateKey = CloudifyUtils.getCloudPrivateKey(cloudFolder);
        if (StringUtils.isEmpty(privateKey)) {
            throw new RuntimeException("Bootstrap failed. No pem file found in cloud directory.");
        }
        logger.info("found PEM string");
        logger.info("Bootstrap cloud command ended successfully");

        logger.info("updating server node with new info");
        serverNode.setPublicIP(publicIp);
        serverNode.setPrivateKey(privateKey);

        serverNode.save();
        logger.info("server node updated and saved");
    } catch (Exception e) {
        serverNode.errorEvent("Invalid Credentials").save();
        throw new RuntimeException("Unable to bootstrap cloud", e);
    } finally {
        if (cloudFolder != null && conf.server.cloudBootstrap.removeCloudFolder) {
            FileUtils.deleteQuietly(cloudFolder);
        }
        if (jCloudsContext != null) {
            jCloudsContext.close();
        }
        serverNode.setStopped(true);

    }
}

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;/*from w w w .j av a  2  s . co  m*/
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // 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: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  w  w .  j a  v  a  2s.  co m
    }

    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:com.github.stephenc.mongodb.maven.StartMongoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {//from   w  ww.ja  va2  s.  c o  m
        getLog().info("Skipping mongodb: mongodb.skip==true");
        return;
    }
    if (installation == null) {
        getLog().info("Using mongod from PATH");
    } else {
        getLog().info("Using mongod installed in " + installation);
    }
    getLog().info("Using database root of " + databaseRoot);
    final Logger mongoLogger = Logger.getLogger("com.mongodb");
    Level mongoLevel = mongoLogger.getLevel();
    try {
        mongoLogger.setLevel(Level.SEVERE);
        MongoOptions opts = new MongoOptions();
        opts.autoConnectRetry = false;
        opts.connectionsPerHost = 1;
        opts.connectTimeout = 50;
        opts.socketTimeout = 50;
        Mongo instance;
        try {
            instance = new Mongo(new ServerAddress("localhost", port), opts);
            List<String> databaseNames = instance.getDatabaseNames();
            throw new MojoExecutionException("Port " + port
                    + " is already running a MongoDb instance with the following databases " + databaseNames);
        } catch (MongoException.Network e) {
            // fine... no instance running
        } catch (MongoException e) {
            throw new MojoExecutionException("Port " + port + " is already running a MongoDb instance");
        } catch (UnknownHostException e) {
            // ignore... localhost is always known!
        }
    } finally {
        mongoLogger.setLevel(mongoLevel);
    }

    CommandLine commandLine = null;
    if (installation != null && installation.isDirectory()) {
        File bin = new File(installation, "bin");
        File exe = new File(bin, Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
        if (exe.isFile()) {
            commandLine = new CommandLine(exe);
        } else {
            throw new MojoExecutionException("Could not find mongo executables in specified installation: "
                    + installation + " expected to find " + exe + " but it does not exist.");
        }
    }
    if (commandLine == null) {
        commandLine = new CommandLine(Os.isFamily(Os.FAMILY_WINDOWS) ? "mongod.exe" : "mongod");
    }
    if (databaseRoot.isFile()) {
        throw new MojoExecutionException("Database root " + databaseRoot + " is a file and not a directory");
    }
    if (databaseRoot.isDirectory() && cleanDatabaseRoot) {
        getLog().info("Cleaning database root directory: " + databaseRoot);
        try {
            FileUtils.deleteDirectory(databaseRoot);
        } catch (IOException e) {
            throw new MojoExecutionException("Could not clean database root directory " + databaseRoot, e);
        }
    }
    if (!databaseRoot.isDirectory()) {
        getLog().debug("Creating database root directory: " + databaseRoot);
        if (!databaseRoot.mkdirs()) {
            throw new MojoExecutionException("Could not create database root directory " + databaseRoot);
        }
    }

    if (!verbose) {
        commandLine.addArgument("--quiet");
    }

    commandLine.addArgument("--logpath");
    commandLine.addArgument(logPath.getAbsolutePath());
    if (logAppend) {
        commandLine.addArgument("--logappend");
    }

    commandLine.addArgument(auth ? "--auth" : "--noauth");

    commandLine.addArgument("--port");
    commandLine.addArgument(Integer.toString(port));

    commandLine.addArgument("--dbpath");
    commandLine.addArgument(databaseRoot.getAbsolutePath());

    if (additionalArguments != null) {
        for (String aa : additionalArguments) {
            commandLine.addArgument(aa);
        }
    }

    Executor exec = new DefaultExecutor();
    DefaultExecuteResultHandler execHandler = new DefaultExecuteResultHandler();
    exec.setWorkingDirectory(databaseRoot);
    ProcessObserver processObserver = new ProcessObserver(new ShutdownHookProcessDestroyer());
    exec.setProcessDestroyer(processObserver);

    LogOutputStream stdout = new MavenLogOutputStream(getLog());
    LogOutputStream stderr = new MavenLogOutputStream(getLog());

    getLog().info("Executing command line: " + commandLine);
    exec.setStreamHandler(new PumpStreamHandler(stdout, stderr));
    try {
        exec.execute(commandLine, execHandler);
        getLog().info("Waiting for MongoDB to start...");
        long timeout = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(120);
        mongoLevel = mongoLogger.getLevel();
        try {
            mongoLogger.setLevel(Level.SEVERE);
            while (System.currentTimeMillis() < timeout && !execHandler.hasResult()) {
                MongoOptions opts = new MongoOptions();
                opts.autoConnectRetry = false;
                opts.connectionsPerHost = 1;
                opts.connectTimeout = 250;
                opts.socketTimeout = 250;
                Mongo instance;
                try {
                    instance = new Mongo(new ServerAddress("localhost", port), opts);
                    List<String> databaseNames = instance.getDatabaseNames();
                    getLog().info("MongoDb started.");
                    getLog().info("Databases: " + databaseNames);
                } catch (MongoException.Network e) {
                    // ignore, wait and try again
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e1) {
                        // ignore
                    }
                    continue;
                } catch (MongoException e) {
                    getLog().info("MongoDb started.");
                    getLog().info("Unable to list databases due to " + e.getMessage());
                }
                break;
            }
        } finally {
            mongoLogger.setLevel(mongoLevel);
        }
        if (execHandler.hasResult()) {
            ExecuteException exception = execHandler.getException();
            if (exception != null) {
                throw new MojoFailureException(exception.getMessage(), exception);
            }
            throw new MojoFailureException(
                    "Command " + commandLine + " exited with exit code " + execHandler.getExitValue());
        }
        Map pluginContext = session.getPluginContext(getPluginDescriptor(), project);
        pluginContext.put(ProcessObserver.class.getName() + ":" + Integer.toString(port), processObserver);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}