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:ae.maven.ActiveEntityGeneratorMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (this.ae == null) {
        throw new MojoExecutionException("no ae project configured");
    }/*from  ww  w .  ja  va  2 s .  c o  m*/
    if (!this.destinationDirectory.exists()) {
        this.destinationDirectory.mkdirs();
    }
    try {
        final Project aeProject = buildActiveEntityProject();
        final Codifier codifier = new Codifier();
        codifier.output(this.destinationDirectory.getAbsolutePath()).templatesDir(this.templatesDirectory)
                .extension(this.generatedExtension).modelTemplate(this.template).modelFileName(this.filename)
                .baseTemplate(this.superTemplate).baseFileName(this.superFilename)
                .javaPackage(aeProject.getDefaultPackage());
        codifier.generateCodeFor(aeProject);
    } catch (final Exception e) {
        throw new MojoExecutionException("Error generating classes: ", e);
    }
}

From source file:aQute.bnd.maven.plugin.BndMavenPlugin.java

License:Open Source License

public void execute() throws MojoExecutionException {
    if (skip) {//from   ww  w . ja v  a2 s.  co m
        logger.debug("skip project as configured");
        return;
    }

    // Exit without generating anything if this is a pom-packaging project.
    // Probably it's just a parent project.
    if (PACKAGING_POM.equals(project.getPackaging())) {
        logger.info("skip project with packaging=pom");
        return;
    }

    Properties beanProperties = new BeanProperties();
    beanProperties.put("project", project);
    beanProperties.put("settings", settings);
    Properties mavenProperties = new Properties(beanProperties);
    mavenProperties.putAll(project.getProperties());

    try (Builder builder = new Builder(new Processor(mavenProperties, false))) {
        builder.setTrace(logger.isDebugEnabled());

        builder.setBase(project.getBasedir());
        propertiesFile = loadProjectProperties(builder, project);
        builder.setProperty("project.output", targetDir.getCanonicalPath());

        // If no bundle to be built, we have nothing to do
        if (Builder.isTrue(builder.getProperty(Constants.NOBUNDLES))) {
            logger.debug(Constants.NOBUNDLES + ": true");
            return;
        }

        // Reject sub-bundle projects
        List<Builder> subs = builder.getSubBuilders();
        if ((subs.size() != 1) || !builder.equals(subs.get(0))) {
            throw new MojoExecutionException("Sub-bundles not permitted in a maven build");
        }

        // Reject wab projects
        if (builder.getProperty(Constants.WAB) != null) {
            throw new MojoExecutionException(Constants.WAB + " not supported in a maven build");
        }
        if (builder.getProperty(Constants.WABLIB) != null) {
            throw new MojoExecutionException(Constants.WABLIB + " not supported in a maven build");
        }

        // Include local project packages automatically
        if (classesDir.isDirectory()) {
            Jar classesDirJar = new Jar(project.getName(), classesDir);
            classesDirJar.setManifest(new Manifest());
            builder.setJar(classesDirJar);
        }

        // Compute bnd classpath
        Set<Artifact> artifacts = project.getArtifacts();
        List<Object> buildpath = new ArrayList<Object>(artifacts.size());
        for (Artifact artifact : artifacts) {
            File cpe = artifact.getFile().getCanonicalFile();
            if (!cpe.exists()) {
                logger.debug("dependency {} does not exist", cpe);
                continue;
            }
            if (cpe.isDirectory()) {
                Jar cpeJar = new Jar(cpe);
                builder.addClose(cpeJar);
                builder.updateModified(cpeJar.lastModified(), cpe.getPath());
                buildpath.add(cpeJar);
            } else {
                if (!artifact.getType().equals("jar")) {
                    /*
                     * Check if it is a valid zip file. We don't create a
                     * Jar object here because we want to avoid the cost of
                     * creating the Jar object if we decide not to build.
                     */
                    try (ZipFile zip = new ZipFile(cpe)) {
                        zip.entries();
                    } catch (ZipException e) {
                        logger.debug("dependency {} is not a zip", cpe);
                        continue;
                    }
                }
                builder.updateModified(cpe.lastModified(), cpe.getPath());
                buildpath.add(cpe);
            }
        }
        builder.setProperty("project.buildpath", Strings.join(File.pathSeparator, buildpath));
        logger.debug("builder classpath: {}", builder.getProperty("project.buildpath"));

        // Compute bnd sourcepath
        boolean delta = !buildContext.isIncremental() || manifestOutOfDate();
        List<File> sourcepath = new ArrayList<File>();
        if (sourceDir.exists()) {
            sourcepath.add(sourceDir.getCanonicalFile());
            delta |= buildContext.hasDelta(sourceDir);
        }
        for (org.apache.maven.model.Resource resource : resources) {
            File resourceDir = new File(resource.getDirectory());
            if (resourceDir.exists()) {
                sourcepath.add(resourceDir.getCanonicalFile());
                delta |= buildContext.hasDelta(resourceDir);
            }
        }
        builder.setProperty("project.sourcepath", Strings.join(File.pathSeparator, sourcepath));
        logger.debug("builder sourcepath: {}", builder.getProperty("project.sourcepath"));

        // Set Bundle-SymbolicName
        if (builder.getProperty(Constants.BUNDLE_SYMBOLICNAME) == null) {
            builder.setProperty(Constants.BUNDLE_SYMBOLICNAME, project.getArtifactId());
        }
        // Set Bundle-Name
        if (builder.getProperty(Constants.BUNDLE_NAME) == null) {
            builder.setProperty(Constants.BUNDLE_NAME, project.getName());
        }
        // Set Bundle-Version
        if (builder.getProperty(Constants.BUNDLE_VERSION) == null) {
            Version version = MavenVersion.parseString(project.getVersion()).getOSGiVersion();
            builder.setProperty(Constants.BUNDLE_VERSION, version.toString());
            if (builder.getProperty(Constants.SNAPSHOT) == null) {
                builder.setProperty(Constants.SNAPSHOT, TSTAMP);
            }
        }

        logger.debug("builder properties: {}", builder.getProperties());
        logger.debug("builder delta: {}", delta);

        if (delta || (builder.getJar() == null) || (builder.lastModified() > builder.getJar().lastModified())) {
            // Set builder paths
            builder.setClasspath(buildpath);
            builder.setSourcepath(sourcepath.toArray(new File[0]));

            // Build bnd Jar (in memory)
            Jar bndJar = builder.build();

            // Expand Jar into target/classes
            expandJar(bndJar, classesDir);
        } else {
            logger.debug("No build");
        }

        // Finally, report
        reportErrorsAndWarnings(builder);
    } catch (MojoExecutionException e) {
        throw e;
    } catch (Exception e) {
        throw new MojoExecutionException("bnd error: " + e.getMessage(), e);
    }
}

