Search in sources :

Example 66 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project maven-plugins by apache.

the class WarProjectPackagingTask method handleDeploymentDescriptors.

/**
     * Handles the deployment descriptors, if specified. Note that the behavior here is slightly different since the
     * customized entry always win, even if an overlay has already packaged a web.xml previously.
     *
     * @param context the packaging context
     * @param webinfDir the web-inf directory
     * @param metainfDir the meta-inf directory
     * @throws MojoFailureException if the web.xml is specified but does not exist
     * @throws MojoExecutionException if an error occurred while copying the descriptors
     */
protected void handleDeploymentDescriptors(WarPackagingContext context, File webinfDir, File metainfDir) throws MojoFailureException, MojoExecutionException {
    try {
        if (webXml != null && StringUtils.isNotEmpty(webXml.getName())) {
            if (!webXml.exists()) {
                throw new MojoFailureException("The specified web.xml file '" + webXml + "' does not exist");
            }
            // Making sure that it won't get overlayed
            context.getWebappStructure().registerFileForced(id, WEB_INF_PATH + "/web.xml");
            if (context.isFilteringDeploymentDescriptors()) {
                context.getMavenFileFilter().copyFile(webXml, new File(webinfDir, "web.xml"), true, context.getFilterWrappers(), getEncoding(webXml));
            } else {
                copyFile(context, webXml, new File(webinfDir, "web.xml"), "WEB-INF/web.xml", true);
            }
        } else {
            // the webXml can be the default one
            File defaultWebXml = new File(context.getWebappSourceDirectory(), WEB_INF_PATH + "/web.xml");
            // if exists we can filter it
            if (defaultWebXml.exists() && context.isFilteringDeploymentDescriptors()) {
                context.getWebappStructure().registerFile(id, WEB_INF_PATH + "/web.xml");
                context.getMavenFileFilter().copyFile(defaultWebXml, new File(webinfDir, "web.xml"), true, context.getFilterWrappers(), getEncoding(defaultWebXml));
            }
        }
        if (containerConfigXML != null && StringUtils.isNotEmpty(containerConfigXML.getName())) {
            String xmlFileName = containerConfigXML.getName();
            context.getWebappStructure().registerFileForced(id, META_INF_PATH + "/" + xmlFileName);
            if (context.isFilteringDeploymentDescriptors()) {
                context.getMavenFileFilter().copyFile(containerConfigXML, new File(metainfDir, xmlFileName), true, context.getFilterWrappers(), getEncoding(containerConfigXML));
            } else {
                copyFile(context, containerConfigXML, new File(metainfDir, xmlFileName), "META-INF/" + xmlFileName, true);
            }
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to copy deployment descriptor", e);
    } catch (MavenFilteringException e) {
        throw new MojoExecutionException("Failed to copy deployment descriptor", e);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MavenFilteringException(org.apache.maven.shared.filtering.MavenFilteringException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) File(java.io.File)

Example 67 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project sling by apache.

the class DisplayBundleUpdatesMojo method execute.

@SuppressWarnings("unchecked")
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        BundleList bundleList = readBundleList(bundleListFile);
        Set<Dependency> bundlesAsDependencies = new HashSet<Dependency>();
        for (StartLevel startLevel : bundleList.getStartLevels()) {
            for (Bundle bundle : startLevel.getBundles()) {
                bundlesAsDependencies.add(asDependency(bundle));
            }
        }
        logUpdates(getHelper().lookupDependenciesUpdates(bundlesAsDependencies, false));
    } catch (Exception e) {
        throw new MojoExecutionException("Unable to read bundle list.", e);
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) BundleList(org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.BundleList) Bundle(org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.Bundle) StartLevel(org.apache.sling.maven.projectsupport.bundlelist.v1_0_0.StartLevel) Dependency(org.apache.maven.model.Dependency) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) IOException(java.io.IOException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) HashSet(java.util.HashSet)

Example 68 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project sling by apache.

the class ValidateMojo method execute.

public void execute() throws MojoExecutionException, MojoFailureException {
    if (skip) {
        getLog().info("Skipping validation.");
        return;
    }
    long start = System.currentTimeMillis();
    if (!sourceDirectory.isAbsolute()) {
        sourceDirectory = new File(project.getBasedir(), sourceDirectory.getPath());
    }
    if (!sourceDirectory.exists()) {
        getLog().info("Source directory does not exist, skipping.");
        return;
    }
    if (!sourceDirectory.isDirectory()) {
        throw new MojoExecutionException(String.format("Configured sourceDirectory={%s} is not a directory.", sourceDirectory.getAbsolutePath()));
    }
    if (!buildContext.hasDelta(sourceDirectory)) {
        getLog().info("No files found to validate, skipping.");
        return;
    }
    // don't fail execution in Eclipse as it generates an error marker in the POM file, which is not desired
    boolean mayFailExecution = !buildContext.getClass().getName().startsWith("org.eclipse.m2e");
    sourceDirectoryLength = sourceDirectory.getAbsolutePath().length();
    processedIncludes = processIncludes();
    processedExcludes = processExcludes();
    try {
        SightlyCompiler compiler = new SightlyCompiler();
        Scanner scanner = buildContext.newScanner(sourceDirectory);
        scanner.setExcludes(new String[] { processedExcludes });
        scanner.setIncludes(new String[] { processedIncludes });
        scanner.scan();
        String[] includedFiles = scanner.getIncludedFiles();
        processedFiles = new ArrayList<>(includedFiles.length);
        for (String includedFile : includedFiles) {
            processedFiles.add(new File(sourceDirectory, includedFile));
        }
        Map<File, CompilationResult> compilationResults = new HashMap<>();
        for (File script : processedFiles) {
            compilationResults.put(script, compiler.compile(getCompilationUnit(script)));
        }
        for (Map.Entry<File, CompilationResult> entry : compilationResults.entrySet()) {
            File script = entry.getKey();
            CompilationResult result = entry.getValue();
            buildContext.removeMessages(script);
            if (result.getWarnings().size() > 0) {
                for (CompilerMessage message : result.getWarnings()) {
                    buildContext.addMessage(script, message.getLine(), message.getColumn(), message.getMessage(), BuildContext.SEVERITY_WARNING, null);
                }
                hasWarnings = true;
            }
            if (result.getErrors().size() > 0) {
                for (CompilerMessage message : result.getErrors()) {
                    String messageString = message.getMessage().replaceAll(System.lineSeparator(), "");
                    buildContext.addMessage(script, message.getLine(), message.getColumn(), messageString, BuildContext.SEVERITY_ERROR, null);
                }
                hasErrors = true;
            }
        }
        getLog().info("Processed " + processedFiles.size() + " files in " + (System.currentTimeMillis() - start) + " milliseconds");
        if (mayFailExecution && hasWarnings && failOnWarnings) {
            throw new MojoFailureException("Compilation warnings were configured to fail the build.");
        }
        if (mayFailExecution && hasErrors) {
            throw new MojoFailureException("Please check the reported syntax errors.");
        }
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Cannot filter files from {%s} with includes {%s} and excludes {%s}.", sourceDirectory.getAbsolutePath(), processedIncludes, processedExcludes), e);
    }
}
Also used : Scanner(org.codehaus.plexus.util.Scanner) CompilerMessage(org.apache.sling.scripting.sightly.compiler.CompilerMessage) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) HashMap(java.util.HashMap) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) SightlyCompiler(org.apache.sling.scripting.sightly.compiler.SightlyCompiler) CompilationResult(org.apache.sling.scripting.sightly.compiler.CompilationResult) File(java.io.File) HashMap(java.util.HashMap) Map(java.util.Map)

