Example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException

List of usage examples for org.apache.maven.plugin MojoExecutionException MojoExecutionException

Introduction

In this page you can find the example usage for org.apache.maven.plugin MojoExecutionException MojoExecutionException.

Prototype

public MojoExecutionException(String message) 

Source Link

Document

Construct a new MojoExecutionException exception providing a message.

Usage

From source file:com.betfair.platform.plugin.testprocess.ProcessLauncherMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {

    List<Process> _containerSystemProcesses;
    Process _testerProcess = null;
    ReaderRunnable testReaderRunnable;//ww w  .ja v  a  2 s.c o m
    ReaderRunnable containerReaderRunnable;
    String testerId;

    validate();

    int terminationChar = processTerminationCharacter;

    finishImmediately = false;
    failed = false;
    containerProcessStartLatches = new HashMap<ContainerProcess, CountDownLatch>();
    testProcessFinishLatches = new HashMap<String, CountDownLatch>();
    containerProcessesById = new HashMap<String, ContainerProcess>();
    failedProcesses = new ArrayList<String>();

    _containerSystemProcesses = new ArrayList<Process>();

    for (ContainerProcess cp : containerProcesses) {
        CountDownLatch latch = new CountDownLatch(1);
        String containerId = CONTAINER + "[" + cp.getId() + "]";
        containerProcessesById.put(containerId, cp);
        ProcessBuilder containerProcessBuilder = cp.createProcessBuilder();

        dumpEnvironment(containerProcessBuilder.environment(), cp.getId());
        try {
            containerProcessStartLatches.put(cp, latch);

            getLog().info("Starting '" + cp.getCommand() + "' in directory '" + cp.getWorkingDir() + "'");
            Process _containerProcess = containerProcessBuilder.start();
            _containerSystemProcesses.add(_containerProcess);
            containerReaderRunnable = new ReaderRunnable(containerId, _containerProcess.getInputStream(),
                    getLog());
            if (cp.getStartWatchString() != null || !"".equals(cp.getStartWatchString())) {
                containerReaderRunnable.setNotifyText(cp.getStartWatchString());
                containerReaderRunnable.setFailureNotifyText(cp.getFailureWatchString());
            }

            containerReaderRunnable.setListener(this);
            Thread containerReaderRunnableThread = new Thread(containerReaderRunnable);
            containerReaderRunnableThread.start();

            getLog().info("Started '" + cp.getCommand());

        } catch (IOException e) {
            throw new MojoExecutionException("Unable to start " + CONTAINER + " process " + e);
        }
    }

    long containerTimeout = -1;
    try {
        containerTimeout = Long.parseLong(containersStartupTimeout);
    } catch (NumberFormatException nfe) {
        // ignore
    }

    failed = false;
    finishImmediately = false;

    // wait for the container to start
    String currentWaitString = null;
    try {
        boolean anyFailed = false;
        if (containerTimeout == -1) {
            for (ContainerProcess container : containerProcessStartLatches.keySet()) {
                CountDownLatch latch = containerProcessStartLatches.get(container);
                if (container.getStartWatchString() != null && !"".equals(container.getStartWatchString())) {
                    currentWaitString = container.getStartWatchString();
                    latch.await();
                }
            }
        } else {
            long latestEndTime = System.currentTimeMillis() + containerTimeout;
            for (ContainerProcess container : containerProcessStartLatches.keySet()) {
                CountDownLatch latch = containerProcessStartLatches.get(container);
                if (container.getStartWatchString() != null && !"".equals(container.getStartWatchString())) {
                    long maxWaitTime = latestEndTime - System.currentTimeMillis();
                    boolean completed = latch.await(maxWaitTime, TimeUnit.MILLISECONDS);
                    if (!completed) {
                        failedProcesses.add(CONTAINER + "[" + container.getId() + "]");
                        anyFailed = true;
                        break;
                    }
                }
            }
        }
        if (anyFailed) {
            failed = true;
            finishImmediately = true;
        }
    } catch (InterruptedException ie) {
        getLog().warn("Interrupted waiting for notify text of '" + currentWaitString + "' to arrive");
    }

    if (!failed) {
        long uberTimeout = -1;
        if (testsCompletionTimeout != null && !"".equals(testsCompletionTimeout)) {
            uberTimeout = Long.parseLong(testsCompletionTimeout);
        }
        long targetEndTime = uberTimeout == -1 ? -1 : System.currentTimeMillis() + uberTimeout;

        for (TestProcess tp : testProcesses) {
            // run out of time
            if (uberTimeout == -1 && ((System.currentTimeMillis() - targetEndTime) <= 0)) {
                finishImmediately = true;
            }
            // exit the loop if we have to (at the top so we can die after container failure)
            if (finishImmediately) {
                break;
            }

            if (tp.getStartupDelay() != null && !"".equals(tp.getStartupDelay())) {
                try {
                    long delayMs = Long.valueOf(tp.getStartupDelay());
                    Thread.sleep(delayMs);

                } catch (InterruptedException ie) {
                    getLog().warn("Startup delay interrupted - you may get some timing issues");

                } catch (NumberFormatException nfe) {
                    getLog().error("Invalid startup delay");
                    throw new MojoExecutionException(
                            "Invalid startup delay.  Expected a number, not '" + tp.getStartupDelay() + "'");
                }
            }

            CountDownLatch latch = new CountDownLatch(1);
            testerId = TESTER + "[" + tp.getId() + "]";
            try {
                testProcessFinishLatches.put(testerId, latch);

                ProcessBuilder testProcessBuilder = tp.createProcessBuilder();
                getLog().info("Starting '" + tp.getCommand() + "' in directory '" + tp.getWorkingDir() + "'");
                _testerProcess = testProcessBuilder.start();
                testReaderRunnable = new ReaderRunnable(testerId, _testerProcess.getInputStream(), getLog());
                testReaderRunnable.setFailureNotifyText(tp.getFailureWatchString());
                testReaderRunnable.setNotifyText(tp.getWatchString());
                testReaderRunnable.setListener(this);
                Thread testReaderRunnableThread = new Thread(testReaderRunnable);
                testReaderRunnableThread.start();

                // make sure we catch the process completing normally
                final Process p = _testerProcess;
                final CountDownLatch l = latch;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            p.waitFor();
                        } catch (InterruptedException e) {
                            // don't care
                        }
                        l.countDown();
                    }
                });

                getLog().info("Started '" + tp.getCommand() + "'");

            } catch (IOException e) {
                getLog().info("Killing " + CONTAINER
                        + " process due to IO exception in, possibly in TEST PROCESS" + e);
                throw new MojoExecutionException("Unable to start " + testerId + " process. " + e);
            }

            getLog().info("Waiting for " + testerId + " process to complete.");
            boolean timedOut;
            try {
                long individualTimeout = tp.getCompletionTimeout() != null
                        ? Long.parseLong(tp.getCompletionTimeout())
                        : -1;
                long overallTimeout = uberTimeout != -1 ? targetEndTime - System.currentTimeMillis() : -1;
                long timeout = Math.max(individualTimeout, overallTimeout);
                if (timeout == -1) {
                    // not allowed
                    getLog().error("No timeout available, treating it as immediate timeout");
                    timedOut = true;
                } else {
                    timedOut = !latch.await(timeout, TimeUnit.MILLISECONDS);
                }
            } catch (InterruptedException e) {
                // ignore, will assume all not ok
                timedOut = true;
            }

            boolean exitedSuccessfully;
            try {
                exitedSuccessfully = _testerProcess.exitValue() == 0;
            } catch (IllegalThreadStateException itse) {
                // process hasn't exited, so assume it was successful, unless we timed out (if it did fail and we
                // noticed via the fail string, then "failed" will be false) - this is because processes don't seem to
                // end nicely
                exitedSuccessfully = true;
            }
            // timeout or failure code from the process
            if (timedOut || !exitedSuccessfully) {
                failed = true;
                failedProcesses.add(testerId);
            }
            if (failed) {
                if (failFast) {
                    finishImmediately = true;
                }
            }

            // now clean up
            getLog().warn(testerId + " process: exitedSuccessfully=" + exitedSuccessfully);
            getLog().warn(testerId + " process: timedOut          =" + timedOut);
            getLog().warn(testerId + " process: failed            =" + failed);

            getLog().warn("Terminating " + testerId + " process cleanly @ " + new Date());
            try {
                _testerProcess.getOutputStream().write(terminationChar);
                _testerProcess.getOutputStream().flush();
            } catch (IOException e) {
                // silent
            }
            _testerProcess.destroy();
            _testerProcess = null; // so noone else tries to cleanup later
        }
    }

    for (Process _containerProcess : _containerSystemProcesses) {
        getLog().warn("Destroying " + CONTAINER + " process @ " + new Date());
        try {
            _containerProcess.getOutputStream().write(terminationChar);
            _containerProcess.getOutputStream().flush();
        } catch (IOException e) {
            // silent
        }
        _containerProcess.destroy();
    }
    if (_testerProcess != null) {
        getLog().warn("Destroying " + TESTER + " process @ " + new Date());
        try {
            _testerProcess.getOutputStream().write(terminationChar);
            _testerProcess.getOutputStream().flush();
        } catch (IOException e) {
            // silent
        }
        _testerProcess.destroy();
    }

    if (failed) {
        String failedProcessesText = Arrays.toString(failedProcesses.toArray());
        throw new MojoFailureException(
                "Failure text arrived on the following processes: " + failedProcessesText);
    }
}