From source file:aQute.bnd.maven.plugin.BndMavenPlugin.java

License:Open Source License

private void reportErrorsAndWarnings(Builder builder) throws MojoExecutionException {
    @SuppressWarnings("unchecked")
    Collection<File> markedFiles = (Collection<File>) buildContext.getValue(MARKED_FILES);
    if (markedFiles == null) {
        buildContext.removeMessages(propertiesFile);
        markedFiles = builder.getIncluded();
    }/*from ww  w. j  ava 2 s.c  o  m*/
    if (markedFiles != null) {
        for (File f : markedFiles) {
            buildContext.removeMessages(f);
        }
    }
    markedFiles = new HashSet<>();

    List<String> warnings = builder.getWarnings();
    for (String warning : warnings) {
        Location location = builder.getLocation(warning);
        if (location == null) {
            location = new Location();
            location.message = warning;
        }
        File f = location.file == null ? propertiesFile : new File(location.file);
        markedFiles.add(f);
        buildContext.addMessage(f, location.line, location.length, location.message,
                BuildContext.SEVERITY_WARNING, null);
    }
    List<String> errors = builder.getErrors();
    for (String error : errors) {
        Location location = builder.getLocation(error);
        if (location == null) {
            location = new Location();
            location.message = error;
        }
        File f = location.file == null ? propertiesFile : new File(location.file);
        markedFiles.add(f);
        buildContext.addMessage(f, location.line, location.length, location.message,
                BuildContext.SEVERITY_ERROR, null);
    }
    buildContext.setValue(MARKED_FILES, markedFiles);
    if (!builder.isOk()) {
        if (errors.size() == 1)
            throw new MojoExecutionException(errors.get(0));
        else
            throw new MojoExecutionException("Errors in bnd processing, see log for details.");
    }
}

