Search in sources :

Example 46 with MojoFailureException

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

the class PmdViolationCheckMojoTest method testDefaultConfiguration.

public void testDefaultConfiguration() throws Exception {
    try {
        final File testPom = new File(getBasedir(), "src/test/resources/unit/default-configuration/pmd-check-default-configuration-plugin-config.xml");
        final PmdViolationCheckMojo mojo = (PmdViolationCheckMojo) lookupMojo("check", testPom);
        mojo.execute();
        fail("MojoFailureException should be thrown.");
    } catch (final Exception e) {
        assertTrue(true);
    }
}
Also used : File(java.io.File) MojoFailureException(org.apache.maven.plugin.MojoFailureException)

Example 47 with MojoFailureException

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

the class PmdViolationCheckMojoTest method testFailurePriority.

public void testFailurePriority() throws Exception {
    File testPom = new File(getBasedir(), "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml");
    final PmdReport mojo = (PmdReport) lookupMojo("pmd", testPom);
    mojo.execute();
    testPom = new File(getBasedir(), "src/test/resources/unit/default-configuration/pmd-check-failonpriority-plugin-config.xml");
    PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo("check", testPom);
    pmdViolationMojo.execute();
    testPom = new File(getBasedir(), "src/test/resources/unit/default-configuration/pmd-check-failandwarnonpriority-plugin-config.xml");
    pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo("check", testPom);
    try {
        pmdViolationMojo.execute();
        fail("Exception Expected");
    } catch (final MojoFailureException e) {
        String message = e.getMessage();
        if (message.contains("You have 5 PMD violations and 3 warnings.")) {
            // expected
            System.out.println("Caught expected message: " + e.getMessage());
        } else {
            throw new AssertionError("Expected: '" + message + "' to contain 'You have 5 PMD violations and 3 warnings.'");
        }
    }
}
Also used : MojoFailureException(org.apache.maven.plugin.MojoFailureException) File(java.io.File)

Example 48 with MojoFailureException

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

the class CheckstyleViolationCheckMojo method execute.