From source file:com.betfair.platform.plugin.testprocess.ProcessLauncherMojo.java

License:Apache License

private void validate() throws MojoExecutionException {
    int errorCount = 0;

    if (containerProcesses != null && containerProcesses.length > 0) {
        Set<String> ids = new HashSet<String>();
        for (ContainerProcess cp : containerProcesses) {
            if (cp.getId() == null || cp.getId().isEmpty()) {
                getLog().error("containerProcess id not specified");
                errorCount++;/*  w w  w .j a  v a2s  . c o m*/
            } else {
                if (!ids.add(cp.getId())) {
                    getLog().error("There is more than one container process with id '" + cp.getId() + "'");
                    errorCount++;
                }
            }
            if (cp.getCommand() == null || cp.getCommand().isEmpty()) {
                getLog().error("containerProcess not specified");
                errorCount++;
            }
            if (cp.getWorkingDir() == null || "".equals(cp.getWorkingDir())) {
                getLog().error("containerProcessWorkingDir not specified");
                errorCount++;
            }
        }
    } else {
        getLog().error("No container processes were specified");
        errorCount++;
    }

    if (testProcesses != null && testProcesses.length > 0) {
        Set<String> ids = new HashSet<String>();
        for (TestProcess tp : testProcesses) {
            if (tp.getId() == null || tp.getId().isEmpty()) {
                getLog().error("testProcess id not specified");
                errorCount++;
            } else {
                if (!ids.add(tp.getId())) {
                    getLog().error("There is more than one test process with id '" + tp.getId() + "'");
                    errorCount++;
                }
            }
            if (tp.getCommand() == null || tp.getCommand().isEmpty()) {
                getLog().error("testProcess not specified");
                errorCount++;
            }
            if (tp.getWorkingDir() == null || "".equals(tp.getWorkingDir())) {
                getLog().error("testProcessWorkingDir not specified");
                errorCount++;
            }
            if (tp.getStartupDelay() == null || "".equals(tp.getStartupDelay())) {
                getLog().warn("No startup delay specified");
            }
        }
    } else {
        getLog().error("No test processes were specified");
    }
    if (errorCount > 0) {
        throw new MojoExecutionException(errorCount + " Configuration error(s) found. Aborting");
    }
}