From source file:at.makubi.maven.plugin.avrohugger.GeneratorMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    String sourceDirectoryPath = sourceDirectory.getAbsolutePath();
    if (!sourceDirectory.isDirectory()) {
        throw new MojoExecutionException(sourceDirectoryPath + " does not exist or is not a directory");
    }/*from   w  ww  .jav  a  2s.c o m*/

    String outputDirectoryPath = outputDirectory.getAbsolutePath();
    getLog().info(
            "Generating Scala files for schemas in " + sourceDirectoryPath + " to " + outputDirectoryPath);

    AvrohuggerGenerator generator = new AvrohuggerGenerator();
    generator.generateScalaFiles(sourceDirectory, outputDirectoryPath, getLog(), recursive,
            limitedNumberOfFieldsInCaseClasses);
}

From source file:at.peppol.maven.s2x.Schematron2XSLTMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    if (m_aSchematronDirectory == null)
        throw new MojoExecutionException("No Schematron directory specified!");
    if (m_aSchematronDirectory.exists() && !m_aSchematronDirectory.isDirectory())
        throw new MojoExecutionException(
                "The specified Schematron directory " + m_aSchematronDirectory + " is not a directory!");
    if (m_sSchematronPattern == null || m_sSchematronPattern.isEmpty()) {
        throw new MojoExecutionException("No Schematron pattern specified!");
    }/*from   w  w  w.  ja  v  a  2  s.  c o  m*/
    if (m_aXSLTDirectory == null)
        throw new MojoExecutionException("No XSLT directory specified!");
    if (m_aXSLTDirectory.exists() && !m_aXSLTDirectory.isDirectory())
        throw new MojoExecutionException(
                "The specified XSLT directory " + m_aXSLTDirectory + " is not a directory!");
    if (m_sXSLTExtension == null || m_sXSLTExtension.length() == 0 || !m_sXSLTExtension.startsWith("."))
        throw new MojoExecutionException("The XSLT extension '" + m_sXSLTExtension + "' is invalid!");

    if (!m_aXSLTDirectory.exists() && !m_aXSLTDirectory.mkdirs())
        throw new MojoExecutionException("Failed to create the XSLT directory " + m_aXSLTDirectory);

    // for all Schematron files that match the pattern
    final DirectoryScanner aScanner = new DirectoryScanner();
    aScanner.setBasedir(m_aSchematronDirectory);
    aScanner.setIncludes(new String[] { m_sSchematronPattern });
    aScanner.setCaseSensitive(true);
    aScanner.scan();
    final String[] aFilenames = aScanner.getIncludedFiles();
    if (aFilenames != null) {
        for (final String sFilename : aFilenames) {
            final File aFile = new File(m_aSchematronDirectory, sFilename);

            // 1. build XSLT file name (outputdir + localpath with new extension)
            final File aXSLTFile = new File(m_aXSLTDirectory,
                    FilenameHelper.getWithoutExtension(sFilename) + m_sXSLTExtension);

            getLog().info("Converting Schematron file '" + aFile.getPath() + "' to XSLT file '"
                    + aXSLTFile.getPath() + "'");

            // 2. The Schematron resource
            final IReadableResource aSchematronResource = new FileSystemResource(aFile);

            // 3. Check if the XSLT file already exists
            if (aXSLTFile.exists() && !m_bOverwriteWithoutQuestion) {
                // 3.1 Not overwriting the existing file
                getLog().debug("Skipping XSLT file '" + aXSLTFile.getPath() + "' because it already exists!");
            } else {
                // 3.2 Create the directory, if necessary
                final File aXsltFileDirectory = aXSLTFile.getParentFile();
                if (aXsltFileDirectory != null && !aXsltFileDirectory.exists()) {
                    getLog().debug("Creating directory '" + aXsltFileDirectory.getPath() + "'");
                    if (!aXsltFileDirectory.mkdirs()) {
                        final String message = "Failed to convert '" + aFile.getPath() + "' because directory '"
                                + aXsltFileDirectory.getPath() + "' could not be created";
                        getLog().error(message);
                        throw new MojoFailureException(message);
                    }
                }
                // 3.3 Okay, write the XSLT file
                try {
                    // Custom error listener to log to the Mojo logger
                    final ErrorListener aMojoErrorListener = new AbstractTransformErrorListener(null) {
                        @Override
                        protected void internalLog(final IResourceError aResError) {
                            if (aResError.isError())
                                getLog().error(aResError.getAsString(Locale.US),
                                        aResError.getLinkedException());
                            else
                                getLog().warn(aResError.getAsString(Locale.US), aResError.getLinkedException());
                        }
                    };

                    // Custom error listener but no custom URI resolver
                    final ISchematronXSLTProvider aXsltProvider = SchematronResourceSCHCache
                            .createSchematronXSLTProvider(aSchematronResource, aMojoErrorListener, null);
                    if (aXsltProvider != null) {
                        // Write the resulting XSLT file to disk
                        XMLWriter.writeToStream(aXsltProvider.getXSLTDocument(),
                                new FileOutputStream(aXSLTFile), XMLWriterSettings.DEFAULT_XML_SETTINGS);
                    } else {
                        final String message = "Failed to convert '" + aFile.getPath()
                                + "': the Schematron resource is invalid";
                        getLog().error(message);
                        throw new MojoFailureException(message);
                    }
                } catch (final MojoFailureException up) {
                    throw up;
                } catch (final Exception ex) {
                    final String message = "Failed to convert '" + aFile.getPath() + "' to XSLT file '"
                            + aXSLTFile.getPath() + "'";
                    getLog().error(message, ex);
                    throw new MojoFailureException(message, ex);
                }
            }
        }
    }
}

