diff --git a/pom.xml b/pom.xml index 5b20c96f..551a3430 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - + - 4.0.0 - maven-plugins org.apache.maven.plugins - 37 + maven-plugins + 39 @@ -34,11 +32,9 @@ under the License. maven-plugin Apache Maven PMD Plugin - - A Maven plugin for the PMD toolkit, that produces a report on both code rule violations and detected copy and paste + A Maven plugin for the PMD toolkit, that produces a report on both code rule violations and detected copy and paste fragments, - as well as being able to fail the build based on these metrics. - + as well as being able to fail the build based on these metrics. 2005 @@ -66,8 +62,8 @@ under the License. scm:git:https://gitbox.apache.org/repos/asf/maven-pmd-plugin.git scm:git:https://gitbox.apache.org/repos/asf/maven-pmd-plugin.git - https://github.com/apache/maven-pmd-plugin/tree/${project.scm.tag} HEAD + https://github.com/apache/maven-pmd-plugin/tree/${project.scm.tag} JIRA @@ -88,7 +84,8 @@ under the License. 3.2.5 1.12.0 1.11.1 - 8 + 8 + 6.55.0 1.7.36 1.0.0.v20140518 @@ -357,11 +354,11 @@ under the License. - generate-sources java xpp3-reader + generate-sources @@ -379,10 +376,10 @@ under the License. check-java-1.8-compat - process-classes check + process-classes diff --git a/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java b/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java index c262397e..0142f2d3 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -36,6 +35,7 @@ import java.util.Set; import java.util.TreeMap; +import net.sourceforge.pmd.PMDVersion; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.ReportPlugin; import org.apache.maven.model.Reporting; @@ -50,17 +50,13 @@ import org.codehaus.plexus.util.PathTool; import org.codehaus.plexus.util.StringUtils; -import net.sourceforge.pmd.PMDVersion; - /** * Base class for the PMD reports. * * @author Brett Porter * @version $Id$ */ -public abstract class AbstractPmdReport - extends AbstractMavenReport -{ +public abstract class AbstractPmdReport extends AbstractMavenReport { // ---------------------------------------------------------------------- // Configurables // ---------------------------------------------------------------------- @@ -68,7 +64,7 @@ public abstract class AbstractPmdReport /** * The output directory for the intermediate XML report. */ - @Parameter( property = "project.build.directory", required = true ) + @Parameter(property = "project.build.directory", required = true) protected File targetDirectory; /** @@ -77,26 +73,26 @@ public abstract class AbstractPmdReport * renderers. XML is produced in any case, since this format is needed * for the check goals (pmd:check, pmd:aggregator-check, pmd:cpd-check, pmd:aggregator-cpd-check). */ - @Parameter( property = "format", defaultValue = "xml" ) + @Parameter(property = "format", defaultValue = "xml") protected String format = "xml"; /** * Link the violation line numbers to the source xref. Links will be created automatically if the jxr plugin is * being used. */ - @Parameter( property = "linkXRef", defaultValue = "true" ) + @Parameter(property = "linkXRef", defaultValue = "true") private boolean linkXRef; /** * Location of the Xrefs to link to. */ - @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref" ) + @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref") private File xrefLocation; /** * Location of the Test Xrefs to link to. */ - @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) + @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref-test") private File xrefTestLocation; /** @@ -124,7 +120,7 @@ public abstract class AbstractPmdReport * Defaults to project.compileSourceRoots. * @since 3.7 */ - @Parameter( defaultValue = "${project.compileSourceRoots}" ) + @Parameter(defaultValue = "${project.compileSourceRoots}") private List compileSourceRoots; /** @@ -132,7 +128,7 @@ public abstract class AbstractPmdReport * Defaults to project.testCompileSourceRoots * @since 3.7 */ - @Parameter( defaultValue = "${project.testCompileSourceRoots}" ) + @Parameter(defaultValue = "${project.testCompileSourceRoots}") private List testSourceRoots; /** @@ -148,7 +144,7 @@ public abstract class AbstractPmdReport * * @since 2.2 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean includeTests; /** @@ -158,7 +154,7 @@ public abstract class AbstractPmdReport * @deprecated since 3.15.0 Use the goals pmd:aggregate-pmd and pmd:aggregate-cpd * instead. */ - @Parameter( property = "aggregate", defaultValue = "false" ) + @Parameter(property = "aggregate", defaultValue = "false") @Deprecated protected boolean aggregate; @@ -167,7 +163,7 @@ public abstract class AbstractPmdReport * * @since 3.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean includeXmlInSite; /** @@ -178,7 +174,7 @@ public abstract class AbstractPmdReport * * @since 3.1 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean skipEmptyReport; /** @@ -189,7 +185,7 @@ public abstract class AbstractPmdReport * * @since 3.7 */ - @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) + @Parameter(property = "pmd.excludeFromFailureFile", defaultValue = "") protected String excludeFromFailureFile; /** @@ -201,7 +197,7 @@ public abstract class AbstractPmdReport * * @since 3.9.0 */ - @Parameter( defaultValue = "true", property = "pmd.showPmdLog" ) + @Parameter(defaultValue = "true", property = "pmd.showPmdLog") protected boolean showPmdLog = true; /** @@ -248,14 +244,14 @@ public abstract class AbstractPmdReport /** * The projects in the reactor for aggregation report. */ - @Parameter( property = "reactorProjects", readonly = true ) + @Parameter(property = "reactorProjects", readonly = true) protected List reactorProjects; /** * The current build session instance. This is used for * toolchain manager API calls and for dependency resolver API calls. */ - @Parameter( defaultValue = "${session}", required = true, readonly = true ) + @Parameter(defaultValue = "${session}", required = true, readonly = true) protected MavenSession session; @Component @@ -268,50 +264,39 @@ public abstract class AbstractPmdReport * {@inheritDoc} */ @Override - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } - protected String constructXRefLocation( boolean test ) - { + protected String constructXRefLocation(boolean test) { String location = null; - if ( linkXRef ) - { + if (linkXRef) { File xrefLoc = test ? xrefTestLocation : xrefLocation; String relativePath = - PathTool.getRelativePath( outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath() ); - if ( StringUtils.isEmpty( relativePath ) ) - { + PathTool.getRelativePath(outputDirectory.getAbsolutePath(), xrefLoc.getAbsolutePath()); + if (StringUtils.isEmpty(relativePath)) { relativePath = "."; } relativePath = relativePath + "/" + xrefLoc.getName(); - if ( xrefLoc.exists() ) - { + if (xrefLoc.exists()) { // XRef was already generated by manual execution of a lifecycle binding location = relativePath; - } - else - { + } else { // Not yet generated - check if the report is on its way Reporting reporting = project.getModel().getReporting(); - List reportPlugins = reporting != null - ? reporting.getPlugins() - : Collections.emptyList(); - for ( ReportPlugin plugin : reportPlugins ) - { + List reportPlugins = + reporting != null ? reporting.getPlugins() : Collections.emptyList(); + for (ReportPlugin plugin : reportPlugins) { String artifactId = plugin.getArtifactId(); - if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) - { + if ("maven-jxr-plugin".equals(artifactId) || "jxr-maven-plugin".equals(artifactId)) { location = relativePath; } } } - if ( location == null ) - { - getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); + if (location == null) { + getLog().warn("Unable to locate Source XRef to link to - DISABLED"); } } return location; @@ -324,112 +309,88 @@ protected String constructXRefLocation( boolean test ) * @throws IOException If an I/O error occurs during construction of the * canonical pathnames of the files */ - protected Map getFilesToProcess() - throws IOException - { - if ( aggregate && !project.isExecutionRoot() ) - { + protected Map getFilesToProcess() throws IOException { + if (aggregate && !project.isExecutionRoot()) { return Collections.emptyMap(); } - if ( excludeRoots == null ) - { + if (excludeRoots == null) { excludeRoots = new File[0]; } - Collection excludeRootFiles = new HashSet<>( excludeRoots.length ); + Collection excludeRootFiles = new HashSet<>(excludeRoots.length); - for ( File file : excludeRoots ) - { - if ( file.isDirectory() ) - { - excludeRootFiles.add( file ); + for (File file : excludeRoots) { + if (file.isDirectory()) { + excludeRootFiles.add(file); } } List directories = new ArrayList<>(); - if ( null == compileSourceRoots ) - { + if (null == compileSourceRoots) { compileSourceRoots = project.getCompileSourceRoots(); } - if ( compileSourceRoots != null ) - { - for ( String root : compileSourceRoots ) - { - File sroot = new File( root ); - if ( sroot.exists() ) - { - String sourceXref = constructXRefLocation( false ); - directories.add( new PmdFileInfo( project, sroot, sourceXref ) ); + if (compileSourceRoots != null) { + for (String root : compileSourceRoots) { + File sroot = new File(root); + if (sroot.exists()) { + String sourceXref = constructXRefLocation(false); + directories.add(new PmdFileInfo(project, sroot, sourceXref)); } } } - if ( null == testSourceRoots ) - { + if (null == testSourceRoots) { testSourceRoots = project.getTestCompileSourceRoots(); } - if ( includeTests && testSourceRoots != null ) - { - for ( String root : testSourceRoots ) - { - File sroot = new File( root ); - if ( sroot.exists() ) - { - String testXref = constructXRefLocation( true ); - directories.add( new PmdFileInfo( project, sroot, testXref ) ); + if (includeTests && testSourceRoots != null) { + for (String root : testSourceRoots) { + File sroot = new File(root); + if (sroot.exists()) { + String testXref = constructXRefLocation(true); + directories.add(new PmdFileInfo(project, sroot, testXref)); } } } - if ( isAggregator() ) - { - for ( MavenProject localProject : getAggregatedProjects() ) - { + if (isAggregator()) { + for (MavenProject localProject : getAggregatedProjects()) { List localCompileSourceRoots = localProject.getCompileSourceRoots(); - for ( String root : localCompileSourceRoots ) - { - File sroot = new File( root ); - if ( sroot.exists() ) - { - String sourceXref = constructXRefLocation( false ); - directories.add( new PmdFileInfo( localProject, sroot, sourceXref ) ); + for (String root : localCompileSourceRoots) { + File sroot = new File(root); + if (sroot.exists()) { + String sourceXref = constructXRefLocation(false); + directories.add(new PmdFileInfo(localProject, sroot, sourceXref)); } } - if ( includeTests ) - { + if (includeTests) { List localTestCompileSourceRoots = localProject.getTestCompileSourceRoots(); - for ( String root : localTestCompileSourceRoots ) - { - File sroot = new File( root ); - if ( sroot.exists() ) - { - String testXref = constructXRefLocation( true ); - directories.add( new PmdFileInfo( localProject, sroot, testXref ) ); + for (String root : localTestCompileSourceRoots) { + File sroot = new File(root); + if (sroot.exists()) { + String testXref = constructXRefLocation(true); + directories.add(new PmdFileInfo(localProject, sroot, testXref)); } } } } - } String excluding = getExcludes(); - getLog().debug( "Exclusions: " + excluding ); + getLog().debug("Exclusions: " + excluding); String including = getIncludes(); - getLog().debug( "Inclusions: " + including ); + getLog().debug("Inclusions: " + including); Map files = new TreeMap<>(); - for ( PmdFileInfo finfo : directories ) - { - getLog().debug( "Searching for files in directory " + finfo.getSourceDirectory().toString() ); + for (PmdFileInfo finfo : directories) { + getLog().debug("Searching for files in directory " + + finfo.getSourceDirectory().toString()); File sourceDirectory = finfo.getSourceDirectory(); - if ( sourceDirectory.isDirectory() && !isDirectoryExcluded( excludeRootFiles, sourceDirectory ) ) - { - List newfiles = FileUtils.getFiles( sourceDirectory, including, excluding ); - for ( File newfile : newfiles ) - { - files.put( newfile.getCanonicalFile(), finfo ); + if (sourceDirectory.isDirectory() && !isDirectoryExcluded(excludeRootFiles, sourceDirectory)) { + List newfiles = FileUtils.getFiles(sourceDirectory, including, excluding); + for (File newfile : newfiles) { + files.put(newfile.getCanonicalFile(), finfo); } } } @@ -437,29 +398,22 @@ protected Map getFilesToProcess() return files; } - private boolean isDirectoryExcluded( Collection excludeRootFiles, File sourceDirectoryToCheck ) - { + private boolean isDirectoryExcluded(Collection excludeRootFiles, File sourceDirectoryToCheck) { boolean returnVal = false; - for ( File excludeDir : excludeRootFiles ) - { - try - { - if ( sourceDirectoryToCheck - .getCanonicalFile() - .toPath() - .startsWith( excludeDir.getCanonicalFile().toPath() ) ) - { - getLog().debug( "Directory " + sourceDirectoryToCheck.getAbsolutePath() - + " has been excluded as it matches excludeRoot " - + excludeDir.getAbsolutePath() ); + for (File excludeDir : excludeRootFiles) { + try { + if (sourceDirectoryToCheck + .getCanonicalFile() + .toPath() + .startsWith(excludeDir.getCanonicalFile().toPath())) { + getLog().debug("Directory " + sourceDirectoryToCheck.getAbsolutePath() + + " has been excluded as it matches excludeRoot " + + excludeDir.getAbsolutePath()); returnVal = true; break; } - } - catch ( IOException e ) - { - getLog().warn( "Error while checking " + sourceDirectoryToCheck - + " whether it should be excluded.", e ); + } catch (IOException e) { + getLog().warn("Error while checking " + sourceDirectoryToCheck + " whether it should be excluded.", e); } } return returnVal; @@ -470,18 +424,15 @@ private boolean isDirectoryExcluded( Collection excludeRootFiles, File sou * * @return The comma separated list of effective include patterns, never null. */ - private String getIncludes() - { + private String getIncludes() { Collection patterns = new LinkedHashSet<>(); - if ( includes != null ) - { - patterns.addAll( includes ); + if (includes != null) { + patterns.addAll(includes); } - if ( patterns.isEmpty() ) - { - patterns.add( "**/*.java" ); + if (patterns.isEmpty()) { + patterns.add("**/*.java"); } - return StringUtils.join( patterns.iterator(), "," ); + return StringUtils.join(patterns.iterator(), ","); } /** @@ -489,134 +440,111 @@ private String getIncludes() * * @return The comma separated list of effective exclude patterns, never null. */ - private String getExcludes() - { - Collection patterns = new LinkedHashSet<>( FileUtils.getDefaultExcludesAsList() ); - if ( excludes != null ) - { - patterns.addAll( excludes ); + private String getExcludes() { + Collection patterns = new LinkedHashSet<>(FileUtils.getDefaultExcludesAsList()); + if (excludes != null) { + patterns.addAll(excludes); } - return StringUtils.join( patterns.iterator(), "," ); + return StringUtils.join(patterns.iterator(), ","); } - protected boolean isXml() - { - return "xml".equals( format ); + protected boolean isXml() { + return "xml".equals(format); } /** * {@inheritDoc} */ @Override - public boolean canGenerateReport() - { - if ( aggregate && !project.isExecutionRoot() ) - { + public boolean canGenerateReport() { + if (aggregate && !project.isExecutionRoot()) { return false; } - if ( !isAggregator() && "pom".equalsIgnoreCase( project.getPackaging() ) ) - { + if (!isAggregator() && "pom".equalsIgnoreCase(project.getPackaging())) { return false; } // if format is XML, we need to output it even if the file list is empty // so the "check" goals can check for failures - if ( isXml() ) - { + if (isXml()) { return true; } - try - { + try { filesToProcess = getFilesToProcess(); - if ( filesToProcess.isEmpty() ) - { + if (filesToProcess.isEmpty()) { return false; } - } - catch ( IOException e ) - { - getLog().error( e ); + } catch (IOException e) { + getLog().error(e); } return true; } - protected String determineCurrentRootLogLevel() - { - String logLevel = System.getProperty( "org.slf4j.simpleLogger.defaultLogLevel" ); - if ( logLevel == null ) - { - logLevel = System.getProperty( "maven.logging.root.level" ); + protected String determineCurrentRootLogLevel() { + String logLevel = System.getProperty("org.slf4j.simpleLogger.defaultLogLevel"); + if (logLevel == null) { + logLevel = System.getProperty("maven.logging.root.level"); } - if ( logLevel == null ) - { + if (logLevel == null) { // TODO: logback level logLevel = "info"; } return logLevel; } - static String getPmdVersion() - { + static String getPmdVersion() { return PMDVersion.VERSION; } - //TODO remove the part with ToolchainManager lookup once we depend on - //3.0.9 (have it as prerequisite). Define as regular component field then. - protected final Toolchain getToolchain() - { + // TODO remove the part with ToolchainManager lookup once we depend on + // 3.0.9 (have it as prerequisite). Define as regular component field then. + protected final Toolchain getToolchain() { Toolchain tc = null; - if ( jdkToolchain != null ) - { + if (jdkToolchain != null) { // Maven 3.3.1 has plugin execution scoped Toolchain Support - try - { - Method getToolchainsMethod = - toolchainManager.getClass().getMethod( "getToolchains", MavenSession.class, String.class, - Map.class ); + try { + Method getToolchainsMethod = toolchainManager + .getClass() + .getMethod("getToolchains", MavenSession.class, String.class, Map.class); - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") List tcs = - (List) getToolchainsMethod.invoke( toolchainManager, session, "jdk", - jdkToolchain ); + (List) getToolchainsMethod.invoke(toolchainManager, session, "jdk", jdkToolchain); - if ( tcs != null && !tcs.isEmpty() ) - { - tc = tcs.get( 0 ); + if (tcs != null && !tcs.isEmpty()) { + tc = tcs.get(0); } - } - catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e ) - { + } catch (NoSuchMethodException + | SecurityException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException e) { // ignore } } - if ( tc == null ) - { - tc = toolchainManager.getToolchainFromBuildContext( "jdk", session ); + if (tc == null) { + tc = toolchainManager.getToolchainFromBuildContext("jdk", session); } return tc; } - protected boolean isAggregator() - { + protected boolean isAggregator() { // returning here aggregate for backwards compatibility return aggregate; } // Note: same logic as in m-javadoc-p (MJAVADOC-134) - protected Collection getAggregatedProjects() - { + protected Collection getAggregatedProjects() { Map reactorProjectsMap = new HashMap<>(); - for ( MavenProject reactorProject : this.reactorProjects ) - { - reactorProjectsMap.put( reactorProject.getBasedir().toPath(), reactorProject ); + for (MavenProject reactorProject : this.reactorProjects) { + reactorProjectsMap.put(reactorProject.getBasedir().toPath(), reactorProject); } - return modulesForAggregatedProject( project, reactorProjectsMap ); + return modulesForAggregatedProject(project, reactorProjectsMap); } /** @@ -626,33 +554,28 @@ protected Collection getAggregatedProjects() * @param reactorProjectsMap map of (still) available reactor projects * @throws MavenReportException if any */ - private Set modulesForAggregatedProject( MavenProject aggregatedProject, - Map reactorProjectsMap ) - { + private Set modulesForAggregatedProject( + MavenProject aggregatedProject, Map reactorProjectsMap) { // Maven does not supply an easy way to get the projects representing // the modules of a project. So we will get the paths to the base // directories of the modules from the project and compare with the // base directories of the projects in the reactor. - if ( aggregatedProject.getModules().isEmpty() ) - { - return Collections.singleton( aggregatedProject ); + if (aggregatedProject.getModules().isEmpty()) { + return Collections.singleton(aggregatedProject); } List modulePaths = new LinkedList(); - for ( String module : aggregatedProject.getModules() ) - { - modulePaths.add( new File( aggregatedProject.getBasedir(), module ).toPath() ); + for (String module : aggregatedProject.getModules()) { + modulePaths.add(new File(aggregatedProject.getBasedir(), module).toPath()); } Set aggregatedModules = new LinkedHashSet<>(); - for ( Path modulePath : modulePaths ) - { - MavenProject module = reactorProjectsMap.remove( modulePath ); - if ( module != null ) - { - aggregatedModules.addAll( modulesForAggregatedProject( module, reactorProjectsMap ) ); + for (Path modulePath : modulePaths) { + MavenProject module = reactorProjectsMap.remove(modulePath); + if (module != null) { + aggregatedModules.addAll(modulesForAggregatedProject(module, reactorProjectsMap)); } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdViolationCheckMojo.java index 88bdabac..48cda50a 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AbstractPmdViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -39,13 +38,11 @@ * @author Brett Porter * @version $Id$ */ -public abstract class AbstractPmdViolationCheckMojo - extends AbstractMojo -{ +public abstract class AbstractPmdViolationCheckMojo extends AbstractMojo { /** * The location of the XML report to check, as generated by the PMD report. */ - @Parameter( property = "project.build.directory", required = true ) + @Parameter(property = "project.build.directory", required = true) private File targetDirectory; /** @@ -53,7 +50,7 @@ public abstract class AbstractPmdViolationCheckMojo * The properties {@code failurePriority} and {@code maxAllowedViolations} control * under which conditions exactly the build should be failed. */ - @Parameter( property = "pmd.failOnViolation", defaultValue = "true", required = true ) + @Parameter(property = "pmd.failOnViolation", defaultValue = "true", required = true) protected boolean failOnViolation; /** @@ -63,14 +60,14 @@ public abstract class AbstractPmdViolationCheckMojo * @deprecated since 3.15.0 Use the goal pmd:aggregate-check or * pmd:aggregate-cpd-check instead. */ - @Parameter( property = "aggregate", defaultValue = "false" ) + @Parameter(property = "aggregate", defaultValue = "false") @Deprecated protected boolean aggregate; /** * Print details of check failures to build output. */ - @Parameter( property = "pmd.verbose", defaultValue = "false" ) + @Parameter(property = "pmd.verbose", defaultValue = "false") private boolean verbose; /** @@ -78,7 +75,7 @@ public abstract class AbstractPmdViolationCheckMojo * * @since 3.0 */ - @Parameter( property = "pmd.printFailingErrors", defaultValue = "false" ) + @Parameter(property = "pmd.printFailingErrors", defaultValue = "false") private boolean printFailingErrors; /** @@ -89,7 +86,7 @@ public abstract class AbstractPmdViolationCheckMojo * * @since 3.0 */ - @Parameter( property = "pmd.excludeFromFailureFile", defaultValue = "" ) + @Parameter(property = "pmd.excludeFromFailureFile", defaultValue = "") private String excludeFromFailureFile; /** @@ -102,7 +99,7 @@ public abstract class AbstractPmdViolationCheckMojo * * @since 3.10.0 */ - @Parameter( property = "pmd.maxAllowedViolations", defaultValue = "0" ) + @Parameter(property = "pmd.maxAllowedViolations", defaultValue = "0") private int maxAllowedViolations; /** Helper to exclude violations from the result. */ @@ -112,80 +109,66 @@ public abstract class AbstractPmdViolationCheckMojo * Initialize this abstact check mojo by giving the correct ExcludeFromFile helper. * @param excludeFromFile the needed helper, for the specific violation type */ - protected AbstractPmdViolationCheckMojo( ExcludeFromFile excludeFromFile ) - { + protected AbstractPmdViolationCheckMojo(ExcludeFromFile excludeFromFile) { this.excludeFromFile = excludeFromFile; } /** * The project to analyze. */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; - protected void executeCheck( final String filename, final String tagName, final String key, - final int failurePriority ) - throws MojoFailureException, MojoExecutionException - { - if ( aggregate && !project.isExecutionRoot() ) - { + protected void executeCheck( + final String filename, final String tagName, final String key, final int failurePriority) + throws MojoFailureException, MojoExecutionException { + if (aggregate && !project.isExecutionRoot()) { return; } - if ( !isAggregator() && "pom".equalsIgnoreCase( project.getPackaging() ) ) - { + if (!isAggregator() && "pom".equalsIgnoreCase(project.getPackaging())) { return; } - excludeFromFile.loadExcludeFromFailuresData( excludeFromFailureFile ); - final File outputFile = new File( targetDirectory, filename ); + excludeFromFile.loadExcludeFromFailuresData(excludeFromFailureFile); + final File outputFile = new File(targetDirectory, filename); - if ( outputFile.exists() ) - { - getLog().info( "PMD version: " + AbstractPmdReport.getPmdVersion() ); + if (outputFile.exists()) { + getLog().info("PMD version: " + AbstractPmdReport.getPmdVersion()); - try - { - final ViolationDetails violations = getViolations( outputFile, failurePriority ); + try { + final ViolationDetails violations = getViolations(outputFile, failurePriority); final List failures = violations.getFailureDetails(); final List warnings = violations.getWarningDetails(); - if ( verbose ) - { - printErrors( failures, warnings ); + if (verbose) { + printErrors(failures, warnings); } final int failureCount = failures.size(); final int warningCount = warnings.size(); - final String message = getMessage( failureCount, warningCount, key, outputFile ); + final String message = getMessage(failureCount, warningCount, key, outputFile); - getLog().debug( "PMD failureCount: " + failureCount + ", warningCount: " + warningCount ); + getLog().debug("PMD failureCount: " + failureCount + ", warningCount: " + warningCount); - if ( failureCount > getMaxAllowedViolations() && isFailOnViolation() ) - { - throw new MojoFailureException( message ); + if (failureCount > getMaxAllowedViolations() && isFailOnViolation()) { + throw new MojoFailureException(message); } - this.getLog().info( message ); + this.getLog().info(message); - if ( failureCount > 0 && isFailOnViolation() && failureCount <= getMaxAllowedViolations() ) - { - this.getLog().info( "The build is not failed, since " + getMaxAllowedViolations() - + " violations are allowed (maxAllowedViolations)." ); + if (failureCount > 0 && isFailOnViolation() && failureCount <= getMaxAllowedViolations()) { + this.getLog() + .info("The build is not failed, since " + getMaxAllowedViolations() + + " violations are allowed (maxAllowedViolations)."); } + } catch (final IOException | XmlPullParserException e) { + throw new MojoExecutionException("Unable to read PMD results xml: " + outputFile.getAbsolutePath(), e); } - catch ( final IOException | XmlPullParserException e ) - { - throw new MojoExecutionException( - "Unable to read PMD results xml: " + outputFile.getAbsolutePath(), - e ); - } - } - else - { - throw new MojoFailureException( "Unable to perform check, " + "unable to find " + outputFile ); + } else { + throw new MojoFailureException("Unable to perform check, " + "unable to find " + outputFile); } } @@ -198,38 +181,32 @@ protected void executeCheck( final String filename, final String tagName, final * @throws XmlPullParserException * @throws IOException */ - private ViolationDetails getViolations( final File analysisFile, final int failurePriority ) - throws XmlPullParserException, IOException - { + private ViolationDetails getViolations(final File analysisFile, final int failurePriority) + throws XmlPullParserException, IOException { final List failures = new ArrayList<>(); final List warnings = new ArrayList<>(); - final List violations = getErrorDetails( analysisFile ); - - for ( final D violation : violations ) - { - final int priority = getPriority( violation ); - if ( priority <= failurePriority && !excludeFromFile.isExcludedFromFailure( violation ) ) - { - failures.add( violation ); - if ( printFailingErrors ) - { - printError( violation, "Failure" ); + final List violations = getErrorDetails(analysisFile); + + for (final D violation : violations) { + final int priority = getPriority(violation); + if (priority <= failurePriority && !excludeFromFile.isExcludedFromFailure(violation)) { + failures.add(violation); + if (printFailingErrors) { + printError(violation, "Failure"); } - } - else - { - warnings.add( violation ); + } else { + warnings.add(violation); } } final ViolationDetails details = newViolationDetailsInstance(); - details.setFailureDetails( failures ); - details.setWarningDetails( warnings ); + details.setFailureDetails(failures); + details.setWarningDetails(warnings); return details; } - protected abstract int getPriority( D errorDetail ); + protected abstract int getPriority(D errorDetail); protected abstract ViolationDetails newViolationDetailsInstance(); @@ -239,16 +216,13 @@ private ViolationDetails getViolations( final File analysisFile, final int fa * @param failures list of failures * @param warnings list of warnings */ - protected void printErrors( final List failures, final List warnings ) - { - for ( final D warning : warnings ) - { - printError( warning, "Warning" ); + protected void printErrors(final List failures, final List warnings) { + for (final D warning : warnings) { + printError(warning, "Warning"); } - for ( final D failure : failures ) - { - printError( failure, "Failure" ); + for (final D failure : failures) { + printError(failure, "Failure"); } } @@ -261,31 +235,27 @@ protected void printErrors( final List failures, final List warnings ) * @param outputFile * @return */ - private String getMessage( final int failureCount, final int warningCount, final String key, final File outputFile ) - { - final StringBuilder message = new StringBuilder( 256 ); - if ( failureCount > 0 || warningCount > 0 ) - { - if ( failureCount > 0 ) - { - message.append( "You have " ).append( failureCount ).append( " " ).append( key ). - append( failureCount > 1 ? "s" : "" ); + private String getMessage(final int failureCount, final int warningCount, final String key, final File outputFile) { + final StringBuilder message = new StringBuilder(256); + if (failureCount > 0 || warningCount > 0) { + if (failureCount > 0) { + message.append("You have ") + .append(failureCount) + .append(" ") + .append(key) + .append(failureCount > 1 ? "s" : ""); } - if ( warningCount > 0 ) - { - if ( failureCount > 0 ) - { - message.append( " and " ); - } - else - { - message.append( "You have " ); + if (warningCount > 0) { + if (failureCount > 0) { + message.append(" and "); + } else { + message.append("You have "); } - message.append( warningCount ).append( " warning" ).append( warningCount > 1 ? "s" : "" ); + message.append(warningCount).append(" warning").append(warningCount > 1 ? "s" : ""); } - message.append( ". For more details see: " ).append( outputFile.getAbsolutePath() ); + message.append(". For more details see: ").append(outputFile.getAbsolutePath()); } return message.toString(); } @@ -297,7 +267,7 @@ private String getMessage( final int failureCount, final int warningCount, final * or a {@link org.apache.maven.plugins.pmd.model.Duplication} from CPD * @param severity the found issue is prefixed with the given severity, usually "Warning" or "Failure". */ - protected abstract void printError( D item, String severity ); + protected abstract void printError(D item, String severity); /** * Gets the attributes and text for the violation tag and puts them in a HashMap @@ -308,21 +278,17 @@ private String getMessage( final int failureCount, final int warningCount, final * @throws XmlPullParserException if the analysis file contains invalid XML * @throws IOException if the analysis file could be read */ - protected abstract List getErrorDetails( File analysisFile ) - throws XmlPullParserException, IOException; + protected abstract List getErrorDetails(File analysisFile) throws XmlPullParserException, IOException; - public boolean isFailOnViolation() - { + public boolean isFailOnViolation() { return failOnViolation; } - public Integer getMaxAllowedViolations() - { + public Integer getMaxAllowedViolations() { return maxAllowedViolations; } - protected boolean isAggregator() - { + protected boolean isAggregator() { // returning here aggregate for backwards compatibility return aggregate; } diff --git a/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdReport.java b/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdReport.java index e3aa9066..482b709b 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugins.annotations.Mojo; @@ -30,12 +29,10 @@ * * @since 3.15.0 */ -@Mojo( name = "aggregate-cpd", aggregator = true, threadSafe = true ) -public class AggregatorCpdReport extends CpdReport -{ +@Mojo(name = "aggregate-cpd", aggregator = true, threadSafe = true) +public class AggregatorCpdReport extends CpdReport { @Override - protected boolean isAggregator() - { + protected boolean isAggregator() { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdViolationCheckMojo.java index 25bbb780..1e034a64 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AggregatorCpdViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -28,13 +27,11 @@ * * @since 3.15.0 */ -@Mojo( name = "aggregate-cpd-check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true, aggregator = true ) -@Execute( goal = "aggregate-cpd" ) -public class AggregatorCpdViolationCheckMojo extends CpdViolationCheckMojo -{ +@Mojo(name = "aggregate-cpd-check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true, aggregator = true) +@Execute(goal = "aggregate-cpd") +public class AggregatorCpdViolationCheckMojo extends CpdViolationCheckMojo { @Override - protected boolean isAggregator() - { + protected boolean isAggregator() { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdNoForkReport.java b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdNoForkReport.java index 216ebae4..84185949 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdNoForkReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdNoForkReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -26,12 +25,13 @@ /** * Creates a PMD site report in an aggregator project without forking the test-compile phase again. - * + * * @since 3.15.0 */ -@Mojo( name = "aggregate-pmd-no-fork", aggregator = true, threadSafe = true, - requiresDependencyResolution = ResolutionScope.TEST ) -@Execute( phase = LifecyclePhase.NONE ) -public class AggregatorPmdNoForkReport extends AggregatorPmdReport -{ -} +@Mojo( + name = "aggregate-pmd-no-fork", + aggregator = true, + threadSafe = true, + requiresDependencyResolution = ResolutionScope.TEST) +@Execute(phase = LifecyclePhase.NONE) +public class AggregatorPmdNoForkReport extends AggregatorPmdReport {} diff --git a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdReport.java b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdReport.java index 3495241c..8e635b4e 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -27,17 +26,14 @@ /** * Creates a PMD site report in an aggregator project based on the rulesets and configuration set in the plugin. * It can also generate a pmd output file aside from the site report in any of the following formats: xml, csv or txt. - * + * * @since 3.15.0 */ -@Mojo( name = "aggregate-pmd", aggregator = true, threadSafe = true, - requiresDependencyResolution = ResolutionScope.TEST ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class AggregatorPmdReport extends PmdReport -{ +@Mojo(name = "aggregate-pmd", aggregator = true, threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class AggregatorPmdReport extends PmdReport { @Override - protected boolean isAggregator() - { + protected boolean isAggregator() { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdViolationCheckMojo.java index 6fdcab3d..48cd8267 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/AggregatorPmdViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -28,13 +27,11 @@ * * @since 3.15.0 */ -@Mojo( name = "aggregate-pmd-check", defaultPhase = LifecyclePhase.VERIFY, aggregator = true, threadSafe = true ) -@Execute( goal = "aggregate-pmd" ) -public class AggregatorPmdViolationCheckMojo extends PmdViolationCheckMojo -{ +@Mojo(name = "aggregate-pmd-check", defaultPhase = LifecyclePhase.VERIFY, aggregator = true, threadSafe = true) +@Execute(goal = "aggregate-pmd") +public class AggregatorPmdViolationCheckMojo extends PmdViolationCheckMojo { @Override - protected boolean isAggregator() - { + protected boolean isAggregator() { return true; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/CpdReport.java b/src/main/java/org/apache/maven/plugins/pmd/CpdReport.java index 522b3503..e5c4249b 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/CpdReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/CpdReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -25,6 +24,8 @@ import java.util.Properties; import java.util.ResourceBundle; +import net.sourceforge.pmd.cpd.JavaTokenizer; +import net.sourceforge.pmd.cpd.renderer.CPDRenderer; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.pmd.exec.CpdExecutor; @@ -33,9 +34,6 @@ import org.apache.maven.reporting.MavenReportException; import org.apache.maven.toolchain.Toolchain; -import net.sourceforge.pmd.cpd.JavaTokenizer; -import net.sourceforge.pmd.cpd.renderer.CPDRenderer; - /** * Creates a report for PMD's Copy/Paste Detector (CPD) tool. * It can also generate a cpd results file in any of these formats: xml, csv or txt. @@ -47,23 +45,21 @@ * @version $Id$ * @since 2.0 */ -@Mojo( name = "cpd", threadSafe = true ) -public class CpdReport - extends AbstractPmdReport -{ +@Mojo(name = "cpd", threadSafe = true) +public class CpdReport extends AbstractPmdReport { /** * The programming language to be analyzed by CPD. Valid values are currently java, * javascript or jsp. * * @since 3.5 */ - @Parameter( defaultValue = "java" ) + @Parameter(defaultValue = "java") private String language; /** * The minimum number of tokens that need to be duplicated before it causes a violation. */ - @Parameter( property = "minimumTokens", defaultValue = "100" ) + @Parameter(property = "minimumTokens", defaultValue = "100") private int minimumTokens; /** @@ -71,7 +67,7 @@ public class CpdReport * * @since 2.1 */ - @Parameter( property = "cpd.skip", defaultValue = "false" ) + @Parameter(property = "cpd.skip", defaultValue = "false") private boolean skip; /** @@ -81,7 +77,7 @@ public class CpdReport * * @since 2.5 */ - @Parameter( property = "cpd.ignoreLiterals", defaultValue = "false" ) + @Parameter(property = "cpd.ignoreLiterals", defaultValue = "false") private boolean ignoreLiterals; /** @@ -89,7 +85,7 @@ public class CpdReport * * @since 2.5 */ - @Parameter( property = "cpd.ignoreIdentifiers", defaultValue = "false" ) + @Parameter(property = "cpd.ignoreIdentifiers", defaultValue = "false") private boolean ignoreIdentifiers; /** @@ -97,7 +93,7 @@ public class CpdReport * * @since 3.11.0 */ - @Parameter( property = "cpd.ignoreAnnotations", defaultValue = "false" ) + @Parameter(property = "cpd.ignoreAnnotations", defaultValue = "false") private boolean ignoreAnnotations; /** @@ -110,154 +106,123 @@ public class CpdReport /** * {@inheritDoc} */ - public String getName( Locale locale ) - { - return getBundle( locale ).getString( "report.cpd.name" ); + public String getName(Locale locale) { + return getBundle(locale).getString("report.cpd.name"); } /** * {@inheritDoc} */ - public String getDescription( Locale locale ) - { - return getBundle( locale ).getString( "report.cpd.description" ); + public String getDescription(Locale locale) { + return getBundle(locale).getString("report.cpd.description"); } /** * {@inheritDoc} */ @Override - public void executeReport( Locale locale ) - throws MavenReportException - { + public void executeReport(Locale locale) throws MavenReportException { ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() ); + try { + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); - generateMavenSiteReport( locale ); - } - finally - { - Thread.currentThread().setContextClassLoader( origLoader ); + generateMavenSiteReport(locale); + } finally { + Thread.currentThread().setContextClassLoader(origLoader); } } @Override - public boolean canGenerateReport() - { - if ( skip ) - { - getLog().info( "Skipping CPD execution" ); + public boolean canGenerateReport() { + if (skip) { + getLog().info("Skipping CPD execution"); return false; } boolean result = super.canGenerateReport(); - if ( result ) - { - try - { + if (result) { + try { executeCpd(); - if ( skipEmptyReport ) - { + if (skipEmptyReport) { result = cpdResult.hasDuplications(); - if ( !result ) - { - getLog().debug( "Skipping report since skipEmptyReport is true and there are no CPD issues." ); + if (!result) { + getLog().debug("Skipping report since skipEmptyReport is true and there are no CPD issues."); } } - } - catch ( MavenReportException e ) - { - throw new RuntimeException( e ); + } catch (MavenReportException e) { + throw new RuntimeException(e); } } return result; } - private void executeCpd() - throws MavenReportException - { - if ( cpdResult != null ) - { + private void executeCpd() throws MavenReportException { + if (cpdResult != null) { // CPD has already been run - getLog().debug( "CPD has already been run - skipping redundant execution." ); + getLog().debug("CPD has already been run - skipping redundant execution."); return; } Properties languageProperties = new Properties(); - if ( ignoreLiterals ) - { - languageProperties.setProperty( JavaTokenizer.IGNORE_LITERALS, "true" ); + if (ignoreLiterals) { + languageProperties.setProperty(JavaTokenizer.IGNORE_LITERALS, "true"); } - if ( ignoreIdentifiers ) - { - languageProperties.setProperty( JavaTokenizer.IGNORE_IDENTIFIERS, "true" ); + if (ignoreIdentifiers) { + languageProperties.setProperty(JavaTokenizer.IGNORE_IDENTIFIERS, "true"); } - if ( ignoreAnnotations ) - { - languageProperties.setProperty( JavaTokenizer.IGNORE_ANNOTATIONS, "true" ); + if (ignoreAnnotations) { + languageProperties.setProperty(JavaTokenizer.IGNORE_ANNOTATIONS, "true"); } - try - { + try { filesToProcess = getFilesToProcess(); CpdRequest request = new CpdRequest(); - request.setMinimumTokens( minimumTokens ); - request.setLanguage( language ); - request.setLanguageProperties( languageProperties ); - request.setSourceEncoding( getInputEncoding() ); - request.addFiles( filesToProcess.keySet() ); - - request.setShowPmdLog( showPmdLog ); - request.setLogLevel( determineCurrentRootLogLevel() ); - - request.setExcludeFromFailureFile( excludeFromFailureFile ); - request.setTargetDirectory( targetDirectory.getAbsolutePath() ); - request.setOutputEncoding( getOutputEncoding() ); - request.setFormat( format ); - request.setIncludeXmlInSite( includeXmlInSite ); - request.setReportOutputDirectory( getReportOutputDirectory().getAbsolutePath() ); + request.setMinimumTokens(minimumTokens); + request.setLanguage(language); + request.setLanguageProperties(languageProperties); + request.setSourceEncoding(getInputEncoding()); + request.addFiles(filesToProcess.keySet()); + + request.setShowPmdLog(showPmdLog); + request.setLogLevel(determineCurrentRootLogLevel()); + + request.setExcludeFromFailureFile(excludeFromFailureFile); + request.setTargetDirectory(targetDirectory.getAbsolutePath()); + request.setOutputEncoding(getOutputEncoding()); + request.setFormat(format); + request.setIncludeXmlInSite(includeXmlInSite); + request.setReportOutputDirectory(getReportOutputDirectory().getAbsolutePath()); Toolchain tc = getToolchain(); - if ( tc != null ) - { - getLog().info( "Toolchain in maven-pmd-plugin: " + tc ); - String javaExecutable = tc.findTool( "java" ); //NOI18N - request.setJavaExecutable( javaExecutable ); + if (tc != null) { + getLog().info("Toolchain in maven-pmd-plugin: " + tc); + String javaExecutable = tc.findTool("java"); // NOI18N + request.setJavaExecutable(javaExecutable); } - getLog().info( "PMD version: " + AbstractPmdReport.getPmdVersion() ); - cpdResult = CpdExecutor.execute( request ); - } - catch ( UnsupportedEncodingException e ) - { - throw new MavenReportException( "Encoding '" + getInputEncoding() + "' is not supported.", e ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + getLog().info("PMD version: " + AbstractPmdReport.getPmdVersion()); + cpdResult = CpdExecutor.execute(request); + } catch (UnsupportedEncodingException e) { + throw new MavenReportException("Encoding '" + getInputEncoding() + "' is not supported.", e); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } } - private void generateMavenSiteReport( Locale locale ) - { - CpdReportGenerator gen = new CpdReportGenerator( getSink(), filesToProcess, getBundle( locale ), - isAggregator() ); - gen.generate( cpdResult.getDuplications() ); + private void generateMavenSiteReport(Locale locale) { + CpdReportGenerator gen = new CpdReportGenerator(getSink(), filesToProcess, getBundle(locale), isAggregator()); + gen.generate(cpdResult.getDuplications()); } /** * {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "cpd"; } - private static ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "cpd-report", locale, CpdReport.class.getClassLoader() ); + private static ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle("cpd-report", locale, CpdReport.class.getClassLoader()); } /** @@ -268,8 +233,7 @@ private static ResourceBundle getBundle( Locale locale ) * @deprecated Use {@link CpdExecutor#createRenderer(String, String)} instead. */ @Deprecated - public CPDRenderer createRenderer() throws MavenReportException - { - return CpdExecutor.createRenderer( format, getOutputEncoding() ); + public CPDRenderer createRenderer() throws MavenReportException { + return CpdExecutor.createRenderer(format, getOutputEncoding()); } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/CpdReportGenerator.java b/src/main/java/org/apache/maven/plugins/pmd/CpdReportGenerator.java index 18230556..dd135949 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/CpdReportGenerator.java +++ b/src/main/java/org/apache/maven/plugins/pmd/CpdReportGenerator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.util.List; @@ -36,8 +35,7 @@ * @author mperham * @version $Id$ */ -public class CpdReportGenerator -{ +public class CpdReportGenerator { private Sink sink; private Map fileMap; @@ -46,8 +44,7 @@ public class CpdReportGenerator private boolean aggregate; - public CpdReportGenerator( Sink sink, Map fileMap, ResourceBundle bundle, boolean aggregate ) - { + public CpdReportGenerator(Sink sink, Map fileMap, ResourceBundle bundle, boolean aggregate) { this.sink = sink; this.fileMap = fileMap; this.bundle = bundle; @@ -59,19 +56,17 @@ public CpdReportGenerator( Sink sink, Map fileMap, ResourceBu * * @return a String that contains the title */ - private String getTitle() - { - return bundle.getString( "report.cpd.title" ); + private String getTitle() { + return bundle.getString("report.cpd.title"); } /** * Method that generates the start of the CPD report. */ - public void beginDocument() - { + public void beginDocument() { sink.head(); sink.title(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.title_(); sink.head_(); @@ -79,15 +74,15 @@ public void beginDocument() sink.section1(); sink.sectionTitle1(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.sectionTitle1_(); sink.paragraph(); - sink.text( bundle.getString( "report.cpd.cpdlink" ) + " " ); - sink.link( "https://pmd.github.io/latest/pmd_userdocs_cpd.html" ); - sink.text( "CPD" ); + sink.text(bundle.getString("report.cpd.cpdlink") + " "); + sink.link("https://pmd.github.io/latest/pmd_userdocs_cpd.html"); + sink.text("CPD"); sink.link_(); - sink.text( " " + AbstractPmdReport.getPmdVersion() + "." ); + sink.text(" " + AbstractPmdReport.getPmdVersion() + "."); sink.paragraph_(); sink.section1_(); @@ -96,7 +91,7 @@ public void beginDocument() sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.cpd.dupes" ) ); + sink.text(bundle.getString("report.cpd.dupes")); sink.sectionTitle1_(); // TODO files summary @@ -105,38 +100,35 @@ public void beginDocument() /** * Method that generates a line of CPD report according to a TokenEntry. */ - private void generateFileLine( CpdFile duplicationMark ) - { + private void generateFileLine(CpdFile duplicationMark) { // Get information for report generation String filename = duplicationMark.getPath(); - File file = new File( filename ); - PmdFileInfo fileInfo = fileMap.get( file ); + File file = new File(filename); + PmdFileInfo fileInfo = fileMap.get(file); File sourceDirectory = fileInfo.getSourceDirectory(); - filename = StringUtils.substring( filename, sourceDirectory.getAbsolutePath().length() + 1 ); + filename = StringUtils.substring( + filename, sourceDirectory.getAbsolutePath().length() + 1); String xrefLocation = fileInfo.getXrefLocation(); MavenProject projectFile = fileInfo.getProject(); int line = duplicationMark.getLine(); sink.tableRow(); sink.tableCell(); - sink.text( filename ); + sink.text(filename); sink.tableCell_(); - if ( aggregate ) - { + if (aggregate) { sink.tableCell(); - sink.text( projectFile.getName() ); + sink.text(projectFile.getName()); sink.tableCell_(); } sink.tableCell(); - if ( xrefLocation != null ) - { - sink.link( xrefLocation + "/" + filename.replaceAll( "\\.java$", ".html" ).replace( '\\', '/' ) + "#L" - + line ); + if (xrefLocation != null) { + sink.link(xrefLocation + "/" + + filename.replaceAll("\\.java$", ".html").replace('\\', '/') + "#L" + line); } - sink.text( String.valueOf( line ) ); - if ( xrefLocation != null ) - { + sink.text(String.valueOf(line)); + if (xrefLocation != null) { sink.link_(); } @@ -149,58 +141,52 @@ private void generateFileLine( CpdFile duplicationMark ) * * @param duplications the found duplications */ - public void generate( List duplications ) - { + public void generate(List duplications) { beginDocument(); - if ( duplications.isEmpty() ) - { + if (duplications.isEmpty()) { sink.paragraph(); - sink.text( bundle.getString( "report.cpd.noProblems" ) ); + sink.text(bundle.getString("report.cpd.noProblems")); sink.paragraph_(); } - for ( Duplication duplication : duplications ) - { + for (Duplication duplication : duplications) { String code = duplication.getCodefragment(); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.cpd.column.file" ) ); + sink.text(bundle.getString("report.cpd.column.file")); sink.tableHeaderCell_(); - if ( aggregate ) - { + if (aggregate) { sink.tableHeaderCell(); - sink.text( bundle.getString( "report.cpd.column.project" ) ); + sink.text(bundle.getString("report.cpd.column.project")); sink.tableHeaderCell_(); } sink.tableHeaderCell(); - sink.text( bundle.getString( "report.cpd.column.line" ) ); + sink.text(bundle.getString("report.cpd.column.line")); sink.tableHeaderCell_(); sink.tableRow_(); // Iterating on every token entry - for ( CpdFile mark : duplication.getFiles() ) - { - generateFileLine( mark ); + for (CpdFile mark : duplication.getFiles()) { + generateFileLine(mark); } // Source snippet sink.tableRow(); int colspan = 2; - if ( aggregate ) - { + if (aggregate) { ++colspan; } // TODO Cleaner way to do this? - sink.rawText( "" ); - sink.verbatim( null ); - sink.text( code ); + sink.rawText(""); + sink.verbatim(null); + sink.text(code); sink.verbatim_(); - sink.rawText( "" ); + sink.rawText(""); sink.tableRow_(); sink.tableRows_(); sink.table_(); diff --git a/src/main/java/org/apache/maven/plugins/pmd/CpdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/pmd/CpdViolationCheckMojo.java index 3feab0d1..7852f760 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/CpdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/CpdViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.FileInputStream; @@ -27,14 +26,14 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.pmd.model.CpdErrorDetail; -import org.apache.maven.plugins.pmd.model.CpdFile; -import org.apache.maven.plugins.pmd.model.Duplication; -import org.apache.maven.plugins.pmd.model.io.xpp3.CpdXpp3Reader; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.pmd.model.CpdErrorDetail; +import org.apache.maven.plugins.pmd.model.CpdFile; +import org.apache.maven.plugins.pmd.model.Duplication; +import org.apache.maven.plugins.pmd.model.io.xpp3.CpdXpp3Reader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; /** @@ -43,23 +42,20 @@ * @version $Id$ * @since 2.0 */ -@Mojo( name = "cpd-check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true ) -@Execute( goal = "cpd" ) -public class CpdViolationCheckMojo - extends AbstractPmdViolationCheckMojo -{ +@Mojo(name = "cpd-check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) +@Execute(goal = "cpd") +public class CpdViolationCheckMojo extends AbstractPmdViolationCheckMojo { /** * Default constructor. Initializes with the correct {@link ExcludeDuplicationsFromFile}. */ - public CpdViolationCheckMojo() - { - super( new ExcludeDuplicationsFromFile() ); + public CpdViolationCheckMojo() { + super(new ExcludeDuplicationsFromFile()); } /** * Skip the CPD violation checks. Most useful on the command line via "-Dcpd.skip=true". */ - @Parameter( property = "cpd.skip", defaultValue = "false" ) + @Parameter(property = "cpd.skip", defaultValue = "false") private boolean skip; /** @@ -67,79 +63,69 @@ public CpdViolationCheckMojo() * * @since 3.0 */ - @Parameter( property = "cpd.failOnViolation", defaultValue = "true", required = true ) + @Parameter(property = "cpd.failOnViolation", defaultValue = "true", required = true) protected boolean failOnViolation; /** * {@inheritDoc} */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping CPD execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping CPD execution"); return; } - executeCheck( "cpd.xml", "duplication", "CPD duplication", 10 ); + executeCheck("cpd.xml", "duplication", "CPD duplication", 10); } /** * {@inheritDoc} */ @Override - protected void printError( Duplication item, String severity ) - { + protected void printError(Duplication item, String severity) { int lines = item.getLines(); - StringBuilder buff = new StringBuilder( 100 ); - buff.append( "CPD " ).append( severity ).append( ": Found " ); - buff.append( lines ).append( " lines of duplicated code at locations:" ); - this.getLog().info( buff.toString() ); - - for ( CpdFile file : item.getFiles() ) - { - buff.setLength( 0 ); - buff.append( " " ); - buff.append( file.getPath() ); - buff.append( " line " ).append( file.getLine() ); - this.getLog().info( buff.toString() ); + StringBuilder buff = new StringBuilder(100); + buff.append("CPD ").append(severity).append(": Found "); + buff.append(lines).append(" lines of duplicated code at locations:"); + this.getLog().info(buff.toString()); + + for (CpdFile file : item.getFiles()) { + buff.setLength(0); + buff.append(" "); + buff.append(file.getPath()); + buff.append(" line ").append(file.getLine()); + this.getLog().info(buff.toString()); } - this.getLog().debug( "CPD " + severity + ": Code Fragment " ); - this.getLog().debug( item.getCodefragment() ); + this.getLog().debug("CPD " + severity + ": Code Fragment "); + this.getLog().debug(item.getCodefragment()); } /** * {@inheritDoc} */ @Override - protected List getErrorDetails( File cpdFile ) throws XmlPullParserException, IOException - { - try ( InputStream in = new FileInputStream( cpdFile ) ) - { + protected List getErrorDetails(File cpdFile) throws XmlPullParserException, IOException { + try (InputStream in = new FileInputStream(cpdFile)) { CpdXpp3Reader reader = new CpdXpp3Reader(); - CpdErrorDetail details = reader.read( in, false ); + CpdErrorDetail details = reader.read(in, false); return details.getDuplications(); } } @Override - protected int getPriority( Duplication errorDetail ) - { + protected int getPriority(Duplication errorDetail) { return 0; } @Override - protected ViolationDetails newViolationDetailsInstance() - { + protected ViolationDetails newViolationDetailsInstance() { return new ViolationDetails<>(); } @Override - public boolean isFailOnViolation() - { + public boolean isFailOnViolation() { return failOnViolation; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/pmd/ExcludeDuplicationsFromFile.java b/src/main/java/org/apache/maven/plugins/pmd/ExcludeDuplicationsFromFile.java index 0f7d4dfc..20bc52dd 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/ExcludeDuplicationsFromFile.java +++ b/src/main/java/org/apache/maven/plugins/pmd/ExcludeDuplicationsFromFile.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.FileReader; import java.io.IOException; @@ -27,14 +26,13 @@ import java.util.List; import java.util.Set; +import net.sourceforge.pmd.cpd.Mark; +import net.sourceforge.pmd.cpd.Match; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.pmd.model.CpdFile; import org.apache.maven.plugins.pmd.model.Duplication; -import net.sourceforge.pmd.cpd.Mark; -import net.sourceforge.pmd.cpd.Match; - /** * This class contains utility methods to load property files which define which files * should be excluded from the CPD duplication results. @@ -42,71 +40,57 @@ * * @author Andreas Dangel */ -public class ExcludeDuplicationsFromFile implements ExcludeFromFile -{ +public class ExcludeDuplicationsFromFile implements ExcludeFromFile { private final List> exclusionList = new ArrayList<>(); @Override - public boolean isExcludedFromFailure( final Duplication errorDetail ) - { + public boolean isExcludedFromFailure(final Duplication errorDetail) { final Set uniquePaths = new HashSet<>(); - for ( final CpdFile cpdFile : errorDetail.getFiles() ) - { - uniquePaths.add( cpdFile.getPath() ); + for (final CpdFile cpdFile : errorDetail.getFiles()) { + uniquePaths.add(cpdFile.getPath()); } - return isExcludedFromFailure( uniquePaths ); + return isExcludedFromFailure(uniquePaths); } /** * Checks whether the given {@link Match} is excluded. * Note: The exclusion must have been loaded before via {@link #loadExcludeFromFailuresData(String)}. - * + * * @param errorDetail the duplication to check * @return true if the given duplication should be excluded, false otherwise. */ - public boolean isExcludedFromFailure( final Match errorDetail ) - { + public boolean isExcludedFromFailure(final Match errorDetail) { final Set uniquePaths = new HashSet<>(); - for ( Mark mark : errorDetail.getMarkSet() ) - { - uniquePaths.add( mark.getFilename() ); + for (Mark mark : errorDetail.getMarkSet()) { + uniquePaths.add(mark.getFilename()); } - return isExcludedFromFailure( uniquePaths ); + return isExcludedFromFailure(uniquePaths); } - private boolean isExcludedFromFailure( Set uniquePaths ) - { - for ( final Set singleExclusionGroup : exclusionList ) - { - if ( uniquePaths.size() == singleExclusionGroup.size() - && duplicationExcludedByGroup( uniquePaths, singleExclusionGroup ) ) - { + private boolean isExcludedFromFailure(Set uniquePaths) { + for (final Set singleExclusionGroup : exclusionList) { + if (uniquePaths.size() == singleExclusionGroup.size() + && duplicationExcludedByGroup(uniquePaths, singleExclusionGroup)) { return true; } } return false; } - private boolean duplicationExcludedByGroup( final Set uniquePaths, final Set singleExclusionGroup ) - { - for ( final String path : uniquePaths ) - { - if ( !fileExcludedByGroup( path, singleExclusionGroup ) ) - { + private boolean duplicationExcludedByGroup(final Set uniquePaths, final Set singleExclusionGroup) { + for (final String path : uniquePaths) { + if (!fileExcludedByGroup(path, singleExclusionGroup)) { return false; } } return true; } - private boolean fileExcludedByGroup( final String path, final Set singleExclusionGroup ) - { - final String formattedPath = path.replace( '\\', '.' ).replace( '/', '.' ); - for ( final String className : singleExclusionGroup ) - { - if ( formattedPath.contains( className ) ) - { + private boolean fileExcludedByGroup(final String path, final Set singleExclusionGroup) { + final String formattedPath = path.replace('\\', '.').replace('/', '.'); + for (final String className : singleExclusionGroup) { + if (formattedPath.contains(className)) { return true; } } @@ -114,44 +98,33 @@ private boolean fileExcludedByGroup( final String path, final Set single } @Override - public void loadExcludeFromFailuresData( final String excludeFromFailureFile ) - throws MojoExecutionException - { - if ( StringUtils.isEmpty( excludeFromFailureFile ) ) - { + public void loadExcludeFromFailuresData(final String excludeFromFailureFile) throws MojoExecutionException { + if (StringUtils.isEmpty(excludeFromFailureFile)) { return; } - try ( LineNumberReader reader = new LineNumberReader( new FileReader( excludeFromFailureFile ) ) ) - { + try (LineNumberReader reader = new LineNumberReader(new FileReader(excludeFromFailureFile))) { String line; - while ( ( line = reader.readLine() ) != null ) - { - if ( !line.startsWith( "#" ) ) - { - exclusionList.add( createSetFromExclusionLine( line ) ); + while ((line = reader.readLine()) != null) { + if (!line.startsWith("#")) { + exclusionList.add(createSetFromExclusionLine(line)); } } - } - catch ( final IOException e ) - { - throw new MojoExecutionException( "Cannot load file " + excludeFromFailureFile, e ); + } catch (final IOException e) { + throw new MojoExecutionException("Cannot load file " + excludeFromFailureFile, e); } } - private Set createSetFromExclusionLine( final String line ) - { + private Set createSetFromExclusionLine(final String line) { final Set result = new HashSet<>(); - for ( final String className : line.split( "," ) ) - { - result.add( className.trim() ); + for (final String className : line.split(",")) { + result.add(className.trim()); } return result; } @Override - public int countExclusions() - { + public int countExclusions() { return exclusionList.size(); } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/ExcludeFromFile.java b/src/main/java/org/apache/maven/plugins/pmd/ExcludeFromFile.java index c9bd0b8e..48d10397 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/ExcludeFromFile.java +++ b/src/main/java/org/apache/maven/plugins/pmd/ExcludeFromFile.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import org.apache.maven.plugin.MojoExecutionException; @@ -26,15 +25,14 @@ * or {@link org.apache.maven.plugins.pmd.model.Duplication}. * @author Andreas Dangel */ -public interface ExcludeFromFile -{ +public interface ExcludeFromFile { /** * Loads the exclude definitions from the given file. * * @param excludeFromFailureFile the path to the properties file * @throws MojoExecutionException if the properties file couldn't be loaded */ - void loadExcludeFromFailuresData( String excludeFromFailureFile ) throws MojoExecutionException; + void loadExcludeFromFailuresData(String excludeFromFailureFile) throws MojoExecutionException; /** * Determines how many exclusions are considered. @@ -49,6 +47,5 @@ public interface ExcludeFromFile * @param errorDetail the violation to check * @return true if the violation should be excluded, false otherwise. */ - boolean isExcludedFromFailure( D errorDetail ); - + boolean isExcludedFromFailure(D errorDetail); } diff --git a/src/main/java/org/apache/maven/plugins/pmd/ExcludeViolationsFromFile.java b/src/main/java/org/apache/maven/plugins/pmd/ExcludeViolationsFromFile.java index a0e96814..13981b3f 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/ExcludeViolationsFromFile.java +++ b/src/main/java/org/apache/maven/plugins/pmd/ExcludeViolationsFromFile.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.FileInputStream; @@ -29,12 +28,11 @@ import java.util.Properties; import java.util.Set; +import net.sourceforge.pmd.RuleViolation; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.pmd.model.Violation; -import net.sourceforge.pmd.RuleViolation; - /** * This class contains utility for loading property files, which define which PMD violations * from which classes should be ignored and not cause a failure. @@ -42,52 +40,41 @@ * * @author Andreas Dangel */ -public class ExcludeViolationsFromFile implements ExcludeFromFile -{ +public class ExcludeViolationsFromFile implements ExcludeFromFile { private Map> excludeFromFailureClasses = new HashMap<>(); @Override - public void loadExcludeFromFailuresData( final String excludeFromFailureFile ) - throws MojoExecutionException - { - if ( StringUtils.isEmpty( excludeFromFailureFile ) ) - { + public void loadExcludeFromFailuresData(final String excludeFromFailureFile) throws MojoExecutionException { + if (StringUtils.isEmpty(excludeFromFailureFile)) { return; } - File file = new File( excludeFromFailureFile ); - if ( !file.exists() ) - { + File file = new File(excludeFromFailureFile); + if (!file.exists()) { return; } final Properties props = new Properties(); - try ( FileInputStream fileInputStream = new FileInputStream( new File( excludeFromFailureFile ) ) ) - { - props.load( fileInputStream ); - } - catch ( final IOException e ) - { - throw new MojoExecutionException( "Cannot load properties file " + excludeFromFailureFile, e ); + try (FileInputStream fileInputStream = new FileInputStream(new File(excludeFromFailureFile))) { + props.load(fileInputStream); + } catch (final IOException e) { + throw new MojoExecutionException("Cannot load properties file " + excludeFromFailureFile, e); } - for ( final Entry propEntry : props.entrySet() ) - { + for (final Entry propEntry : props.entrySet()) { final Set excludedRuleSet = new HashSet<>(); final String className = propEntry.getKey().toString(); - final String[] excludedRules = propEntry.getValue().toString().split( "," ); - for ( final String excludedRule : excludedRules ) - { - excludedRuleSet.add( excludedRule.trim() ); + final String[] excludedRules = propEntry.getValue().toString().split(","); + for (final String excludedRule : excludedRules) { + excludedRuleSet.add(excludedRule.trim()); } - excludeFromFailureClasses.put( className, excludedRuleSet ); + excludeFromFailureClasses.put(className, excludedRuleSet); } } @Override - public boolean isExcludedFromFailure( final Violation errorDetail ) - { - final String className = extractClassName( errorDetail.getViolationPackage(), errorDetail.getViolationClass(), - errorDetail.getFileName() ); - return isExcludedFromFailure( className, errorDetail.getRule() ); + public boolean isExcludedFromFailure(final Violation errorDetail) { + final String className = extractClassName( + errorDetail.getViolationPackage(), errorDetail.getViolationClass(), errorDetail.getFileName()); + return isExcludedFromFailure(className, errorDetail.getRule()); } /** @@ -97,51 +84,41 @@ public boolean isExcludedFromFailure( final Violation errorDetail ) * @param errorDetail the violation to check * @return true if the violation should be excluded, false otherwise. */ - public boolean isExcludedFromFailure( final RuleViolation errorDetail ) - { - final String className = extractClassName( errorDetail.getPackageName(), errorDetail.getClassName(), - errorDetail.getFilename() ); - return isExcludedFromFailure( className, errorDetail.getRule().getName() ); + public boolean isExcludedFromFailure(final RuleViolation errorDetail) { + final String className = + extractClassName(errorDetail.getPackageName(), errorDetail.getClassName(), errorDetail.getFilename()); + return isExcludedFromFailure(className, errorDetail.getRule().getName()); } @Override - public int countExclusions() - { + public int countExclusions() { int result = 0; - for ( Set rules : excludeFromFailureClasses.values() ) - { + for (Set rules : excludeFromFailureClasses.values()) { result += rules.size(); } return result; } - private boolean isExcludedFromFailure( String className, String ruleName ) - { - final Set excludedRuleSet = excludeFromFailureClasses.get( className ); - return excludedRuleSet != null && excludedRuleSet.contains( ruleName ); + private boolean isExcludedFromFailure(String className, String ruleName) { + final Set excludedRuleSet = excludeFromFailureClasses.get(className); + return excludedRuleSet != null && excludedRuleSet.contains(ruleName); } - private String extractClassName( String packageName, String className, String fullPath ) - { + private String extractClassName(String packageName, String className, String fullPath) { // for some reason, some violations don't contain the package name, so we have to guess the full class name // this looks like a bug in PMD - at least for UnusedImport rule. - if ( StringUtils.isNotEmpty( packageName ) && StringUtils.isNotEmpty( className ) ) - { + if (StringUtils.isNotEmpty(packageName) && StringUtils.isNotEmpty(className)) { return packageName + "." + className; - } - else if ( StringUtils.isNotEmpty( packageName ) ) - { + } else if (StringUtils.isNotEmpty(packageName)) { String fileName = fullPath; - fileName = fileName.substring( fileName.lastIndexOf( File.separatorChar ) + 1 ); - fileName = fileName.substring( 0, fileName.length() - 5 ); + fileName = fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1); + fileName = fileName.substring(0, fileName.length() - 5); return packageName + "." + fileName; - } - else - { + } else { final String fileName = fullPath; - final int javaIdx = fileName.indexOf( File.separator + "java" + File.separator ); - return fileName.substring( javaIdx >= 0 ? javaIdx + 6 : 0, fileName.length() - 5 ).replace( - File.separatorChar, '.' ); + final int javaIdx = fileName.indexOf(File.separator + "java" + File.separator); + return fileName.substring(javaIdx >= 0 ? javaIdx + 6 : 0, fileName.length() - 5) + .replace(File.separatorChar, '.'); } } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/PmdCollectingRenderer.java b/src/main/java/org/apache/maven/plugins/pmd/PmdCollectingRenderer.java index d95f54cf..1fd8645b 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/PmdCollectingRenderer.java +++ b/src/main/java/org/apache/maven/plugins/pmd/PmdCollectingRenderer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.IOException; import java.util.ArrayList; @@ -26,52 +25,46 @@ import java.util.List; import java.util.Map; -import org.codehaus.plexus.util.StringUtils; - import net.sourceforge.pmd.Report; import net.sourceforge.pmd.Report.ProcessingError; import net.sourceforge.pmd.Report.SuppressedViolation; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.renderers.AbstractRenderer; import net.sourceforge.pmd.util.datasource.DataSource; - +import org.codehaus.plexus.util.StringUtils; /** * A PMD renderer, that collects all violations and processing errors * from a pmd execution. - * + * * @author Andreas Dangel * @deprecated not used anymore */ @Deprecated -public class PmdCollectingRenderer extends AbstractRenderer -{ - private List errors = Collections.synchronizedList( new ArrayList<>() ); - private List violations = Collections.synchronizedList( new ArrayList<>() ); - private List suppressed = Collections.synchronizedList( new ArrayList<> () ); +public class PmdCollectingRenderer extends AbstractRenderer { + private List errors = Collections.synchronizedList(new ArrayList<>()); + private List violations = Collections.synchronizedList(new ArrayList<>()); + private List suppressed = Collections.synchronizedList(new ArrayList<>()); /** * Collects all reports from all threads. */ - public PmdCollectingRenderer() - { - super( PmdCollectingRenderer.class.getSimpleName(), "Collects all reports from all threads" ); + public PmdCollectingRenderer() { + super(PmdCollectingRenderer.class.getSimpleName(), "Collects all reports from all threads"); } @Override - public void renderFileReport( Report report ) throws IOException - { - violations.addAll( report.getViolations() ); - errors.addAll( report.getProcessingErrors() ); - suppressed.addAll( report.getSuppressedViolations() ); + public void renderFileReport(Report report) throws IOException { + violations.addAll(report.getViolations()); + errors.addAll(report.getProcessingErrors()); + suppressed.addAll(report.getSuppressedViolations()); } /** * Checks whether any violations have been found. * @return true if at least one violations has been found */ - public boolean hasViolations() - { + public boolean hasViolations() { return !violations.isEmpty(); } @@ -79,8 +72,7 @@ public boolean hasViolations() * Gets the list of all found violations. * @return the violations */ - public List getViolations() - { + public List getViolations() { return violations; } @@ -88,8 +80,7 @@ public List getViolations() * Checks whether any processing errors have been found. * @return true if any errors have been found */ - public boolean hasErrors() - { + public boolean hasErrors() { return !errors.isEmpty(); } @@ -97,8 +88,7 @@ public boolean hasErrors() * Gets all the processing errors. * @return the errors */ - public List getErrors() - { + public List getErrors() { return errors; } @@ -107,68 +97,54 @@ public List getErrors() * @param withDetails if true then add the error details additionally (contains e.g. the stacktrace) * @return the errors as string */ - public String getErrorsAsString( boolean withDetails ) - { - List errorsAsString = new ArrayList<>( errors.size() ); - for ( ProcessingError error : errors ) - { - errorsAsString.add( error.getFile() + ": " + error.getMsg() ); - if ( withDetails ) - { - errorsAsString.add( error.getDetail() ); + public String getErrorsAsString(boolean withDetails) { + List errorsAsString = new ArrayList<>(errors.size()); + for (ProcessingError error : errors) { + errorsAsString.add(error.getFile() + ": " + error.getMsg()); + if (withDetails) { + errorsAsString.add(error.getDetail()); } } - return StringUtils.join( errorsAsString.toArray(), System.getProperty( "line.separator" ) ); + return StringUtils.join(errorsAsString.toArray(), System.getProperty("line.separator")); } /** * Create a new single report with all violations for further rendering into other formats than HTML. * @return the report */ - public Report asReport() - { + public Report asReport() { Report report = new Report(); - for ( RuleViolation v : violations ) - { - report.addRuleViolation( v ); + for (RuleViolation v : violations) { + report.addRuleViolation(v); } - for ( ProcessingError e : errors ) - { - report.addError( e ); + for (ProcessingError e : errors) { + report.addError(e); } Map suppressedLines = new HashMap(); - for ( SuppressedViolation s : suppressed ) - { - if ( s.suppressedByNOPMD() ) - { - suppressedLines.put( s.getRuleViolation().getBeginLine(), s.getUserMessage() ); + for (SuppressedViolation s : suppressed) { + if (s.suppressedByNOPMD()) { + suppressedLines.put(s.getRuleViolation().getBeginLine(), s.getUserMessage()); } } - report.suppress( suppressedLines ); - for ( SuppressedViolation s : suppressed ) - { - report.addRuleViolation( s.getRuleViolation() ); + report.suppress(suppressedLines); + for (SuppressedViolation s : suppressed) { + report.addRuleViolation(s.getRuleViolation()); } return report; } - // stubs need to fulfill the Renderer interface @Override - public String defaultFileExtension() - { + public String defaultFileExtension() { return null; } + @Override - public void start() throws IOException - { - } + public void start() throws IOException {} + @Override - public void startFileAnalysis( DataSource dataSource ) - { - } + public void startFileAnalysis(DataSource dataSource) {} + @Override - public void end() throws IOException - { - } + public void end() throws IOException {} } diff --git a/src/main/java/org/apache/maven/plugins/pmd/PmdFileInfo.java b/src/main/java/org/apache/maven/plugins/pmd/PmdFileInfo.java index 5c9291a6..f690d833 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/PmdFileInfo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/PmdFileInfo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -27,8 +26,7 @@ /** * @version $Id$ */ -public class PmdFileInfo -{ +public class PmdFileInfo { private MavenProject project; @@ -36,34 +34,25 @@ public class PmdFileInfo private String xref; - public PmdFileInfo( MavenProject project, File dir, String x ) - throws IOException - { + public PmdFileInfo(MavenProject project, File dir, String x) throws IOException { this.project = project; - if ( dir.isAbsolute() ) - { + if (dir.isAbsolute()) { this.sourceDir = dir.getCanonicalFile(); - } - else - { - this.sourceDir = new File( project.getBasedir(), dir.getPath() ).getCanonicalFile(); + } else { + this.sourceDir = new File(project.getBasedir(), dir.getPath()).getCanonicalFile(); } this.xref = x; } - public String getXrefLocation() - { + public String getXrefLocation() { return xref; } - public File getSourceDirectory() - { + public File getSourceDirectory() { return sourceDir; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/pmd/PmdReport.java b/src/main/java/org/apache/maven/plugins/pmd/PmdReport.java index c8e5f58f..c3f10652 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/PmdReport.java +++ b/src/main/java/org/apache/maven/plugins/pmd/PmdReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -27,6 +26,7 @@ import java.util.Locale; import java.util.ResourceBundle; +import net.sourceforge.pmd.renderers.Renderer; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Mojo; @@ -52,8 +52,6 @@ import org.codehaus.plexus.resource.loader.ResourceNotFoundException; import org.codehaus.plexus.util.StringUtils; -import net.sourceforge.pmd.renderers.Renderer; - /** * Creates a PMD site report based on the rulesets and configuration set in the plugin. * It can also generate a pmd output file aside from the site report in any of the following formats: xml, csv or txt. @@ -62,10 +60,8 @@ * @version $Id$ * @since 2.0 */ -@Mojo( name = "pmd", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST ) -public class PmdReport - extends AbstractPmdReport -{ +@Mojo(name = "pmd", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST) +public class PmdReport extends AbstractPmdReport { /** * The target JDK to analyze based on. Should match the source used in the compiler plugin. Valid values * with the default PMD version are @@ -81,7 +77,7 @@ public class PmdReport * Note: this parameter is only used if the language parameter is set to java. *