Example 69 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project sling by apache.

the class ValidateMojoTest method testFailOnWarnings.

@Test
public void testFailOnWarnings() throws Exception {
    File baseDir = new File(System.getProperty("basedir"));
    ValidateMojo validateMojo = getMojo(baseDir, FAIL_ON_WARNINGS_POM);
    Exception exception = null;
    try {
        validateMojo.execute();
    } catch (MojoFailureException e) {
        exception = e;
    }
    List<File> processedFiles = validateMojo.getProcessedFiles();
    assertNotNull("Expected a MojoFailureException.", exception);
    assertEquals("Expected 1 file to process.", 1, processedFiles.size());
    assertTrue("Expected warning.sly to be one of the processed files.", processedFiles.contains(new File(baseDir, WARNING_SLY)));
    assertEquals("Expected compilation warnings.", true, validateMojo.hasWarnings());
}
Also used : MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Test(org.junit.Test)

Example 70 with MojoFailureException

use of org.apache.maven.plugin.MojoFailureException in project sling by apache.

the class JcrOcmMojo method execute.

public void execute() throws MojoFailureException {
    boolean hasFailures = false;
    // prepare QDox and prime with the compile class path of the project
    JavaDocBuilder builder = new JavaDocBuilder();
    try {
        builder.getClassLibrary().addClassLoader(this.getCompileClassLoader());
    } catch (IOException ioe) {
        throw new MojoFailureException("Cannot prepare QDox");
    }
    // add the sources from the project
    for (Iterator i = this.project.getCompileSourceRoots().iterator(); i.hasNext(); ) {
        try {
            builder.addSourceTree(new File((String) i.next()));
        } catch (OutOfMemoryError oome) {
            // this may be the case for big sources and not enough VM mem
            // drop the builder to help GC now
            builder = null;
            // fail with some explanation
            throw new MojoFailureException("Failed analyzing source due to not enough memory, try setting Max Heap Size higher, e.g. using MAVEN_OPTS=-Xmx128m");
        }
    }
    // parse the sources and get them
    JavaSource[] javaSources = builder.getSources();
    List descriptors = new ArrayList();
    for (int i = 0; i < javaSources.length; i++) {
        JavaClass[] javaClasses = javaSources[i].getClasses();
        for (int j = 0; javaClasses != null && j < javaClasses.length; j++) {
            DocletTag tag = javaClasses[j].getTagByName(ClassDescriptor.TAG_CLASS_DESCRIPTOR);
            if (tag != null) {
                ClassDescriptor descriptor = this.createClassDescriptor(javaClasses[j]);
                if (descriptor != null) {
                    descriptors.add(descriptor);
                } else {
                    hasFailures = true;
                }
            }
        }
    }
    // after checking all classes, throw if there were any failures
    if (hasFailures) {
        throw new MojoFailureException("Jackrabbit OCM Descriptor parsing had failures (see log)");
    }
    // terminate if there is nothing to write
    if (descriptors.isEmpty()) {
        this.getLog().info("No Jackrabbit OCM Descriptors found in project");
        return;
    }
    // finally the descriptors have to be written ....
    if (StringUtils.isEmpty(this.finalName)) {
        this.getLog().error("Descriptor file name must not be empty");
        return;
    }
    // prepare the descriptor output file
    File descriptorFile = new File(new File(this.outputDirectory, "SLING-INF"), this.finalName);
    // ensure parent dir
    descriptorFile.getParentFile().mkdirs();
    this.getLog().info("Generating " + descriptors.size() + " OCM Mapping Descriptors to " + descriptorFile);
    // write out all the class descriptors in parse order
    FileOutputStream descriptorStream = null;
    XMLWriter xw = null;
    try {
        descriptorStream = new FileOutputStream(descriptorFile);
        xw = new XMLWriter(descriptorStream, false);
        xw.printElementStart("jackrabbit-ocm", false);
        for (Iterator di = descriptors.iterator(); di.hasNext(); ) {
            ClassDescriptor sd = (ClassDescriptor) di.next();
            sd.generate(xw);
        }
        xw.printElementEnd("jackrabbit-ocm");
    } catch (IOException ioe) {
        hasFailures = true;
        this.getLog().error("Cannot write descriptor to " + descriptorFile, ioe);
        throw new MojoFailureException("Failed to write descriptor to " + descriptorFile);
    } finally {
        IOUtil.close(xw);
        IOUtil.close(descriptorStream);
        // remove the descriptor file in case of write failure
        if (hasFailures) {
            descriptorFile.delete();
        }
    }
    // now add the descriptor file to the maven resources
    final String ourRsrcPath = this.outputDirectory.getAbsolutePath();
    boolean found = false;
    final Iterator rsrcIterator = this.project.getResources().iterator();
    while (!found && rsrcIterator.hasNext()) {
        final Resource rsrc = (Resource) rsrcIterator.next();
        found = rsrc.getDirectory().equals(ourRsrcPath);
    }
    if (!found) {
        final Resource resource = new Resource();
        resource.setDirectory(this.outputDirectory.getAbsolutePath());
        this.project.addResource(resource);
    }
    // and set include accordingly
    this.project.getProperties().setProperty("Sling-Mappings", "SLING-INF/" + this.finalName);
}
Also used : MojoFailureException(org.apache.maven.plugin.MojoFailureException) ArrayList(java.util.ArrayList) Resource(org.apache.maven.model.Resource) IOException(java.io.IOException) JavaDocBuilder(com.thoughtworks.qdox.JavaDocBuilder) JavaClass(com.thoughtworks.qdox.model.JavaClass) FileOutputStream(java.io.FileOutputStream) Iterator(java.util.Iterator) JavaSource(com.thoughtworks.qdox.model.JavaSource) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) DocletTag(com.thoughtworks.qdox.model.DocletTag)

Aggregations

MojoFailureException (org.apache.maven.plugin.MojoFailureException)157 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)94 File (java.io.File)93 IOException (java.io.IOException)91 ArrayList (java.util.ArrayList)50 TreeSet (java.util.TreeSet)33 FileInputStream (java.io.FileInputStream)32 FileOutputStream (java.io.FileOutputStream)21 List (java.util.List)21 Map (java.util.Map)21 MavenProject (org.apache.maven.project.MavenProject)18 Set (java.util.Set)15 MalformedURLException (java.net.MalformedURLException)14 HashMap (java.util.HashMap)13 HashSet (java.util.HashSet)13 InputStream (java.io.InputStream)12 URLClassLoader (java.net.URLClassLoader)12 Matcher (java.util.regex.Matcher)12 Artifact (org.apache.maven.artifact.Artifact)12 AbstractMojo (org.apache.maven.plugin.AbstractMojo)12