From source file:au.com.clearboxsystems.maven.plugins.nodejs.NodeJsMojoBase.java

License:Apache License

protected static NodeInstallInformation getNodeInstallationInformation(String version, File directory)
        throws MojoExecutionException {
    String baseURL = "http://nodejs.org/dist/v" + version + "/";
    String basePath = directory.getAbsolutePath() + File.separator;
    String arch;//w w w  .j  a  va 2  s .  c o m
    if (Os.isArch("x86") || Os.isArch("i386")) {
        arch = "x86";
    } else if (Os.isArch("x86_64") || Os.isArch("amd64")) {
        arch = "x64";
    } else {
        throw new MojoExecutionException("Unsupported OS arch: " + Os.OS_ARCH);
    }

    NodeInstallInformation result = new NodeInstallInformation();
    try {
        if (Os.isFamily(Os.FAMILY_WINDOWS) || Os.isFamily(Os.FAMILY_WIN9X)) {
            result.url = new URL(baseURL + "node.exe");
            result.archive = new File(basePath + "node-" + version + ".exe");
            result.executable = new File(basePath + "node-" + version + ".exe");
        } else if (Os.isFamily(Os.FAMILY_MAC)) {
            result.url = new URL(baseURL + "node-v" + version + "-darwin-" + arch + ".tar.gz");
            result.archive = new File(basePath + "node-v" + version + "-darwin-" + arch + ".tar.gz");
            result.executable = new File(basePath + "node-v" + version + "-darwin-" + arch + File.separator
                    + "bin" + File.separator + "node");
        } else if (Os.isFamily(Os.FAMILY_UNIX)) {
            result.url = new URL(baseURL + "node-v" + version + "-linux-" + arch + ".tar.gz");
            result.archive = new File(basePath + "node-v" + version + "-linux-" + arch + ".tar.gz");
            result.executable = new File(basePath + "node-v" + version + "-linux-" + arch + File.separator
                    + "bin" + File.separator + "node");
        } else {
            throw new MojoExecutionException("Unsupported OS: " + Os.OS_FAMILY);
        }
    } catch (java.net.MalformedURLException ex) {
        throw new MojoExecutionException("Malformed node URL", ex);
    }
    return result;
}

From source file:au.com.clearboxsystems.maven.plugins.nodejs.NodeJsMojoBase.java

License:Apache License

/**
 * Executes the given commandline/*  w ww.  j av  a  2 s.com*/
 *
 * @param commandLine
 * @return
 * @throws CommandLineException
 */