From source file:com.beyondconstraint.bounty.plugin.GeneratorMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("source: " + source);
    getLog().info("brokerSchema:" + brokerSchema);
    logTemplateDir(templateDir);/*from  w ww .j  av  a 2s  .c  om*/
    getLog().info("outputDir: " + outputDir);
    getLog().info("formatter: " + formatter);
    getLog().info("language: " + language);

    try {
        CodeGen.getBuilder().source(source).schema(brokerSchema).outputDir(outputDir).formatter(formatter)
                .language(language).addTemplateDirs(templateDir).generateCode();
    } catch (Throwable e) {
        getLog().error("");
        getLog().error("plugin stack trace:");
        getLog().error("-----------");
        getLog().error(" ", e);
        getLog().error("-----------");

        throw new MojoExecutionException(e.getMessage());
    }
}

From source file:com.bicosyes.simpleGwt.SimpleGwtCompile.java

License:Apache License

public void execute() throws MojoExecutionException {
    // debug stuff
    if (getLog().isDebugEnabled()) {
        getLog().debug("fork: " + fork);
        getLog().debug("failOnError: " + failOnError);
        getLog().debug("debug: " + debug);
        getLog().debug("verbose: " + verbose);
        getLog().debug("showDep: " + showDeprecation);
        getLog().debug("opt: " + optimize);
        getLog().debug("showWarn: " + showWarnings);
        getLog().debug("out: " + outputDirectory);
        getLog().debug("build: " + buildDirectory);
        getLog().debug("web: " + webappDirectory);
        getLog().debug("homeGWT: " + gwtHome);
        StringBuffer srcRoots = new StringBuffer("src: ");

        for (Object root : compileSourceRoots)
            srcRoots.append(" ").append(root);
        getLog().debug(srcRoots.toString());

        StringBuffer classpath = new StringBuffer("cp: ");
        for (Object path : classpathElements)
            classpath.append(" ").append(path);
        getLog().debug(classpath.toString());

        StringBuffer moduleInfo = new StringBuffer("mods: ");
        for (Object module : modules)
            moduleInfo.append(" ").append(module);
        getLog().debug(moduleInfo.toString());
    }//from   ww w .  j av  a2  s.c  om

    if (!webappDirectory.exists()) {
        webappDirectory.mkdirs();
        getLog().info("Created directory: " + webappDirectory.getAbsolutePath());
    }

    String activeModule = null;
    byte[] buffer = new byte[1024];
    String classpath;
    StringBuffer cp = new StringBuffer();

    for (Object path : compileSourceRoots)
        cp.append(File.pathSeparator).append(path);

    for (Object path : classpathElements)
        cp.append(File.pathSeparator).append(path);

    cp.append(File.pathSeparator).append(getGWTjar(gwtHome, os));

    classpath = cp.toString();

    getLog().debug("CP: " + classpath);
    ProcessBuilder processBuilder = new ProcessBuilder("java", "-classpath", classpath,
            "com.google.gwt.dev.GWTCompiler", "-out", webappDirectory.getAbsolutePath());
    processBuilder.directory(webappDirectory);
    try {
        for (Object module : modules) {
            activeModule = module.toString();
            List<String> commands = processBuilder.command();
            while (commands.size() > 6)
                commands.remove(6);

            commands.add(activeModule);
            Process process = processBuilder.start();
            InputStream std = process.getInputStream();
            for (int read = std.read(buffer); read != -1; read = std.read(buffer))
                getLog().info(new String(buffer, 0, read).trim());

            std = process.getErrorStream();
            for (int read = std.read(buffer); read != -1; read = std.read(buffer))
                getLog().error(new String(buffer, 0, read).trim());

            if (process.waitFor() != 0)
                throw new MojoExecutionException("Error compiling module " + activeModule);

            if (move) {
                File moduleDir = new File(
                        webappDirectory.getAbsolutePath() + File.separatorChar + activeModule);
                for (File f : moduleDir.listFiles()) {
                    getLog().debug(
                            "Copy to " + webappDirectory.getAbsolutePath() + File.separator + f.getName());
                    if (f.isDirectory())
                        copyDirectory(f,
                                new File(webappDirectory.getAbsolutePath() + File.separator + f.getName()));
                    else
                        copyFile(f, new File(webappDirectory.getAbsolutePath() + File.separator + f.getName()));
                }
                deleteResource(moduleDir);
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Error compiling module " + activeModule, e);
    }
}

From source file:com.bicosyes.simpleGwt.SimpleGwtDelete.java

License:Apache License

private void deleteGWTstuff(File classesDirectory, String module, List deletes) throws MojoExecutionException {
    // module is something like com.bicosyes.someApp     
    String[] stuffToDelete;//w  ww .j a v  a 2s. c o  m
    if (deletes == null) {
        String GWTXML = module.substring(module.lastIndexOf(".") + 1) + ".gwt.xml"; // someApp.gwt.xml
        stuffToDelete = new String[] { "public", "client", GWTXML };
    } else {
        stuffToDelete = new String[deletes.size()];
        for (int i = 0; i < deletes.size(); i++)
            stuffToDelete[i] = (String) deletes.get(i);
    }
    String stuffToBeDeleted = "";
    for (String s : stuffToDelete)
        stuffToBeDeleted += s + " ";
    getLog().debug("The following file will be deleted: " + stuffToBeDeleted);
    module = module.substring(0, module.lastIndexOf("."));
    String path = "";
    int levels = 0;
    while (module.indexOf(".") != -1) {
        path += module.substring(0, module.indexOf(".")) + File.separator;
        module = module.substring(module.indexOf(".") + 1, module.length());
        levels++;
    }
    path += module; // path would be com/bicosyes
    levels++;
    File gwtModuleDir = new File(classesDirectory.getAbsolutePath() + File.separator + path);
    if (!gwtModuleDir.exists() || !gwtModuleDir.isDirectory())
        throw new MojoExecutionException(
                "Error trying to remove the gwt stuff." + "The following directory should exists!: "
                        + gwtModuleDir.getAbsolutePath() + ".  WTF just happened?");
    else
        getLog().debug("Ready for starting since " + gwtModuleDir.getAbsolutePath());
    // go to delete!     
    for (String toDelete : stuffToDelete) {
        File crap = new File(gwtModuleDir.getAbsolutePath() + File.separator + toDelete);
        getLog().debug("Deleting " + crap.getAbsolutePath());
        if (crap.exists())
            deleteResource(crap, true);
    }

    while (gwtModuleDir.list().length == 0 && levels > 0) { // deleteing dir's :-/ so dangerous...
        File aux = gwtModuleDir.getParentFile();
        getLog().debug("Deleting " + gwtModuleDir.getAbsolutePath());
        if (!deleteResource(gwtModuleDir))
            throw new MojoExecutionException("Error while trying to remove " + gwtModuleDir.getAbsolutePath());
        gwtModuleDir = aux;
        levels--;
    }
}

From source file:com.btmatthews.maven.plugins.crx.CRXMojo.java

License:Apache License

/**
 * Called when the Maven plug-in is executing. It creates an in-memory ZIP file of all the Chrome Extension
 * source files, generates as signature using the private key from the PEM file, outputs a CRX file containing
 * a header, the public key, the signature and the ZIP data.
 *
 * @throws MojoExecutionException If there was an error that should stop the build.
 * @throws MojoFailureException   If there was an error but the build might be allowed to continue.
 *//*from w  ww  .  j a  v  a2  s.  c om*/
@Override
public final void execute() throws MojoExecutionException, MojoFailureException {

    // Make sure we have a manifest file for the CRX

    final File manifestFile = new File(crxSourceDirectory, "manifest.json");
    if (!manifestFile.exists()) {
        throw new MojoExecutionException("Missing manifest.json file");
    }

    // Generate CRX file name

    final StringBuilder crxFilename = new StringBuilder();
    crxFilename.append(finalName);
    if (StringUtils.isNotEmpty(classifier)) {
        crxFilename.append('-');
        crxFilename.append(classifier);
    }
    final File crxDirectory = new File(outputDirectory, crxFilename.toString());
    crxFilename.append(".crx");

    copyFiles(crxSourceDirectory, crxDirectory);

    // Generate the CRX file

    final File crxFile = new File(outputDirectory, crxFilename.toString());
    final String[] includes = ParameterUtils.splitParameter(packagingIncludes);
    final String[] excludes = ParameterUtils.splitParameter(packagingExcludes);

    crxArchiver.setPemFile(pemFile);
    crxArchiver.setPemPassword(pemPassword);
    crxArchiver.addDirectory(crxDirectory, includes, excludes);
    crxArchiver.setDestFile(crxFile);

    try {
        crxArchiver.createArchive();
    } catch (final IOException e) {
        throw new MojoExecutionException("Failed to package and sign the Google Chrome Extension", e);
    } catch (final ArchiverException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    // Attach the artifact to the build life-cycle

    if (StringUtils.isNotEmpty(classifier)) {
        projectHelper.attachArtifact(project, "crx", classifier, crxFile);
    } else {
        project.getArtifact().setFile(crxFile);
    }
}

From source file:com.btmatthews.maven.plugins.crx.CRXMojo.java

License:Apache License

/**
 * Recursively copy from a source directory to a destination directory applying resource filtering if necessary.
 *
 * @param source      The source directory.
 * @param destination The destination directory.
 * @throws MojoExecutionException If there was an error during the recursive copying or filtering.
 * @since 1.2.0//from  ww  w  . ja  va2 s  .  c o m
 */
private void copyFiles(final File source, final File destination) throws MojoExecutionException {
    try {
        if (!destination.exists() && !destination.mkdirs()) {
            throw new MojoExecutionException("Could not create directory: " + destination.getAbsolutePath());
        }
        for (final File sourceItem : source.listFiles()) {
            final File destinationItem = new File(destination, sourceItem.getName());
            if (sourceItem.isDirectory()) {
                copyFiles(sourceItem, destinationItem);
            } else {
                if (filtering && !isNonFilteredExtension(sourceItem.getName())) {
                    mavenFileFilter.copyFile(sourceItem, destinationItem, true, getFilterWrappers(), null);
                } else {
                    FileUtils.copyFile(sourceItem, destinationItem);
                }
            }
        }
    } catch (final MavenFilteringException e) {
        throw new MojoExecutionException("Failed to build filtering wrappers", e);
    } catch (final IOException e) {
        throw new MojoExecutionException("Error copying file: " + source.getAbsolutePath(), e);
    }
}

From source file:com.btmatthews.maven.plugins.ldap.mojo.LoadMojo.java

License:Apache License

/**
 * Execute the plugin goal iterating over the list of source files and loading the LDAP directory entries from
 * each file using the appropriate handler.
 *
 * @throws MojoExecutionException If there was an error executing the plugin goal.
 *///from w  ww.jav  a 2 s . c o  m
public void execute() throws MojoExecutionException {
    if (!isSkip()) {
        final LDAPConnection connection = connect();
        try {
            for (final Source source : sources) {
                try {
                    getLog().info("Processing input source: " + source);
                    final FormatHandler handler = getFormatHandler(source);
                    if (handler == null) {
                        getLog().warn("No handler for input source: " + source);
                    } else {
                        final InputStream inputStream = source.open();
                        if (inputStream == null) {
                            if (!this.continueOnError) {
                                throw new MojoExecutionException("Cannot open source for reading: " + source);
                            } else {
                                getLog().warn(
                                        "Skipping source that could not be opened for reading: " + source);
                            }
                        } else {
                            try {
                                handler.load(connection, source.open(), continueOnError, this, true);
                            } catch (final LDIFException e) {
                                throw new MojoExecutionException("Error during LDAP load", e);
                            } catch (final LDAPException e) {
                                throw new MojoExecutionException("Error during LDAP load", e);
                            } finally {
                                inputStream.close();
                            }
                        }
                    }
                } catch (final IOException e) {
                    if (!this.continueOnError) {
                        throw new MojoExecutionException("Error closing input source: " + source, e);
                    } else {
                        this.getLog().warn("Ignoring error closing input source: " + source, e);
                    }
                }
            }
        } finally {
            connection.close();
        }
    }
}

From source file:com.btmatthews.maven.plugins.xcodebuilder.AbstractProjectMojo.java

License:Apache License

/**
 * Execute the command line build by the sub-class implementation of the {@link AbstractProjectMojo#buildCommand()}
 * method. Output from the command line execution is logged as an error if it was written to stderr or logged as
 * an information message if it was written to stdout.
 *
 * @throws MojoExecutionException If there was a problem executing the build command itself.
 * @throws MojoFailureException   If the build command reported an error.
 *//*from   www  . j a v  a 2  s .  c  o  m*/
public void execute() throws MojoExecutionException, MojoFailureException {
    final Commandline command = buildCommand();
    try {
        final int rc = CommandLineUtils.executeCommandLine(command, new InfoConsumer(getLog()),
                new ErrorConsumer(getLog()));
        if (rc != 0) {
            throw new MojoExecutionException("Error while executing xcodebuild command. Return code was " + rc);
        }
    } catch (CommandLineException e) {
        throw new MojoExecutionException("Unable to execute xcodebuild command", e);
    }
}

From source file:com.bugvm.maven.plugin.AbstractBugVMMojo.java

License:Apache License

protected Config.Builder configure(Config.Builder builder) throws MojoExecutionException {
    builder.logger(getBugVMLogger());/*from   www . j a  va  2 s . c om*/

    // load config base file if it exists (and properties)

    if (os != null) {
        builder.os(OS.valueOf(os));
    }

    if (propertiesFile != null) {
        if (!propertiesFile.exists()) {
            throw new MojoExecutionException(
                    "Invalid 'propertiesFile' specified for BugVM compile: " + propertiesFile);
        }
        try {
            getLog().debug(
                    "Including properties file in BugVM compiler config: " + propertiesFile.getAbsolutePath());
            builder.addProperties(propertiesFile);
        } catch (IOException e) {
            throw new MojoExecutionException(
                    "Failed to add properties file to BugVM config: " + propertiesFile);
        }
    } else {
        try {
            builder.readProjectProperties(project.getBasedir(), false);
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read BugVM project properties file(s) in "
                    + project.getBasedir().getAbsolutePath(), e);
        }
    }

    if (configFile != null) {
        if (!configFile.exists()) {
            throw new MojoExecutionException("Invalid 'configFile' specified for BugVM compile: " + configFile);
        }
        try {
            getLog().debug("Loading config file for BugVM compiler: " + configFile.getAbsolutePath());
            builder.read(configFile);
        } catch (Exception e) {
            throw new MojoExecutionException("Failed to read BugVM config file: " + configFile);
        }
    } else {
        try {
            builder.readProjectConfig(project.getBasedir(), false);
        } catch (Exception e) {
            throw new MojoExecutionException(
                    "Failed to read project BugVM config file in " + project.getBasedir().getAbsolutePath(), e);
        }
    }

    // Read embedded BugVM <config> if there is one
    Plugin plugin = project.getPlugin("com.bugvm:bugvm-maven-plugin");
    MavenProject p = project;
    while (p != null && plugin == null) {
        plugin = p.getPluginManagement().getPluginsAsMap().get("com.bugvm:bugvm-maven-plugin");
        if (plugin == null)
            p = p.getParent();
    }
    if (plugin != null) {
        getLog().debug("Reading BugVM plugin configuration from " + p.getFile().getAbsolutePath());
        Xpp3Dom configDom = (Xpp3Dom) plugin.getConfiguration();
        if (configDom != null && configDom.getChild("config") != null) {
            StringWriter sw = new StringWriter();
            XMLWriter xmlWriter = new PrettyPrintXMLWriter(sw, "UTF-8", null);
            Xpp3DomWriter.write(xmlWriter, configDom.getChild("config"));
            try {
                builder.read(new StringReader(sw.toString()), project.getBasedir());
            } catch (Exception e) {
                throw new MojoExecutionException("Failed to read BugVM config embedded in POM", e);
            }
        }
    }

    File tmpDir = new File(project.getBuild().getDirectory(), "bugvm.tmp");
    try {
        FileUtils.deleteDirectory(tmpDir);
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to clean output dir " + tmpDir, e);
    }
    tmpDir.mkdirs();

    Home home = null;
    try {
        home = Home.find();
    } catch (Throwable t) {
    }
    if (home == null || !home.isDev()) {
        home = new Config.Home(unpackBugVMDist());
    }
    builder.home(home).tmpDir(tmpDir).skipInstall(true).installDir(installDir);
    if (home.isDev()) {
        builder.useDebugLibs(Boolean.getBoolean("bugvm.useDebugLibs"));
        builder.dumpIntermediates(true);
    }

    if (debug != null && !debug.equals("false")) {
        builder.debug(true);
        if (debugPort != -1) {
            builder.addPluginArgument("debug:jdwpport=" + debugPort);
        }
        if ("clientmode".equals(debug)) {
            builder.addPluginArgument("debug:clientmode=true");
        }
    }

    if (skipSigning) {
        builder.iosSkipSigning(true);
    } else {
        if (signIdentity != null) {
            getLog().debug("Using explicit signing identity: " + signIdentity);
            builder.iosSignIdentity(SigningIdentity.find(SigningIdentity.list(), signIdentity));
        }

        if (provisioningProfile != null) {
            getLog().debug("Using explicit provisioning profile: " + provisioningProfile);
            builder.iosProvisioningProfile(
                    ProvisioningProfile.find(ProvisioningProfile.list(), provisioningProfile));
        }

        // if (keychainPassword != null) {
        //     builder.keychainPassword(keychainPassword);
        // } else if (keychainPasswordFile != null) {
        //     builder.keychainPasswordFile(keychainPasswordFile);
        // }
    }

    if (cacheDir != null) {
        builder.cacheDir(cacheDir);
    }

    builder.clearClasspathEntries();

    // configure the runtime classpath

    try {
        for (Object object : project.getRuntimeClasspathElements()) {
            String path = (String) object;
            if (getLog().isDebugEnabled()) {
                getLog().debug("Including classpath element for BugVM app: " + path);
            }
            builder.addClasspathEntry(new File(path));
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error resolving application classpath for BugVM build", e);
    }

    return builder;
}