/** {@inheritDoc} */
public void execute() throws MojoExecutionException, MojoFailureException {
    checkDeprecatedParameterUsage(sourceDirectory, "sourceDirectory", "sourceDirectories");
    checkDeprecatedParameterUsage(testSourceDirectory, "testSourceDirectory", "testSourceDirectories");
    if (skip) {
        return;
    }
    outputXmlFile = outputFile;
    if (!skipExec) {
        if (checkstyleRules != null) {
            if (!"sun_checks.xml".equals(configLocation)) {
                throw new MojoExecutionException("If you use inline configuration for rules, don't specify " + "a configLocation");
            }
            if (checkstyleRules.getChildCount() > 1) {
                throw new MojoExecutionException("Currently only one root module is supported");
            }
            PlexusConfiguration checkerModule = checkstyleRules.getChild(0);
            try {
                FileUtils.forceMkdir(rulesFiles.getParentFile());
                FileUtils.fileWrite(rulesFiles, CHECKSTYLE_FILE_HEADER + checkerModule.toString());
            } catch (final IOException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
            configLocation = rulesFiles.getAbsolutePath();
        }
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            CheckstyleExecutorRequest request = new CheckstyleExecutorRequest();
            request.setConsoleListener(getConsoleListener()).setConsoleOutput(consoleOutput).setExcludes(excludes).setFailsOnError(failsOnError).setIncludes(includes).setResourceIncludes(resourceIncludes).setResourceExcludes(resourceExcludes).setIncludeResources(includeResources).setIncludeTestResources(includeTestResources).setIncludeTestSourceDirectory(includeTestSourceDirectory).setListener(getListener()).setProject(project).setSourceDirectories(getSourceDirectories()).setResources(resources).setTestResources(testResources).setStringOutputStream(stringOutputStream).setSuppressionsLocation(suppressionsLocation).setTestSourceDirectories(getTestSourceDirectories()).setConfigLocation(configLocation).setConfigurationArtifacts(collectArtifacts("config")).setPropertyExpansion(propertyExpansion).setHeaderLocation(headerLocation).setLicenseArtifacts(collectArtifacts("license")).setCacheFile(cacheFile).setSuppressionsFileExpression(suppressionsFileExpression).setEncoding(encoding).setPropertiesLocation(propertiesLocation).setOmitIgnoredModules(omitIgnoredModules);
            checkstyleExecutor.executeCheckstyle(request);
        } catch (CheckstyleException e) {
            throw new MojoExecutionException("Failed during checkstyle configuration", e);
        } catch (CheckstyleExecutorException e) {
            throw new MojoExecutionException("Failed during checkstyle execution", e);
        } finally {
            //be sure to restore original context classloader
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
    if (!"xml".equals(outputFileFormat) && skipExec) {
        throw new MojoExecutionException("Output format is '" + outputFileFormat + "', checkstyle:check requires format to be 'xml' when using skipExec.");
    }
    if (!outputXmlFile.exists()) {
        getLog().info("Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile.");
        return;
    }
    try (Reader reader = new BufferedReader(ReaderFactory.newXmlReader(outputXmlFile))) {
        XmlPullParser xpp = new MXParser();
        xpp.setInput(reader);
        int violations = countViolations(xpp);
        if (violations > maxAllowedViolations) {
            if (failOnViolation) {
                String msg = "You have " + violations + " Checkstyle violation" + ((violations > 1) ? "s" : "") + ".";
                if (maxAllowedViolations > 0) {
                    msg += " The maximum number of allowed violations is " + maxAllowedViolations + ".";
                }
                throw new MojoFailureException(msg);
            }
            getLog().warn("checkstyle:check violations detected but failOnViolation set to false");
        }
    } catch (IOException | XmlPullParserException e) {
        throw new MojoExecutionException("Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e);
    }
}
Also used : PlexusConfiguration(org.codehaus.plexus.configuration.PlexusConfiguration) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MXParser(org.codehaus.plexus.util.xml.pull.MXParser) CheckstyleExecutorRequest(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorRequest) CheckstyleExecutorException(org.apache.maven.plugins.checkstyle.exec.CheckstyleExecutorException) XmlPullParser(org.codehaus.plexus.util.xml.pull.XmlPullParser) MojoFailureException(org.apache.maven.plugin.MojoFailureException) Reader(java.io.Reader) BufferedReader(java.io.BufferedReader) CheckstyleException(com.puppycrawl.tools.checkstyle.api.CheckstyleException) IOException(java.io.IOException) BufferedReader(java.io.BufferedReader) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException)

Example 49 with MojoFailureException

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

the class CheckstyleViolationCheckMojo method getListener.

private AuditListener getListener() throws MojoFailureException, MojoExecutionException {
    AuditListener listener = null;
    if (StringUtils.isNotEmpty(outputFileFormat)) {
        File resultFile = outputFile;
        OutputStream out = getOutputStream(resultFile);
        if ("xml".equals(outputFileFormat)) {
            listener = new XMLLogger(out, true);
        } else if ("plain".equals(outputFileFormat)) {
            try {
                // Write a plain output file to the standard output file,
                // and write an XML output file to the temp directory that can be used to count violations
                outputXmlFile = File.createTempFile("checkstyle-result", ".xml");
                outputXmlFile.deleteOnExit();
                OutputStream xmlOut = getOutputStream(outputXmlFile);
                CompositeAuditListener compoundListener = new CompositeAuditListener();
                compoundListener.addListener(new XMLLogger(xmlOut, true));
                compoundListener.addListener(new DefaultLogger(out, true));
                listener = compoundListener;
            } catch (IOException e) {
                throw new MojoExecutionException("Unable to create temporary file", e);
            }
        } else {
            throw new MojoFailureException("Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'.");
        }
    }
    return listener;
}
Also used : XMLLogger(com.puppycrawl.tools.checkstyle.XMLLogger) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) MojoFailureException(org.apache.maven.plugin.MojoFailureException) IOException(java.io.IOException) AuditListener(com.puppycrawl.tools.checkstyle.api.AuditListener) File(java.io.File) DefaultLogger(com.puppycrawl.tools.checkstyle.DefaultLogger)

Example 50 with MojoFailureException

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

the class EarMojo method changeManifestClasspath.

private void changeManifestClasspath(EarModule module, File original, JavaEEVersion javaEEVersion) throws MojoFailureException {
    try {
        File workDirectory;
        // Handle the case that the destination might be a directory (project-038)
        if (original.isFile()) {
            // Create a temporary work directory
            // MEAR-167 use uri as directory to prevent merging of artifacts with the same artifactId
            workDirectory = new File(new File(getTempFolder(), "temp"), module.getUri());
            workDirectory.mkdirs();
            getLog().debug("Created a temporary work directory: " + workDirectory.getAbsolutePath());
            // Unpack the archive to a temporary work directory
            zipUnArchiver.setSourceFile(original);
            zipUnArchiver.setDestDirectory(workDirectory);
            zipUnArchiver.extract();
        } else {
            workDirectory = original;
        }
        // Create a META-INF/MANIFEST.MF file if it doesn't exist (project-038)
        File metaInfDirectory = new File(workDirectory, "META-INF");
        boolean newMetaInfCreated = metaInfDirectory.mkdirs();
        if (newMetaInfCreated) {
            // CHECKSTYLE_OFF: LineLength
            getLog().debug("This project did not have a META-INF directory before, so a new directory was created.");
        // CHECKSTYLE_ON: LineLength
        }
        File newCreatedManifestFile = new File(metaInfDirectory, "MANIFEST.MF");
        boolean newManifestCreated = newCreatedManifestFile.createNewFile();
        if (newManifestCreated) {
            // CHECKSTYLE_OFF: LineLength
            getLog().debug("This project did not have a META-INF/MANIFEST.MF file before, so a new file was created.");
        // CHECKSTYLE_ON: LineLength
        }
        // Read the manifest from disk
        Manifest mf = new Manifest(new FileInputStream(newCreatedManifestFile));
        Attribute classPath = mf.getMainSection().getAttribute("Class-Path");
        List<String> classPathElements = new ArrayList<String>();
        if (classPath != null) {
            classPathElements.addAll(Arrays.asList(classPath.getValue().split(" ")));
        } else {
            classPath = new Attribute("Class-Path", "");
        }
        // Remove JAR modules
        for (JarModule jm : getAllJarModules()) {
            if (module.getLibDir() != null) {
                // MEAR-189:
                // We use the original name, cause in case of fileNameMapping to no-version/full
                // we could not not delete it and it will end up in the resulting EAR and the WAR
                // will not be cleaned up.
                File artifact = new File(new File(workDirectory, module.getLibDir()), jm.getOriginalBundleFileName());
                // the artifact is not found. Therefore respect the current fileNameMapping additionally.
                if (!artifact.exists()) {
                    artifact = new File(new File(workDirectory, module.getLibDir()), jm.getBundleFileName());
                }
                if (artifact.exists()) {
                    getLog().debug(" -> Artifact to delete: " + artifact);
                    if (!artifact.delete()) {
                        getLog().error("Could not delete '" + artifact + "'");
                    }
                }
            }
        }
        // Modify the classpath entries in the manifest
        for (EarModule o : getModules()) {
            if (o instanceof JarModule) {
                JarModule jm = (JarModule) o;
                if (classPathElements.contains(jm.getBundleFileName())) {
                    classPathElements.set(classPathElements.indexOf(jm.getBundleFileName()), jm.getUri());
                } else {
                    if (!skipClassPathModification) {
                        classPathElements.add(jm.getUri());
                    } else {
                        if (javaEEVersion.lt(JavaEEVersion.FIVE) || defaultLibBundleDir == null) {
                            classPathElements.add(jm.getUri());
                        }
                    }
                }
            }
        }
        classPath.setValue(StringUtils.join(classPathElements.iterator(), " "));
        mf.getMainSection().addConfiguredAttribute(classPath);
        // Write the manifest to disk
        PrintWriter pw = new PrintWriter(newCreatedManifestFile);
        mf.write(pw);
        pw.close();
        if (original.isFile()) {
            // Pack up the archive again from the work directory
            if (!original.delete()) {
                getLog().error("Could not delete original artifact file " + original);
            }
            getLog().debug("Zipping module");
            zipArchiver.setDestFile(original);
            zipArchiver.addDirectory(workDirectory);
            zipArchiver.createArchive();
        }
    } catch (ManifestException e) {
        throw new MojoFailureException(e.getMessage());
    } catch (ZipException e) {
        throw new MojoFailureException(e.getMessage());
    } catch (IOException e) {
        throw new MojoFailureException(e.getMessage());
    } catch (ArchiverException e) {
        throw new MojoFailureException(e.getMessage());
    }
}
Also used : Attribute(org.codehaus.plexus.archiver.jar.Manifest.Attribute) NoSuchArchiverException(org.codehaus.plexus.archiver.manager.NoSuchArchiverException) ArchiverException(org.codehaus.plexus.archiver.ArchiverException) ArrayList(java.util.ArrayList) MojoFailureException(org.apache.maven.plugin.MojoFailureException) ZipException(java.util.zip.ZipException) IOException(java.io.IOException) Manifest(org.codehaus.plexus.archiver.jar.Manifest) ManifestException(org.codehaus.plexus.archiver.jar.ManifestException) FileInputStream(java.io.FileInputStream) File(java.io.File) PrintWriter(java.io.PrintWriter)

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