protected void executeCommandLine(Commandline commandLine) throws CommandLineException, MojoExecutionException {
    getLog().info("Executing command: " + commandLine.toString());
    CommandLineUtils.StringStreamConsumer systemErr = new CommandLineUtils.StringStreamConsumer();
    CommandLineUtils.StringStreamConsumer systemOut = new CommandLineUtils.StringStreamConsumer();

    int exitCode = CommandLineUtils.executeCommandLine(commandLine, systemOut, systemErr);
    String output = systemOut.getOutput().trim();
    if (!StringUtils.isEmpty(output)) {
        getLog().info("");
        for (String line : output.split("\n")) {
            getLog().info(line);
        }
        getLog().info("");
    }
    output = systemErr.getOutput().trim();
    if (!StringUtils.isEmpty(output)) {
        getLog().error("");
        for (String line : output.split("\n")) {
            getLog().error(line);
        }
        getLog().error("");
    }
    if (exitCode != 0) {
        throw new MojoExecutionException("Result of " + commandLine + " execution is: '" + exitCode + "'.");
    }
}

From source file:au.com.clearboxsystems.maven.plugins.nodejs.NodeJsMojoBase.java

License:Apache License

protected void executeTask(Task task, NodeInstallInformation information)
        throws CommandLineException, MojoExecutionException {
    if (task instanceof NodeJsTask) {
        NodeJsTask nodeJsTask = (NodeJsTask) task;
        Commandline commandLine = getCommandLine(nodeJsTask.workingDirectory,
                information.executable.getAbsolutePath(), nodeJsTask.name, nodeJsTask.arguments);
        executeCommandLine(commandLine);
    } else if (task instanceof ClosureCompilerTask) {
        ClosureCompilerTask closureCompilerTask = (ClosureCompilerTask) task;
        executeClosureCompiler(closureCompilerTask);
    } else {//  w w  w .  j  a v a  2  s. c  o  m
        throw new MojoExecutionException("Unknown task type");
    }
}

From source file:b2s.maven.AbstractMojo.java

License:Apache License

public final void execute() throws MojoExecutionException, MojoFailureException {
    PluginContext context = pluginContextFactory.build(this);
    if (validator != null) {
        PluginErrors errors = pluginErrorsFactory.build();
        validator.validate(context, errors);

        if (errors.hasErrors()) {
            String errorMessages = StringUtils.join(errors.getErrors(), "\n\t");
            throw new MojoExecutionException(
                    "There is a problem with how you configured the plugin. Below are the reason(s):\n\t"
                            + errorMessages);
        }//from w  w  w. ja  va2 s  .c o m
    }
    executePlugin(context);
}

From source file:be.hikage.maven.plugin.xmlmerge.MergeXmlMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    getLog().info("EXECUTE on " + outputDirectory.getAbsolutePath());
    getLog().info("Process prolog : " + processProlog);

    List<File> xmlFiles = new ArrayList<File>();

    Pattern regex = Pattern.compile(mergeFilenamePattern);

    getLog().info("Search file that match " + mergeFilenamePattern);
    findXmlToMerge(inputDirectory, xmlFiles);

    getLog().info("Number of file found to merge :" + xmlFiles.size());

    try {//from  w ww . j a v a  2  s . c o m
        for (File fileToMerge : xmlFiles) {
            Matcher matcher = regex.matcher(fileToMerge.getName());
            if (matcher.matches() && matcher.groupCount() == 2) {

                String baseFileName = matcher.group(2);

                File basefile = getBaseFile(fileToMerge, baseFileName);
                File outputFile = getOutputFile(fileToMerge, baseFileName);

                getLog().debug("Merge Base :" + basefile.getAbsolutePath());
                getLog().debug("Merge Transform :" + fileToMerge.getAbsolutePath());
                getLog().debug("Merge Output :" + outputFile.getAbsolutePath());

                if (basefile.exists()) {

                    StringBuilder prologHeader = processProlog ? new StringBuilder() : null;
                    Document documentBase = Dom4JUtils.readDocument(basefile.toURI().toURL(), prologHeader);
                    Document result = xmlMerger.mergeXml(documentBase, loadXml(fileToMerge));

                    writeMergedXml(outputFile, result, prologHeader);

                    if (removeMergeDocumentAfterProcessing) {
                        boolean fileDeleted = fileToMerge.delete();
                        if (!fileDeleted)
                            getLog().warn("Unable to delete file :" + fileToMerge.getAbsolutePath());
                    }

                } else {
                    getLog().warn("No filebase found for " + fileToMerge.getAbsolutePath());
                }

            } else {
                throw new MojoExecutionException("The file do not matches regex");

            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to merge xml", e);
    }

}