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);
}
}
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.'");
}
}
}
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);
}
}
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;
}
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());
}
}
Aggregations