*/ - @Parameter( property = "targetJdk", defaultValue = "${maven.compiler.source}" ) + @Parameter(property = "targetJdk", defaultValue = "${maven.compiler.source}") private String targetJdk; /** @@ -90,7 +86,7 @@ public class PmdReport * * @since 3.0 */ - @Parameter( defaultValue = "java" ) + @Parameter(defaultValue = "java") private String language; /** @@ -98,7 +94,7 @@ public class PmdReport * * @since 2.1 */ - @Parameter( property = "minimumPriority", defaultValue = "5" ) + @Parameter(property = "minimumPriority", defaultValue = "5") private int minimumPriority = 5; /** @@ -106,7 +102,7 @@ public class PmdReport * * @since 2.1 */ - @Parameter( property = "pmd.skip", defaultValue = "false" ) + @Parameter(property = "pmd.skip", defaultValue = "false") private boolean skip; /** @@ -117,7 +113,7 @@ public class PmdReport * (/rulesets/java/maven-pmd-plugin-default.xml). */ @Parameter - String[] rulesets = new String[] { "/rulesets/java/maven-pmd-plugin-default.xml" }; + String[] rulesets = new String[] {"/rulesets/java/maven-pmd-plugin-default.xml"}; /** * Controls whether the project's compile/test classpath should be passed to PMD to enable its type resolution @@ -125,7 +121,7 @@ public class PmdReport * * @since 3.0 */ - @Parameter( property = "pmd.typeResolution", defaultValue = "true" ) + @Parameter(property = "pmd.typeResolution", defaultValue = "true") private boolean typeResolution; /** @@ -133,7 +129,7 @@ public class PmdReport * * @since 3.1 */ - @Parameter( property = "pmd.benchmark", defaultValue = "false" ) + @Parameter(property = "pmd.benchmark", defaultValue = "false") private boolean benchmark; /** @@ -141,8 +137,7 @@ public class PmdReport * * @since 3.1 */ - @Parameter( property = "pmd.benchmarkOutputFilename", - defaultValue = "${project.build.directory}/pmd-benchmark.txt" ) + @Parameter(property = "pmd.benchmarkOutputFilename", defaultValue = "${project.build.directory}/pmd-benchmark.txt") private String benchmarkOutputFilename; /** @@ -152,7 +147,7 @@ public class PmdReport * * @since 3.4 */ - @Parameter( property = "pmd.suppressMarker" ) + @Parameter(property = "pmd.suppressMarker") private String suppressMarker; /** @@ -160,7 +155,7 @@ public class PmdReport * * @since 3.1 */ - @Parameter( property = "pmd.skipPmdError", defaultValue = "true" ) + @Parameter(property = "pmd.skipPmdError", defaultValue = "true") private boolean skipPmdError; /** @@ -171,7 +166,7 @@ public class PmdReport * * @since 3.8 */ - @Parameter( property = "pmd.analysisCache", defaultValue = "false" ) + @Parameter(property = "pmd.analysisCache", defaultValue = "false") private boolean analysisCache; /** @@ -183,7 +178,7 @@ public class PmdReport * * @since 3.8 */ - @Parameter( property = "pmd.analysisCacheLocation", defaultValue = "${project.build.directory}/pmd/pmd.cache" ) + @Parameter(property = "pmd.analysisCacheLocation", defaultValue = "${project.build.directory}/pmd/pmd.cache") private String analysisCacheLocation; /** @@ -195,7 +190,7 @@ public class PmdReport * * @since 3.9.0 */ - @Parameter( property = "pmd.renderProcessingErrors", defaultValue = "true" ) + @Parameter(property = "pmd.renderProcessingErrors", defaultValue = "true") private boolean renderProcessingErrors = true; /** @@ -203,7 +198,7 @@ public class PmdReport * * @since 3.10.0 */ - @Parameter( property = "pmd.renderRuleViolationPriority", defaultValue = "true" ) + @Parameter(property = "pmd.renderRuleViolationPriority", defaultValue = "true") private boolean renderRuleViolationPriority = true; /** @@ -212,7 +207,7 @@ public class PmdReport * * @since 3.12.0 */ - @Parameter( property = "pmd.renderViolationsByPriority", defaultValue = "true" ) + @Parameter(property = "pmd.renderViolationsByPriority", defaultValue = "true") private boolean renderViolationsByPriority = true; /** @@ -220,7 +215,7 @@ public class PmdReport * * @since 3.17.0 */ - @Parameter( property = "pmd.renderSuppressedViolations", defaultValue = "true" ) + @Parameter(property = "pmd.renderSuppressedViolations", defaultValue = "true") private boolean renderSuppressedViolations = true; /** @@ -229,7 +224,7 @@ public class PmdReport * * @since 3.13.0 */ - @Parameter( property = "pmd.rulesetsTargetDirectory", defaultValue = "${project.build.directory}/pmd/rulesets" ) + @Parameter(property = "pmd.rulesetsTargetDirectory", defaultValue = "${project.build.directory}/pmd/rulesets") private File rulesetsTargetDirectory; /** @@ -253,18 +248,16 @@ public class PmdReport * {@inheritDoc} */ @Override - public String getName( Locale locale ) - { - return getBundle( locale ).getString( "report.pmd.name" ); + public String getName(Locale locale) { + return getBundle(locale).getString("report.pmd.name"); } /** * {@inheritDoc} */ @Override - public String getDescription( Locale locale ) - { - return getBundle( locale ).getString( "report.pmd.description" ); + public String getDescription(Locale locale) { + return getBundle(locale).getString("report.pmd.description"); } /** @@ -274,121 +267,98 @@ public String getDescription( Locale locale ) * @param rulesets the PMD rulesets to be used. * @see #rulesets */ - public void setRulesets( String[] rulesets ) - { - this.rulesets = Arrays.copyOf( rulesets, rulesets.length ); + public void setRulesets(String[] rulesets) { + this.rulesets = Arrays.copyOf(rulesets, rulesets.length); } /** * {@inheritDoc} */ @Override - public void executeReport( Locale locale ) - throws MavenReportException - { + public void executeReport(Locale locale) throws MavenReportException { ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() ); + try { + Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader()); - generateMavenSiteReport( locale ); - } - finally - { - Thread.currentThread().setContextClassLoader( origLoader ); + generateMavenSiteReport(locale); + } finally { + Thread.currentThread().setContextClassLoader(origLoader); } } @Override - public boolean canGenerateReport() - { - if ( skip ) - { - getLog().info( "Skipping PMD execution" ); + public boolean canGenerateReport() { + if (skip) { + getLog().info("Skipping PMD execution"); return false; } boolean result = super.canGenerateReport(); - if ( result ) - { - try - { + if (result) { + try { executePmd(); - if ( skipEmptyReport ) - { + if (skipEmptyReport) { result = pmdResult.hasViolations(); - if ( !result ) - { - getLog().debug( "Skipping report since skipEmptyReport is true and " - + "there are no PMD violations." ); + if (!result) { + getLog().debug("Skipping report since skipEmptyReport is true and " + + "there are no PMD violations."); } } - } - catch ( MavenReportException e ) - { - throw new RuntimeException( e ); + } catch (MavenReportException e) { + throw new RuntimeException(e); } } return result; } - private void executePmd() - throws MavenReportException - { - if ( pmdResult != null ) - { + private void executePmd() throws MavenReportException { + if (pmdResult != null) { // PMD has already been run - getLog().debug( "PMD has already been run - skipping redundant execution." ); + getLog().debug("PMD has already been run - skipping redundant execution."); return; } - try - { + try { filesToProcess = getFilesToProcess(); - if ( filesToProcess.isEmpty() && !"java".equals( language ) ) - { - getLog().warn( "No files found to process. Did you add your additional source folders like javascript?" - + " (see also build-helper-maven-plugin)" ); + if (filesToProcess.isEmpty() && !"java".equals(language)) { + getLog().warn("No files found to process. Did you add your additional source folders like javascript?" + + " (see also build-helper-maven-plugin)"); } + } catch (IOException e) { + throw new MavenReportException("Can't get file list", e); } - catch ( IOException e ) - { - throw new MavenReportException( "Can't get file list", e ); - } - PmdRequest request = new PmdRequest(); - request.setLanguageAndVersion( language, targetJdk ); - request.setRulesets( resolveRulesets() ); - request.setAuxClasspath( typeResolution ? determineAuxClasspath() : null ); - request.setSourceEncoding( getInputEncoding() ); - request.addFiles( filesToProcess.keySet() ); - request.setMinimumPriority( minimumPriority ); - request.setSuppressMarker( suppressMarker ); - request.setBenchmarkOutputLocation( benchmark ? benchmarkOutputFilename : null ); - request.setAnalysisCacheLocation( analysisCache ? analysisCacheLocation : null ); - request.setExcludeFromFailureFile( excludeFromFailureFile ); - - request.setTargetDirectory( targetDirectory.getAbsolutePath() ); - request.setOutputEncoding( getOutputEncoding() ); - request.setFormat( format ); - request.setShowPmdLog( showPmdLog ); - request.setSkipPmdError( skipPmdError ); - request.setIncludeXmlInSite( includeXmlInSite ); - request.setReportOutputDirectory( getReportOutputDirectory().getAbsolutePath() ); - request.setLogLevel( determineCurrentRootLogLevel() ); + request.setLanguageAndVersion(language, targetJdk); + request.setRulesets(resolveRulesets()); + request.setAuxClasspath(typeResolution ? determineAuxClasspath() : null); + request.setSourceEncoding(getInputEncoding()); + request.addFiles(filesToProcess.keySet()); + request.setMinimumPriority(minimumPriority); + request.setSuppressMarker(suppressMarker); + request.setBenchmarkOutputLocation(benchmark ? benchmarkOutputFilename : null); + request.setAnalysisCacheLocation(analysisCache ? analysisCacheLocation : null); + request.setExcludeFromFailureFile(excludeFromFailureFile); + + request.setTargetDirectory(targetDirectory.getAbsolutePath()); + request.setOutputEncoding(getOutputEncoding()); + request.setFormat(format); + request.setShowPmdLog(showPmdLog); + request.setSkipPmdError(skipPmdError); + request.setIncludeXmlInSite(includeXmlInSite); + request.setReportOutputDirectory(getReportOutputDirectory().getAbsolutePath()); + request.setLogLevel(determineCurrentRootLogLevel()); Toolchain tc = getToolchain(); - if ( tc != null ) - { - getLog().info( "Toolchain in maven-pmd-plugin: " + tc ); - String javaExecutable = tc.findTool( "java" ); //NOI18N - request.setJavaExecutable( javaExecutable ); + if (tc != null) { + getLog().info("Toolchain in maven-pmd-plugin: " + tc); + String javaExecutable = tc.findTool("java"); // NOI18N + request.setJavaExecutable(javaExecutable); } - getLog().info( "PMD version: " + AbstractPmdReport.getPmdVersion() ); - pmdResult = PmdExecutor.execute( request ); + getLog().info("PMD version: " + AbstractPmdReport.getPmdVersion()); + pmdResult = PmdExecutor.execute(request); } /** @@ -397,99 +367,81 @@ private void executePmd() * @return comma separated list of absolute file paths of ruleset files * @throws MavenReportException if a ruleset could not be found */ - private List resolveRulesets() throws MavenReportException - { + private List resolveRulesets() throws MavenReportException { // configure ResourceManager - will search for urls (URLResourceLoader) and files in various directories: // in the directory of the current project's pom file - note: extensions might replace the pom file on the fly - locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() ); + locator.addSearchPath( + FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath()); // in the current project's directory - locator.addSearchPath( FileResourceLoader.ID, project.getBasedir().getAbsolutePath() ); + locator.addSearchPath(FileResourceLoader.ID, project.getBasedir().getAbsolutePath()); // in the base directory - that's the directory of the initial pom requested to build, // e.g. the root of a multi module build - locator.addSearchPath( FileResourceLoader.ID, session.getRequest().getBaseDirectory() ); - locator.setOutputDirectory( rulesetsTargetDirectory ); + locator.addSearchPath(FileResourceLoader.ID, session.getRequest().getBaseDirectory()); + locator.setOutputDirectory(rulesetsTargetDirectory); String[] sets = new String[rulesets.length]; - try - { - for ( int idx = 0; idx < rulesets.length; idx++ ) - { + try { + for (int idx = 0; idx < rulesets.length; idx++) { String set = rulesets[idx]; - getLog().debug( "Preparing ruleset: " + set ); - String rulesetFilename = determineRulesetFilename( set ); - File ruleset = locator.getResourceAsFile( rulesetFilename, getLocationTemp( set ) ); - if ( null == ruleset ) - { - throw new MavenReportException( "Could not resolve " + set ); + getLog().debug("Preparing ruleset: " + set); + String rulesetFilename = determineRulesetFilename(set); + File ruleset = locator.getResourceAsFile(rulesetFilename, getLocationTemp(set)); + if (null == ruleset) { + throw new MavenReportException("Could not resolve " + set); } sets[idx] = ruleset.getAbsolutePath(); } + } catch (ResourceNotFoundException | FileResourceCreationException e) { + throw new MavenReportException(e.getMessage(), e); } - catch ( ResourceNotFoundException | FileResourceCreationException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - return Arrays.asList( sets ); + return Arrays.asList(sets); } - private String determineRulesetFilename( String ruleset ) - { + private String determineRulesetFilename(String ruleset) { String result = ruleset.trim(); - String lowercase = result.toLowerCase( Locale.ROOT ); - if ( lowercase.startsWith( "http://" ) || lowercase.startsWith( "https://" ) || lowercase.endsWith( ".xml" ) ) - { + String lowercase = result.toLowerCase(Locale.ROOT); + if (lowercase.startsWith("http://") || lowercase.startsWith("https://") || lowercase.endsWith(".xml")) { return result; } // assume last part is a single rule, e.g. myruleset.xml/SingleRule - if ( result.indexOf( '/' ) > -1 ) - { - String rulesetFilename = result.substring( 0, result.lastIndexOf( '/' ) ); - if ( rulesetFilename.toLowerCase( Locale.ROOT ).endsWith( ".xml" ) ) - { + if (result.indexOf('/') > -1) { + String rulesetFilename = result.substring(0, result.lastIndexOf('/')); + if (rulesetFilename.toLowerCase(Locale.ROOT).endsWith(".xml")) { return rulesetFilename; } } // maybe a built-in ruleset name, e.g. java-design -> rulesets/java/design.xml - int dashIndex = lowercase.indexOf( '-' ); - if ( dashIndex > -1 && lowercase.indexOf( '-', dashIndex + 1 ) == -1 ) - { - String language = result.substring( 0, dashIndex ); - String rulesetName = result.substring( dashIndex + 1 ); + int dashIndex = lowercase.indexOf('-'); + if (dashIndex > -1 && lowercase.indexOf('-', dashIndex + 1) == -1) { + String language = result.substring(0, dashIndex); + String rulesetName = result.substring(dashIndex + 1); return "rulesets/" + language + "/" + rulesetName + ".xml"; } // fallback - no change of the given ruleset specifier return result; } - private void generateMavenSiteReport( Locale locale ) - throws MavenReportException - { + private void generateMavenSiteReport(Locale locale) throws MavenReportException { Sink sink = getSink(); - PmdReportGenerator doxiaRenderer = new PmdReportGenerator( getLog(), sink, getBundle( locale ), - isAggregator() ); - doxiaRenderer.setRenderRuleViolationPriority( renderRuleViolationPriority ); - doxiaRenderer.setRenderViolationsByPriority( renderViolationsByPriority ); - doxiaRenderer.setFiles( filesToProcess ); - doxiaRenderer.setViolations( pmdResult.getViolations() ); - if ( renderSuppressedViolations ) - { - doxiaRenderer.setSuppressedViolations( pmdResult.getSuppressedViolations() ); + PmdReportGenerator doxiaRenderer = new PmdReportGenerator(getLog(), sink, getBundle(locale), isAggregator()); + doxiaRenderer.setRenderRuleViolationPriority(renderRuleViolationPriority); + doxiaRenderer.setRenderViolationsByPriority(renderViolationsByPriority); + doxiaRenderer.setFiles(filesToProcess); + doxiaRenderer.setViolations(pmdResult.getViolations()); + if (renderSuppressedViolations) { + doxiaRenderer.setSuppressedViolations(pmdResult.getSuppressedViolations()); } - if ( renderProcessingErrors ) - { - doxiaRenderer.setProcessingErrors( pmdResult.getErrors() ); + if (renderProcessingErrors) { + doxiaRenderer.setProcessingErrors(pmdResult.getErrors()); } - try - { + try { doxiaRenderer.beginDocument(); doxiaRenderer.render(); doxiaRenderer.endDocument(); - } - catch ( IOException e ) - { - getLog().warn( "Failure creating the report: " + e.getLocalizedMessage(), e ); + } catch (IOException e) { + getLog().warn("Failure creating the report: " + e.getLocalizedMessage(), e); } } @@ -499,111 +451,95 @@ private void generateMavenSiteReport( Locale locale ) * @param name the name of the file whose location is to be resolved * @return a String that contains the absolute file name of the file */ - protected String getLocationTemp( String name ) - { + protected String getLocationTemp(String name) { String loc = name; - if ( loc.indexOf( '/' ) != -1 ) - { - loc = loc.substring( loc.lastIndexOf( '/' ) + 1 ); + if (loc.indexOf('/') != -1) { + loc = loc.substring(loc.lastIndexOf('/') + 1); } - if ( loc.indexOf( '\\' ) != -1 ) - { - loc = loc.substring( loc.lastIndexOf( '\\' ) + 1 ); + if (loc.indexOf('\\') != -1) { + loc = loc.substring(loc.lastIndexOf('\\') + 1); } // MPMD-127 in the case that the rules are defined externally on a url // we need to replace some special url characters that cannot be // used in filenames on disk or produce ackward filenames. // replace all occurrences of the following characters: ? : & = % - loc = loc.replaceAll( "[\\?\\:\\&\\=\\%]", "_" ); + loc = loc.replaceAll("[\\?\\:\\&\\=\\%]", "_"); - if ( !loc.endsWith( ".xml" ) ) - { + if (!loc.endsWith(".xml")) { loc = loc + ".xml"; } - getLog().debug( "Before: " + name + " After: " + loc ); + getLog().debug("Before: " + name + " After: " + loc); return loc; } - private String determineAuxClasspath() throws MavenReportException - { - try - { + private String determineAuxClasspath() throws MavenReportException { + try { List classpath = new ArrayList<>(); - if ( isAggregator() ) - { + if (isAggregator()) { List dependencies = new ArrayList<>(); // collect exclusions for projects within the reactor // if module a depends on module b and both are in the reactor // then we don't want to resolve the dependency as an artifact. List exclusionPatterns = new ArrayList<>(); - for ( MavenProject localProject : getAggregatedProjects() ) - { - exclusionPatterns.add( localProject.getGroupId() + ":" + localProject.getArtifactId() ); + for (MavenProject localProject : getAggregatedProjects()) { + exclusionPatterns.add(localProject.getGroupId() + ":" + localProject.getArtifactId()); } - TransformableFilter filter = new AndFilter( Arrays.asList( - new ExclusionsFilter( exclusionPatterns ), - includeTests ? ScopeFilter.including( "compile", "provided", "test" ) - : ScopeFilter.including( "compile", "provided" ) - ) ); - - for ( MavenProject localProject : getAggregatedProjects() ) - { - ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest( - session.getProjectBuildingRequest() ); + TransformableFilter filter = new AndFilter(Arrays.asList( + new ExclusionsFilter(exclusionPatterns), + includeTests + ? ScopeFilter.including("compile", "provided", "test") + : ScopeFilter.including("compile", "provided"))); + + for (MavenProject localProject : getAggregatedProjects()) { + ProjectBuildingRequest buildingRequest = + new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()); // use any additional configured repo as well - buildingRequest.getRemoteRepositories().addAll( localProject.getRemoteArtifactRepositories() ); + buildingRequest.getRemoteRepositories().addAll(localProject.getRemoteArtifactRepositories()); Iterable resolvedDependencies = dependencyResolver.resolveDependencies( - buildingRequest, localProject.getDependencies(), null, filter ); + buildingRequest, localProject.getDependencies(), null, filter); - for ( ArtifactResult resolvedArtifact : resolvedDependencies ) - { - dependencies.add( resolvedArtifact.getArtifact().getFile().toString() ); + for (ArtifactResult resolvedArtifact : resolvedDependencies) { + dependencies.add( + resolvedArtifact.getArtifact().getFile().toString()); } - List projectClasspath = includeTests ? localProject.getTestClasspathElements() + List projectClasspath = includeTests + ? localProject.getTestClasspathElements() : localProject.getCompileClasspathElements(); // Add the project's target folder first - classpath.addAll( projectClasspath ); - if ( !localProject.isExecutionRoot() ) - { - for ( String path : projectClasspath ) - { - File pathFile = new File( path ); + classpath.addAll(projectClasspath); + if (!localProject.isExecutionRoot()) { + for (String path : projectClasspath) { + File pathFile = new File(path); String[] children = pathFile.list(); - if ( !pathFile.exists() || ( children != null && children.length == 0 ) ) - { - getLog().warn( "The project " + localProject.getArtifactId() - + " does not seem to be compiled. PMD results might be inaccurate." ); + if (!pathFile.exists() || (children != null && children.length == 0)) { + getLog().warn("The project " + localProject.getArtifactId() + + " does not seem to be compiled. PMD results might be inaccurate."); } } } - } // Add the dependencies as last entries - classpath.addAll( dependencies ); + classpath.addAll(dependencies); - getLog().debug( "Using aggregated aux classpath: " + classpath ); - } - else - { - classpath.addAll( includeTests ? project.getTestClasspathElements() - : project.getCompileClasspathElements() ); + getLog().debug("Using aggregated aux classpath: " + classpath); + } else { + classpath.addAll( + includeTests ? project.getTestClasspathElements() : project.getCompileClasspathElements()); - getLog().debug( "Using aux classpath: " + classpath ); + getLog().debug("Using aux classpath: " + classpath); } - String path = StringUtils.join( classpath.iterator(), File.pathSeparator ); + String path = StringUtils.join(classpath.iterator(), File.pathSeparator); return path; - } - catch ( Exception e ) - { - throw new MavenReportException( e.getMessage(), e ); + } catch (Exception e) { + throw new MavenReportException(e.getMessage(), e); } } @@ -611,14 +547,12 @@ private String determineAuxClasspath() throws MavenReportException * {@inheritDoc} */ @Override - public String getOutputName() - { + public String getOutputName() { return "pmd"; } - private static ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "pmd-report", locale, PmdReport.class.getClassLoader() ); + private static ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle("pmd-report", locale, PmdReport.class.getClassLoader()); } /** @@ -629,8 +563,7 @@ private static ResourceBundle getBundle( Locale locale ) * @deprecated Use {@link PmdExecutor#createRenderer(String, String)} instead. */ @Deprecated - public final Renderer createRenderer() throws MavenReportException - { - return PmdExecutor.createRenderer( format, getOutputEncoding() ); + public final Renderer createRenderer() throws MavenReportException { + return PmdExecutor.createRenderer(format, getOutputEncoding()); } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/PmdReportGenerator.java b/src/main/java/org/apache/maven/plugins/pmd/PmdReportGenerator.java index 623b7c94..bb836c95 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/PmdReportGenerator.java +++ b/src/main/java/org/apache/maven/plugins/pmd/PmdReportGenerator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -32,6 +31,7 @@ import java.util.ResourceBundle; import java.util.Set; +import net.sourceforge.pmd.RulePriority; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.pmd.model.ProcessingError; @@ -39,16 +39,13 @@ import org.apache.maven.plugins.pmd.model.Violation; import org.codehaus.plexus.util.StringUtils; -import net.sourceforge.pmd.RulePriority; - /** * Render the PMD violations into Doxia events. * * @author Brett Porter * @version $Id$ */ -public class PmdReportGenerator -{ +public class PmdReportGenerator { private Log log; private Sink sink; @@ -73,41 +70,34 @@ public class PmdReportGenerator // private List metrics = new ArrayList(); - public PmdReportGenerator( Log log, Sink sink, ResourceBundle bundle, boolean aggregate ) - { + public PmdReportGenerator(Log log, Sink sink, ResourceBundle bundle, boolean aggregate) { this.log = log; this.sink = sink; this.bundle = bundle; this.aggregate = aggregate; } - private String getTitle() - { - return bundle.getString( "report.pmd.title" ); + private String getTitle() { + return bundle.getString("report.pmd.title"); } - public void setViolations( Collection violations ) - { - this.violations = new HashSet<>( violations ); + public void setViolations(Collection violations) { + this.violations = new HashSet<>(violations); } - public List getViolations() - { - return new ArrayList<>( violations ); + public List getViolations() { + return new ArrayList<>(violations); } - public void setSuppressedViolations( Collection suppressedViolations ) - { - this.suppressedViolations = new ArrayList<>( suppressedViolations ); + public void setSuppressedViolations(Collection suppressedViolations) { + this.suppressedViolations = new ArrayList<>(suppressedViolations); } - public void setProcessingErrors( Collection errors ) - { - this.processingErrors = new ArrayList<>( errors ); + public void setProcessingErrors(Collection errors) { + this.processingErrors = new ArrayList<>(errors); } - public List getProcessingErrors() - { + public List getProcessingErrors() { return processingErrors; } @@ -121,121 +111,107 @@ public List getProcessingErrors() // this.metrics = metrics; // } - private String shortenFilename( String filename, PmdFileInfo fileInfo ) - { + private String shortenFilename(String filename, PmdFileInfo fileInfo) { String result = filename; - if ( fileInfo != null && fileInfo.getSourceDirectory() != null ) - { - result = StringUtils.substring( result, fileInfo.getSourceDirectory().getAbsolutePath().length() + 1 ); + if (fileInfo != null && fileInfo.getSourceDirectory() != null) { + result = StringUtils.substring( + result, fileInfo.getSourceDirectory().getAbsolutePath().length() + 1); } - return StringUtils.replace( result, "\\", "/" ); + return StringUtils.replace(result, "\\", "/"); } - private String makeFileSectionName( String filename, PmdFileInfo fileInfo ) - { - if ( aggregate && fileInfo != null && fileInfo.getProject() != null ) - { + private String makeFileSectionName(String filename, PmdFileInfo fileInfo) { + if (aggregate && fileInfo != null && fileInfo.getProject() != null) { return fileInfo.getProject().getName() + " - " + filename; } return filename; } - private PmdFileInfo determineFileInfo( String filename ) - throws IOException - { - File canonicalFilename = new File( filename ).getCanonicalFile(); - PmdFileInfo fileInfo = files.get( canonicalFilename ); - if ( fileInfo == null ) - { - log.warn( "Couldn't determine PmdFileInfo for file " + filename + " (canonical: " + canonicalFilename - + "). XRef links won't be available." ); + private PmdFileInfo determineFileInfo(String filename) throws IOException { + File canonicalFilename = new File(filename).getCanonicalFile(); + PmdFileInfo fileInfo = files.get(canonicalFilename); + if (fileInfo == null) { + log.warn("Couldn't determine PmdFileInfo for file " + filename + " (canonical: " + canonicalFilename + + "). XRef links won't be available."); } return fileInfo; } - private void startFileSection( int level, String currentFilename, PmdFileInfo fileInfo ) - { - sink.section( level, null ); - sink.sectionTitle( level, null ); + private void startFileSection(int level, String currentFilename, PmdFileInfo fileInfo) { + sink.section(level, null); + sink.sectionTitle(level, null); // prepare the filename - this.currentFilename = shortenFilename( currentFilename, fileInfo ); + this.currentFilename = shortenFilename(currentFilename, fileInfo); - sink.text( makeFileSectionName( this.currentFilename, fileInfo ) ); - sink.sectionTitle_( level ); + sink.text(makeFileSectionName(this.currentFilename, fileInfo)); + sink.sectionTitle_(level); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.column.rule" ) ); + sink.text(bundle.getString("report.pmd.column.rule")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.column.violation" ) ); + sink.text(bundle.getString("report.pmd.column.violation")); sink.tableHeaderCell_(); - if ( this.renderRuleViolationPriority ) - { + if (this.renderRuleViolationPriority) { sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.column.priority" ) ); + sink.text(bundle.getString("report.pmd.column.priority")); sink.tableHeaderCell_(); } sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.column.line" ) ); + sink.text(bundle.getString("report.pmd.column.line")); sink.tableHeaderCell_(); sink.tableRow_(); } - private void endFileSection( int level ) - { + private void endFileSection(int level) { sink.tableRows_(); sink.table_(); - sink.section_( level ); + sink.section_(level); } - private void addRuleName( Violation ruleViolation ) - { - boolean hasUrl = StringUtils.isNotBlank( ruleViolation.getExternalInfoUrl() ); + private void addRuleName(Violation ruleViolation) { + boolean hasUrl = StringUtils.isNotBlank(ruleViolation.getExternalInfoUrl()); - if ( hasUrl ) - { - sink.link( ruleViolation.getExternalInfoUrl() ); + if (hasUrl) { + sink.link(ruleViolation.getExternalInfoUrl()); } - sink.text( ruleViolation.getRule() ); + sink.text(ruleViolation.getRule()); - if ( hasUrl ) - { + if (hasUrl) { sink.link_(); } } - private void processSingleRuleViolation( Violation ruleViolation, PmdFileInfo fileInfo ) - { + private void processSingleRuleViolation(Violation ruleViolation, PmdFileInfo fileInfo) { sink.tableRow(); sink.tableCell(); - addRuleName( ruleViolation ); + addRuleName(ruleViolation); sink.tableCell_(); sink.tableCell(); - sink.text( ruleViolation.getText() ); + sink.text(ruleViolation.getText()); sink.tableCell_(); - if ( this.renderRuleViolationPriority ) - { + if (this.renderRuleViolationPriority) { sink.tableCell(); - sink.text( String.valueOf( RulePriority.valueOf( ruleViolation.getPriority() ).getPriority() ) ); + sink.text(String.valueOf( + RulePriority.valueOf(ruleViolation.getPriority()).getPriority())); sink.tableCell_(); } sink.tableCell(); int beginLine = ruleViolation.getBeginline(); - outputLineLink( beginLine, fileInfo ); + outputLineLink(beginLine, fileInfo); int endLine = ruleViolation.getEndline(); - if ( endLine != beginLine ) - { - sink.text( "–" ); // \u2013 is a medium long dash character - outputLineLink( endLine, fileInfo ); + if (endLine != beginLine) { + sink.text("–"); // \u2013 is a medium long dash character + outputLineLink(endLine, fileInfo); } sink.tableCell_(); @@ -245,26 +221,22 @@ private void processSingleRuleViolation( Violation ruleViolation, PmdFileInfo fi // PMD might run the analysis multi-threaded, so the violations might be reported // out of order. We sort them here by filename and line number before writing them to // the report. - private void renderViolations() - throws IOException - { + private void renderViolations() throws IOException { sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.pmd.files" ) ); + sink.text(bundle.getString("report.pmd.files")); sink.sectionTitle1_(); // TODO files summary - List violations2 = new ArrayList<>( violations ); - renderViolationsTable( 2, violations2 ); + List violations2 = new ArrayList<>(violations); + renderViolationsTable(2, violations2); sink.section1_(); } - private void renderViolationsByPriority() throws IOException - { - if ( !renderViolationsByPriority ) - { + private void renderViolationsByPriority() throws IOException { + if (!renderViolationsByPriority) { return; } @@ -273,44 +245,39 @@ private void renderViolationsByPriority() throws IOException sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.pmd.violationsByPriority" ) ); + sink.text(bundle.getString("report.pmd.violationsByPriority")); sink.sectionTitle1_(); Map> violationsByPriority = new HashMap<>(); - for ( Violation violation : violations ) - { - RulePriority priority = RulePriority.valueOf( violation.getPriority() ); - List violationSegment = violationsByPriority.get( priority ); - if ( violationSegment == null ) - { + for (Violation violation : violations) { + RulePriority priority = RulePriority.valueOf(violation.getPriority()); + List violationSegment = violationsByPriority.get(priority); + if (violationSegment == null) { violationSegment = new ArrayList<>(); - violationsByPriority.put( priority, violationSegment ); + violationsByPriority.put(priority, violationSegment); } - violationSegment.add( violation ); + violationSegment.add(violation); } - for ( RulePriority priority : RulePriority.values() ) - { - List violationsWithPriority = violationsByPriority.get( priority ); - if ( violationsWithPriority == null || violationsWithPriority.isEmpty() ) - { + for (RulePriority priority : RulePriority.values()) { + List violationsWithPriority = violationsByPriority.get(priority); + if (violationsWithPriority == null || violationsWithPriority.isEmpty()) { continue; } sink.section2(); sink.sectionTitle2(); - sink.text( bundle.getString( "report.pmd.priority" ) + " " + priority.getPriority() ); + sink.text(bundle.getString("report.pmd.priority") + " " + priority.getPriority()); sink.sectionTitle2_(); - renderViolationsTable( 3, violationsWithPriority ); + renderViolationsTable(3, violationsWithPriority); sink.section2_(); } - if ( violations.isEmpty() ) - { + if (violations.isEmpty()) { sink.paragraph(); - sink.text( bundle.getString( "report.pmd.noProblems" ) ); + sink.text(bundle.getString("report.pmd.noProblems")); sink.paragraph_(); } @@ -319,70 +286,55 @@ private void renderViolationsByPriority() throws IOException this.renderRuleViolationPriority = oldPriorityColumn; } - private void renderViolationsTable( int level, List violationSegment ) - throws IOException - { - Collections.sort( violationSegment, new Comparator() - { + private void renderViolationsTable(int level, List violationSegment) throws IOException { + Collections.sort(violationSegment, new Comparator() { /** {@inheritDoc} */ - public int compare( Violation o1, Violation o2 ) - { - int filenames = o1.getFileName().compareTo( o2.getFileName() ); - if ( filenames == 0 ) - { + public int compare(Violation o1, Violation o2) { + int filenames = o1.getFileName().compareTo(o2.getFileName()); + if (filenames == 0) { return o1.getBeginline() - o2.getBeginline(); - } - else - { + } else { return filenames; } } - } ); + }); boolean fileSectionStarted = false; String previousFilename = null; - for ( Violation ruleViolation : violationSegment ) - { + for (Violation ruleViolation : violationSegment) { String currentFn = ruleViolation.getFileName(); - PmdFileInfo fileInfo = determineFileInfo( currentFn ); + PmdFileInfo fileInfo = determineFileInfo(currentFn); - if ( !currentFn.equalsIgnoreCase( previousFilename ) && fileSectionStarted ) - { - endFileSection( level ); + if (!currentFn.equalsIgnoreCase(previousFilename) && fileSectionStarted) { + endFileSection(level); fileSectionStarted = false; } - if ( !fileSectionStarted ) - { - startFileSection( level, currentFn, fileInfo ); + if (!fileSectionStarted) { + startFileSection(level, currentFn, fileInfo); fileSectionStarted = true; } - processSingleRuleViolation( ruleViolation, fileInfo ); + processSingleRuleViolation(ruleViolation, fileInfo); previousFilename = currentFn; } - if ( fileSectionStarted ) - { - endFileSection( level ); + if (fileSectionStarted) { + endFileSection(level); } } - private void outputLineLink( int line, PmdFileInfo fileInfo ) - { + private void outputLineLink(int line, PmdFileInfo fileInfo) { String xrefLocation = null; - if ( fileInfo != null ) - { + if (fileInfo != null) { xrefLocation = fileInfo.getXrefLocation(); } - if ( xrefLocation != null ) - { - sink.link( xrefLocation + "/" + currentFilename.replaceAll( "\\.java$", ".html" ) + "#L" + line ); + if (xrefLocation != null) { + sink.link(xrefLocation + "/" + currentFilename.replaceAll("\\.java$", ".html") + "#L" + line); } - sink.text( String.valueOf( line ) ); - if ( xrefLocation != null ) - { + sink.text(String.valueOf(line)); + if (xrefLocation != null) { sink.link_(); } } @@ -390,62 +342,57 @@ private void outputLineLink( int line, PmdFileInfo fileInfo ) // PMD might run the analysis multi-threaded, so the suppressed violations might be reported // out of order. We sort them here by filename before writing them to // the report. - private void renderSuppressedViolations() - throws IOException - { + private void renderSuppressedViolations() throws IOException { sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.pmd.suppressedViolations.title" ) ); + sink.text(bundle.getString("report.pmd.suppressedViolations.title")); sink.sectionTitle1_(); - Collections.sort( suppressedViolations, new Comparator() - { + Collections.sort(suppressedViolations, new Comparator() { @Override - public int compare( SuppressedViolation o1, SuppressedViolation o2 ) - { - return o1.getFilename().compareTo( o2.getFilename() ); + public int compare(SuppressedViolation o1, SuppressedViolation o2) { + return o1.getFilename().compareTo(o2.getFilename()); } - } ); + }); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.suppressedViolations.column.filename" ) ); + sink.text(bundle.getString("report.pmd.suppressedViolations.column.filename")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.suppressedViolations.column.ruleMessage" ) ); + sink.text(bundle.getString("report.pmd.suppressedViolations.column.ruleMessage")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.suppressedViolations.column.suppressionType" ) ); + sink.text(bundle.getString("report.pmd.suppressedViolations.column.suppressionType")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.suppressedViolations.column.userMessage" ) ); + sink.text(bundle.getString("report.pmd.suppressedViolations.column.userMessage")); sink.tableHeaderCell_(); sink.tableRow_(); - for ( SuppressedViolation suppressedViolation : suppressedViolations ) - { + for (SuppressedViolation suppressedViolation : suppressedViolations) { String filename = suppressedViolation.getFilename(); - PmdFileInfo fileInfo = determineFileInfo( filename ); - filename = shortenFilename( filename, fileInfo ); + PmdFileInfo fileInfo = determineFileInfo(filename); + filename = shortenFilename(filename, fileInfo); sink.tableRow(); sink.tableCell(); - sink.text( filename ); + sink.text(filename); sink.tableCell_(); sink.tableCell(); - sink.text( suppressedViolation.getRuleMessage() ); + sink.text(suppressedViolation.getRuleMessage()); sink.tableCell_(); sink.tableCell(); - sink.text( suppressedViolation.getSuppressionType() ); + sink.text(suppressedViolation.getSuppressionType()); sink.tableCell_(); sink.tableCell(); - sink.text( suppressedViolation.getUserMessage() ); + sink.text(suppressedViolation.getUserMessage()); sink.tableCell_(); sink.tableRow_(); @@ -456,38 +403,34 @@ public int compare( SuppressedViolation o1, SuppressedViolation o2 ) sink.section1_(); } - private void processProcessingErrors() throws IOException - { + private void processProcessingErrors() throws IOException { // sort the problem by filename first, since PMD is executed multi-threaded // and might reports the results unsorted - Collections.sort( processingErrors, new Comparator() - { + Collections.sort(processingErrors, new Comparator() { @Override - public int compare( ProcessingError e1, ProcessingError e2 ) - { - return e1.getFilename().compareTo( e2.getFilename() ); + public int compare(ProcessingError e1, ProcessingError e2) { + return e1.getFilename().compareTo(e2.getFilename()); } - } ); + }); sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.pmd.processingErrors.title" ) ); + sink.text(bundle.getString("report.pmd.processingErrors.title")); sink.sectionTitle1_(); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.processingErrors.column.filename" ) ); + sink.text(bundle.getString("report.pmd.processingErrors.column.filename")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.pmd.processingErrors.column.problem" ) ); + sink.text(bundle.getString("report.pmd.processingErrors.column.problem")); sink.tableHeaderCell_(); sink.tableRow_(); - for ( ProcessingError error : processingErrors ) - { - processSingleProcessingError( error ); + for (ProcessingError error : processingErrors) { + processSingleProcessingError(error); } sink.tableRows_(); @@ -496,30 +439,28 @@ public int compare( ProcessingError e1, ProcessingError e2 ) sink.section1_(); } - private void processSingleProcessingError( ProcessingError error ) throws IOException - { + private void processSingleProcessingError(ProcessingError error) throws IOException { String filename = error.getFilename(); - PmdFileInfo fileInfo = determineFileInfo( filename ); - filename = makeFileSectionName( shortenFilename( filename, fileInfo ), fileInfo ); + PmdFileInfo fileInfo = determineFileInfo(filename); + filename = makeFileSectionName(shortenFilename(filename, fileInfo), fileInfo); sink.tableRow(); sink.tableCell(); - sink.text( filename ); + sink.text(filename); sink.tableCell_(); sink.tableCell(); - sink.text( error.getMsg() ); - sink.verbatim( null ); - sink.rawText( error.getDetail() ); + sink.text(error.getMsg()); + sink.verbatim(null); + sink.rawText(error.getDetail()); sink.verbatim_(); sink.tableCell_(); sink.tableRow_(); } - public void beginDocument() - { + public void beginDocument() { sink.head(); sink.title(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.title_(); sink.head_(); @@ -527,15 +468,15 @@ public void beginDocument() sink.section1(); sink.sectionTitle1(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.sectionTitle1_(); sink.paragraph(); - sink.text( bundle.getString( "report.pmd.pmdlink" ) + " " ); - sink.link( "https://pmd.github.io" ); - sink.text( "PMD" ); + sink.text(bundle.getString("report.pmd.pmdlink") + " "); + sink.link("https://pmd.github.io"); + sink.text("PMD"); sink.link_(); - sink.text( " " + AbstractPmdReport.getPmdVersion() + "." ); + sink.text(" " + AbstractPmdReport.getPmdVersion() + "."); sink.paragraph_(); sink.section1_(); @@ -557,36 +498,27 @@ public void beginDocument() * sink.section1_(); } */ - public void render() - throws IOException - { - if ( !violations.isEmpty() ) - { + public void render() throws IOException { + if (!violations.isEmpty()) { renderViolationsByPriority(); renderViolations(); - } - else - { + } else { sink.paragraph(); - sink.text( bundle.getString( "report.pmd.noProblems" ) ); + sink.text(bundle.getString("report.pmd.noProblems")); sink.paragraph_(); } - if ( !suppressedViolations.isEmpty() ) - { + if (!suppressedViolations.isEmpty()) { renderSuppressedViolations(); } - if ( !processingErrors.isEmpty() ) - { + if (!processingErrors.isEmpty()) { processProcessingErrors(); } } - public void endDocument() - throws IOException - { + public void endDocument() throws IOException { // The Metrics report useless with the current PMD metrics impl. // For instance, run the coupling ruleset and you will get a boatload // of excessive imports metrics, none of which is really any use. @@ -601,18 +533,15 @@ public void endDocument() sink.close(); } - public void setFiles( Map files ) - { + public void setFiles(Map files) { this.files = files; } - public void setRenderRuleViolationPriority( boolean renderRuleViolationPriority ) - { + public void setRenderRuleViolationPriority(boolean renderRuleViolationPriority) { this.renderRuleViolationPriority = renderRuleViolationPriority; } - public void setRenderViolationsByPriority( boolean renderViolationsByPriority ) - { + public void setRenderViolationsByPriority(boolean renderViolationsByPriority) { this.renderViolationsByPriority = renderViolationsByPriority; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojo.java index 39cb7ef2..45d63537 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.FileInputStream; @@ -28,14 +27,14 @@ import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.pmd.model.PmdErrorDetail; -import org.apache.maven.plugins.pmd.model.PmdFile; -import org.apache.maven.plugins.pmd.model.Violation; -import org.apache.maven.plugins.pmd.model.io.xpp3.PmdXpp3Reader; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.pmd.model.PmdErrorDetail; +import org.apache.maven.plugins.pmd.model.PmdFile; +import org.apache.maven.plugins.pmd.model.Violation; +import org.apache.maven.plugins.pmd.model.io.xpp3.PmdXpp3Reader; import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; @@ -45,17 +44,14 @@ * @version $Id$ * @since 2.0 */ -@Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true ) -@Execute( goal = "pmd" ) -public class PmdViolationCheckMojo - extends AbstractPmdViolationCheckMojo -{ +@Mojo(name = "check", defaultPhase = LifecyclePhase.VERIFY, threadSafe = true) +@Execute(goal = "pmd") +public class PmdViolationCheckMojo extends AbstractPmdViolationCheckMojo { /** * Default constructor. Initializes with the correct {@link ExcludeViolationsFromFile}. */ - public PmdViolationCheckMojo() - { - super( new ExcludeViolationsFromFile() ); + public PmdViolationCheckMojo() { + super(new ExcludeViolationsFromFile()); } /** @@ -70,76 +66,64 @@ public PmdViolationCheckMojo() * Setting a value of 1 will treat all violations as warnings. * Only values from 1 to 5 are valid. */ - @Parameter( property = "pmd.failurePriority", defaultValue = "5", required = true ) + @Parameter(property = "pmd.failurePriority", defaultValue = "5", required = true) private int failurePriority = 5; /** * Skip the PMD checks. Most useful on the command line via "-Dpmd.skip=true". */ - @Parameter( property = "pmd.skip", defaultValue = "false" ) + @Parameter(property = "pmd.skip", defaultValue = "false") private boolean skip; /** * {@inheritDoc} */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping PMD execution" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping PMD execution"); return; } - executeCheck( "pmd.xml", "violation", "PMD violation", failurePriority ); + executeCheck("pmd.xml", "violation", "PMD violation", failurePriority); } /** * {@inheritDoc} */ - protected void printError( Violation item, String severity ) - { - - StringBuilder buff = new StringBuilder( 100 ); - buff.append( "PMD " ).append( severity ).append( ": " ); - if ( item.getViolationClass() != null ) - { - if ( item.getViolationPackage() != null ) - { - buff.append( item.getViolationPackage() ); - buff.append( "." ); + protected void printError(Violation item, String severity) { + + StringBuilder buff = new StringBuilder(100); + buff.append("PMD ").append(severity).append(": "); + if (item.getViolationClass() != null) { + if (item.getViolationPackage() != null) { + buff.append(item.getViolationPackage()); + buff.append("."); } - buff.append( item.getViolationClass() ); - } - else - { - buff.append( item.getFileName() ); + buff.append(item.getViolationClass()); + } else { + buff.append(item.getFileName()); } - buff.append( ":" ); - buff.append( item.getBeginline() ); - buff.append( " Rule:" ).append( item.getRule() ); - buff.append( " Priority:" ).append( item.getPriority() ); - buff.append( " " ).append( item.getText() ).append( "." ); + buff.append(":"); + buff.append(item.getBeginline()); + buff.append(" Rule:").append(item.getRule()); + buff.append(" Priority:").append(item.getPriority()); + buff.append(" ").append(item.getText()).append("."); - this.getLog().info( buff.toString() ); + this.getLog().info(buff.toString()); } @Override - protected List getErrorDetails( File pmdFile ) throws XmlPullParserException, IOException - { - try ( InputStream in = new FileInputStream( pmdFile ) ) - { + protected List getErrorDetails(File pmdFile) throws XmlPullParserException, IOException { + try (InputStream in = new FileInputStream(pmdFile)) { PmdXpp3Reader reader = new PmdXpp3Reader(); - PmdErrorDetail details = reader.read( in, false ); + PmdErrorDetail details = reader.read(in, false); List violations = new ArrayList<>(); - for ( PmdFile file : details.getFiles() ) - { + for (PmdFile file : details.getFiles()) { String fullPath = file.getName(); - for ( Violation violation : file.getViolations() ) - { - violation.setFileName( getFilename( fullPath, violation.getViolationPackage() ) ); - violations.add( violation ); + for (Violation violation : file.getViolations()) { + violation.setFileName(getFilename(fullPath, violation.getViolationPackage())); + violations.add(violation); } } return violations; @@ -147,34 +131,29 @@ protected List getErrorDetails( File pmdFile ) throws XmlPullParserEx } @Override - protected int getPriority( Violation errorDetail ) - { + protected int getPriority(Violation errorDetail) { return errorDetail.getPriority(); } @Override - protected ViolationDetails newViolationDetailsInstance() - { + protected ViolationDetails newViolationDetailsInstance() { return new ViolationDetails<>(); } - private String getFilename( String fullpath, String pkg ) - { - int index = fullpath.lastIndexOf( File.separatorChar ); + private String getFilename(String fullpath, String pkg) { + int index = fullpath.lastIndexOf(File.separatorChar); - while ( StringUtils.isNotEmpty( pkg ) ) - { - index = fullpath.substring( 0, index ).lastIndexOf( File.separatorChar ); + while (StringUtils.isNotEmpty(pkg)) { + index = fullpath.substring(0, index).lastIndexOf(File.separatorChar); - int dot = pkg.indexOf( '.' ); + int dot = pkg.indexOf('.'); - if ( dot < 0 ) - { + if (dot < 0) { break; } - pkg = pkg.substring( dot + 1 ); + pkg = pkg.substring(dot + 1); } - return fullpath.substring( index + 1 ); + return fullpath.substring(index + 1); } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/ViolationDetails.java b/src/main/java/org/apache/maven/plugins/pmd/ViolationDetails.java index 98e1ce7c..b19b1bb5 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/ViolationDetails.java +++ b/src/main/java/org/apache/maven/plugins/pmd/ViolationDetails.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.util.ArrayList; import java.util.List; @@ -30,8 +29,7 @@ * @author Robert Scholte * @since 2.7 */ -public class ViolationDetails -{ +public class ViolationDetails { private List warningDetails = new ArrayList<>(); private List failureDetails = new ArrayList<>(); @@ -39,32 +37,28 @@ public class ViolationDetails /** * @return the warningDetails, never {@code null} */ - public List getWarningDetails() - { + public List getWarningDetails() { return warningDetails; } /** * @param warningDetails the warningDetails to set */ - public void setWarningDetails( List warningDetails ) - { + public void setWarningDetails(List warningDetails) { this.warningDetails = warningDetails; } /** * @return the failureDetails, never {@code null} */ - public List getFailureDetails() - { + public List getFailureDetails() { return failureDetails; } /** * @param failureDetails the failureDetails to set */ - public void setFailureDetails( List failureDetails ) - { + public void setFailureDetails(List failureDetails) { this.failureDetails = failureDetails; } -} \ No newline at end of file +} diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdExecutor.java b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdExecutor.java index 998c8e3f..43ba3c06 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdExecutor.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.io.FileInputStream; @@ -32,13 +31,6 @@ import java.util.List; import java.util.Objects; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.pmd.ExcludeDuplicationsFromFile; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.util.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import net.sourceforge.pmd.cpd.CPD; import net.sourceforge.pmd.cpd.CPDConfiguration; import net.sourceforge.pmd.cpd.CSVRenderer; @@ -51,81 +43,70 @@ import net.sourceforge.pmd.cpd.SimpleRenderer; import net.sourceforge.pmd.cpd.XMLRenderer; import net.sourceforge.pmd.cpd.renderer.CPDRenderer; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.pmd.ExcludeDuplicationsFromFile; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.util.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Executes CPD with the configuration provided via {@link CpdRequest}. */ -public class CpdExecutor extends Executor -{ - private static final Logger LOG = LoggerFactory.getLogger( CpdExecutor.class ); +public class CpdExecutor extends Executor { + private static final Logger LOG = LoggerFactory.getLogger(CpdExecutor.class); - public static CpdResult execute( CpdRequest request ) throws MavenReportException - { - if ( request.getJavaExecutable() != null ) - { - return fork( request ); + public static CpdResult execute(CpdRequest request) throws MavenReportException { + if (request.getJavaExecutable() != null) { + return fork(request); } ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( CpdExecutor.class.getClassLoader() ); - CpdExecutor cpdExecutor = new CpdExecutor( request ); + try { + Thread.currentThread().setContextClassLoader(CpdExecutor.class.getClassLoader()); + CpdExecutor cpdExecutor = new CpdExecutor(request); return cpdExecutor.run(); - } - finally - { - Thread.currentThread().setContextClassLoader( origLoader ); + } finally { + Thread.currentThread().setContextClassLoader(origLoader); } } - private static CpdResult fork( CpdRequest request ) - throws MavenReportException - { - File basePmdDir = new File ( request.getTargetDirectory(), "pmd" ); + private static CpdResult fork(CpdRequest request) throws MavenReportException { + File basePmdDir = new File(request.getTargetDirectory(), "pmd"); basePmdDir.mkdirs(); - File cpdRequestFile = new File( basePmdDir, "cpdrequest.bin" ); - try ( ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( cpdRequestFile ) ) ) - { - out.writeObject( request ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + File cpdRequestFile = new File(basePmdDir, "cpdrequest.bin"); + try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(cpdRequestFile))) { + out.writeObject(request); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } String classpath = buildClasspath(); ProcessBuilder pb = new ProcessBuilder(); // note: using env variable instead of -cp cli arg to avoid length limitations under Windows - pb.environment().put( "CLASSPATH", classpath ); - pb.command().add( request.getJavaExecutable() ); - pb.command().add( CpdExecutor.class.getName() ); - pb.command().add( cpdRequestFile.getAbsolutePath() ); + pb.environment().put("CLASSPATH", classpath); + pb.command().add(request.getJavaExecutable()); + pb.command().add(CpdExecutor.class.getName()); + pb.command().add(cpdRequestFile.getAbsolutePath()); - LOG.debug( "Executing: CLASSPATH={}, command={}", classpath, pb.command() ); - try - { + LOG.debug("Executing: CLASSPATH={}, command={}", classpath, pb.command()); + try { final Process p = pb.start(); // Note: can't use pb.inheritIO(), since System.out/System.err has been modified after process start // and inheritIO would only inherit file handles, not the changed streams. - ProcessStreamHandler.start( p.getInputStream(), System.out ); - ProcessStreamHandler.start( p.getErrorStream(), System.err ); + ProcessStreamHandler.start(p.getInputStream(), System.out); + ProcessStreamHandler.start(p.getErrorStream(), System.err); int exit = p.waitFor(); - LOG.debug( "CpdExecutor exit code: {}", exit ); - if ( exit != 0 ) - { - throw new MavenReportException( "CpdExecutor exited with exit code " + exit ); + LOG.debug("CpdExecutor exit code: {}", exit); + if (exit != 0) { + throw new MavenReportException("CpdExecutor exited with exit code " + exit); } - return new CpdResult( new File( request.getTargetDirectory(), "cpd.xml" ), request.getOutputEncoding() ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - catch ( InterruptedException e ) - { + return new CpdResult(new File(request.getTargetDirectory(), "cpd.xml"), request.getOutputEncoding()); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new MavenReportException( e.getMessage(), e ); + throw new MavenReportException(e.getMessage(), e); } } @@ -140,22 +121,18 @@ private static CpdResult fork( CpdRequest request ) * * @param args */ - public static void main( String[] args ) - { - File requestFile = new File( args[0] ); - try ( ObjectInputStream in = new ObjectInputStream( new FileInputStream( requestFile ) ) ) - { + public static void main(String[] args) { + File requestFile = new File(args[0]); + try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(requestFile))) { CpdRequest request = (CpdRequest) in.readObject(); - CpdExecutor cpdExecutor = new CpdExecutor( request ); - cpdExecutor.setupLogLevel( request.getLogLevel() ); + CpdExecutor cpdExecutor = new CpdExecutor(request); + cpdExecutor.setupLogLevel(request.getLogLevel()); cpdExecutor.run(); - System.exit( 0 ); + System.exit(0); + } catch (IOException | ClassNotFoundException | MavenReportException e) { + LOG.error(e.getMessage(), e); } - catch ( IOException | ClassNotFoundException | MavenReportException e ) - { - LOG.error( e.getMessage(), e ); - } - System.exit( 1 ); + System.exit(1); } private final CpdRequest request; @@ -163,124 +140,94 @@ public static void main( String[] args ) /** Helper to exclude duplications from the result. */ private final ExcludeDuplicationsFromFile excludeDuplicationsFromFile = new ExcludeDuplicationsFromFile(); - public CpdExecutor( CpdRequest request ) - { - this.request = Objects.requireNonNull( request ); + public CpdExecutor(CpdRequest request) { + this.request = Objects.requireNonNull(request); } - private CpdResult run() throws MavenReportException - { - setupPmdLogging( request.isShowPmdLog(), request.getLogLevel() ); + private CpdResult run() throws MavenReportException { + setupPmdLogging(request.isShowPmdLog(), request.getLogLevel()); - try - { - excludeDuplicationsFromFile.loadExcludeFromFailuresData( request.getExcludeFromFailureFile() ); - } - catch ( MojoExecutionException e ) - { - throw new MavenReportException( "Error loading exclusions", e ); + try { + excludeDuplicationsFromFile.loadExcludeFromFailuresData(request.getExcludeFromFailureFile()); + } catch (MojoExecutionException e) { + throw new MavenReportException("Error loading exclusions", e); } CPDConfiguration cpdConfiguration = new CPDConfiguration(); - cpdConfiguration.setMinimumTileSize( request.getMinimumTokens() ); - + cpdConfiguration.setMinimumTileSize(request.getMinimumTokens()); + Language cpdLanguage; - if ( "java".equals ( request.getLanguage() ) || null == request.getLanguage() ) - { - cpdLanguage = new JavaLanguage( request.getLanguageProperties() ); - } - else if ( "javascript".equals( request.getLanguage() ) ) - { + if ("java".equals(request.getLanguage()) || null == request.getLanguage()) { + cpdLanguage = new JavaLanguage(request.getLanguageProperties()); + } else if ("javascript".equals(request.getLanguage())) { cpdLanguage = new EcmascriptLanguage(); - } - else if ( "jsp".equals( request.getLanguage() ) ) - { + } else if ("jsp".equals(request.getLanguage())) { cpdLanguage = new JSPLanguage(); + } else { + cpdLanguage = LanguageFactory.createLanguage(request.getLanguage(), request.getLanguageProperties()); } - else - { - cpdLanguage = LanguageFactory.createLanguage( request.getLanguage(), request.getLanguageProperties() ); - } - - cpdConfiguration.setLanguage( cpdLanguage ); - cpdConfiguration.setSourceEncoding( request.getSourceEncoding() ); - CPD cpd = new CPD( cpdConfiguration ); - try - { - cpd.add( request.getFiles() ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + cpdConfiguration.setLanguage(cpdLanguage); + cpdConfiguration.setSourceEncoding(request.getSourceEncoding()); + + CPD cpd = new CPD(cpdConfiguration); + try { + cpd.add(request.getFiles()); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } - LOG.debug( "Executing CPD..." ); + LOG.debug("Executing CPD..."); cpd.go(); - LOG.debug( "CPD finished." ); + LOG.debug("CPD finished."); // always create XML format. we need to output it even if the file list is empty or we have no duplications // so the "check" goals can check for violations - writeXmlReport( cpd ); + writeXmlReport(cpd); // html format is handled by maven site report, xml format has already been rendered String format = request.getFormat(); - if ( !"html".equals( format ) && !"xml".equals( format ) ) - { - writeFormattedReport( cpd ); + if (!"html".equals(format) && !"xml".equals(format)) { + writeFormattedReport(cpd); } - return new CpdResult( new File( request.getTargetDirectory(), "cpd.xml" ), request.getOutputEncoding() ); + return new CpdResult(new File(request.getTargetDirectory(), "cpd.xml"), request.getOutputEncoding()); } - private void writeXmlReport( CPD cpd ) throws MavenReportException - { - File targetFile = writeReport( cpd, new XMLRenderer( request.getOutputEncoding() ), "xml" ); - if ( request.isIncludeXmlInSite() ) - { - File siteDir = new File( request.getReportOutputDirectory() ); + private void writeXmlReport(CPD cpd) throws MavenReportException { + File targetFile = writeReport(cpd, new XMLRenderer(request.getOutputEncoding()), "xml"); + if (request.isIncludeXmlInSite()) { + File siteDir = new File(request.getReportOutputDirectory()); siteDir.mkdirs(); - try - { - FileUtils.copyFile( targetFile, new File( siteDir, "cpd.xml" ) ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + try { + FileUtils.copyFile(targetFile, new File(siteDir, "cpd.xml")); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } } } - private File writeReport( CPD cpd, CPDRenderer r, String extension ) throws MavenReportException - { - if ( r == null ) - { + private File writeReport(CPD cpd, CPDRenderer r, String extension) throws MavenReportException { + if (r == null) { return null; } - File targetDir = new File( request.getTargetDirectory() ); + File targetDir = new File(request.getTargetDirectory()); targetDir.mkdirs(); - File targetFile = new File( targetDir, "cpd." + extension ); - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( targetFile ), - request.getOutputEncoding() ) ) - { - r.render( filterMatches( cpd.getMatches() ), writer ); + File targetFile = new File(targetDir, "cpd." + extension); + try (Writer writer = new OutputStreamWriter(new FileOutputStream(targetFile), request.getOutputEncoding())) { + r.render(filterMatches(cpd.getMatches()), writer); writer.flush(); - } - catch ( IOException ioe ) - { - throw new MavenReportException( ioe.getMessage(), ioe ); + } catch (IOException ioe) { + throw new MavenReportException(ioe.getMessage(), ioe); } return targetFile; } - private void writeFormattedReport( CPD cpd ) - throws MavenReportException - { - CPDRenderer r = createRenderer( request.getFormat(), request.getOutputEncoding() ); - writeReport( cpd, r, request.getFormat() ); - - } + private void writeFormattedReport(CPD cpd) throws MavenReportException { + CPDRenderer r = createRenderer(request.getFormat(), request.getOutputEncoding()); + writeReport(cpd, r, request.getFormat()); + } /** * Create and return the correct renderer for the output type. @@ -288,60 +235,44 @@ private void writeFormattedReport( CPD cpd ) * @return the renderer based on the configured output * @throws org.apache.maven.reporting.MavenReportException if no renderer found for the output type */ - public static CPDRenderer createRenderer( String format, String outputEncoding ) - throws MavenReportException - { + public static CPDRenderer createRenderer(String format, String outputEncoding) throws MavenReportException { CPDRenderer renderer = null; - if ( "xml".equals( format ) ) - { - renderer = new XMLRenderer( outputEncoding ); - } - else if ( "csv".equals( format ) ) - { + if ("xml".equals(format)) { + renderer = new XMLRenderer(outputEncoding); + } else if ("csv".equals(format)) { renderer = new CSVRenderer(); - } - else if ( "txt".equals( format ) ) - { + } else if ("txt".equals(format)) { renderer = new SimpleRenderer(); - } - else if ( !"".equals( format ) && !"none".equals( format ) ) - { - try - { - renderer = (CPDRenderer) Class.forName( format ).getConstructor().newInstance(); - } - catch ( Exception e ) - { - throw new MavenReportException( "Can't find CPD custom format " + format + ": " - + e.getClass().getName(), e ); + } else if (!"".equals(format) && !"none".equals(format)) { + try { + renderer = (CPDRenderer) Class.forName(format).getConstructor().newInstance(); + } catch (Exception e) { + throw new MavenReportException( + "Can't find CPD custom format " + format + ": " + + e.getClass().getName(), + e); } } return renderer; } - private Iterator filterMatches( Iterator matches ) - { - LOG.debug( "Filtering duplications. Using " + excludeDuplicationsFromFile.countExclusions() - + " configured exclusions." ); + private Iterator filterMatches(Iterator matches) { + LOG.debug("Filtering duplications. Using " + excludeDuplicationsFromFile.countExclusions() + + " configured exclusions."); List filteredMatches = new ArrayList<>(); int excludedDuplications = 0; - while ( matches.hasNext() ) - { + while (matches.hasNext()) { Match match = matches.next(); - if ( excludeDuplicationsFromFile.isExcludedFromFailure( match ) ) - { + if (excludeDuplicationsFromFile.isExcludedFromFailure(match)) { excludedDuplications++; - } - else - { - filteredMatches.add( match ); + } else { + filteredMatches.add(match); } } - LOG.debug( "Excluded " + excludedDuplications + " duplications." ); + LOG.debug("Excluded " + excludedDuplications + " duplications."); return filteredMatches.iterator(); } - } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdRequest.java b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdRequest.java index 51c333a4..ebbff049 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdRequest.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.io.Serializable; @@ -29,13 +28,12 @@ /** * Data object to store all configuration options needed to execute CPD * as a separate process. - * + * *

This class is intended to be serialized and read back. - * + * *

Some properties might be optional and can be null. */ -public class CpdRequest implements Serializable -{ +public class CpdRequest implements Serializable { private static final long serialVersionUID = -7585852992660240668L; private String javaExecutable; @@ -56,143 +54,115 @@ public class CpdRequest implements Serializable private boolean includeXmlInSite; private String reportOutputDirectory; - public void setJavaExecutable( String javaExecutable ) - { + public void setJavaExecutable(String javaExecutable) { this.javaExecutable = javaExecutable; } - public void setMinimumTokens( int minimumTokens ) - { + public void setMinimumTokens(int minimumTokens) { this.minimumTokens = minimumTokens; } - public void setLanguage( String language ) - { + public void setLanguage(String language) { this.language = language; } - public void setLanguageProperties( Properties languageProperties ) - { + public void setLanguageProperties(Properties languageProperties) { this.languageProperties = languageProperties; } - public void setSourceEncoding( String sourceEncoding ) - { + public void setSourceEncoding(String sourceEncoding) { this.sourceEncoding = sourceEncoding; } - public void addFiles( Collection files ) - { - this.files.addAll( files ); + public void addFiles(Collection files) { + this.files.addAll(files); } - public void setExcludeFromFailureFile( String excludeFromFailureFile ) - { + public void setExcludeFromFailureFile(String excludeFromFailureFile) { this.excludeFromFailureFile = excludeFromFailureFile; } - public void setTargetDirectory( String targetDirectory ) - { + public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } - public void setOutputEncoding( String outputEncoding ) - { + public void setOutputEncoding(String outputEncoding) { this.outputEncoding = outputEncoding; } - public void setFormat( String format ) - { + public void setFormat(String format) { this.format = format; } - public void setIncludeXmlInSite( boolean includeXmlInSite ) - { + public void setIncludeXmlInSite(boolean includeXmlInSite) { this.includeXmlInSite = includeXmlInSite; } - public void setReportOutputDirectory( String reportOutputDirectory ) - { + public void setReportOutputDirectory(String reportOutputDirectory) { this.reportOutputDirectory = reportOutputDirectory; } - public void setShowPmdLog( boolean showPmdLog ) - { + public void setShowPmdLog(boolean showPmdLog) { this.showPmdLog = showPmdLog; } - public void setLogLevel( String logLevel ) - { + public void setLogLevel(String logLevel) { this.logLevel = logLevel; } - public String getJavaExecutable() - { + public String getJavaExecutable() { return javaExecutable; } - public int getMinimumTokens() - { + public int getMinimumTokens() { return minimumTokens; } - public String getLanguage() - { + public String getLanguage() { return language; } - public Properties getLanguageProperties() - { + public Properties getLanguageProperties() { return languageProperties; } - public String getSourceEncoding() - { + public String getSourceEncoding() { return sourceEncoding; } - public List getFiles() - { + public List getFiles() { return files; } - public String getExcludeFromFailureFile() - { + public String getExcludeFromFailureFile() { return excludeFromFailureFile; } - public String getTargetDirectory() - { + public String getTargetDirectory() { return targetDirectory; } - public String getOutputEncoding() - { + public String getOutputEncoding() { return outputEncoding; } - public String getFormat() - { + public String getFormat() { return format; } - public boolean isIncludeXmlInSite() - { + public boolean isIncludeXmlInSite() { return includeXmlInSite; } - public String getReportOutputDirectory() - { + public String getReportOutputDirectory() { return reportOutputDirectory; } - public boolean isShowPmdLog() - { + public boolean isShowPmdLog() { return showPmdLog; } - public String getLogLevel() - { + public String getLogLevel() { return logLevel; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdResult.java b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdResult.java index 6ea18ceb..283d1355 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/CpdResult.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/CpdResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.io.FileInputStream; @@ -34,36 +33,28 @@ /** * Provides access to the result of the CPD analysis. */ -public class CpdResult -{ +public class CpdResult { private final List duplications = new ArrayList<>(); - public CpdResult( File report, String encoding ) throws MavenReportException - { - loadResult( report, encoding ); + public CpdResult(File report, String encoding) throws MavenReportException { + loadResult(report, encoding); } - public List getDuplications() - { + public List getDuplications() { return duplications; } - public boolean hasDuplications() - { + public boolean hasDuplications() { return !duplications.isEmpty(); } - private void loadResult( File report, String encoding ) throws MavenReportException - { - try ( Reader reader1 = new InputStreamReader( new FileInputStream( report ), encoding ) ) - { + private void loadResult(File report, String encoding) throws MavenReportException { + try (Reader reader1 = new InputStreamReader(new FileInputStream(report), encoding)) { CpdXpp3Reader reader = new CpdXpp3Reader(); - CpdErrorDetail details = reader.read( reader1, false ); - duplications.addAll( details.getDuplications() ); - } - catch ( Exception e ) - { - throw new MavenReportException( e.getMessage(), e ); + CpdErrorDetail details = reader.read(reader1, false); + duplications.addAll(details.getDuplications()); + } catch (Exception e) { + throw new MavenReportException(e.getMessage(), e); } } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/Executor.java b/src/main/java/org/apache/maven/plugins/pmd/exec/Executor.java index 3b3679cc..d8f902c0 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/Executor.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/Executor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -42,9 +41,8 @@ import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; -abstract class Executor -{ - private static final Logger LOG = LoggerFactory.getLogger( Executor.class ); +abstract class Executor { + private static final Logger LOG = LoggerFactory.getLogger(Executor.class); /** * This holds a strong reference in case we configured the logger to @@ -53,137 +51,106 @@ abstract class Executor */ private java.util.logging.Logger julLogger; - protected void setupPmdLogging( boolean showPmdLog, String logLevel ) - { - if ( !showPmdLog ) - { + protected void setupPmdLogging(boolean showPmdLog, String logLevel) { + if (!showPmdLog) { return; } - java.util.logging.Logger logger = java.util.logging.Logger.getLogger( "net.sourceforge.pmd" ); + java.util.logging.Logger logger = java.util.logging.Logger.getLogger("net.sourceforge.pmd"); boolean slf4jBridgeAlreadyAdded = false; - for ( Handler handler : logger.getHandlers() ) - { - if ( handler instanceof SLF4JBridgeHandler ) - { + for (Handler handler : logger.getHandlers()) { + if (handler instanceof SLF4JBridgeHandler) { slf4jBridgeAlreadyAdded = true; break; } } - if ( slf4jBridgeAlreadyAdded ) - { + if (slf4jBridgeAlreadyAdded) { return; } SLF4JBridgeHandler handler = new SLF4JBridgeHandler(); SimpleFormatter formatter = new SimpleFormatter(); - handler.setFormatter( formatter ); - logger.setUseParentHandlers( false ); - logger.addHandler( handler ); - handler.setLevel( Level.ALL ); - logger.setLevel( Level.ALL ); + handler.setFormatter(formatter); + logger.setUseParentHandlers(false); + logger.addHandler(handler); + handler.setLevel(Level.ALL); + logger.setLevel(Level.ALL); julLogger = logger; - julLogger.fine( "Configured jul-to-slf4j bridge for " + logger.getName() ); + julLogger.fine("Configured jul-to-slf4j bridge for " + logger.getName()); } - protected void setupLogLevel( String logLevel ) - { + protected void setupLogLevel(String logLevel) { ILoggerFactory slf4jLoggerFactory = LoggerFactory.getILoggerFactory(); - Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory - .getConfiguration( slf4jLoggerFactory ); - if ( "debug".equals( logLevel ) ) - { - slf4jConfiguration - .setRootLoggerLevel( Slf4jConfiguration.Level.DEBUG ); - } - else if ( "info".equals( logLevel ) ) - { - slf4jConfiguration - .setRootLoggerLevel( Slf4jConfiguration.Level.INFO ); - } - else - { - slf4jConfiguration - .setRootLoggerLevel( Slf4jConfiguration.Level.ERROR ); + Slf4jConfiguration slf4jConfiguration = Slf4jConfigurationFactory.getConfiguration(slf4jLoggerFactory); + if ("debug".equals(logLevel)) { + slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.DEBUG); + } else if ("info".equals(logLevel)) { + slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.INFO); + } else { + slf4jConfiguration.setRootLoggerLevel(Slf4jConfiguration.Level.ERROR); } slf4jConfiguration.activate(); } - protected static String buildClasspath() - { + protected static String buildClasspath() { StringBuilder classpath = new StringBuilder(); // plugin classpath needs to come first ClassLoader pluginClassloader = Executor.class.getClassLoader(); - buildClasspath( classpath, pluginClassloader ); + buildClasspath(classpath, pluginClassloader); ClassLoader coreClassloader = ConsoleLogger.class.getClassLoader(); - buildClasspath( classpath, coreClassloader ); + buildClasspath(classpath, coreClassloader); return classpath.toString(); } - static void buildClasspath( StringBuilder classpath, ClassLoader cl ) - { - if ( cl instanceof URLClassLoader ) - { - for ( URL url : ( (URLClassLoader) cl ).getURLs() ) - { - if ( "file".equalsIgnoreCase( url.getProtocol() ) ) - { - try - { - String filename = URLDecoder.decode( url.getPath(), StandardCharsets.UTF_8.name() ); - classpath.append( new File( filename ).getPath() ).append( File.pathSeparatorChar ); - } - catch ( UnsupportedEncodingException e ) - { - LOG.warn( "Ignoring " + url + " in classpath due to UnsupportedEncodingException", e ); + static void buildClasspath(StringBuilder classpath, ClassLoader cl) { + if (cl instanceof URLClassLoader) { + for (URL url : ((URLClassLoader) cl).getURLs()) { + if ("file".equalsIgnoreCase(url.getProtocol())) { + try { + String filename = URLDecoder.decode(url.getPath(), StandardCharsets.UTF_8.name()); + classpath.append(new File(filename).getPath()).append(File.pathSeparatorChar); + } catch (UnsupportedEncodingException e) { + LOG.warn("Ignoring " + url + " in classpath due to UnsupportedEncodingException", e); } } } } } - protected static class ProcessStreamHandler implements Runnable - { + protected static class ProcessStreamHandler implements Runnable { private static final int BUFFER_SIZE = 8192; private final BufferedInputStream in; private final BufferedOutputStream out; - public static void start( InputStream in, OutputStream out ) - { - Thread t = new Thread( new ProcessStreamHandler( in, out ) ); + public static void start(InputStream in, OutputStream out) { + Thread t = new Thread(new ProcessStreamHandler(in, out)); t.start(); } - private ProcessStreamHandler( InputStream in, OutputStream out ) - { - this.in = new BufferedInputStream( in ); - this.out = new BufferedOutputStream( out ); + private ProcessStreamHandler(InputStream in, OutputStream out) { + this.in = new BufferedInputStream(in); + this.out = new BufferedOutputStream(out); } @Override - public void run() - { + public void run() { byte[] buffer = new byte[BUFFER_SIZE]; - try - { - int count = in.read( buffer ); - while ( count != -1 ) - { - out.write( buffer, 0, count ); + try { + int count = in.read(buffer); + while (count != -1) { + out.write(buffer, 0, count); out.flush(); - count = in.read( buffer ); + count = in.read(buffer); } out.flush(); - } - catch ( IOException e ) - { - LOG.error( e.getMessage(), e ); + } catch (IOException e) { + LOG.error(e.getMessage(), e); } } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdExecutor.java b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdExecutor.java index cc25c80e..8e96bf41 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdExecutor.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.Closeable; import java.io.File; @@ -32,15 +31,8 @@ import java.util.List; import java.util.Objects; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.pmd.ExcludeViolationsFromFile; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.util.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.PMDConfiguration; +import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RulePriority; import net.sourceforge.pmd.RuleSetLoadException; @@ -59,82 +51,71 @@ import net.sourceforge.pmd.renderers.TextRenderer; import net.sourceforge.pmd.renderers.XMLRenderer; import net.sourceforge.pmd.util.Predicate; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.pmd.ExcludeViolationsFromFile; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.util.FileUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Executes PMD with the configuration provided via {@link PmdRequest}. */ -public class PmdExecutor extends Executor -{ - private static final Logger LOG = LoggerFactory.getLogger( PmdExecutor.class ); - - public static PmdResult execute( PmdRequest request ) throws MavenReportException - { - if ( request.getJavaExecutable() != null ) - { - return fork( request ); +public class PmdExecutor extends Executor { + private static final Logger LOG = LoggerFactory.getLogger(PmdExecutor.class); + + public static PmdResult execute(PmdRequest request) throws MavenReportException { + if (request.getJavaExecutable() != null) { + return fork(request); } // make sure the class loaders are correct and call this in the same JVM ClassLoader origLoader = Thread.currentThread().getContextClassLoader(); - try - { - Thread.currentThread().setContextClassLoader( PmdExecutor.class.getClassLoader() ); - PmdExecutor executor = new PmdExecutor( request ); + try { + Thread.currentThread().setContextClassLoader(PmdExecutor.class.getClassLoader()); + PmdExecutor executor = new PmdExecutor(request); return executor.run(); - } - finally - { - Thread.currentThread().setContextClassLoader( origLoader ); + } finally { + Thread.currentThread().setContextClassLoader(origLoader); } } - private static PmdResult fork( PmdRequest request ) - throws MavenReportException - { - File basePmdDir = new File ( request.getTargetDirectory(), "pmd" ); + private static PmdResult fork(PmdRequest request) throws MavenReportException { + File basePmdDir = new File(request.getTargetDirectory(), "pmd"); basePmdDir.mkdirs(); - File pmdRequestFile = new File( basePmdDir, "pmdrequest.bin" ); - try ( ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream( pmdRequestFile ) ) ) - { - out.writeObject( request ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + File pmdRequestFile = new File(basePmdDir, "pmdrequest.bin"); + try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(pmdRequestFile))) { + out.writeObject(request); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } String classpath = buildClasspath(); ProcessBuilder pb = new ProcessBuilder(); // note: using env variable instead of -cp cli arg to avoid length limitations under Windows - pb.environment().put( "CLASSPATH", classpath ); - pb.command().add( request.getJavaExecutable() ); - pb.command().add( PmdExecutor.class.getName() ); - pb.command().add( pmdRequestFile.getAbsolutePath() ); - - LOG.debug( "Executing: CLASSPATH={}, command={}", classpath, pb.command() ); - try - { + pb.environment().put("CLASSPATH", classpath); + pb.command().add(request.getJavaExecutable()); + pb.command().add(PmdExecutor.class.getName()); + pb.command().add(pmdRequestFile.getAbsolutePath()); + + LOG.debug("Executing: CLASSPATH={}, command={}", classpath, pb.command()); + try { final Process p = pb.start(); // Note: can't use pb.inheritIO(), since System.out/System.err has been modified after process start // and inheritIO would only inherit file handles, not the changed streams. - ProcessStreamHandler.start( p.getInputStream(), System.out ); - ProcessStreamHandler.start( p.getErrorStream(), System.err ); + ProcessStreamHandler.start(p.getInputStream(), System.out); + ProcessStreamHandler.start(p.getErrorStream(), System.err); int exit = p.waitFor(); - LOG.debug( "PmdExecutor exit code: {}", exit ); - if ( exit != 0 ) - { - throw new MavenReportException( "PmdExecutor exited with exit code " + exit ); + LOG.debug("PmdExecutor exit code: {}", exit); + if (exit != 0) { + throw new MavenReportException("PmdExecutor exited with exit code " + exit); } - return new PmdResult( new File( request.getTargetDirectory(), "pmd.xml" ), request.getOutputEncoding() ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - catch ( InterruptedException e ) - { + return new PmdResult(new File(request.getTargetDirectory(), "pmd.xml"), request.getOutputEncoding()); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); + } catch (InterruptedException e) { Thread.currentThread().interrupt(); - throw new MavenReportException( e.getMessage(), e ); + throw new MavenReportException(e.getMessage(), e); } } @@ -149,162 +130,128 @@ private static PmdResult fork( PmdRequest request ) * * @param args */ - public static void main( String[] args ) - { - File requestFile = new File( args[0] ); - try ( ObjectInputStream in = new ObjectInputStream( new FileInputStream( requestFile ) ) ) - { + public static void main(String[] args) { + File requestFile = new File(args[0]); + try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(requestFile))) { PmdRequest request = (PmdRequest) in.readObject(); - PmdExecutor pmdExecutor = new PmdExecutor( request ); - pmdExecutor.setupLogLevel( request.getLogLevel() ); + PmdExecutor pmdExecutor = new PmdExecutor(request); + pmdExecutor.setupLogLevel(request.getLogLevel()); pmdExecutor.run(); - System.exit( 0 ); - } - catch ( IOException | ClassNotFoundException | MavenReportException e ) - { - LOG.error( e.getMessage(), e ); + System.exit(0); + } catch (IOException | ClassNotFoundException | MavenReportException e) { + LOG.error(e.getMessage(), e); } - System.exit( 1 ); + System.exit(1); } private final PmdRequest request; - public PmdExecutor( PmdRequest request ) - { - this.request = Objects.requireNonNull( request ); + public PmdExecutor(PmdRequest request) { + this.request = Objects.requireNonNull(request); } - private PmdResult run() throws MavenReportException - { - setupPmdLogging( request.isShowPmdLog(), request.getLogLevel() ); + private PmdResult run() throws MavenReportException { + setupPmdLogging(request.isShowPmdLog(), request.getLogLevel()); PMDConfiguration configuration = new PMDConfiguration(); LanguageVersion languageVersion = null; - Language language = LanguageRegistry - .findLanguageByTerseName( request.getLanguage() != null ? request.getLanguage() : "java" ); - if ( language == null ) - { - throw new MavenReportException( "Unsupported language: " + request.getLanguage() ); - } - if ( request.getLanguageVersion() != null ) - { - languageVersion = language.getVersion( request.getLanguageVersion() ); - if ( languageVersion == null ) - { - throw new MavenReportException( "Unsupported targetJdk value '" + request.getLanguageVersion() + "'." ); + Language language = LanguageRegistry.findLanguageByTerseName( + request.getLanguage() != null ? request.getLanguage() : "java"); + if (language == null) { + throw new MavenReportException("Unsupported language: " + request.getLanguage()); + } + if (request.getLanguageVersion() != null) { + languageVersion = language.getVersion(request.getLanguageVersion()); + if (languageVersion == null) { + throw new MavenReportException("Unsupported targetJdk value '" + request.getLanguageVersion() + "'."); } - } - else - { + } else { languageVersion = language.getDefaultVersion(); } - LOG.debug( "Using language " + languageVersion ); - configuration.setDefaultLanguageVersion( languageVersion ); + LOG.debug("Using language " + languageVersion); + configuration.setDefaultLanguageVersion(languageVersion); - if ( request.getSourceEncoding() != null ) - { - configuration.setSourceEncoding( request.getSourceEncoding() ); + if (request.getSourceEncoding() != null) { + configuration.setSourceEncoding(request.getSourceEncoding()); } - configuration.prependAuxClasspath( request.getAuxClasspath() ); + configuration.prependAuxClasspath(request.getAuxClasspath()); - if ( request.getSuppressMarker() != null ) - { - configuration.setSuppressMarker( request.getSuppressMarker() ); - } - if ( request.getAnalysisCacheLocation() != null ) - { - configuration.setAnalysisCacheLocation( request.getAnalysisCacheLocation() ); - LOG.debug( "Using analysis cache location: " + request.getAnalysisCacheLocation() ); + if (request.getSuppressMarker() != null) { + configuration.setSuppressMarker(request.getSuppressMarker()); } - else - { - configuration.setIgnoreIncrementalAnalysis( true ); + if (request.getAnalysisCacheLocation() != null) { + configuration.setAnalysisCacheLocation(request.getAnalysisCacheLocation()); + LOG.debug("Using analysis cache location: " + request.getAnalysisCacheLocation()); + } else { + configuration.setIgnoreIncrementalAnalysis(true); } - configuration.setRuleSets( request.getRulesets() ); - configuration.setMinimumPriority( RulePriority.valueOf( request.getMinimumPriority() ) ); - if ( request.getBenchmarkOutputLocation() != null ) - { - configuration.setBenchmark( true ); + configuration.setRuleSets(request.getRulesets()); + configuration.setMinimumPriority(RulePriority.valueOf(request.getMinimumPriority())); + if (request.getBenchmarkOutputLocation() != null) { + configuration.setBenchmark(true); } List files = request.getFiles(); Report report = null; - if ( request.getRulesets().isEmpty() ) - { - LOG.debug( "Skipping PMD execution as no rulesets are defined." ); - } - else - { - if ( request.getBenchmarkOutputLocation() != null ) - { + if (request.getRulesets().isEmpty()) { + LOG.debug("Skipping PMD execution as no rulesets are defined."); + } else { + if (request.getBenchmarkOutputLocation() != null) { TimeTracker.startGlobalTracking(); } - try - { - report = processFilesWithPMD( configuration, files ); - } - finally - { - if ( request.getAuxClasspath() != null ) - { + try { + report = processFilesWithPMD(configuration, files); + } finally { + if (request.getAuxClasspath() != null) { ClassLoader classLoader = configuration.getClassLoader(); - if ( classLoader instanceof Closeable ) - { + if (classLoader instanceof Closeable) { Closeable closeable = (Closeable) classLoader; - try - { + try { closeable.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } } - if ( request.getBenchmarkOutputLocation() != null ) - { + if (request.getBenchmarkOutputLocation() != null) { TimingReport timingReport = TimeTracker.stopGlobalTracking(); - writeBenchmarkReport( timingReport, request.getBenchmarkOutputLocation(), - request.getOutputEncoding() ); + writeBenchmarkReport( + timingReport, request.getBenchmarkOutputLocation(), request.getOutputEncoding()); } } } - if ( report != null && !report.getProcessingErrors().isEmpty() ) - { + if (report != null && !report.getProcessingErrors().isEmpty()) { List errors = report.getProcessingErrors(); - if ( !request.isSkipPmdError() ) - { - LOG.error( "PMD processing errors:" ); - LOG.error( getErrorsAsString( errors, request.isDebugEnabled() ) ); - throw new MavenReportException( "Found " + errors.size() - + " PMD processing errors" ); + if (!request.isSkipPmdError()) { + LOG.error("PMD processing errors:"); + LOG.error(getErrorsAsString(errors, request.isDebugEnabled())); + throw new MavenReportException("Found " + errors.size() + " PMD processing errors"); } - LOG.warn( "There are {} PMD processing errors:", errors.size() ); - LOG.warn( getErrorsAsString( errors, request.isDebugEnabled() ) ); + LOG.warn("There are {} PMD processing errors:", errors.size()); + LOG.warn(getErrorsAsString(errors, request.isDebugEnabled())); } - report = removeExcludedViolations( report ); + report = removeExcludedViolations(report); // always write XML report, as this might be needed by the check mojo // we need to output it even if the file list is empty or we have no violations // so the "check" goals can check for violations - writeXmlReport( report ); + writeXmlReport(report); // write any other format except for xml and html. xml has just been produced. // html format is produced by the maven site formatter. Excluding html here // avoids using PMD's own html formatter, which doesn't fit into the maven site // considering the html/css styling String format = request.getFormat(); - if ( !"html".equals( format ) && !"xml".equals( format ) ) - { - writeFormattedReport( report ); + if (!"html".equals(format) && !"xml".equals(format)) { + writeFormattedReport(report); } - return new PmdResult( new File( request.getTargetDirectory(), "pmd.xml" ), request.getOutputEncoding() ); + return new PmdResult(new File(request.getTargetDirectory(), "pmd.xml"), request.getOutputEncoding()); } /** @@ -312,68 +259,52 @@ private PmdResult run() throws MavenReportException * @param withDetails if true then add the error details additionally (contains e.g. the stacktrace) * @return the errors as string */ - private String getErrorsAsString( List errors, boolean withDetails ) - { - List errorsAsString = new ArrayList<>( errors.size() ); - for ( Report.ProcessingError error : errors ) - { - errorsAsString.add( error.getFile() + ": " + error.getMsg() ); - if ( withDetails ) - { - errorsAsString.add( error.getDetail() ); + private String getErrorsAsString(List errors, boolean withDetails) { + List errorsAsString = new ArrayList<>(errors.size()); + for (Report.ProcessingError error : errors) { + errorsAsString.add(error.getFile() + ": " + error.getMsg()); + if (withDetails) { + errorsAsString.add(error.getDetail()); } } - return String.join( System.lineSeparator(), errorsAsString ); + return String.join(System.lineSeparator(), errorsAsString); } - private void writeBenchmarkReport( TimingReport timingReport, String benchmarkOutputLocation, String encoding ) - { - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( benchmarkOutputLocation ), encoding ) ) - { + private void writeBenchmarkReport(TimingReport timingReport, String benchmarkOutputLocation, String encoding) { + try (Writer writer = new OutputStreamWriter(new FileOutputStream(benchmarkOutputLocation), encoding)) { final TimingReportRenderer renderer = new TextTimingReportRenderer(); - renderer.render( timingReport, writer ); - } - catch ( IOException e ) - { - LOG.error( "Unable to generate benchmark file: {}", benchmarkOutputLocation, e ); + renderer.render(timingReport, writer); + } catch (IOException e) { + LOG.error("Unable to generate benchmark file: {}", benchmarkOutputLocation, e); } } - private Report processFilesWithPMD( PMDConfiguration pmdConfiguration, List files ) - throws MavenReportException - { + private Report processFilesWithPMD(PMDConfiguration pmdConfiguration, List files) + throws MavenReportException { Report report = null; - RuleSetLoader rulesetLoader = RuleSetLoader.fromPmdConfig( pmdConfiguration ) - .warnDeprecated( true ); - try - { + RuleSetLoader rulesetLoader = + RuleSetLoader.fromPmdConfig(pmdConfiguration).warnDeprecated(true); + try { // load the ruleset once to log out any deprecated rules as warnings - rulesetLoader.loadFromResources( pmdConfiguration.getRuleSetPaths() ); - } - catch ( RuleSetLoadException e1 ) - { - throw new MavenReportException( "The ruleset could not be loaded", e1 ); + rulesetLoader.loadFromResources(pmdConfiguration.getRuleSetPaths()); + } catch (RuleSetLoadException e1) { + throw new MavenReportException("The ruleset could not be loaded", e1); } - try ( PmdAnalysis pmdAnalysis = PmdAnalysis.create( pmdConfiguration ) ) - { - for ( File file : files ) - { - pmdAnalysis.files().addFile( file.toPath() ); + try (PmdAnalysis pmdAnalysis = PmdAnalysis.create(pmdConfiguration)) { + for (File file : files) { + pmdAnalysis.files().addFile(file.toPath()); } - LOG.debug( "Executing PMD..." ); + LOG.debug("Executing PMD..."); report = pmdAnalysis.performAnalysisAndCollectReport(); - LOG.debug( "PMD finished. Found {} violations.", report.getViolations().size() ); - } - catch ( Exception e ) - { + LOG.debug( + "PMD finished. Found {} violations.", report.getViolations().size()); + } catch (Exception e) { String message = "Failure executing PMD: " + e.getLocalizedMessage(); - if ( !request.isSkipPmdError() ) - { - throw new MavenReportException( message, e ); + if (!request.isSkipPmdError()) { + throw new MavenReportException(message, e); } - LOG.warn( message, e ); - + LOG.warn(message, e); } return report; } @@ -385,51 +316,39 @@ private Report processFilesWithPMD( PMDConfiguration pmdConfiguration, List() - { + Report filtered = report.filterViolations(new Predicate() { @Override - public boolean test( RuleViolation ruleViolation ) - { - return !excludeFromFile.isExcludedFromFailure( ruleViolation ); + public boolean test(RuleViolation ruleViolation) { + return !excludeFromFile.isExcludedFromFailure(ruleViolation); } - } ); + }); - int numberOfExcludedViolations = violationsBefore - filtered.getViolations().size(); - LOG.debug( "Excluded {} violations.", numberOfExcludedViolations ); + int numberOfExcludedViolations = + violationsBefore - filtered.getViolations().size(); + LOG.debug("Excluded {} violations.", numberOfExcludedViolations); return filtered; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdRequest.java b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdRequest.java index 0c3a5e9b..d1a80998 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdRequest.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.io.Serializable; @@ -28,13 +27,12 @@ /** * Data object to store all configuration options needed to execute PMD * as a separate process. - * + * *

This class is intended to be serialized and read back. - * + * *

Some properties might be optional and can be null. */ -public class PmdRequest implements Serializable -{ +public class PmdRequest implements Serializable { private static final long serialVersionUID = -6324416880563476455L; private String javaExecutable; @@ -67,223 +65,172 @@ public class PmdRequest implements Serializable * @param language the language * @param targetJdk the language version, optional, can be null */ - public void setLanguageAndVersion( String language, String targetJdk ) - { - if ( "java".equals( language ) || null == language ) - { + public void setLanguageAndVersion(String language, String targetJdk) { + if ("java".equals(language) || null == language) { this.language = "java"; this.languageVersion = targetJdk; - } - else if ( "javascript".equals( language ) || "ecmascript".equals( language ) ) - { + } else if ("javascript".equals(language) || "ecmascript".equals(language)) { this.language = "ecmascript"; - } - else if ( "jsp".equals( language ) ) - { + } else if ("jsp".equals(language)) { this.language = "jsp"; - } - else - { + } else { this.language = language; } } - public void setJavaExecutable( String javaExecutable ) - { + public void setJavaExecutable(String javaExecutable) { this.javaExecutable = javaExecutable; } - public void setMinimumPriority( int minimumPriority ) - { + public void setMinimumPriority(int minimumPriority) { this.minimumPriority = minimumPriority; } - public void setAuxClasspath( String auxClasspath ) - { + public void setAuxClasspath(String auxClasspath) { this.auxClasspath = auxClasspath; } - public void setSuppressMarker( String suppressMarker ) - { + public void setSuppressMarker(String suppressMarker) { this.suppressMarker = suppressMarker; } - public void setAnalysisCacheLocation( String analysisCacheLocation ) - { + public void setAnalysisCacheLocation(String analysisCacheLocation) { this.analysisCacheLocation = analysisCacheLocation; } - public void setRulesets( List rulesets ) - { + public void setRulesets(List rulesets) { this.rulesets = rulesets; } - public void setSourceEncoding( String sourceEncoding ) - { + public void setSourceEncoding(String sourceEncoding) { this.sourceEncoding = sourceEncoding; } - public void addFiles( Collection files ) - { - this.files.addAll( files ); + public void addFiles(Collection files) { + this.files.addAll(files); } - public void setBenchmarkOutputLocation( String benchmarkOutputLocation ) - { + public void setBenchmarkOutputLocation(String benchmarkOutputLocation) { this.benchmarkOutputLocation = benchmarkOutputLocation; } - public void setTargetDirectory( String targetDirectory ) - { + public void setTargetDirectory(String targetDirectory) { this.targetDirectory = targetDirectory; } - public void setOutputEncoding( String outputEncoding ) - { + public void setOutputEncoding(String outputEncoding) { this.outputEncoding = outputEncoding; } - public void setFormat( String format ) - { + public void setFormat(String format) { this.format = format; } - public void setShowPmdLog( boolean showPmdLog ) - { + public void setShowPmdLog(boolean showPmdLog) { this.showPmdLog = showPmdLog; } - public void setLogLevel( String logLevel ) - { + public void setLogLevel(String logLevel) { this.logLevel = logLevel; } - public void setSkipPmdError( boolean skipPmdError ) - { + public void setSkipPmdError(boolean skipPmdError) { this.skipPmdError = skipPmdError; } - public void setIncludeXmlInSite( boolean includeXmlInSite ) - { + public void setIncludeXmlInSite(boolean includeXmlInSite) { this.includeXmlInSite = includeXmlInSite; } - public void setReportOutputDirectory( String reportOutputDirectory ) - { + public void setReportOutputDirectory(String reportOutputDirectory) { this.reportOutputDirectory = reportOutputDirectory; } - public void setExcludeFromFailureFile( String excludeFromFailureFile ) - { + public void setExcludeFromFailureFile(String excludeFromFailureFile) { this.excludeFromFailureFile = excludeFromFailureFile; } - - - - - public String getJavaExecutable() - { + public String getJavaExecutable() { return javaExecutable; } - public String getLanguage() - { + public String getLanguage() { return language; } - public String getLanguageVersion() - { + public String getLanguageVersion() { return languageVersion; } - public int getMinimumPriority() - { + public int getMinimumPriority() { return minimumPriority; } - public String getAuxClasspath() - { + public String getAuxClasspath() { return auxClasspath; } - public String getSuppressMarker() - { + public String getSuppressMarker() { return suppressMarker; } - public String getAnalysisCacheLocation() - { + public String getAnalysisCacheLocation() { return analysisCacheLocation; } - public List getRulesets() - { + public List getRulesets() { return rulesets; } - public String getSourceEncoding() - { + public String getSourceEncoding() { return sourceEncoding; } - public List getFiles() - { + public List getFiles() { return files; } - public String getBenchmarkOutputLocation() - { + public String getBenchmarkOutputLocation() { return benchmarkOutputLocation; } - public String getTargetDirectory() - { + public String getTargetDirectory() { return targetDirectory; } - public String getOutputEncoding() - { + public String getOutputEncoding() { return outputEncoding; } - public String getFormat() - { + public String getFormat() { return format; } - public boolean isShowPmdLog() - { + public boolean isShowPmdLog() { return showPmdLog; } - public String getLogLevel() - { + public String getLogLevel() { return logLevel; } - public boolean isDebugEnabled() - { - return "debug".equals( logLevel ); + public boolean isDebugEnabled() { + return "debug".equals(logLevel); } - public boolean isSkipPmdError() - { + public boolean isSkipPmdError() { return skipPmdError; } - public boolean isIncludeXmlInSite() - { + public boolean isIncludeXmlInSite() { return includeXmlInSite; } - public String getReportOutputDirectory() - { + public String getReportOutputDirectory() { return reportOutputDirectory; } - public String getExcludeFromFailureFile() - { + public String getExcludeFromFailureFile() { return excludeFromFailureFile; } } diff --git a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdResult.java b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdResult.java index 667b8491..15cbe58e 100644 --- a/src/main/java/org/apache/maven/plugins/pmd/exec/PmdResult.java +++ b/src/main/java/org/apache/maven/plugins/pmd/exec/PmdResult.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.io.FileInputStream; @@ -40,103 +39,81 @@ /** * Provides access to the result of the pmd analysis. */ -public class PmdResult -{ +public class PmdResult { private final List processingErrors = new ArrayList<>(); private final List violations = new ArrayList<>(); private final List suppressedViolations = new ArrayList<>(); public static final PmdResult EMPTY = new PmdResult(); - private PmdResult() - { - } + private PmdResult() {} - public PmdResult( File pmdFile, String encoding ) throws MavenReportException - { - loadResult( pmdFile, encoding ); + public PmdResult(File pmdFile, String encoding) throws MavenReportException { + loadResult(pmdFile, encoding); } - public boolean hasViolations() - { + public boolean hasViolations() { return !violations.isEmpty(); } - private void loadResult( File pmdFile, String encoding ) throws MavenReportException - { - try ( Reader reader1 = new BomFilter( encoding, new InputStreamReader( - new FileInputStream( pmdFile ), encoding ) ) ) - { + private void loadResult(File pmdFile, String encoding) throws MavenReportException { + try (Reader reader1 = new BomFilter(encoding, new InputStreamReader(new FileInputStream(pmdFile), encoding))) { PmdXpp3Reader reader = new PmdXpp3Reader(); - PmdErrorDetail details = reader.read( reader1, false ); - processingErrors.addAll( details.getErrors() ); - suppressedViolations.addAll( details.getSuppressedViolations() ); + PmdErrorDetail details = reader.read(reader1, false); + processingErrors.addAll(details.getErrors()); + suppressedViolations.addAll(details.getSuppressedViolations()); - for ( PmdFile file : details.getFiles() ) - { + for (PmdFile file : details.getFiles()) { String filename = file.getName(); - for ( Violation violation : file.getViolations() ) - { - violation.setFileName( filename ); - violations.add( violation ); + for (Violation violation : file.getViolations()) { + violation.setFileName(filename); + violations.add(violation); } } - } - catch ( Exception e ) - { - throw new MavenReportException( e.getMessage(), e ); + } catch (Exception e) { + throw new MavenReportException(e.getMessage(), e); } } // Note: This seems to be a bug in PMD's XMLRenderer. The BOM is rendered multiple times. // once at the beginning of the file, which is Ok, but also in the middle of the file. // This filter just skips all BOMs if the encoding is not UTF-8 - private static class BomFilter extends FilterReader - { + private static class BomFilter extends FilterReader { private static final char BOM = '\uFEFF'; private final boolean filter; - BomFilter( String encoding, Reader in ) - { - super( in ); - filter = !"UTF-8".equalsIgnoreCase( encoding ); + BomFilter(String encoding, Reader in) { + super(in); + filter = !"UTF-8".equalsIgnoreCase(encoding); } @Override - public int read() throws IOException - { + public int read() throws IOException { int c = super.read(); - if ( !filter ) - { + if (!filter) { return c; } - while ( c != -1 && c == BOM ) - { + while (c != -1 && c == BOM) { c = super.read(); } return c; } @Override - public int read( char[] cbuf, int off, int len ) throws IOException - { - int count = super.read( cbuf, off, len ); + public int read(char[] cbuf, int off, int len) throws IOException { + int count = super.read(cbuf, off, len); - if ( !filter ) - { + if (!filter) { return count; } - if ( count != -1 ) - { - for ( int i = off; i < off + count; i++ ) - { - if ( cbuf[i] == BOM ) - { + if (count != -1) { + for (int i = off; i < off + count; i++) { + if (cbuf[i] == BOM) { // shift the content one char to the left - System.arraycopy( cbuf, i + 1, cbuf, i, off + count - 1 - i ); + System.arraycopy(cbuf, i + 1, cbuf, i, off + count - 1 - i); count--; } } @@ -145,18 +122,15 @@ public int read( char[] cbuf, int off, int len ) throws IOException } } - public Collection getViolations() - { + public Collection getViolations() { return violations; } - public Collection getSuppressedViolations() - { + public Collection getSuppressedViolations() { return suppressedViolations; } - public Collection getErrors() - { + public Collection getErrors() { return processingErrors; } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/AbstractPmdReportTestCase.java b/src/test/java/org/apache/maven/plugins/pmd/AbstractPmdReportTestCase.java index f0d5524c..fce2159b 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/AbstractPmdReportTestCase.java +++ b/src/test/java/org/apache/maven/plugins/pmd/AbstractPmdReportTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -41,9 +40,7 @@ * @version $Id$ * @since 2.5 */ -public abstract class AbstractPmdReportTestCase - extends AbstractMojoTestCase -{ +public abstract class AbstractPmdReportTestCase extends AbstractMojoTestCase { private ArtifactStubFactory artifactStubFactory; /** @@ -52,13 +49,11 @@ public abstract class AbstractPmdReportTestCase private MavenProject testMavenProject; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - CapturingPrintStream.init( true ); + CapturingPrintStream.init(true); - artifactStubFactory = new DependencyArtifactStubFactory( getTestFile( "target" ), true, false ); + artifactStubFactory = new DependencyArtifactStubFactory(getTestFile("target"), true, false); artifactStubFactory.getWorkingDir().mkdirs(); } @@ -67,8 +62,7 @@ protected void setUp() * * @return the maven project */ - protected MavenProject getTestMavenProject() - { + protected MavenProject getTestMavenProject() { return testMavenProject; } @@ -79,15 +73,13 @@ protected MavenProject getTestMavenProject() * @return the generated report as file * @throws IOException if the return file doesnt exist */ - protected File getGeneratedReport( String name ) - throws IOException - { - String outputDirectory = getBasedir() + "/target/test/unit/" + getTestMavenProject().getArtifactId(); - - File report = new File( outputDirectory, name ); - if ( !report.exists() ) - { - throw new IOException( "File not found. Attempted: " + report ); + protected File getGeneratedReport(String name) throws IOException { + String outputDirectory = + getBasedir() + "/target/test/unit/" + getTestMavenProject().getArtifactId(); + + File report = new File(outputDirectory, name); + if (!report.exists()) { + throw new IOException("File not found. Attempted: " + report); } return report; @@ -101,58 +93,51 @@ protected File getGeneratedReport( String name ) * @return the generated HTML file * @throws Exception if any */ - protected File generateReport( String goal, String pluginXml ) - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/unit/" + pluginXml ); - AbstractPmdReport mojo = createReportMojo( goal, pluginXmlFile ); - return generateReport( mojo, pluginXmlFile ); + protected File generateReport(String goal, String pluginXml) throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/unit/" + pluginXml); + AbstractPmdReport mojo = createReportMojo(goal, pluginXmlFile); + return generateReport(mojo, pluginXmlFile); } - protected AbstractPmdReport createReportMojo( String goal, File pluginXmlFile ) - throws Exception - { - AbstractPmdReport mojo = (AbstractPmdReport) lookupMojo( goal, pluginXmlFile ); - assertNotNull( "Mojo not found.", mojo ); + protected AbstractPmdReport createReportMojo(String goal, File pluginXmlFile) throws Exception { + AbstractPmdReport mojo = (AbstractPmdReport) lookupMojo(goal, pluginXmlFile); + assertNotNull("Mojo not found.", mojo); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( newMavenSession( new MavenProjectStub() ) ); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(newMavenSession(new MavenProjectStub())); DefaultRepositorySystemSession repoSession = - (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); - repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repoSession, new LocalRepository( artifactStubFactory.getWorkingDir() ) ) ); + (DefaultRepositorySystemSession) legacySupport.getRepositorySession(); + repoSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repoSession, new LocalRepository(artifactStubFactory.getWorkingDir()))); - setVariableValueToObject( mojo, "session", legacySupport.getSession() ); - setVariableValueToObject( mojo, "remoteRepositories", mojo.getProject().getRemoteArtifactRepositories() ); + setVariableValueToObject(mojo, "session", legacySupport.getSession()); + setVariableValueToObject(mojo, "remoteRepositories", mojo.getProject().getRemoteArtifactRepositories()); return mojo; } - protected File generateReport( AbstractPmdReport mojo, File pluginXmlFile ) - throws Exception - { + protected File generateReport(AbstractPmdReport mojo, File pluginXmlFile) throws Exception { mojo.execute(); - ProjectBuilder builder = lookup( ProjectBuilder.class ); + ProjectBuilder builder = lookup(ProjectBuilder.class); ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(); - buildingRequest.setRepositorySession( lookup( LegacySupport.class ).getRepositorySession() ); + buildingRequest.setRepositorySession(lookup(LegacySupport.class).getRepositorySession()); - testMavenProject = builder.build( pluginXmlFile, buildingRequest ).getProject(); + testMavenProject = builder.build(pluginXmlFile, buildingRequest).getProject(); File outputDir = mojo.getReportOutputDirectory(); String filename = mojo.getOutputName() + ".html"; - return new File( outputDir, filename ); + return new File(outputDir, filename); } /** * Read the contents of the specified file object into a string */ - protected String readFile( File pmdTestDir, String fileName ) throws IOException - { - return new String( Files.readAllBytes( pmdTestDir.toPath().resolve( fileName ) ) ); + protected String readFile(File pmdTestDir, String fileName) throws IOException { + return new String(Files.readAllBytes(pmdTestDir.toPath().resolve(fileName))); } - /** * Checks, whether the string contained is contained in * the given text ignoring case. @@ -161,8 +146,7 @@ protected String readFile( File pmdTestDir, String fileName ) throws IOException * @param contains the string, the should be searched * @return true if the string is contained, otherwise false. */ - public static boolean lowerCaseContains( String text, String contains ) - { - return text.toLowerCase( Locale.ROOT ).contains( contains.toLowerCase( Locale.ROOT ) ); + public static boolean lowerCaseContains(String text, String contains) { + return text.toLowerCase(Locale.ROOT).contains(contains.toLowerCase(Locale.ROOT)); } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/CapturingPrintStream.java b/src/test/java/org/apache/maven/plugins/pmd/CapturingPrintStream.java index 272a302b..f22d8fa5 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/CapturingPrintStream.java +++ b/src/test/java/org/apache/maven/plugins/pmd/CapturingPrintStream.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.PrintStream; @@ -30,54 +29,44 @@ class CapturingPrintStream extends PrintStream { private boolean quiet; private StringBuilder buffer = new StringBuilder(); - private CapturingPrintStream( boolean quiet ) { - super( System.out, true ); + private CapturingPrintStream(boolean quiet) { + super(System.out, true); this.quiet = quiet; } @Override - public void println( String x ) - { - if ( !quiet ) - { - super.println( x ); + public void println(String x) { + if (!quiet) { + super.println(x); } - buffer.append( x ).append( System.lineSeparator() ); + buffer.append(x).append(System.lineSeparator()); } - public static void init( boolean quiet ) - { + public static void init(boolean quiet) { CapturingPrintStream capture = get(); - if ( capture != null ) - { - capture.buffer.setLength( 0 ); + if (capture != null) { + capture.buffer.setLength(0); capture.quiet = quiet; - } - else - { - capture = new CapturingPrintStream( quiet ); - System.setOut( capture ); + } else { + capture = new CapturingPrintStream(quiet); + System.setOut(capture); MavenSlf4jSimpleFriend.init(); } } - public static CapturingPrintStream get() - { - if ( System.out instanceof CapturingPrintStream ) - { + public static CapturingPrintStream get() { + if (System.out instanceof CapturingPrintStream) { return (CapturingPrintStream) System.out; } return null; } - public static String getOutput() - { + public static String getOutput() { CapturingPrintStream stream = get(); - if ( stream != null ) - { + if (stream != null) { stream.flush(); return stream.buffer.toString(); } return ""; } -} \ No newline at end of file +} diff --git a/src/test/java/org/apache/maven/plugins/pmd/CpdReportTest.java b/src/test/java/org/apache/maven/plugins/pmd/CpdReportTest.java index efb3d581..ac49a29b 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/CpdReportTest.java +++ b/src/test/java/org/apache/maven/plugins/pmd/CpdReportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import java.io.BufferedReader; import java.io.File; @@ -25,9 +27,6 @@ import java.io.IOException; import java.util.Locale; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - import org.apache.commons.lang3.StringUtils; import org.codehaus.plexus.util.FileUtils; import org.w3c.dom.Document; @@ -36,19 +35,15 @@ * @author Maria Odea Ching * @version $Id$ */ -public class CpdReportTest - extends AbstractPmdReportTestCase -{ +public class CpdReportTest extends AbstractPmdReportTestCase { /** * {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - Locale.setDefault( Locale.ENGLISH ); - FileUtils.deleteDirectory( new File( getBasedir(), "target/test/unit" ) ); + Locale.setDefault(Locale.ENGLISH); + FileUtils.deleteDirectory(new File(getBasedir(), "target/test/unit")); } /** @@ -56,26 +51,25 @@ protected void setUp() * * @throws Exception */ - public void testDefaultConfiguration() - throws Exception - { - File generatedReport = generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testDefaultConfiguration() throws Exception { + File generatedReport = + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the CPD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check the contents of cpd.html - String str = readFile( generatedReport ); - assertTrue( lowerCaseContains( str, "AppSample.java" ) ); - assertTrue( lowerCaseContains( str, "App.java" ) ); - assertTrue( lowerCaseContains( str, "public String dup( String str )" ) ); - assertTrue( lowerCaseContains( str, "tmp = tmp + str.substring( i, i + 1);" ) ); + String str = readFile(generatedReport); + assertTrue(lowerCaseContains(str, "AppSample.java")); + assertTrue(lowerCaseContains(str, "App.java")); + assertTrue(lowerCaseContains(str, "public String dup( String str )")); + assertTrue(lowerCaseContains(str, "tmp = tmp + str.substring( i, i + 1);")); // the version should be logged String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "PMD version: " + AbstractPmdReport.getPmdVersion() ) ); + assertTrue(output.contains("PMD version: " + AbstractPmdReport.getPmdVersion())); } /** @@ -83,23 +77,21 @@ public void testDefaultConfiguration() * * @throws Exception */ - public void testTxtFormat() - throws Exception - { - generateReport( "cpd", "custom-configuration/cpd-txt-format-configuration-plugin-config.xml" ); + public void testTxtFormat() throws Exception { + generateReport("cpd", "custom-configuration/cpd-txt-format-configuration-plugin-config.xml"); // check if the CPD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/cpd.txt" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.txt"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check the contents of cpd.txt - String str = readFile( generatedFile ); + String str = readFile(generatedFile); // Contents that should NOT be in the report - assertFalse( lowerCaseContains( str, "public static void main( String[] args )" ) ); + assertFalse(lowerCaseContains(str, "public static void main( String[] args )")); // Contents that should be in the report - assertTrue( lowerCaseContains( str, "public void duplicateMethod( int i )" ) ); + assertTrue(lowerCaseContains(str, "public void duplicateMethod( int i )")); } /** @@ -107,24 +99,22 @@ public void testTxtFormat() * * @throws Exception */ - public void testCustomConfiguration() - throws Exception - { - File generatedReport = generateReport( "cpd", "custom-configuration/cpd-custom-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testCustomConfiguration() throws Exception { + File generatedReport = generateReport("cpd", "custom-configuration/cpd-custom-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the CPD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/cpd.csv" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/cpd.csv"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - String str = readFile( generatedReport ); + String str = readFile(generatedReport); // Contents that should NOT be in the report - assertFalse( lowerCaseContains( str, "/Sample.java" ) ); - assertFalse( lowerCaseContains( str, "public void duplicateMethod( int i )" ) ); + assertFalse(lowerCaseContains(str, "/Sample.java")); + assertFalse(lowerCaseContains(str, "public void duplicateMethod( int i )")); // Contents that should be in the report - assertTrue( lowerCaseContains( str, "AnotherSample.java" ) ); - assertTrue( lowerCaseContains( str, "public static void main( String[] args )" ) ); - assertTrue( lowerCaseContains( str, "private String unusedMethod(" ) ); + assertTrue(lowerCaseContains(str, "AnotherSample.java")); + assertTrue(lowerCaseContains(str, "public static void main( String[] args )")); + assertTrue(lowerCaseContains(str, "private String unusedMethod(")); } /** @@ -132,24 +122,19 @@ public void testCustomConfiguration() * * @throws Exception */ - public void testInvalidFormat() - throws Exception - { - try - { - File testPom = - new File( getBasedir(), "src/test/resources/unit/invalid-format/cpd-invalid-format-plugin-config.xml" ); - AbstractPmdReport mojo = createReportMojo( "cpd", testPom ); - setVariableValueToObject( mojo, "compileSourceRoots", mojo.getProject().getCompileSourceRoots() ); - generateReport( mojo, testPom ); - - fail( "MavenReportException must be thrown" ); - } - catch ( Exception e ) - { - assertTrue( true ); + public void testInvalidFormat() throws Exception { + try { + File testPom = new File( + getBasedir(), "src/test/resources/unit/invalid-format/cpd-invalid-format-plugin-config.xml"); + AbstractPmdReport mojo = createReportMojo("cpd", testPom); + setVariableValueToObject( + mojo, "compileSourceRoots", mojo.getProject().getCompileSourceRoots()); + generateReport(mojo, testPom); + + fail("MavenReportException must be thrown"); + } catch (Exception e) { + assertTrue(true); } - } /** @@ -159,147 +144,123 @@ public void testInvalidFormat() * @return a String object that contains the contents of the file * @throws java.io.IOException */ - private String readFile( File file ) - throws IOException - { + private String readFile(File file) throws IOException { String strTmp; - StringBuilder str = new StringBuilder( (int) file.length() ); - try ( BufferedReader in = new BufferedReader( new FileReader( file ) ) ) - { - while ( ( strTmp = in.readLine() ) != null ) - { - str.append( ' ' ); - str.append( strTmp ); + StringBuilder str = new StringBuilder((int) file.length()); + try (BufferedReader in = new BufferedReader(new FileReader(file))) { + while ((strTmp = in.readLine()) != null) { + str.append(' '); + str.append(strTmp); } } return str.toString(); } - public void testWriteNonHtml() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); + public void testWriteNonHtml() throws Exception { + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); // check if the CPD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document pmdCpdDocument = builder.parse( generatedFile ); - assertNotNull( pmdCpdDocument ); - - String str = readFile( generatedFile ); - assertTrue( lowerCaseContains( str, "AppSample.java" ) ); - assertTrue( lowerCaseContains( str, "App.java" ) ); - assertTrue( lowerCaseContains( str, "public String dup( String str )" ) ); - assertTrue( lowerCaseContains( str, "tmp = tmp + str.substring( i, i + 1);" ) ); + Document pmdCpdDocument = builder.parse(generatedFile); + assertNotNull(pmdCpdDocument); + + String str = readFile(generatedFile); + assertTrue(lowerCaseContains(str, "AppSample.java")); + assertTrue(lowerCaseContains(str, "App.java")); + assertTrue(lowerCaseContains(str, "public String dup( String str )")); + assertTrue(lowerCaseContains(str, "tmp = tmp + str.substring( i, i + 1);")); } /** * verify the cpd.xml file is included in the site when requested. * @throws Exception */ - public void testIncludeXmlInSite() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-report-include-xml-in-site-plugin-config.xml" ); + public void testIncludeXmlInSite() throws Exception { + generateReport("cpd", "default-configuration/cpd-report-include-xml-in-site-plugin-config.xml"); - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document pmdCpdDocument = builder.parse( generatedFile ); - assertNotNull( pmdCpdDocument ); + Document pmdCpdDocument = builder.parse(generatedFile); + assertNotNull(pmdCpdDocument); - String str = readFile( generatedFile ); - assertTrue( str.contains( "" ) ); + String str = readFile(generatedFile); + assertTrue(str.contains("")); - File siteReport = new File( getBasedir(), "target/test/unit/default-configuration/target/site/cpd.xml" ); - assertTrue( FileUtils.fileExists( siteReport.getAbsolutePath() ) ); - String siteReportContent = readFile( siteReport ); - assertTrue( siteReportContent.contains( "" ) ); - assertEquals( str, siteReportContent ); + File siteReport = new File(getBasedir(), "target/test/unit/default-configuration/target/site/cpd.xml"); + assertTrue(FileUtils.fileExists(siteReport.getAbsolutePath())); + String siteReportContent = readFile(siteReport); + assertTrue(siteReportContent.contains("")); + assertEquals(str, siteReportContent); } - - public void testSkipEmptyReportConfiguration() - throws Exception - { + public void testSkipEmptyReportConfiguration() throws Exception { // verify the generated files do not exist because PMD was skipped - File generatedReport = generateReport( "cpd", "empty-report/cpd-skip-empty-report-plugin-config.xml" ); - assertFalse( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport("cpd", "empty-report/cpd-skip-empty-report-plugin-config.xml"); + assertFalse(FileUtils.fileExists(generatedReport.getAbsolutePath())); } - public void testEmptyReportConfiguration() - throws Exception - { + public void testEmptyReportConfiguration() throws Exception { // verify the generated files do exist, even if there are no violations - File generatedReport = generateReport( "cpd", "empty-report/cpd-empty-report-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport("cpd", "empty-report/cpd-empty-report-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); - String str = readFile( generatedReport ); - assertFalse( lowerCaseContains( str, "Hello.java" ) ); - assertTrue( str.contains( "CPD found no problems in your source code." ) ); + String str = readFile(generatedReport); + assertFalse(lowerCaseContains(str, "Hello.java")); + assertTrue(str.contains("CPD found no problems in your source code.")); } - public void testCpdEncodingConfiguration() - throws Exception - { - String originalEncoding = System.getProperty( "file.encoding" ); - try - { - System.setProperty( "file.encoding", "UTF-16" ); + public void testCpdEncodingConfiguration() throws Exception { + String originalEncoding = System.getProperty("file.encoding"); + try { + System.setProperty("file.encoding", "UTF-16"); - generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); // check if the CPD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertTrue( lowerCaseContains( str, "AppSample.java" ) ); - } - finally - { - System.setProperty( "file.encoding", originalEncoding ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); + assertTrue(lowerCaseContains(str, "AppSample.java")); + } finally { + System.setProperty("file.encoding", originalEncoding); } } - public void testCpdJavascriptConfiguration() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-javascript-plugin-config.xml" ); + public void testCpdJavascriptConfiguration() throws Exception { + generateReport("cpd", "default-configuration/cpd-javascript-plugin-config.xml"); // verify the generated file to exist and violations are reported - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertTrue( lowerCaseContains( str, "Sample.js" ) ); - assertTrue( lowerCaseContains( str, "SampleDup.js" ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); + assertTrue(lowerCaseContains(str, "Sample.js")); + assertTrue(lowerCaseContains(str, "SampleDup.js")); } - public void testCpdJspConfiguration() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-jsp-plugin-config.xml" ); + public void testCpdJspConfiguration() throws Exception { + generateReport("cpd", "default-configuration/cpd-jsp-plugin-config.xml"); // verify the generated file to exist and violations are reported - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertTrue( lowerCaseContains( str, "sample.jsp" ) ); - assertTrue( lowerCaseContains( str, "sampleDup.jsp" ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/cpd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); + assertTrue(lowerCaseContains(str, "sample.jsp")); + assertTrue(lowerCaseContains(str, "sampleDup.jsp")); } - public void testExclusionsConfiguration() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-report-cpd-exclusions-configuration-plugin-config.xml" ); + public void testExclusionsConfiguration() throws Exception { + generateReport("cpd", "default-configuration/cpd-report-cpd-exclusions-configuration-plugin-config.xml"); // verify the generated file to exist and no duplications are reported - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/cpd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertEquals( 0, StringUtils.countMatches( str, "Maria Odea Ching * @version $Id$ */ -public class CpdViolationCheckMojoTest - extends AbstractPmdReportTestCase -{ +public class CpdViolationCheckMojoTest extends AbstractPmdReportTestCase { - public void testDefaultConfiguration() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); + public void testDefaultConfiguration() throws Exception { + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); // clear the output from previous pmd:cpd execution - CapturingPrintStream.init( true ); - - try - { - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-default-configuration-plugin-config.xml" ); - final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo( "cpd-check", testPom ); + CapturingPrintStream.init(true); + + try { + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/pmd-check-default-configuration-plugin-config.xml"); + final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo("cpd-check", testPom); cpdViolationMojo.execute(); - fail( "MojoFailureException should be thrown." ); - } - catch ( final Exception e ) - { + fail("MojoFailureException should be thrown."); + } catch (final Exception e) { // the version should be logged String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "PMD version: " + AbstractPmdReport.getPmdVersion() ) ); + assertTrue(output.contains("PMD version: " + AbstractPmdReport.getPmdVersion())); - assertTrue( e.getMessage().startsWith( "You have 1 CPD duplication." ) ); + assertTrue(e.getMessage().startsWith("You have 1 CPD duplication.")); } } - public void testNotFailOnViolation() - throws Exception - { + public void testNotFailOnViolation() throws Exception { - generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/cpd-check-notfailonviolation-plugin-config.xml" ); - final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo( "cpd-check", testPom ); + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/cpd-check-notfailonviolation-plugin-config.xml"); + final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo("cpd-check", testPom); cpdViolationMojo.execute(); - assertTrue( true ); + assertTrue(true); } - public void testException() - throws Exception - { - try - { - final File testPom = - new File( getBasedir(), - "src/test/resources/unit/custom-configuration/pmd-check-exception-test-plugin-config.xml" ); - final CpdViolationCheckMojo mojo = (CpdViolationCheckMojo) lookupMojo( "cpd-check", testPom ); + public void testException() throws Exception { + try { + final File testPom = new File( + getBasedir(), + "src/test/resources/unit/custom-configuration/pmd-check-exception-test-plugin-config.xml"); + final CpdViolationCheckMojo mojo = (CpdViolationCheckMojo) lookupMojo("cpd-check", testPom); mojo.execute(); - fail( "MojoFailureException should be thrown." ); - } - catch ( final Exception e ) - { - assertTrue( true ); + fail("MojoFailureException should be thrown."); + } catch (final Exception e) { + assertTrue(true); } } - public void testExclusionsConfiguration() - throws Exception - { - generateReport( "cpd", "default-configuration/cpd-default-configuration-plugin-config.xml" ); + public void testExclusionsConfiguration() throws Exception { + generateReport("cpd", "default-configuration/cpd-default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/cpd-check-cpd-exclusions-configuration-plugin-config.xml" ); - final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo( "cpd-check", testPom ); + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/cpd-check-cpd-exclusions-configuration-plugin-config.xml"); + final CpdViolationCheckMojo cpdViolationMojo = (CpdViolationCheckMojo) lookupMojo("cpd-check", testPom); // this call shouldn't throw an exception, as the classes with duplications have been excluded cpdViolationMojo.execute(); diff --git a/src/test/java/org/apache/maven/plugins/pmd/DependencyArtifactStubFactory.java b/src/test/java/org/apache/maven/plugins/pmd/DependencyArtifactStubFactory.java index 7cd70cdc..881286ca 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/DependencyArtifactStubFactory.java +++ b/src/test/java/org/apache/maven/plugins/pmd/DependencyArtifactStubFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; import java.io.IOException; @@ -27,42 +26,44 @@ import org.apache.maven.artifact.versioning.VersionRange; import org.apache.maven.plugin.testing.ArtifactStubFactory; -public class DependencyArtifactStubFactory - extends ArtifactStubFactory -{ +public class DependencyArtifactStubFactory extends ArtifactStubFactory { private boolean flattenedPath = true; - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles, boolean flattenedPath ) - { - this( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles, boolean flattenedPath) { + this(theWorkingDir, theCreateFiles); this.flattenedPath = flattenedPath; } - public DependencyArtifactStubFactory( File theWorkingDir, boolean theCreateFiles ) - { - super( theWorkingDir, theCreateFiles ); + public DependencyArtifactStubFactory(File theWorkingDir, boolean theCreateFiles) { + super(theWorkingDir, theCreateFiles); } @Override - public Artifact createArtifact( String groupId, String artifactId, VersionRange versionRange, String scope, - String type, String classifier, boolean optional ) - throws IOException - { + public Artifact createArtifact( + String groupId, + String artifactId, + VersionRange versionRange, + String scope, + String type, + String classifier, + boolean optional) + throws IOException { File workingDir = getWorkingDir(); - if ( !flattenedPath ) - { + if (!flattenedPath) { // don't use flatten directories, won't happen at runtime - String path = groupId.replace( '.', '/' ) + '/' + - artifactId + '/' + - ArtifactUtils.toSnapshotVersion( versionRange.getRecommendedVersion().toString() ); - setWorkingDir( new File( workingDir, path ) ); + String path = groupId.replace('.', '/') + + '/' + + artifactId + + '/' + + ArtifactUtils.toSnapshotVersion( + versionRange.getRecommendedVersion().toString()); + setWorkingDir(new File(workingDir, path)); } - Artifact artifact = - super.createArtifact( groupId, artifactId, versionRange, scope, type, classifier, optional ); + Artifact artifact = super.createArtifact(groupId, artifactId, versionRange, scope, type, classifier, optional); - setWorkingDir( workingDir ); + setWorkingDir(workingDir); return artifact; } diff --git a/src/test/java/org/apache/maven/plugins/pmd/PmdReportTest.java b/src/test/java/org/apache/maven/plugins/pmd/PmdReportTest.java index d53ba481..eed633a4 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/PmdReportTest.java +++ b/src/test/java/org/apache/maven/plugins/pmd/PmdReportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.BufferedReader; import java.io.File; @@ -28,241 +27,241 @@ import java.nio.charset.StandardCharsets; import java.util.Locale; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; +import net.sourceforge.pmd.renderers.Renderer; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.maven.plugins.pmd.exec.PmdExecutor; import org.apache.maven.reporting.MavenReportException; import org.codehaus.plexus.util.FileUtils; -import net.sourceforge.pmd.renderers.Renderer; - -import com.github.tomakehurst.wiremock.WireMockServer; -import com.github.tomakehurst.wiremock.client.WireMock; - /** * @author Maria Odea Ching * @version $Id$ */ -public class PmdReportTest - extends AbstractPmdReportTestCase -{ +public class PmdReportTest extends AbstractPmdReportTestCase { /** * {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - Locale.setDefault( Locale.ENGLISH ); - FileUtils.deleteDirectory( new File( getBasedir(), "target/test/unit" ) ); + Locale.setDefault(Locale.ENGLISH); + FileUtils.deleteDirectory(new File(getBasedir(), "target/test/unit")); } - public void testDefaultConfiguration() - throws Exception - { - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) ); + public void testDefaultConfiguration() throws Exception { + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/default-configuration/target/site")); - File generatedReport = generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check if the rulesets, that have been applied, have been copied - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/maven-pmd-plugin-default.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File( + getBasedir(), + "target/test/unit/default-configuration/target/pmd/rulesets/maven-pmd-plugin-default.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check if there's a link to the JXR files - String str = readFile( generatedReport ); + String str = readFile(generatedReport); - assertTrue( str.contains( "/xref/def/configuration/App.html#L31" ) ); + assertTrue(str.contains("/xref/def/configuration/App.html#L31")); - assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L45" ) ); + assertTrue(str.contains("/xref/def/configuration/AppSample.html#L45")); // check if there's a priority column - assertTrue( str.contains( "Priority" ) ); + assertTrue(str.contains("Priority")); // there should be a rule column - assertTrue( str.contains( "Rule" ) ); + assertTrue(str.contains("Rule")); // along with a link to the rule - assertTrue( str.contains( "pmd_rules_java_bestpractices.html#unusedprivatefield\">UnusedPrivateField" ) ); + assertTrue(str.contains("pmd_rules_java_bestpractices.html#unusedprivatefield\">UnusedPrivateField")); // there should be the section Violations By Priority - assertTrue( str.contains( "Violations By Priority" ) ); - assertTrue( str.contains( "Priority 3" ) ); - assertTrue( str.contains( "Priority 4" ) ); + assertTrue(str.contains("Violations By Priority")); + assertTrue(str.contains("Priority 3")); + assertTrue(str.contains("Priority 4")); // the file App.java is mentioned 3 times: in prio 3, in prio 4 and in the files section - assertEquals( 3, StringUtils.countMatches( str, "def/configuration/App.java" ) ); + assertEquals(3, StringUtils.countMatches(str, "def/configuration/App.java")); // there must be no warnings (like deprecated rules) in the log output String output = CapturingPrintStream.getOutput(); - assertFalse( output.contains( "deprecated Rule name" ) ); - assertFalse( output.contains( "Discontinue using Rule name" ) ); - assertFalse( output.contains( "is referenced multiple times" ) ); + assertFalse(output.contains("deprecated Rule name")); + assertFalse(output.contains("Discontinue using Rule name")); + assertFalse(output.contains("is referenced multiple times")); // the version should be logged - assertTrue ( output.contains( "PMD version: " + AbstractPmdReport.getPmdVersion() ) ); + assertTrue(output.contains("PMD version: " + AbstractPmdReport.getPmdVersion())); } - public void testDefaultConfigurationNotRenderRuleViolationPriority() - throws Exception - { - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) ); + public void testDefaultConfigurationNotRenderRuleViolationPriority() throws Exception { + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/default-configuration/target/site")); - File generatedReport = generateReport( "pmd", "default-configuration/pmd-report-not-render-rule-priority-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = + generateReport("pmd", "default-configuration/pmd-report-not-render-rule-priority-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); - String str = readFile( generatedReport ); + String str = readFile(generatedReport); // check that there's no priority column - assertFalse( str.contains( "Priority" ) ); + assertFalse(str.contains("Priority")); } - public void testDefaultConfigurationNoRenderViolationsByPriority() - throws Exception - { - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) ); + public void testDefaultConfigurationNoRenderViolationsByPriority() throws Exception { + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/default-configuration/target/site")); - File generatedReport = generateReport( "pmd", "default-configuration/pmd-report-no-render-violations-by-priority.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = + generateReport("pmd", "default-configuration/pmd-report-no-render-violations-by-priority.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); - String str = readFile( generatedReport ); + String str = readFile(generatedReport); // there should be no section Violations By Priority - assertFalse( str.contains( "Violations By Priority" ) ); - assertFalse( str.contains( "Priority 3" ) ); - assertFalse( str.contains( "Priority 4" ) ); + assertFalse(str.contains("Violations By Priority")); + assertFalse(str.contains("Priority 3")); + assertFalse(str.contains("Priority 4")); // the file App.java is mentioned once: in the files section - assertEquals( 1, StringUtils.countMatches( str, "def/configuration/App.java" ) ); + assertEquals(1, StringUtils.countMatches(str, "def/configuration/App.java")); } + public void testDefaultConfigurationWithAnalysisCache() throws Exception { + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/pmd-with-analysis-cache-plugin-config/target/site")); - public void testDefaultConfigurationWithAnalysisCache() - throws Exception - { - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/pmd-with-analysis-cache-plugin-config/target/site" ) ); - - generateReport( "pmd", "default-configuration/pmd-with-analysis-cache-plugin-config.xml" ); + generateReport("pmd", "default-configuration/pmd-with-analysis-cache-plugin-config.xml"); // check if the PMD analysis cache file has been generated - File cacheFile = new File( getBasedir(), "target/test/unit/pmd-with-analysis-cache-plugin-config/target/pmd/pmd.cache" ); - assertTrue( FileUtils.fileExists( cacheFile.getAbsolutePath() ) ); + File cacheFile = + new File(getBasedir(), "target/test/unit/pmd-with-analysis-cache-plugin-config/target/pmd/pmd.cache"); + assertTrue(FileUtils.fileExists(cacheFile.getAbsolutePath())); } - public void testJavascriptConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "default-configuration/javascript-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testJavascriptConfiguration() throws Exception { + File generatedReport = + generateReport("pmd", "default-configuration/javascript-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // these are the rulesets, that have been applied... - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/codestyle.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/codestyle.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/errorprone.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/errorprone.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - String str = readFile( generatedReport ); - assertTrue( str.contains( "Avoid using global variables" ) ); + String str = readFile(generatedReport); + assertTrue(str.contains("Avoid using global variables")); } - public void testFileURL() - throws Exception - { - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) ); + public void testFileURL() throws Exception { + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/default-configuration/target/site")); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" ); - PmdReport mojo = (PmdReport) createReportMojo( "pmd", testPom ); + File testPom = new File( + getBasedir(), "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml"); + PmdReport mojo = (PmdReport) createReportMojo("pmd", testPom); // Additional test case for MPMD-174 (https://issues.apache.org/jira/browse/MPMD-174). int port = determineFreePort(); - WireMockServer mockServer = new WireMockServer( port ); + WireMockServer mockServer = new WireMockServer(port); mockServer.start(); - String sonarRuleset = - IOUtils.toString( getClass().getClassLoader().getResourceAsStream( "unit/default-configuration/rulesets/sonar-way-ruleset.xml" ), - StandardCharsets.UTF_8 ); + String sonarRuleset = IOUtils.toString( + getClass() + .getClassLoader() + .getResourceAsStream("unit/default-configuration/rulesets/sonar-way-ruleset.xml"), + StandardCharsets.UTF_8); - String sonarMainPageHtml = - IOUtils.toString( getClass().getClassLoader().getResourceAsStream( "unit/default-configuration/rulesets/sonar-main-page.html" ), - StandardCharsets.UTF_8 ); + String sonarMainPageHtml = IOUtils.toString( + getClass() + .getClassLoader() + .getResourceAsStream("unit/default-configuration/rulesets/sonar-main-page.html"), + StandardCharsets.UTF_8); final String sonarBaseUrl = "/profiles"; final String sonarProfileUrl = sonarBaseUrl + "/export?format=pmd&language=java&name=Sonar%2520way"; final String sonarExportRulesetUrl = "http://localhost:" + mockServer.port() + sonarProfileUrl; - WireMock.configureFor( "localhost", port ); - WireMock.stubFor( WireMock.get( WireMock.urlEqualTo( sonarBaseUrl ) ).willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type", - "text/html" ).withBody( sonarMainPageHtml ) ) ); + WireMock.configureFor("localhost", port); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(sonarBaseUrl)) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/html") + .withBody(sonarMainPageHtml))); - WireMock.stubFor( WireMock.get( WireMock.urlEqualTo( sonarProfileUrl ) ).willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type", - "text/xml" ).withBody( sonarRuleset ) ) ); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(sonarProfileUrl)) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(sonarRuleset))); - URL url = getClass().getClassLoader().getResource( "rulesets/java/basic.xml" ); - URL url2 = getClass().getClassLoader().getResource( "rulesets/java/unusedcode.xml" ); - URL url3 = getClass().getClassLoader().getResource( "rulesets/java/imports.xml" ); - mojo.setRulesets( new String[] { url.toString(), url2.toString(), url3.toString(), sonarExportRulesetUrl } ); + URL url = getClass().getClassLoader().getResource("rulesets/java/basic.xml"); + URL url2 = getClass().getClassLoader().getResource("rulesets/java/unusedcode.xml"); + URL url3 = getClass().getClassLoader().getResource("rulesets/java/imports.xml"); + mojo.setRulesets(new String[] {url.toString(), url2.toString(), url3.toString(), sonarExportRulesetUrl}); - File generatedReport = generateReport( mojo, testPom ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport(mojo, testPom); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // the resolved and extracted rulesets - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/basic.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/imports.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/basic.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/unusedcode.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/imports.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); generatedFile = - new File( getBasedir(), - "target/test/unit/default-configuration/target/pmd/rulesets/export_format_pmd_language_java_name_Sonar_2520way.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/unusedcode.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + + generatedFile = new File( + getBasedir(), + "target/test/unit/default-configuration/target/pmd/rulesets/export_format_pmd_language_java_name_Sonar_2520way.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check if there's a link to the JXR files - String str = readFile( generatedReport ); + String str = readFile(generatedReport); - assertTrue( str.contains( "/xref/def/configuration/App.html#L31" ) ); + assertTrue(str.contains("/xref/def/configuration/App.html#L31")); - assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L45" ) ); + assertTrue(str.contains("/xref/def/configuration/AppSample.html#L45")); mockServer.stop(); } - private int determineFreePort() - { + private int determineFreePort() { try (ServerSocket socket = new ServerSocket(0)) { return socket.getLocalPort(); } catch (IOException e) { - throw new RuntimeException( "Couldn't find a free port.", e ); + throw new RuntimeException("Couldn't find a free port.", e); } } @@ -271,35 +270,34 @@ private int determineFreePort() * * @throws Exception */ - public void testCustomConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "custom-configuration/custom-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testCustomConfiguration() throws Exception { + File generatedReport = generateReport("pmd", "custom-configuration/custom-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check the generated files - File generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/pmd.csv" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/pmd.csv"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/pmd/rulesets/custom.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/pmd/rulesets/custom.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // check if custom ruleset was applied - String str = readFile( generatedReport ); + String str = readFile(generatedReport); // codestyle.xml/ControlStatementBraces: - assertTrue( lowerCaseContains( str, "This statement should have braces" ) ); + assertTrue(lowerCaseContains(str, "This statement should have braces")); // Must be false as codestyle.xml/ControlStatementBraces with checkIfElseStmt=false is used - assertFalse( lowerCaseContains( str, "Avoid using if...else statements without curly braces" ) ); + assertFalse(lowerCaseContains(str, "Avoid using if...else statements without curly braces")); - assertFalse( "unnecessary constructor should not be triggered because of low priority", - lowerCaseContains( str, "Avoid unnecessary constructors - the compiler will generate these for you" ) ); + assertFalse( + "unnecessary constructor should not be triggered because of low priority", + lowerCaseContains(str, "Avoid unnecessary constructors - the compiler will generate these for you")); // veryLongVariableNameWithViolation is really too long - assertTrue( lowerCaseContains( str, "veryLongVariableNameWithViolation" ) ); + assertTrue(lowerCaseContains(str, "veryLongVariableNameWithViolation")); // notSoLongVariableName should not be reported - assertFalse( lowerCaseContains( str, "notSoLongVariableName" ) ); + assertFalse(lowerCaseContains(str, "notSoLongVariableName")); } /** @@ -307,78 +305,63 @@ public void testCustomConfiguration() * * @throws Exception */ - public void testSkipConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "custom-configuration/skip-plugin-config.xml" ); - assertFalse( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testSkipConfiguration() throws Exception { + File generatedReport = generateReport("pmd", "custom-configuration/skip-plugin-config.xml"); + assertFalse(FileUtils.fileExists(generatedReport.getAbsolutePath())); // verify the generated files do not exist because PMD was skipped - File generatedFile = new File( getBasedir(), "target/test/unit/skip-configuration/target/pmd.csv" ); - assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/skip-configuration/target/pmd.csv"); + assertFalse(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/custom-configuration/target/custom.xml" ); - assertFalse( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File(getBasedir(), "target/test/unit/custom-configuration/target/custom.xml"); + assertFalse(FileUtils.fileExists(generatedFile.getAbsolutePath())); // the fact, the PMD execution has been skipped, should be logged String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "Skipping PMD execution" ) ); + assertTrue(output.contains("Skipping PMD execution")); } - public void testSkipEmptyReportConfiguration() - throws Exception - { + public void testSkipEmptyReportConfiguration() throws Exception { // verify the generated files do not exist because PMD was skipped - File generatedReport = generateReport( "pmd", "empty-report/skip-empty-report-plugin-config.xml" ); - assertFalse( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport("pmd", "empty-report/skip-empty-report-plugin-config.xml"); + assertFalse(FileUtils.fileExists(generatedReport.getAbsolutePath())); } - public void testEmptyReportConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "empty-report/empty-report-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testEmptyReportConfiguration() throws Exception { + File generatedReport = generateReport("pmd", "empty-report/empty-report-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // verify the generated files do exist, even if there are no violations - String str = readFile( generatedReport ); - assertFalse( lowerCaseContains( str, "Hello.java" ) ); - assertEquals( 1, StringUtils.countMatches( str, "PMD found no problems in your source code." ) ); + String str = readFile(generatedReport); + assertFalse(lowerCaseContains(str, "Hello.java")); + assertEquals(1, StringUtils.countMatches(str, "PMD found no problems in your source code.")); // no sections files or violations by priority - assertFalse( str.contains( "Files" ) ); - assertFalse( str.contains( "Violations By Priority" ) ); + assertFalse(str.contains("Files")); + assertFalse(str.contains("Violations By Priority")); } - public void testInvalidFormat() - throws Exception - { - try - { + public void testInvalidFormat() throws Exception { + try { File testPom = - new File( getBasedir(), "src/test/resources/unit/invalid-format/invalid-format-plugin-config.xml" ); - AbstractPmdReport mojo = createReportMojo( "pmd", testPom ); - setVariableValueToObject( mojo, "compileSourceRoots", mojo.getProject().getCompileSourceRoots() ); - generateReport( mojo, testPom ); - - fail( "Must throw MavenReportException." ); - } - catch ( Exception e ) - { - assertTrue( true ); + new File(getBasedir(), "src/test/resources/unit/invalid-format/invalid-format-plugin-config.xml"); + AbstractPmdReport mojo = createReportMojo("pmd", testPom); + setVariableValueToObject( + mojo, "compileSourceRoots", mojo.getProject().getCompileSourceRoots()); + generateReport(mojo, testPom); + + fail("Must throw MavenReportException."); + } catch (Exception e) { + assertTrue(true); } } - public void testInvalidTargetJdk() - throws Exception - { - try - { - generateReport( "pmd", "empty-report/invalid-format/invalid-target-jdk-plugin-config.xml" ); + public void testInvalidTargetJdk() throws Exception { + try { + generateReport("pmd", "empty-report/invalid-format/invalid-target-jdk-plugin-config.xml"); - fail( "Must throw MavenReportException." ); - } - catch ( Exception e ) - { - assertTrue( true ); + fail("Must throw MavenReportException."); + } catch (Exception e) { + assertTrue(true); } } @@ -386,22 +369,21 @@ public void testInvalidTargetJdk() * verify the pmd.xml file is included in the site when requested. * @throws Exception */ - public void testIncludeXmlInSite() - throws Exception - { - File generatedReport = generateReport( "pmd", "default-configuration/pmd-report-include-xml-in-site-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testIncludeXmlInSite() throws Exception { + File generatedReport = + generateReport("pmd", "default-configuration/pmd-report-include-xml-in-site-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // verify the pmd file is included in site - File generatedXmlFile = new File( getBasedir(), "target/test/unit/default-configuration/target/site/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedXmlFile.getAbsolutePath() ) ); + File generatedXmlFile = new File(getBasedir(), "target/test/unit/default-configuration/target/site/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedXmlFile.getAbsolutePath())); - String pmdXmlTarget = readFile( new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ) ); - assertTrue( pmdXmlTarget.contains( "" ) ); + String pmdXmlTarget = readFile(new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml")); + assertTrue(pmdXmlTarget.contains("")); // check that pmd.xml file has the closing element - String pmdXml = readFile( generatedXmlFile ); - assertTrue( pmdXml.contains( "" ) ); + String pmdXml = readFile(generatedXmlFile); + assertTrue(pmdXml.contains("")); } /** @@ -411,18 +393,14 @@ public void testIncludeXmlInSite() * @return a String object that contains the contents of the file * @throws java.io.IOException */ - private String readFile( File file ) - throws IOException - { - try ( BufferedReader reader = new BufferedReader( new FileReader( file ) ) ) - { - final StringBuilder str = new StringBuilder( (int) file.length() ); - - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - str.append( ' ' ); - str.append( line ); - str.append( '\n' ); + private String readFile(File file) throws IOException { + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { + final StringBuilder str = new StringBuilder((int) file.length()); + + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + str.append(' '); + str.append(line); + str.append('\n'); } return str.toString(); } @@ -433,19 +411,17 @@ private String readFile( File file ) * * @throws Exception */ - public void testLocationTemp() - throws Exception - { - - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" ); - PmdReport mojo = (PmdReport) lookupMojo( "pmd", testPom ); + public void testLocationTemp() throws Exception { - assertEquals( "locationTemp is not correctly encoding filename", - "export_format_pmd_language_java_name_some_2520name.xml", - mojo.getLocationTemp( "http://nemo.sonarsource.org/sonar/profiles/export?format=pmd&language=java&name=some%2520name" ) ); + File testPom = new File( + getBasedir(), "src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml"); + PmdReport mojo = (PmdReport) lookupMojo("pmd", testPom); + assertEquals( + "locationTemp is not correctly encoding filename", + "export_format_pmd_language_java_name_some_2520name.xml", + mojo.getLocationTemp( + "http://nemo.sonarsource.org/sonar/profiles/export?format=pmd&language=java&name=some%2520name")); } /** @@ -453,259 +429,262 @@ public void testLocationTemp() * * @throws Exception */ - public void testSuppressMarkerConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "default-configuration/pmd-with-suppressMarker-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testSuppressMarkerConfiguration() throws Exception { + File generatedReport = generateReport("pmd", "default-configuration/pmd-with-suppressMarker-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - String str = readFile( generatedFile ); + String str = readFile(generatedFile); // check that there is no violation reported for "unusedVar2" - as it is suppressed - assertFalse( str.contains( "Avoid unused private fields such as 'unusedVar2'.\n " ) ); + assertFalse(str.contains("Avoid unused private fields such as 'unusedVar2'.\n ")); // but it appears as suppressed - assertTrue( str.contains( "suppressiontype=\"nopmd\" msg=\"Avoid unused private fields such as 'unusedVar2'.\"" )); + assertTrue(str.contains("suppressiontype=\"nopmd\" msg=\"Avoid unused private fields such as 'unusedVar2'.\"")); // check if there's a link to the JXR files - str = readFile( generatedReport ); + str = readFile(generatedReport); - assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L27" ) ); + assertTrue(str.contains("/xref/def/configuration/AppSample.html#L27")); // suppressed violation - assertTrue( str.contains( "Avoid unused private fields such as 'unusedVar2'." ) ); + assertTrue(str.contains("Avoid unused private fields such as 'unusedVar2'.")); } - public void testSuppressMarkerConfigurationWithoutRendering() - throws Exception - { - File generatedReport = generateReport( "pmd", "default-configuration/pmd-with-suppressMarker-no-render-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testSuppressMarkerConfigurationWithoutRendering() throws Exception { + File generatedReport = + generateReport("pmd", "default-configuration/pmd-with-suppressMarker-no-render-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - String str = readFile( generatedFile ); + String str = readFile(generatedFile); // check that there is no violation reported for "unusedVar2" - as it is suppressed - assertFalse( str.contains( "Avoid unused private fields such as 'unusedVar2'.\n " ) ); + assertFalse(str.contains("Avoid unused private fields such as 'unusedVar2'.\n ")); // but it appears as suppressed - assertTrue( str.contains( "suppressiontype=\"nopmd\" msg=\"Avoid unused private fields such as 'unusedVar2'.\"" )); + assertTrue(str.contains("suppressiontype=\"nopmd\" msg=\"Avoid unused private fields such as 'unusedVar2'.\"")); // check if there's a link to the JXR files - str = readFile( generatedReport ); + str = readFile(generatedReport); - assertTrue( str.contains( "/xref/def/configuration/AppSample.html#L27" ) ); + assertTrue(str.contains("/xref/def/configuration/AppSample.html#L27")); // suppressed violations are not rendered - assertFalse( str.contains( "Avoid unused private fields such as 'unusedVar2'." ) ); + assertFalse(str.contains("Avoid unused private fields such as 'unusedVar2'.")); } - public void testJspConfiguration() - throws Exception - { - File generatedReport = generateReport( "pmd", "default-configuration/jsp-configuration-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testJspConfiguration() throws Exception { + File generatedReport = generateReport("pmd", "default-configuration/jsp-configuration-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); // check if the PMD files were generated - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); // these are the rulesets, that have been applied... - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/codestyle.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/codestyle.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/design.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/design.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/errorprone.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/errorprone.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/security.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/security.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - String str = readFile( generatedReport ); + String str = readFile(generatedReport); assertTrue(str.contains("JSP file should use UTF-8 encoding")); assertTrue(str.contains("Using unsanitized JSP expression can lead to Cross Site Scripting (XSS) attacks")); assertTrue(str.contains("Avoid having style information in JSP files.")); } - public void testPMDProcessingError() - throws Exception - { + public void testPMDProcessingError() throws Exception { try { - generateReport( "pmd", "processing-error/pmd-processing-error-plugin-config.xml" ); + generateReport("pmd", "processing-error/pmd-processing-error-plugin-config.xml"); fail("Expected exception"); } catch (RuntimeException e) { - assertTrue( e.getMessage().endsWith( "Found 1 PMD processing errors" ) ); + assertTrue(e.getMessage().endsWith("Found 1 PMD processing errors")); } } - public void testPMDProcessingErrorWithDetailsSkipped() - throws Exception - { - File generatedReport = generateReport( "pmd", "processing-error/pmd-processing-error-skip-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testPMDProcessingErrorWithDetailsSkipped() throws Exception { + File generatedReport = generateReport("pmd", "processing-error/pmd-processing-error-skip-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "There are 1 PMD processing errors:" ) ); + assertTrue(output.contains("There are 1 PMD processing errors:")); - File generatedFile = new File( getBasedir(), "target/test/unit/parse-error/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertTrue( str.contains( "Error while parsing" ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/parse-error/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); + assertTrue(str.contains("Error while parsing")); // The parse exception must be in the XML report - assertTrue( str.contains( "ParseException: Encountered \"\" at line 23, column 5." ) ); + assertTrue(str.contains("ParseException: Encountered \"\" at line 23, column 5.")); - str = readFile( generatedReport ); + str = readFile(generatedReport); // The parse exception must also be in the HTML report - assertTrue( str.contains( "ParseException: Encountered \"\" at line 23, column 5." ) ); + assertTrue(str.contains("ParseException: Encountered \"\" at line 23, column 5.")); } - public void testPMDProcessingErrorWithDetailsNoReport() - throws Exception - { - File generatedReport = generateReport( "pmd", "processing-error/pmd-processing-error-no-report-plugin-config.xml" ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + public void testPMDProcessingErrorWithDetailsNoReport() throws Exception { + File generatedReport = + generateReport("pmd", "processing-error/pmd-processing-error-no-report-plugin-config.xml"); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "There are 1 PMD processing errors:" ) ); + assertTrue(output.contains("There are 1 PMD processing errors:")); - File generatedFile = new File( getBasedir(), "target/test/unit/parse-error/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); - assertTrue( str.contains( "Error while parsing" ) ); + File generatedFile = new File(getBasedir(), "target/test/unit/parse-error/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); + assertTrue(str.contains("Error while parsing")); // The parse exception must be in the XML report - assertTrue( str.contains( "ParseException: Encountered \"\" at line 23, column 5." ) ); + assertTrue(str.contains("ParseException: Encountered \"\" at line 23, column 5.")); - str = readFile( generatedReport ); + str = readFile(generatedReport); // The parse exception must NOT be in the HTML report, since reportProcessingErrors is false - assertFalse( str.contains( "ParseException: Encountered \"\" at line 23, column 5." ) ); + assertFalse(str.contains("ParseException: Encountered \"\" at line 23, column 5.")); } - public void testPMDExcludeRootsShouldExcludeSubdirectories() - throws Exception - { - generateReport( "pmd", "exclude-roots/pmd-exclude-roots-plugin-config.xml" ); + public void testPMDExcludeRootsShouldExcludeSubdirectories() throws Exception { + generateReport("pmd", "exclude-roots/pmd-exclude-roots-plugin-config.xml"); - File generatedFile = new File( getBasedir(), "target/test/unit/exclude-roots/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); + File generatedFile = new File(getBasedir(), "target/test/unit/exclude-roots/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); - assertTrue( "Seems like all directories are excluded now", str.contains( "ForLoopShouldBeWhileLoop" ) ); - assertFalse( "Exclusion of an exact source directory not working", str.contains( "OverrideBothEqualsAndHashcode" ) ); - assertFalse( "Exclusion of basedirectory with subdirectories not working (MPMD-178)", str.contains( "JumbledIncrementer") ); + assertTrue("Seems like all directories are excluded now", str.contains("ForLoopShouldBeWhileLoop")); + assertFalse( + "Exclusion of an exact source directory not working", str.contains("OverrideBothEqualsAndHashcode")); + assertFalse( + "Exclusion of basedirectory with subdirectories not working (MPMD-178)", + str.contains("JumbledIncrementer")); } - public void testViolationExclusion() - throws Exception - { - generateReport( "pmd", "default-configuration/pmd-report-pmd-exclusions-configuration-plugin-config.xml" ); + public void testViolationExclusion() throws Exception { + generateReport("pmd", "default-configuration/pmd-report-pmd-exclusions-configuration-plugin-config.xml"); - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); - String str = readFile( generatedFile ); + File generatedFile = new File(getBasedir(), "target/test/unit/default-configuration/target/pmd.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); + String str = readFile(generatedFile); assertEquals(0, StringUtils.countMatches(str, "CustomRule" ) ); + assertEquals(2, StringUtils.countMatches(str, "CustomRule")); // standard rule with link - assertEquals( 4, StringUtils.countMatches( str, "\">UnusedPrivateField" ) ); + assertEquals(4, StringUtils.countMatches(str, "\">UnusedPrivateField")); } - public void testPmdReportResolveRulesets() - throws Exception - { + public void testPmdReportResolveRulesets() throws Exception { int port = determineFreePort(); - WireMockServer mockServer = new WireMockServer( port ); + WireMockServer mockServer = new WireMockServer(port); mockServer.start(); - String sonarRuleset = - IOUtils.toString( getClass().getClassLoader().getResourceAsStream( "unit/default-configuration/rulesets/sonar-way-ruleset.xml" ), - StandardCharsets.UTF_8 ); + String sonarRuleset = IOUtils.toString( + getClass() + .getClassLoader() + .getResourceAsStream("unit/default-configuration/rulesets/sonar-way-ruleset.xml"), + StandardCharsets.UTF_8); final String sonarProfileUrl = "/profiles/export?format=pmd&language=java&name=Sonar%2520way"; final String sonarExportRulesetUrl = "http://localhost:" + mockServer.port() + sonarProfileUrl; final String myRulesetBaseUrl = "/config/my-ruleset.xml"; final String myRulesetUrl = "http://localhost:" + mockServer.port() + myRulesetBaseUrl; - final String notAInternalRulesetBaseUrl = "/projects/OURPROJECT/repos/ourproject-pmd/raw/InProgressRuleset.xml?at=refs%2Fheads%2Fmaster"; + final String notAInternalRulesetBaseUrl = + "/projects/OURPROJECT/repos/ourproject-pmd/raw/InProgressRuleset.xml?at=refs%2Fheads%2Fmaster"; final String notAInternalRulesetUrl = "http://localhost:" + mockServer.port() + notAInternalRulesetBaseUrl; - WireMock.configureFor( "localhost", port ); - WireMock.stubFor( WireMock.get( WireMock.urlEqualTo( sonarProfileUrl ) ) - .willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type", - "text/xml" ).withBody( sonarRuleset ) ) ); - WireMock.stubFor( WireMock.get( WireMock.urlEqualTo( myRulesetBaseUrl ) ) - .willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type", - "text/xml" ).withBody( sonarRuleset ) ) ); - WireMock.stubFor( WireMock.get( WireMock.urlEqualTo( notAInternalRulesetBaseUrl ) ) - .willReturn( WireMock.aResponse().withStatus( 200 ).withHeader( "Content-Type", - "text/xml" ).withBody( sonarRuleset ) ) ); - - FileUtils.copyDirectoryStructure( new File( getBasedir(), - "src/test/resources/unit/default-configuration/jxr-files" ), - new File( getBasedir(), "target/test/unit/default-configuration/target/site" ) ); + WireMock.configureFor("localhost", port); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(sonarProfileUrl)) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(sonarRuleset))); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(myRulesetBaseUrl)) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(sonarRuleset))); + WireMock.stubFor(WireMock.get(WireMock.urlEqualTo(notAInternalRulesetBaseUrl)) + .willReturn(WireMock.aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody(sonarRuleset))); + + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/default-configuration/jxr-files"), + new File(getBasedir(), "target/test/unit/default-configuration/target/site")); File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-report-resolve-rulesets.xml" ); - PmdReport mojo = (PmdReport) createReportMojo( "pmd", testPom ); + new File(getBasedir(), "src/test/resources/unit/default-configuration/pmd-report-resolve-rulesets.xml"); + PmdReport mojo = (PmdReport) createReportMojo("pmd", testPom); mojo.rulesets[3] = sonarExportRulesetUrl; mojo.rulesets[4] = myRulesetUrl; mojo.rulesets[5] = notAInternalRulesetUrl; - generateReport( mojo, testPom ); + generateReport(mojo, testPom); // these are the rulesets, that have been copied to target/pmd/rulesets - File generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/custom-rules.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + File generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/custom-rules.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/bestpractices.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/java-design.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/java-design.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/export_format_pmd_language_java_name_Sonar_2520way.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File( + getBasedir(), + "target/test/unit/default-configuration/target/pmd/rulesets/export_format_pmd_language_java_name_Sonar_2520way.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/my-ruleset.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = + new File(getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/my-ruleset.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); - generatedFile = new File( getBasedir(), "target/test/unit/default-configuration/target/pmd/rulesets/InProgressRuleset.xml_at_refs_2Fheads_2Fmaster.xml" ); - assertTrue( FileUtils.fileExists( generatedFile.getAbsolutePath() ) ); + generatedFile = new File( + getBasedir(), + "target/test/unit/default-configuration/target/pmd/rulesets/InProgressRuleset.xml_at_refs_2Fheads_2Fmaster.xml"); + assertTrue(FileUtils.fileExists(generatedFile.getAbsolutePath())); mockServer.stop(); } - } diff --git a/src/test/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojoTest.java b/src/test/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojoTest.java index e97fc8ad..b47508b8 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/pmd/PmdViolationCheckMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd; import java.io.File; @@ -27,154 +26,119 @@ * @author Maria Odea Ching * @version $Id$ */ -public class PmdViolationCheckMojoTest - extends AbstractPmdReportTestCase -{ +public class PmdViolationCheckMojoTest extends AbstractPmdReportTestCase { - public void testDefaultConfiguration() - throws Exception - { - generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); + public void testDefaultConfiguration() throws Exception { + generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); // clear the output from previous pmd:pmd execution - CapturingPrintStream.init( true ); - - 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 ); + CapturingPrintStream.init(true); + + 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 ) - { + fail("MojoFailureException should be thrown."); + } catch (final Exception e) { // the version should be logged String output = CapturingPrintStream.getOutput(); - assertTrue ( output.contains( "PMD version: " + AbstractPmdReport.getPmdVersion() ) ); + assertTrue(output.contains("PMD version: " + AbstractPmdReport.getPmdVersion())); - assertTrue( e.getMessage().startsWith( "You have 8 PMD violations." ) ); + assertTrue(e.getMessage().startsWith("You have 8 PMD violations.")); } } - public void testNotFailOnViolation() - throws Exception - { - generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); + public void testNotFailOnViolation() throws Exception { + generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-notfailonviolation-plugin-config.xml" ); - final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/pmd-check-notfailonviolation-plugin-config.xml"); + final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo("check", testPom); pmdViolationMojo.execute(); - assertTrue( true ); + assertTrue(true); } - public void testMaxAllowedViolations() - throws Exception - { - generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); + public void testMaxAllowedViolations() throws Exception { + generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-notfailmaxviolation-plugin-config.xml" ); - final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/pmd-check-notfailmaxviolation-plugin-config.xml"); + final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo("check", testPom); pmdViolationMojo.execute(); - testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-failmaxviolation-plugin-config.xml" ); - final PmdViolationCheckMojo pmdViolationMojoFail = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/pmd-check-failmaxviolation-plugin-config.xml"); + final PmdViolationCheckMojo pmdViolationMojoFail = (PmdViolationCheckMojo) lookupMojo("check", testPom); - try - { + try { pmdViolationMojoFail.execute(); - fail( "Exception Expected" ); - } - catch ( final MojoFailureException e ) - { + fail("Exception Expected"); + } catch (final MojoFailureException e) { String message = e.getMessage(); - if ( message.contains( "You have 5 PMD violations and 3 warnings." ) ) - { - System.out.println( "Caught expected message: " + e.getMessage() );// expected - } - else - { - throw new AssertionError( "Expected: '" + message - + "' to contain 'You have 5 PMD violations and 3 warnings.'" ); + if (message.contains("You have 5 PMD violations and 3 warnings.")) { + System.out.println("Caught expected message: " + e.getMessage()); // expected + } else { + throw new AssertionError( + "Expected: '" + message + "' to contain 'You have 5 PMD violations and 3 warnings.'"); } } - } - public void testFailurePriority() - throws Exception - { - generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); + public void testFailurePriority() throws Exception { + generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-failonpriority-plugin-config.xml" ); - PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + File 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 - { + 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 ) - { + fail("Exception Expected"); + } catch (final MojoFailureException e) { String message = e.getMessage(); - if ( message.contains( "You have 5 PMD violations and 3 warnings." ) ) - { - System.out.println( "Caught expected message: " + e.getMessage() );// expected - } - else - { - throw new AssertionError( "Expected: '" + message - + "' to contain 'You have 5 PMD violations and 3 warnings.'" ); + if (message.contains("You have 5 PMD violations and 3 warnings.")) { + System.out.println("Caught expected message: " + e.getMessage()); // expected + } else { + throw new AssertionError( + "Expected: '" + message + "' to contain 'You have 5 PMD violations and 3 warnings.'"); } } - } - public void testException() - throws Exception - { - try - { - final File testPom = - new File( getBasedir(), - "src/test/resources/unit/custom-configuration/pmd-check-exception-test-plugin-config.xml" ); - final PmdViolationCheckMojo mojo = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + public void testException() throws Exception { + try { + final File testPom = new File( + getBasedir(), + "src/test/resources/unit/custom-configuration/pmd-check-exception-test-plugin-config.xml"); + final PmdViolationCheckMojo mojo = (PmdViolationCheckMojo) lookupMojo("check", testPom); mojo.execute(); - fail( "MojoFailureException should be thrown." ); - } - catch ( final Exception e ) - { - assertTrue( true ); + fail("MojoFailureException should be thrown."); + } catch (final Exception e) { + assertTrue(true); } - } - public void testViolationExclusion() - throws Exception - { - generateReport( "pmd", "default-configuration/default-configuration-plugin-config.xml" ); + public void testViolationExclusion() throws Exception { + generateReport("pmd", "default-configuration/default-configuration-plugin-config.xml"); - File testPom = - new File( getBasedir(), - "src/test/resources/unit/default-configuration/pmd-check-pmd-exclusions-configuration-plugin-config.xml" ); - final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo( "check", testPom ); + File testPom = new File( + getBasedir(), + "src/test/resources/unit/default-configuration/pmd-check-pmd-exclusions-configuration-plugin-config.xml"); + final PmdViolationCheckMojo pmdViolationMojo = (PmdViolationCheckMojo) lookupMojo("check", testPom); // this call shouldn't throw an exception, as the classes with violations have been excluded pmdViolationMojo.execute(); diff --git a/src/test/java/org/apache/maven/plugins/pmd/exec/ExecutorTest.java b/src/test/java/org/apache/maven/plugins/pmd/exec/ExecutorTest.java index d63eecbb..fadd7197 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/exec/ExecutorTest.java +++ b/src/test/java/org/apache/maven/plugins/pmd/exec/ExecutorTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,31 +16,29 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.exec; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; -import org.apache.commons.lang3.SystemUtils; - import junit.framework.Assert; import junit.framework.TestCase; +import org.apache.commons.lang3.SystemUtils; -public class ExecutorTest extends TestCase -{ +public class ExecutorTest extends TestCase { public void testBuildClasspath() throws MalformedURLException { String basename = "home/test/dir with space/mylib.jar"; String pathname = new File("/", basename).getPath(); - if ( SystemUtils.IS_OS_WINDOWS ) - { - pathname = new File( File.listRoots()[0], basename ).getPath(); + if (SystemUtils.IS_OS_WINDOWS) { + pathname = new File(File.listRoots()[0], basename).getPath(); } - URL[] urls = new URL[] { new File(pathname).toURI().toURL() }; - URLClassLoader mockedClassLoader = new URLClassLoader( urls ); + URL[] urls = new URL[] {new File(pathname).toURI().toURL()}; + URLClassLoader mockedClassLoader = new URLClassLoader(urls); StringBuilder classpath = new StringBuilder(); Executor.buildClasspath(classpath, mockedClassLoader); - Assert.assertEquals( pathname + File.pathSeparator, classpath.toString() ); + Assert.assertEquals(pathname + File.pathSeparator, classpath.toString()); } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/CustomConfigurationMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/CustomConfigurationMavenProjectStub.java index 4fe1d674..93609dc7 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/CustomConfigurationMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/CustomConfigurationMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import java.io.File; import java.io.FileReader; @@ -35,85 +34,73 @@ * @author Maria Odea Ching * @version $Id$ */ -public class CustomConfigurationMavenProjectStub - extends PmdProjectStub -{ +public class CustomConfigurationMavenProjectStub extends PmdProjectStub { private Build build; private List reportPlugins = new ArrayList<>(); - public CustomConfigurationMavenProjectStub() - { + public CustomConfigurationMavenProjectStub() { MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; - try - { - model = - pomReader.read( new FileReader( new File( getBasedir() - + "/src/test/resources/unit/custom-configuration/custom-configuration-plugin-config.xml" ) ) ); - setModel( model ); - } - catch ( Exception e ) - { + try { + model = pomReader.read(new FileReader(new File(getBasedir() + + "/src/test/resources/unit/custom-configuration/custom-configuration-plugin-config.xml"))); + setModel(model); + } catch (Exception e) { } - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); Build build = new Build(); - build.setFinalName( model.getBuild().getFinalName() ); - build.setDirectory( getBasedir() + "/target/test/unit/custom-configuration/target" ); - build.setSourceDirectory( getBasedir() + "/src/test/resources/unit/custom-configuration" ); - setBuild( build ); + build.setFinalName(model.getBuild().getFinalName()); + build.setDirectory(getBasedir() + "/target/test/unit/custom-configuration/target"); + build.setSourceDirectory(getBasedir() + "/src/test/resources/unit/custom-configuration"); + setBuild(build); - setReportPlugins( model.getReporting().getPlugins() ); + setReportPlugins(model.getReporting().getPlugins()); String basedir = getBasedir().getAbsolutePath(); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( basedir + "/src/test/resources/unit/custom-configuration/custom/configuration" ); - setCompileSourceRoots( compileSourceRoots ); + compileSourceRoots.add(basedir + "/src/test/resources/unit/custom-configuration/custom/configuration"); + setCompileSourceRoots(compileSourceRoots); - Artifact artifact = new PmdPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); + Artifact artifact = new PmdPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); - setFile( new File( getBasedir().getAbsolutePath() + "/pom.xml" ) ); + setFile(new File(getBasedir().getAbsolutePath() + "/pom.xml")); } /** {@inheritDoc} */ @Override - public void setBuild( Build build ) - { + public void setBuild(Build build) { this.build = build; } /** {@inheritDoc} */ @Override - public Build getBuild() - { + public Build getBuild() { return build; } - public void setReportPlugins( List plugins ) - { + public void setReportPlugins(List plugins) { this.reportPlugins = plugins; } /** {@inheritDoc} */ @Override - public List getReportPlugins() - { + public List getReportPlugins() { return reportPlugins; } - } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultArtifactHandlerStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultArtifactHandlerStub.java index 4e9d7a96..388d4c52 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultArtifactHandlerStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultArtifactHandlerStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import org.apache.maven.artifact.handler.DefaultArtifactHandler; @@ -25,25 +24,20 @@ * @author Maria Odea Ching * @version $Id$ */ -public class DefaultArtifactHandlerStub - extends DefaultArtifactHandler -{ +public class DefaultArtifactHandlerStub extends DefaultArtifactHandler { private String language; /** {@inheritDoc} */ @Override - public String getLanguage() - { - if ( language == null ) - { + public String getLanguage() { + if (language == null) { language = "java"; } return language; } - public void setLanguage( String language ) - { + public void setLanguage(String language) { this.language = language; } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultConfigurationMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultConfigurationMavenProjectStub.java index daac7959..b16da8d4 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultConfigurationMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/DefaultConfigurationMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import java.io.File; import java.io.FileReader; @@ -35,87 +34,74 @@ * @author Maria Odea Ching * @version $Id$ */ -public class DefaultConfigurationMavenProjectStub - extends PmdProjectStub -{ +public class DefaultConfigurationMavenProjectStub extends PmdProjectStub { private List reportPlugins = new ArrayList<>(); private Build build; - public DefaultConfigurationMavenProjectStub() - { + public DefaultConfigurationMavenProjectStub() { MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; - try ( FileReader reader = new FileReader( new File( getBasedir() - + "/src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml" ) ) ) - { - model = pomReader.read( reader ); - setModel( model ); - } - catch ( Exception e ) - { + try (FileReader reader = new FileReader(new File(getBasedir() + + "/src/test/resources/unit/default-configuration/default-configuration-plugin-config.xml"))) { + model = pomReader.read(reader); + setModel(model); + } catch (Exception e) { } - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); Build build = new Build(); - build.setFinalName( model.getBuild() - .getFinalName() ); - build.setDirectory( getBasedir() + "/target/test/unit/default-configuration/target" ); - build.setSourceDirectory( getBasedir() + "/src/test/resources/unit/default-configuration" ); - setBuild( build ); + build.setFinalName(model.getBuild().getFinalName()); + build.setDirectory(getBasedir() + "/target/test/unit/default-configuration/target"); + build.setSourceDirectory(getBasedir() + "/src/test/resources/unit/default-configuration"); + setBuild(build); - setReportPlugins( model.getReporting() - .getPlugins() ); + setReportPlugins(model.getReporting().getPlugins()); String basedir = getBasedir().getAbsolutePath(); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( basedir + "/src/test/resources/unit/default-configuration/def/configuration" ); - setCompileSourceRoots( compileSourceRoots ); - - File file = new File( getBasedir().getAbsolutePath() + "/pom.xml" ); - setFile( file ); + compileSourceRoots.add(basedir + "/src/test/resources/unit/default-configuration/def/configuration"); + setCompileSourceRoots(compileSourceRoots); - Artifact artifact = new PmdPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); + File file = new File(getBasedir().getAbsolutePath() + "/pom.xml"); + setFile(file); + Artifact artifact = new PmdPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); } - public void setReportPlugins( List plugins ) - { + public void setReportPlugins(List plugins) { this.reportPlugins = plugins; } /** {@inheritDoc} */ @Override - public List getReportPlugins() - { + public List getReportPlugins() { return reportPlugins; } /** {@inheritDoc} */ @Override - public void setBuild( Build build ) - { + public void setBuild(Build build) { this.build = build; } /** {@inheritDoc} */ @Override - public Build getBuild() - { + public Build getBuild() { return build; } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/InvalidFormatMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/InvalidFormatMavenProjectStub.java index f7003139..c08e19cb 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/InvalidFormatMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/InvalidFormatMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import java.io.File; import java.io.FileReader; @@ -34,70 +33,59 @@ * @author Maria Odea Ching * @version $Id$ */ -public class InvalidFormatMavenProjectStub - extends PmdProjectStub -{ +public class InvalidFormatMavenProjectStub extends PmdProjectStub { private Build build; - public InvalidFormatMavenProjectStub() - { + public InvalidFormatMavenProjectStub() { MavenXpp3Reader pomReader = new MavenXpp3Reader(); Model model = null; - try - { - model = - pomReader.read( new FileReader( new File( getBasedir() - + "/src/test/resources/unit/invalid-format/invalid-format-plugin-config.xml" ) ) ); - setModel( model ); - } - catch ( Exception e ) - { + try { + model = pomReader.read(new FileReader(new File( + getBasedir() + "/src/test/resources/unit/invalid-format/invalid-format-plugin-config.xml"))); + setModel(model); + } catch (Exception e) { } - setGroupId( model.getGroupId() ); - setArtifactId( model.getArtifactId() ); - setVersion( model.getVersion() ); - setName( model.getName() ); - setUrl( model.getUrl() ); - setPackaging( model.getPackaging() ); + setGroupId(model.getGroupId()); + setArtifactId(model.getArtifactId()); + setVersion(model.getVersion()); + setName(model.getName()); + setUrl(model.getUrl()); + setPackaging(model.getPackaging()); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); Build build = new Build(); - build.setFinalName( model.getBuild().getFinalName() ); - build.setDirectory( getBasedir() + "/target/test/unit/invalid-format/target" ); - build.setSourceDirectory( getBasedir() + "/src/test/resources/unit/invalid-format" ); - setBuild( build ); + build.setFinalName(model.getBuild().getFinalName()); + build.setDirectory(getBasedir() + "/target/test/unit/invalid-format/target"); + build.setSourceDirectory(getBasedir() + "/src/test/resources/unit/invalid-format"); + setBuild(build); String basedir = getBasedir().getAbsolutePath(); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( basedir + "/src/test/resources/unit/invalid-format/invalid/format" ); - setCompileSourceRoots( compileSourceRoots ); - - Artifact artifact = new PmdPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); + compileSourceRoots.add(basedir + "/src/test/resources/unit/invalid-format/invalid/format"); + setCompileSourceRoots(compileSourceRoots); - setFile( new File( getBasedir().getAbsolutePath() + "/pom.xml" ) ); + Artifact artifact = new PmdPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); + setFile(new File(getBasedir().getAbsolutePath() + "/pom.xml")); } /** {@inheritDoc} */ @Override - public void setBuild( Build build ) - { + public void setBuild(Build build) { this.build = build; } /** {@inheritDoc} */ @Override - public Build getBuild() - { + public Build getBuild() { return build; } - } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdPluginArtifactStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdPluginArtifactStub.java index 7ce2471e..89df0853 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdPluginArtifactStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdPluginArtifactStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import org.apache.maven.artifact.handler.ArtifactHandler; import org.apache.maven.artifact.versioning.VersionRange; @@ -27,9 +26,7 @@ * @author Maria Odea Ching * @version $Id$ */ -public class PmdPluginArtifactStub - extends ArtifactStub -{ +public class PmdPluginArtifactStub extends ArtifactStub { private String groupId; private String artifactId; @@ -42,92 +39,79 @@ public class PmdPluginArtifactStub private ArtifactHandler handler; - public PmdPluginArtifactStub( String groupId, String artifactId, String version, String packaging ) - { + public PmdPluginArtifactStub(String groupId, String artifactId, String version, String packaging) { this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.packaging = packaging; - versionRange = VersionRange.createFromVersion( version ); + versionRange = VersionRange.createFromVersion(version); } /** {@inheritDoc} */ @Override - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } /** {@inheritDoc} */ @Override - public String getGroupId() - { + public String getGroupId() { return groupId; } /** {@inheritDoc} */ @Override - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } /** {@inheritDoc} */ @Override - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } /** {@inheritDoc} */ @Override - public void setVersion( String version ) - { + public void setVersion(String version) { this.version = version; } /** {@inheritDoc} */ @Override - public String getVersion() - { + public String getVersion() { return version; } - public void setPackaging( String packaging ) - { + public void setPackaging(String packaging) { this.packaging = packaging; } - public String getPackaging() - { + public String getPackaging() { return packaging; } /** {@inheritDoc} */ @Override - public VersionRange getVersionRange() - { + public VersionRange getVersionRange() { return versionRange; } /** {@inheritDoc} */ @Override - public void setVersionRange( VersionRange versionRange ) - { + public void setVersionRange(VersionRange versionRange) { this.versionRange = versionRange; } /** {@inheritDoc} */ @Override - public ArtifactHandler getArtifactHandler() - { + public ArtifactHandler getArtifactHandler() { return handler; } /** {@inheritDoc} */ @Override - public void setArtifactHandler( ArtifactHandler handler ) - { + public void setArtifactHandler(ArtifactHandler handler) { this.handler = handler; } } diff --git a/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdProjectStub.java b/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdProjectStub.java index 0b8f6f93..fd34c4f6 100644 --- a/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/pmd/stubs/PmdProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.pmd.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.pmd.stubs; import java.util.Collections; import java.util.List; @@ -28,15 +27,16 @@ import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -public abstract class PmdProjectStub - extends MavenProjectStub -{ +public abstract class PmdProjectStub extends MavenProjectStub { @Override - public List getRemoteArtifactRepositories() - { - ArtifactRepository repository = new MavenArtifactRepository( "central", "https://repo1.maven.org/maven2", - new DefaultRepositoryLayout(), new ArtifactRepositoryPolicy(), new ArtifactRepositoryPolicy() ); + public List getRemoteArtifactRepositories() { + ArtifactRepository repository = new MavenArtifactRepository( + "central", + "https://repo1.maven.org/maven2", + new DefaultRepositoryLayout(), + new ArtifactRepositoryPolicy(), + new ArtifactRepositoryPolicy()); - return Collections.singletonList( repository ); + return Collections.singletonList(repository); } }