diff --git a/pom.xml b/pom.xml index 2870b8f1..3de11b9b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 - maven-plugins org.apache.maven.plugins - 37 + maven-plugins + 39 @@ -37,6 +35,18 @@ under the License. Generates a report on violations of code style and optionally fails the build if violations are detected. 2005 + + + Baron Roberts + + + Benson Margulies + + + Csaba Kozák + + + ${mavenVersion} @@ -44,8 +54,8 @@ under the License. scm:git:https://gitbox.apache.org/repos/asf/maven-checkstyle-plugin.git scm:git:https://gitbox.apache.org/repos/asf/maven-checkstyle-plugin.git - https://github.com/apache/maven-checkstyle-plugin/tree/${project.scm.tag} maven-checkstyle-plugin-3.2.2 + https://github.com/apache/maven-checkstyle-plugin/tree/${project.scm.tag} JIRA @@ -74,18 +84,6 @@ under the License. 2023-04-18T14:54:00Z - - - Baron Roberts - - - Benson Margulies - - - Csaba Kozák - - - @@ -117,6 +115,11 @@ under the License. maven-plugin-annotations provided + + org.eclipse.sisu + org.eclipse.sisu.plexus + provided + @@ -151,6 +154,7 @@ under the License. org.codehaus.plexus plexus-component-annotations + 2.1.1 org.codehaus.plexus @@ -158,8 +162,8 @@ under the License. 1.1.0 - plexus-container-default org.codehaus.plexus + plexus-container-default @@ -194,6 +198,11 @@ under the License. checkstyle ${checkstyleVersion} + + org.apache.commons + commons-lang3 + 3.12.0 + @@ -294,23 +303,6 @@ under the License. - - - maven-checkstyle-plugin - 3.1.1 - - - com.puppycrawl.tools - checkstyle - ${checkstyleVersion} - - - org.apache.maven.shared - maven-shared-resources - 4 - - - @@ -350,10 +342,10 @@ under the License. check-java-compatibility - process-classes check + process-classes @@ -427,6 +419,13 @@ under the License. [9,) + + + javax.xml.bind + jaxb-api + 2.3.1 + + @@ -449,13 +448,6 @@ under the License. - - - javax.xml.bind - jaxb-api - 2.3.1 - - diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleReport.java b/src/main/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleReport.java index f6e4d66c..f0691d83 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleReport.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.ByteArrayOutputStream; import java.io.File; @@ -32,6 +31,11 @@ import java.util.Map; import java.util.ResourceBundle; +import com.puppycrawl.tools.checkstyle.DefaultLogger; +import com.puppycrawl.tools.checkstyle.XMLLogger; +import com.puppycrawl.tools.checkstyle.api.AuditListener; +import com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; @@ -57,33 +61,25 @@ import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.PathTool; -import com.puppycrawl.tools.checkstyle.DefaultLogger; -import com.puppycrawl.tools.checkstyle.XMLLogger; -import com.puppycrawl.tools.checkstyle.api.AuditListener; -import com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; - /** * Base abstract class for Checkstyle reports. * * */ -public abstract class AbstractCheckstyleReport - extends AbstractMavenReport -{ +public abstract class AbstractCheckstyleReport extends AbstractMavenReport { public static final String PLUGIN_RESOURCES = "org/apache/maven/plugins/checkstyle"; protected static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) private MavenSession session; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ - @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) + @Parameter(defaultValue = "${project.build.directory}/checkstyle-cachefile") protected String cacheFile; /** @@ -107,19 +103,19 @@ public abstract class AbstractCheckstyleReport *
  • google_checks.xml: Google Checks.
  • * */ - @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) + @Parameter(property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION) protected String configLocation; /** * Output errors to console. */ - @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) + @Parameter(property = "checkstyle.consoleOutput", defaultValue = "false") protected boolean consoleOutput; /** * Specifies if the build should fail upon a violation. */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean failsOnError; /** @@ -140,7 +136,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.0-beta-2 */ - @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) + @Parameter(property = "checkstyle.header.file", defaultValue = "LICENSE.txt") protected String headerLocation; /** @@ -148,7 +144,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.2 */ - @Parameter( property = "checkstyle.skip", defaultValue = "false" ) + @Parameter(property = "checkstyle.skip", defaultValue = "false") protected boolean skip; /** @@ -156,7 +152,7 @@ public abstract class AbstractCheckstyleReport * of the output file is determined by the outputFileFormat * parameter. */ - @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) + @Parameter(property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml") private File outputFile; /** @@ -175,7 +171,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.0-beta-2 */ - @Parameter( property = "checkstyle.properties.location" ) + @Parameter(property = "checkstyle.properties.location") protected String propertiesLocation; /** @@ -189,7 +185,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.10 */ - @Parameter( defaultValue = "${project.resources}", readonly = true ) + @Parameter(defaultValue = "${project.resources}", readonly = true) protected List resources; /** @@ -197,27 +193,27 @@ public abstract class AbstractCheckstyleReport * * @since 2.11 */ - @Parameter( defaultValue = "${project.testResources}", readonly = true ) + @Parameter(defaultValue = "${project.testResources}", readonly = true) protected List testResources; /** * Specifies the names filter of the source files to be used for Checkstyle. */ - @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) + @Parameter(property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true) protected String includes; /** * Specifies the names filter of the source files to be excluded for * Checkstyle. */ - @Parameter( property = "checkstyle.excludes" ) + @Parameter(property = "checkstyle.excludes") protected String excludes; /** * Specifies the names filter of the resource files to be used for Checkstyle. * @since 2.11 */ - @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) + @Parameter(property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true) protected String resourceIncludes; /** @@ -225,21 +221,21 @@ public abstract class AbstractCheckstyleReport * Checkstyle. * @since 2.11 */ - @Parameter( property = "checkstyle.resourceExcludes" ) + @Parameter(property = "checkstyle.resourceExcludes") protected String resourceExcludes; /** * Specifies whether to include the resource directories in the check. * @since 2.11 */ - @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) + @Parameter(property = "checkstyle.includeResources", defaultValue = "true", required = true) protected boolean includeResources; /** * Specifies whether to include the test resource directories in the check. * @since 2.11 */ - @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) + @Parameter(property = "checkstyle.includeTestResources", defaultValue = "true", required = true) protected boolean includeTestResources; /** @@ -286,7 +282,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.2 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") protected boolean includeTestSourceDirectory; /** @@ -294,7 +290,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.1 */ - @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) + @Parameter(property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file") protected String suppressionsFileExpression; /** @@ -311,7 +307,7 @@ public abstract class AbstractCheckstyleReport * * @since 2.0-beta-2 */ - @Parameter( property = "checkstyle.suppressions.location" ) + @Parameter(property = "checkstyle.suppressions.location") protected String suppressionsLocation; /** @@ -325,25 +321,25 @@ public abstract class AbstractCheckstyleReport * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ - @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) + @Parameter(property = "checkstyle.output.format", defaultValue = "xml") private String outputFileFormat; /** * Specifies if the Rules summary should be enabled or not. */ - @Parameter( property = "checkstyle.enable.rules.summary", defaultValue = "true" ) + @Parameter(property = "checkstyle.enable.rules.summary", defaultValue = "true") private boolean enableRulesSummary; /** * Specifies if the Severity summary should be enabled or not. */ - @Parameter( property = "checkstyle.enable.severity.summary", defaultValue = "true" ) + @Parameter(property = "checkstyle.enable.severity.summary", defaultValue = "true") private boolean enableSeveritySummary; /** * Specifies if the Files summary should be enabled or not. */ - @Parameter( property = "checkstyle.enable.files.summary", defaultValue = "true" ) + @Parameter(property = "checkstyle.enable.files.summary", defaultValue = "true") private boolean enableFilesSummary; /** @@ -351,14 +347,14 @@ public abstract class AbstractCheckstyleReport * * @deprecated This feature will be removed in a future version. */ - @Parameter( property = "checkstyle.enable.rss", defaultValue = "false" ) + @Parameter(property = "checkstyle.enable.rss", defaultValue = "false") @Deprecated private boolean enableRSS; /** * The Plugin Descriptor */ - @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) + @Parameter(defaultValue = "${plugin}", readonly = true, required = true) private PluginDescriptor plugin; /** @@ -367,19 +363,19 @@ public abstract class AbstractCheckstyleReport * * @since 2.1 */ - @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 XrefTests to link to. */ - @Parameter( defaultValue = "${project.reporting.outputDirectory}/xref-test" ) + @Parameter(defaultValue = "${project.reporting.outputDirectory}/xref-test") private File xrefTestLocation; /** @@ -397,7 +393,7 @@ public abstract class AbstractCheckstyleReport * * @since 3.0.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean omitIgnoredModules; /** @@ -430,17 +426,19 @@ public abstract class AbstractCheckstyleReport /** * Dump file for inlined Checkstyle rules. */ - @Parameter( property = "checkstyle.output.rules.file", - defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) + @Parameter( + property = "checkstyle.output.rules.file", + defaultValue = "${project.build.directory}/checkstyle-rules.xml") private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ - @Parameter( defaultValue = "\n" - + "\n" ) + @Parameter( + defaultValue = "\n" + + "\n") private String checkstyleRulesHeader; /** @@ -453,116 +451,98 @@ public abstract class AbstractCheckstyleReport * * @since 2.4 */ - @Component( role = CheckstyleRssGenerator.class, hint = "default" ) + @Component(role = CheckstyleRssGenerator.class, hint = "default") @Deprecated protected CheckstyleRssGenerator checkstyleRssGenerator; /** * @since 2.5 */ - @Component( role = CheckstyleExecutor.class, hint = "default" ) + @Component(role = CheckstyleExecutor.class, hint = "default") protected CheckstyleExecutor checkstyleExecutor; protected ByteArrayOutputStream stringOutputStream; /** {@inheritDoc} */ - public String getName( Locale locale ) - { - return getBundle( locale ).getString( "report.checkstyle.name" ); + public String getName(Locale locale) { + return getBundle(locale).getString("report.checkstyle.name"); } /** {@inheritDoc} */ - public String getDescription( Locale locale ) - { - return getBundle( locale ).getString( "report.checkstyle.description" ); + public String getDescription(Locale locale) { + return getBundle(locale).getString("report.checkstyle.description"); } /** {@inheritDoc} */ - public void executeReport( Locale locale ) - throws MavenReportException - { - checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); - checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); + public void executeReport(Locale locale) throws MavenReportException { + checkDeprecatedParameterUsage(sourceDirectory, "sourceDirectory", "sourceDirectories"); + checkDeprecatedParameterUsage(testSourceDirectory, "testSourceDirectory", "testSourceDirectories"); - locator.addSearchPath( FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath() ); - locator.addSearchPath( "url", "" ); + locator.addSearchPath( + FileResourceLoader.ID, project.getFile().getParentFile().getAbsolutePath()); + locator.addSearchPath("url", ""); - locator.setOutputDirectory( new File( project.getBuild().getDirectory() ) ); + locator.setOutputDirectory(new File(project.getBuild().getDirectory())); // for when we start using maven-shared-io and maven-shared-monitor... // locator = new Locator( new MojoLogMonitorAdaptor( getLog() ) ); // locator = new Locator( getLog(), new File( project.getBuild().getDirectory() ) ); String effectiveConfigLocation = configLocation; - if ( checkstyleRules != null ) - { - if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) - { - throw new MavenReportException( "If you use inline configuration for rules, don't specify " - + "a configLocation" ); + if (checkstyleRules != null) { + if (!DEFAULT_CONFIG_LOCATION.equals(configLocation)) { + throw new MavenReportException( + "If you use inline configuration for rules, don't specify " + "a configLocation"); } - if ( checkstyleRules.getChildCount() > 1 ) - { - throw new MavenReportException( "Currently only one root module is supported" ); + if (checkstyleRules.getChildCount() > 1) { + throw new MavenReportException("Currently only one root module is supported"); } - PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); + PlexusConfiguration checkerModule = checkstyleRules.getChild(0); - try - { - FileUtils.forceMkdir( rulesFiles.getParentFile() ); - FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); - } - catch ( final IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + try { + FileUtils.forceMkdir(rulesFiles.getParentFile()); + FileUtils.fileWrite(rulesFiles, checkstyleRulesHeader + checkerModule.toString()); + } catch (final IOException e) { + throw new MavenReportException(e.getMessage(), e); } effectiveConfigLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - CheckstyleExecutorRequest request = createRequest().setLicenseArtifacts( collectArtifacts( "license" ) ) - .setConfigurationArtifacts( collectArtifacts( "configuration" ) ) - .setOmitIgnoredModules( omitIgnoredModules ) - .setConfigLocation( effectiveConfigLocation ); + try { + CheckstyleExecutorRequest request = createRequest() + .setLicenseArtifacts(collectArtifacts("license")) + .setConfigurationArtifacts(collectArtifacts("configuration")) + .setOmitIgnoredModules(omitIgnoredModules) + .setConfigLocation(effectiveConfigLocation); - CheckstyleResults results = checkstyleExecutor.executeCheckstyle( request ); + CheckstyleResults results = checkstyleExecutor.executeCheckstyle(request); - ResourceBundle bundle = getBundle( locale ); + ResourceBundle bundle = getBundle(locale); generateReportStatics(); - generateMainReport( results, bundle, effectiveConfigLocation ); - if ( enableRSS ) - { + generateMainReport(results, bundle, effectiveConfigLocation); + if (enableRSS) { CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest = - new CheckstyleRssGeneratorRequest( this.project, this.getCopyright(), outputDirectory, getLog() ); - checkstyleRssGenerator.generateRSS( results, checkstyleRssGeneratorRequest ); + new CheckstyleRssGeneratorRequest(this.project, this.getCopyright(), outputDirectory, getLog()); + checkstyleRssGenerator.generateRSS(results, checkstyleRssGeneratorRequest); } - } - catch ( CheckstyleException e ) - { - throw new MavenReportException( "Failed during checkstyle configuration", e ); - } - catch ( CheckstyleExecutorException e ) - { - throw new MavenReportException( "Failed during checkstyle execution", e ); - } - finally - { - //be sure to restore original context classloader - Thread.currentThread().setContextClassLoader( currentClassLoader ); + } catch (CheckstyleException e) { + throw new MavenReportException("Failed during checkstyle configuration", e); + } catch (CheckstyleExecutorException e) { + throw new MavenReportException("Failed during checkstyle execution", e); + } finally { + // be sure to restore original context classloader + Thread.currentThread().setContextClassLoader(currentClassLoader); } } - private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) - throws MavenReportException - { - if ( parameter != null ) - { - throw new MavenReportException( "You are using '" + name + "' which has been removed" - + " from the maven-checkstyle-plugin. " + "Please use '" + replacement - + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); + private void checkDeprecatedParameterUsage(Object parameter, String name, String replacement) + throws MavenReportException { + if (parameter != null) { + throw new MavenReportException("You are using '" + name + "' which has been removed" + + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site."); } } @@ -572,36 +552,31 @@ private void checkDeprecatedParameterUsage( Object parameter, String name, Strin * @return The executor request. * @throws MavenReportException If something goes wrong during creation. */ - protected abstract CheckstyleExecutorRequest createRequest() - throws MavenReportException; + protected abstract CheckstyleExecutorRequest createRequest() throws MavenReportException; - private List collectArtifacts( String hint ) - { + private List collectArtifacts(String hint) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); - if ( pluginManagement != null ) - { - artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); + if (pluginManagement != null) { + artifacts.addAll(getCheckstylePluginDependenciesAsArtifacts(pluginManagement.getPluginsAsMap(), hint)); } - artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); + artifacts.addAll( + getCheckstylePluginDependenciesAsArtifacts(project.getBuild().getPluginsAsMap(), hint)); return artifacts; } - private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) - { + private List getCheckstylePluginDependenciesAsArtifacts(Map plugins, String hint) { List artifacts = new ArrayList<>(); - Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); - if ( checkstylePlugin != null ) - { - for ( Dependency dep : checkstylePlugin.getDependencies() ) - { - // @todo if we can filter on hints, it should be done here... + Plugin checkstylePlugin = plugins.get(plugin.getGroupId() + ":" + plugin.getArtifactId()); + if (checkstylePlugin != null) { + for (Dependency dep : checkstylePlugin.getDependencies()) { + // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); - artifacts.add( plugin.getArtifactMap().get( depKey ) ); + artifacts.add(plugin.getArtifactMap().get(depKey)); } } return artifacts; @@ -613,54 +588,40 @@ private List getCheckstylePluginDependenciesAsArtifacts( Map 0 ) - { - getLog().warn( "Unable to locate Source XRef to link to - DISABLED" ); + new CheckstyleReportGenerator(getSink(), bundle, project.getBasedir(), siteTool, configLocation); + + generator.setLog(getLog()); + generator.setEnableRulesSummary(enableRulesSummary); + generator.setEnableSeveritySummary(enableSeveritySummary); + generator.setEnableFilesSummary(enableFilesSummary); + generator.setEnableRSS(enableRSS); + generator.setCheckstyleConfig(results.getConfiguration()); + if (linkXRef) { + initializeXrefLocation(generator); + if (generator.getXrefLocation() == null && results.getFileCount() > 0) { + getLog().warn("Unable to locate Source XRef to link to - DISABLED"); } - initializeXrefTestLocation( generator ); - if ( generator.getXrefTestLocation() == null && results.getFileCount() > 0 ) - { - getLog().warn( "Unable to locate Test Source XRef to link to - DISABLED" ); + initializeXrefTestLocation(generator); + if (generator.getXrefTestLocation() == null && results.getFileCount() > 0) { + getLog().warn("Unable to locate Test Source XRef to link to - DISABLED"); } - generator.setTestSourceDirectories( getTestSourceDirectories() ); + generator.setTestSourceDirectories(getTestSourceDirectories()); } - if ( treeWalkerNames != null ) - { - generator.setTreeWalkerNames( treeWalkerNames ); + if (treeWalkerNames != null) { + generator.setTreeWalkerNames(treeWalkerNames); } - generator.generateReport( results ); + generator.generateReport(results); } - private void initializeXrefLocation( CheckstyleReportGenerator generator ) - { - String relativePath = determineRelativePath( xrefLocation ); - if ( xrefLocation.exists() || checkMavenJxrPluginIsConfigured() ) - { - // XRef was already generated by manual execution of a lifecycle binding - // the report is on its way - generator.setXrefLocation( relativePath ); - } + private void initializeXrefLocation(CheckstyleReportGenerator generator) { + String relativePath = determineRelativePath(xrefLocation); + if (xrefLocation.exists() || checkMavenJxrPluginIsConfigured()) { + // XRef was already generated by manual execution of a lifecycle binding + // the report is on its way + generator.setXrefLocation(relativePath); + } } - private void initializeXrefTestLocation( CheckstyleReportGenerator generator ) - { - String relativePath = determineRelativePath( xrefTestLocation ); - if ( xrefTestLocation.exists() || checkMavenJxrPluginIsConfigured() ) - { - // XRef was already generated by manual execution of a lifecycle binding - // the report is on its way - generator.setXrefTestLocation( relativePath ); - } + private void initializeXrefTestLocation(CheckstyleReportGenerator generator) { + String relativePath = determineRelativePath(xrefTestLocation); + if (xrefTestLocation.exists() || checkMavenJxrPluginIsConfigured()) { + // XRef was already generated by manual execution of a lifecycle binding + // the report is on its way + generator.setXrefTestLocation(relativePath); + } } - private String determineRelativePath( File location ) - { - String relativePath = PathTool.getRelativePath( getOutputDirectory(), location.getAbsolutePath() ); - if ( relativePath == null || relativePath.trim().isEmpty() ) - { - relativePath = "."; - } + private String determineRelativePath(File location) { + String relativePath = PathTool.getRelativePath(getOutputDirectory(), location.getAbsolutePath()); + if (relativePath == null || relativePath.trim().isEmpty()) { + relativePath = "."; + } - return relativePath + "/" + location.getName(); + return relativePath + "/" + location.getName(); } - private boolean checkMavenJxrPluginIsConfigured() - { - for ( ReportPlugin report : (Iterable) getProject().getReportPlugins() ) - { + private boolean checkMavenJxrPluginIsConfigured() { + for (ReportPlugin report : (Iterable) getProject().getReportPlugins()) { String artifactId = report.getArtifactId(); - if ( "maven-jxr-plugin".equals( artifactId ) || "jxr-maven-plugin".equals( artifactId ) ) - { + if ("maven-jxr-plugin".equals(artifactId) || "jxr-maven-plugin".equals(artifactId)) { return true; } } @@ -808,35 +740,28 @@ private boolean checkMavenJxrPluginIsConfigured() return false; } - private static ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "checkstyle-report", locale, AbstractCheckstyleReport.class.getClassLoader() ); + private static ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle("checkstyle-report", locale, AbstractCheckstyleReport.class.getClassLoader()); } - protected List getSourceDirectories() - { - if ( sourceDirectories == null ) - { + protected List getSourceDirectories() { + if (sourceDirectories == null) { sourceDirectories = project.getCompileSourceRoots(); } - List sourceDirs = new ArrayList<>( sourceDirectories.size() ); - for ( String sourceDir : sourceDirectories ) - { - sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); + List sourceDirs = new ArrayList<>(sourceDirectories.size()); + for (String sourceDir : sourceDirectories) { + sourceDirs.add(FileUtils.resolveFile(project.getBasedir(), sourceDir)); } return sourceDirs; } - protected List getTestSourceDirectories() - { - if ( testSourceDirectories == null ) - { + protected List getTestSourceDirectories() { + if (testSourceDirectories == null) { testSourceDirectories = project.getTestCompileSourceRoots(); } - List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); - for ( String testSourceDir : testSourceDirectories ) - { - testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); + List testSourceDirs = new ArrayList<>(testSourceDirectories.size()); + for (String testSourceDir : testSourceDirectories) { + testSourceDirs.add(FileUtils.resolveFile(project.getBasedir(), testSourceDir)); } return testSourceDirs; } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleAggregateReport.java b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleAggregateReport.java index 6d9b3813..79563e16 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleAggregateReport.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleAggregateReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle; + +import java.util.List; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @@ -26,8 +27,6 @@ import org.apache.maven.project.MavenProject; import org.apache.maven.reporting.MavenReportException; -import java.util.List; - /** * A reporting task that performs Checkstyle analysis and generates an aggregate * HTML report on the violations that Checkstyle finds in a multi-module reactor @@ -35,61 +34,66 @@ * * */ -@Mojo( name = "checkstyle-aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true ) -public class CheckstyleAggregateReport - extends AbstractCheckstyleReport -{ +@Mojo( + name = "checkstyle-aggregate", + aggregator = true, + requiresDependencyResolution = ResolutionScope.COMPILE, + threadSafe = true) +public class CheckstyleAggregateReport extends AbstractCheckstyleReport { /** * The projects in the reactor for aggregation report. * * @since 2.8 */ - @Parameter( property = "reactorProjects", readonly = true ) + @Parameter(property = "reactorProjects", readonly = true) private List reactorProjects; /** {@inheritDoc} */ - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ - protected CheckstyleExecutorRequest createRequest() - throws MavenReportException - { + protected CheckstyleExecutorRequest createRequest() throws MavenReportException { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); - request.setAggregate( true ) - .setReactorProjects( reactorProjects ) - .setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) - .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) - .setIncludeResources( includeResources ) - .setIncludeTestResources( includeTestResources ) - .setResourceIncludes( resourceIncludes ) - .setResourceExcludes( resourceExcludes ) - .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) - .setProject( project ).setSourceDirectories( getSourceDirectories() ) - .setResources( resources ).setTestResources( testResources ) - .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) - .setTestSourceDirectories( getTestSourceDirectories() ) - .setPropertyExpansion( propertyExpansion ).setHeaderLocation( headerLocation ) - .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) - .setEncoding( getInputEncoding() ).setPropertiesLocation( propertiesLocation ); + request.setAggregate(true) + .setReactorProjects(reactorProjects) + .setConsoleListener(getConsoleListener()) + .setConsoleOutput(consoleOutput) + .setExcludes(excludes) + .setFailsOnError(failsOnError) + .setIncludes(includes) + .setIncludeResources(includeResources) + .setIncludeTestResources(includeTestResources) + .setResourceIncludes(resourceIncludes) + .setResourceExcludes(resourceExcludes) + .setIncludeTestSourceDirectory(includeTestSourceDirectory) + .setListener(getListener()) + .setProject(project) + .setSourceDirectories(getSourceDirectories()) + .setResources(resources) + .setTestResources(testResources) + .setStringOutputStream(stringOutputStream) + .setSuppressionsLocation(suppressionsLocation) + .setTestSourceDirectories(getTestSourceDirectories()) + .setPropertyExpansion(propertyExpansion) + .setHeaderLocation(headerLocation) + .setCacheFile(cacheFile) + .setSuppressionsFileExpression(suppressionsFileExpression) + .setEncoding(getInputEncoding()) + .setPropertiesLocation(propertiesLocation); return request; } - /** {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "checkstyle-aggregate"; } /** {@inheritDoc} */ - public boolean canGenerateReport() - { + public boolean canGenerateReport() { // TODO: would be good to scan the files here return !skip && project.isExecutionRoot() && reactorProjects.size() > 1; } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReport.java b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReport.java index c7424219..08d5835b 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReport.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.File; import java.util.List; @@ -38,78 +37,72 @@ * @author Joakim Erdfelt * */ -@Mojo( name = "checkstyle", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) -public class CheckstyleReport - extends AbstractCheckstyleReport -{ +@Mojo(name = "checkstyle", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) +public class CheckstyleReport extends AbstractCheckstyleReport { /** {@inheritDoc} */ - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } /** * {@inheritDoc} */ - protected CheckstyleExecutorRequest createRequest() - throws MavenReportException - { + protected CheckstyleExecutorRequest createRequest() throws MavenReportException { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); - request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) - .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) - .setResourceIncludes( resourceIncludes ) - .setResourceExcludes( resourceExcludes ) - .setIncludeResources( includeResources ) - .setIncludeTestResources( includeTestResources ) - .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) - .setProject( project ).setSourceDirectories( getSourceDirectories() ) - .setResources( resources ) - .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) - .setTestSourceDirectories( getTestSourceDirectories() ) - .setPropertyExpansion( propertyExpansion ).setHeaderLocation( headerLocation ) - .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) - .setEncoding( getInputEncoding() ).setPropertiesLocation( propertiesLocation ); + request.setConsoleListener(getConsoleListener()) + .setConsoleOutput(consoleOutput) + .setExcludes(excludes) + .setFailsOnError(failsOnError) + .setIncludes(includes) + .setResourceIncludes(resourceIncludes) + .setResourceExcludes(resourceExcludes) + .setIncludeResources(includeResources) + .setIncludeTestResources(includeTestResources) + .setIncludeTestSourceDirectory(includeTestSourceDirectory) + .setListener(getListener()) + .setProject(project) + .setSourceDirectories(getSourceDirectories()) + .setResources(resources) + .setStringOutputStream(stringOutputStream) + .setSuppressionsLocation(suppressionsLocation) + .setTestSourceDirectories(getTestSourceDirectories()) + .setPropertyExpansion(propertyExpansion) + .setHeaderLocation(headerLocation) + .setCacheFile(cacheFile) + .setSuppressionsFileExpression(suppressionsFileExpression) + .setEncoding(getInputEncoding()) + .setPropertiesLocation(propertiesLocation); return request; } /** {@inheritDoc} */ - public String getOutputName() - { + public String getOutputName() { return "checkstyle"; } /** {@inheritDoc} */ - public boolean canGenerateReport() - { - if ( skip ) - { + public boolean canGenerateReport() { + if (skip) { return false; } // TODO: would be good to scan the files here - for ( File sourceDirectory : getSourceDirectories() ) - { - if ( sourceDirectory.exists() ) - { + for (File sourceDirectory : getSourceDirectories()) { + if (sourceDirectory.exists()) { return true; } } - if ( includeTestSourceDirectory ) - { - for ( File testSourceDirectory : getTestSourceDirectories() ) - { - if ( testSourceDirectory.exists() ) - { + if (includeTestSourceDirectory) { + for (File testSourceDirectory : getTestSourceDirectories()) { + if (testSourceDirectory.exists()) { return true; } } } - return ( ( includeResources && hasResources( resources ) ) - || ( includeTestResources && hasResources( testResources ) ) - ); + return ((includeResources && hasResources(resources)) || (includeTestResources && hasResources(testResources))); } /** @@ -117,16 +110,12 @@ public boolean canGenerateReport() * @param resources The resources to check * @return true if the resource directory exist */ - private boolean hasResources( List resources ) - { - for ( Resource resource : resources ) - { - if ( new File( resource.getDirectory() ).exists() ) - { + private boolean hasResources(List resources) { + for (Resource resource : resources) { + if (new File(resource.getDirectory()).exists()) { return true; } } - return false; + return false; } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReportGenerator.java b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReportGenerator.java index af163b23..ce5553e7 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReportGenerator.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleReportGenerator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.File; import java.util.ArrayList; @@ -26,6 +25,10 @@ import java.util.List; import java.util.ResourceBundle; +import com.puppycrawl.tools.checkstyle.api.AuditEvent; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import org.apache.commons.lang3.StringUtils; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkEventAttributes; @@ -35,18 +38,12 @@ import org.apache.maven.plugin.logging.SystemStreamLog; import org.apache.maven.plugins.checkstyle.exec.CheckstyleResults; -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.api.SeverityLevel; - /** * Generate a report based on CheckstyleResults. * * */ -public class CheckstyleReportGenerator -{ +public class CheckstyleReportGenerator { private Log log; private final File basedir; @@ -76,15 +73,14 @@ public class CheckstyleReportGenerator private List testSourceDirectories = new ArrayList<>(); - private List treeWalkerNames = Collections.singletonList( "TreeWalker" ); + private List treeWalkerNames = Collections.singletonList("TreeWalker"); private final IconTool iconTool; private final String ruleset; - public CheckstyleReportGenerator( Sink sink, ResourceBundle bundle, File basedir, SiteTool siteTool, - String ruleset ) - { + public CheckstyleReportGenerator( + Sink sink, ResourceBundle bundle, File basedir, SiteTool siteTool, String ruleset) { this.bundle = bundle; this.sink = sink; @@ -99,72 +95,59 @@ public CheckstyleReportGenerator( Sink sink, ResourceBundle bundle, File basedir this.enableSeveritySummary = true; this.enableFilesSummary = true; this.enableRSS = false; - this.iconTool = new IconTool( sink, bundle ); + this.iconTool = new IconTool(sink, bundle); } - public Log getLog() - { - if ( this.log == null ) - { + public Log getLog() { + if (this.log == null) { this.log = new SystemStreamLog(); } return this.log; } - public void setLog( Log log ) - { + public void setLog(Log log) { this.log = log; } - private String getTitle() - { + private String getTitle() { String title; - if ( getSeverityLevel() == null ) - { - title = bundle.getString( "report.checkstyle.title" ); - } - else - { - title = bundle.getString( "report.checkstyle.severity_title" ) + severityLevel.getName(); + if (getSeverityLevel() == null) { + title = bundle.getString("report.checkstyle.title"); + } else { + title = bundle.getString("report.checkstyle.severity_title") + severityLevel.getName(); } return title; } - public void generateReport( CheckstyleResults results ) - { + public void generateReport(CheckstyleResults results) { doHeading(); - if ( getSeverityLevel() == null ) - { - if ( enableSeveritySummary ) - { - doSeveritySummary( results ); + if (getSeverityLevel() == null) { + if (enableSeveritySummary) { + doSeveritySummary(results); } - if ( enableFilesSummary ) - { - doFilesSummary( results ); + if (enableFilesSummary) { + doFilesSummary(results); } - if ( enableRulesSummary ) - { - doRulesSummary( results ); + if (enableRulesSummary) { + doRulesSummary(results); } } - doDetails( results ); + doDetails(results); sink.body_(); sink.flush(); sink.close(); } - private void doHeading() - { + private void doHeading() { sink.head(); sink.title(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.title_(); sink.head_(); @@ -172,33 +155,31 @@ private void doHeading() sink.section1(); sink.sectionTitle1(); - sink.text( getTitle() ); + sink.text(getTitle()); sink.sectionTitle1_(); sink.paragraph(); - sink.text( bundle.getString( "report.checkstyle.checkstylelink" ) + " " ); - sink.link( "https://checkstyle.org/" ); - sink.text( "Checkstyle" ); + sink.text(bundle.getString("report.checkstyle.checkstylelink") + " "); + sink.link("https://checkstyle.org/"); + sink.text("Checkstyle"); sink.link_(); String version = getCheckstyleVersion(); - if ( version != null ) - { - sink.text( " " ); - sink.text( version ); + if (version != null) { + sink.text(" "); + sink.text(version); } - sink.text( " " ); - sink.text( String.format( bundle.getString( "report.checkstyle.ruleset" ), ruleset ) ); - sink.text( "." ); + sink.text(" "); + sink.text(String.format(bundle.getString("report.checkstyle.ruleset"), ruleset)); + sink.text("."); - if ( enableRSS ) - { + if (enableRSS) { sink.nonBreakingSpace(); - sink.link( "checkstyle.rss" ); + sink.link("checkstyle.rss"); sink.figure(); sink.figureCaption(); - sink.text( "rss feed" ); + sink.text("rss feed"); sink.figureCaption_(); - sink.figureGraphics( "images/rss.png" ); + sink.figureGraphics("images/rss.png"); sink.figure_(); sink.link_(); } @@ -220,25 +201,20 @@ private void doHeading() * @param defaultValue The default value to use if the attribute cannot be found in any configuration * @return The value of the specified attribute */ - private String getConfigAttribute( Configuration config, ChainedItem parentConfiguration, - String attributeName, String defaultValue ) - { + private String getConfigAttribute( + Configuration config, + ChainedItem parentConfiguration, + String attributeName, + String defaultValue) { String ret; - try - { - ret = config.getAttribute( attributeName ); - } - catch ( CheckstyleException e ) - { + try { + ret = config.getAttribute(attributeName); + } catch (CheckstyleException e) { // Try to find the attribute in a parent, if there are any - if ( parentConfiguration != null ) - { - ret = - getConfigAttribute( parentConfiguration.value, parentConfiguration.parent, attributeName, - defaultValue ); - } - else - { + if (parentConfiguration != null) { + ret = getConfigAttribute( + parentConfiguration.value, parentConfiguration.parent, attributeName, defaultValue); + } else { ret = defaultValue; } } @@ -250,56 +226,50 @@ private String getConfigAttribute( Configuration config, ChainedItem parentConfiguration = ref.parentConfiguration; String ruleName = checkerConfig.getName(); @@ -328,80 +297,65 @@ private void doRuleRow( ConfReference ref, CheckstyleResults results, String pre // column 1: rule category sink.tableCell(); String category = ref.category; - if ( !category.equals( previousCategory ) ) - { - sink.text( category ); + if (!category.equals(previousCategory)) { + sink.text(category); } sink.tableCell_(); // column 2: Rule name + configured attributes sink.tableCell(); - if ( !"extension".equals( category ) ) - { - sink.link( "https://checkstyle.org/config_" + category + ".html#" + ruleName ); - sink.text( ruleName ); + if (!"extension".equals(category)) { + sink.link("https://checkstyle.org/config_" + category + ".html#" + ruleName); + sink.text(ruleName); sink.link_(); - } - else - { - sink.text( ruleName ); + } else { + sink.text(ruleName); } - List attribnames = new ArrayList<>( Arrays.asList( checkerConfig.getAttributeNames() ) ); - attribnames.remove( "severity" ); // special value (deserves unique column) - if ( !attribnames.isEmpty() ) - { + List attribnames = new ArrayList<>(Arrays.asList(checkerConfig.getAttributeNames())); + attribnames.remove("severity"); // special value (deserves unique column) + if (!attribnames.isEmpty()) { sink.list(); - for ( String name : attribnames ) - { + for (String name : attribnames) { sink.listItem(); - sink.text( name ); + sink.text(name); - String value = getConfigAttribute( checkerConfig, null, name, "" ); + String value = getConfigAttribute(checkerConfig, null, name, ""); // special case, Header.header and RegexpHeader.header - if ( "header".equals( name ) && ( "Header".equals( ruleName ) || "RegexpHeader".equals( ruleName ) ) ) - { - String[] lines = StringUtils.split( value, "\\n" ); + if ("header".equals(name) && ("Header".equals(ruleName) || "RegexpHeader".equals(ruleName))) { + String[] lines = StringUtils.split(value, "\\n"); int linenum = 1; - for ( String line : lines ) - { + for (String line : lines) { sink.lineBreak(); - sink.rawText( "" ); - sink.text( linenum + ":" ); - sink.rawText( "" ); + sink.rawText(""); + sink.text(linenum + ":"); + sink.rawText(""); sink.nonBreakingSpace(); sink.monospaced(); - sink.text( line ); + sink.text(line); sink.monospaced_(); linenum++; } - } - else if ( "headerFile".equals( name ) && "RegexpHeader".equals( ruleName ) ) - { - sink.text( ": " ); + } else if ("headerFile".equals(name) && "RegexpHeader".equals(ruleName)) { + sink.text(": "); sink.monospaced(); - sink.text( "\"" ); - if ( basedir != null ) - { + sink.text("\""); + if (basedir != null) { // Make the headerFile value relative to ${basedir} - String path = siteTool.getRelativePath( value, basedir.getAbsolutePath() ); - sink.text( path.replace( '\\', '/' ) ); - } - else - { - sink.text( value ); + String path = siteTool.getRelativePath(value, basedir.getAbsolutePath()); + sink.text(path.replace('\\', '/')); + } else { + sink.text(value); } - sink.text( "\"" ); + sink.text("\""); sink.monospaced_(); - } - else - { - sink.text( ": " ); + } else { + sink.text(": "); sink.monospaced(); - sink.text( "\"" ); - sink.text( value ); - sink.text( "\"" ); + sink.text("\""); + sink.text(value); + sink.text("\""); sink.monospaced_(); } sink.listItem_(); @@ -413,15 +367,15 @@ else if ( "headerFile".equals( name ) && "RegexpHeader".equals( ruleName ) ) // column 3: rule violation count sink.tableCell(); - sink.text( String.valueOf( ref.violations ) ); + sink.text(String.valueOf(ref.violations)); sink.tableCell_(); // column 4: severity sink.tableCell(); // Grab the severity from the rule configuration, this time use error as default value // Also pass along all parent configurations, so that we can try to find the severity there - String severity = getConfigAttribute( checkerConfig, parentConfiguration, "severity", "error" ); - iconTool.iconSeverity( severity, IconTool.TEXT_SIMPLE ); + String severity = getConfigAttribute(checkerConfig, parentConfiguration, "severity", "error"); + iconTool.iconSeverity(severity, IconTool.TEXT_SIMPLE); sink.tableCell_(); sink.tableRow_(); @@ -436,25 +390,20 @@ else if ( "headerFile".equals( name ) && "RegexpHeader".equals( ruleName ) ) * @param expectedSeverity A severity that, if it's not null, will be matched to the severity from the violation * @return The number of rule violations */ - public boolean matchRule( AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity ) - { - if ( !ruleName.equals( RuleUtil.getName( event ) ) ) - { + public boolean matchRule(AuditEvent event, String ruleName, String expectedMessage, String expectedSeverity) { + if (!ruleName.equals(RuleUtil.getName(event))) { return false; } // check message too, for those that have a specific one. // like GenericIllegalRegexp and Regexp - if ( expectedMessage != null ) - { + if (expectedMessage != null) { // event.getMessage() uses java.text.MessageFormat in its implementation. // Read MessageFormat Javadoc about single quote: // http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html - String msgWithoutSingleQuote = StringUtils.replace( expectedMessage, "'", "" ); + String msgWithoutSingleQuote = StringUtils.replace(expectedMessage, "'", ""); - if ( ! ( expectedMessage.equals( event.getMessage() ) - || msgWithoutSingleQuote.equals( event.getMessage() ) ) ) - { + if (!(expectedMessage.equals(event.getMessage()) || msgWithoutSingleQuote.equals(event.getMessage()))) { return false; } } @@ -462,56 +411,53 @@ public boolean matchRule( AuditEvent event, String ruleName, String expectedMess // different configurations for the same rule, where each // configuration has a different severity, like JavadocMethod. // See also https://issues.apache.org/jira/browse/MCHECKSTYLE-41 - if ( expectedSeverity != null ) - { - if ( !expectedSeverity.equals( event.getSeverityLevel().getName() ) ) - { + if (expectedSeverity != null) { + if (!expectedSeverity.equals(event.getSeverityLevel().getName())) { return false; } } return true; } - private void doSeveritySummary( CheckstyleResults results ) - { + private void doSeveritySummary(CheckstyleResults results) { sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.checkstyle.summary" ) ); + sink.text(bundle.getString("report.checkstyle.summary")); sink.sectionTitle1_(); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.files" ) ); + sink.text(bundle.getString("report.checkstyle.files")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconInfo( IconTool.TEXT_TITLE ); + iconTool.iconInfo(IconTool.TEXT_TITLE); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconWarning( IconTool.TEXT_TITLE ); + iconTool.iconWarning(IconTool.TEXT_TITLE); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconError( IconTool.TEXT_TITLE ); + iconTool.iconError(IconTool.TEXT_TITLE); sink.tableHeaderCell_(); sink.tableRow_(); sink.tableRow(); sink.tableCell(); - sink.text( String.valueOf( results.getFileCount() ) ); + sink.text(String.valueOf(results.getFileCount())); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.INFO ) ) ); + sink.text(String.valueOf(results.getSeverityCount(SeverityLevel.INFO))); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.WARNING ) ) ); + sink.text(String.valueOf(results.getSeverityCount(SeverityLevel.WARNING))); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( SeverityLevel.ERROR ) ) ); + sink.text(String.valueOf(results.getSeverityCount(SeverityLevel.ERROR))); sink.tableCell_(); sink.tableRow_(); @@ -521,40 +467,37 @@ private void doSeveritySummary( CheckstyleResults results ) sink.section1_(); } - private void doFilesSummary( CheckstyleResults results ) - { + private void doFilesSummary(CheckstyleResults results) { sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.checkstyle.files" ) ); + sink.text(bundle.getString("report.checkstyle.files")); sink.sectionTitle1_(); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.file" ) ); + sink.text(bundle.getString("report.checkstyle.file")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconInfo( IconTool.TEXT_ABBREV ); + iconTool.iconInfo(IconTool.TEXT_ABBREV); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconWarning( IconTool.TEXT_ABBREV ); + iconTool.iconWarning(IconTool.TEXT_ABBREV); sink.tableHeaderCell_(); sink.tableHeaderCell(); - iconTool.iconError( IconTool.TEXT_ABBREV ); + iconTool.iconError(IconTool.TEXT_ABBREV); sink.tableHeaderCell_(); sink.tableRow_(); // Sort the files before writing them to the report - List fileList = new ArrayList<>( results.getFiles().keySet() ); - Collections.sort( fileList ); - - for ( String filename : fileList ) - { - List violations = results.getFileViolations( filename ); - if ( violations.isEmpty() ) - { + List fileList = new ArrayList<>(results.getFiles().keySet()); + Collections.sort(fileList); + + for (String filename : fileList) { + List violations = results.getFileViolations(filename); + if (violations.isEmpty()) { // skip files without violations continue; } @@ -562,21 +505,21 @@ private void doFilesSummary( CheckstyleResults results ) sink.tableRow(); sink.tableCell(); - sink.link( "#" + filename.replace( '/', '.' ) ); - sink.text( filename ); + sink.link("#" + filename.replace('/', '.')); + sink.text(filename); sink.link_(); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.INFO ) ) ); + sink.text(String.valueOf(results.getSeverityCount(violations, SeverityLevel.INFO))); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.WARNING ) ) ); + sink.text(String.valueOf(results.getSeverityCount(violations, SeverityLevel.WARNING))); sink.tableCell_(); sink.tableCell(); - sink.text( String.valueOf( results.getSeverityCount( violations, SeverityLevel.ERROR ) ) ); + sink.text(String.valueOf(results.getSeverityCount(violations, SeverityLevel.ERROR))); sink.tableCell_(); sink.tableRow_(); @@ -588,57 +531,54 @@ private void doFilesSummary( CheckstyleResults results ) sink.section1_(); } - private void doDetails( CheckstyleResults results ) - { + private void doDetails(CheckstyleResults results) { sink.section1(); sink.sectionTitle1(); - sink.text( bundle.getString( "report.checkstyle.details" ) ); + sink.text(bundle.getString("report.checkstyle.details")); sink.sectionTitle1_(); // Sort the files before writing their details to the report - List fileList = new ArrayList<>( results.getFiles().keySet() ); - Collections.sort( fileList ); + List fileList = new ArrayList<>(results.getFiles().keySet()); + Collections.sort(fileList); - for ( String file : fileList ) - { - List violations = results.getFileViolations( file ); + for (String file : fileList) { + List violations = results.getFileViolations(file); - if ( violations.isEmpty() ) - { + if (violations.isEmpty()) { // skip files without violations continue; } sink.section2(); SinkEventAttributes attrs = new SinkEventAttributeSet(); - attrs.addAttribute( SinkEventAttributes.ID, file.replace( '/', '.' ) ); - sink.sectionTitle( Sink.SECTION_LEVEL_2, attrs ); - sink.text( file ); - sink.sectionTitle_( Sink.SECTION_LEVEL_2 ); + attrs.addAttribute(SinkEventAttributes.ID, file.replace('/', '.')); + sink.sectionTitle(Sink.SECTION_LEVEL_2, attrs); + sink.text(file); + sink.sectionTitle_(Sink.SECTION_LEVEL_2); sink.table(); - sink.tableRows( null, false ); + sink.tableRows(null, false); sink.tableRow(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.column.severity" ) ); + sink.text(bundle.getString("report.checkstyle.column.severity")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.rule.category" ) ); + sink.text(bundle.getString("report.checkstyle.rule.category")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.rule" ) ); + sink.text(bundle.getString("report.checkstyle.rule")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.column.message" ) ); + sink.text(bundle.getString("report.checkstyle.column.message")); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( bundle.getString( "report.checkstyle.column.line" ) ); + sink.text(bundle.getString("report.checkstyle.column.line")); sink.tableHeaderCell_(); sink.tableRow_(); - doFileEvents( violations, file ); + doFileEvents(violations, file); sink.tableRows_(); sink.table_(); @@ -649,57 +589,48 @@ private void doDetails( CheckstyleResults results ) sink.section1_(); } - private void doFileEvents( List eventList, String filename ) - { - for ( AuditEvent event : eventList ) - { + private void doFileEvents(List eventList, String filename) { + for (AuditEvent event : eventList) { SeverityLevel level = event.getSeverityLevel(); - if ( ( getSeverityLevel() != null ) && !( getSeverityLevel() != level ) ) - { + if ((getSeverityLevel() != null) && !(getSeverityLevel() != level)) { continue; } sink.tableRow(); sink.tableCell(); - iconTool.iconSeverity( level.getName(), IconTool.TEXT_SIMPLE ); + iconTool.iconSeverity(level.getName(), IconTool.TEXT_SIMPLE); sink.tableCell_(); sink.tableCell(); - String category = RuleUtil.getCategory( event ); - if ( category != null ) - { - sink.text( category ); + String category = RuleUtil.getCategory(event); + if (category != null) { + sink.text(category); } sink.tableCell_(); sink.tableCell(); - String ruleName = RuleUtil.getName( event ); - if ( ruleName != null ) - { - sink.text( ruleName ); + String ruleName = RuleUtil.getName(event); + if (ruleName != null) { + sink.text(ruleName); } sink.tableCell_(); sink.tableCell(); - sink.text( event.getMessage() ); + sink.text(event.getMessage()); sink.tableCell_(); sink.tableCell(); int line = event.getLine(); - String effectiveXrefLocation = getEffectiveXrefLocation( eventList ); - if ( effectiveXrefLocation != null && line != 0 ) - { - sink.link( effectiveXrefLocation + "/" + filename.replaceAll( "\\.java$", ".html" ) + "#L" - + line ); - sink.text( String.valueOf( line ) ); + String effectiveXrefLocation = getEffectiveXrefLocation(eventList); + if (effectiveXrefLocation != null && line != 0) { + sink.link(effectiveXrefLocation + "/" + filename.replaceAll("\\.java$", ".html") + "#L" + line); + sink.text(String.valueOf(line)); sink.link_(); - } - else if ( line != 0 ) - { - sink.text( String.valueOf( line ) ); + } else if (line != 0) { + sink.text(String.valueOf(line)); } sink.tableCell_(); @@ -707,25 +638,18 @@ else if ( line != 0 ) } } - private String getEffectiveXrefLocation( List eventList ) - { - String absoluteFilename = eventList.get( 0 ).getFileName(); - if ( isTestSource( absoluteFilename ) ) - { + private String getEffectiveXrefLocation(List eventList) { + String absoluteFilename = eventList.get(0).getFileName(); + if (isTestSource(absoluteFilename)) { return getXrefTestLocation(); - } - else - { + } else { return getXrefLocation(); } } - private boolean isTestSource( final String absoluteFilename ) - { - for ( File testSourceDirectory : testSourceDirectories ) - { - if ( absoluteFilename.startsWith( testSourceDirectory.getAbsolutePath() ) ) - { + private boolean isTestSource(final String absoluteFilename) { + for (File testSourceDirectory : testSourceDirectories) { + if (absoluteFilename.startsWith(testSourceDirectory.getAbsolutePath())) { return true; } } @@ -733,105 +657,85 @@ private boolean isTestSource( final String absoluteFilename ) return false; } - public SeverityLevel getSeverityLevel() - { + public SeverityLevel getSeverityLevel() { return severityLevel; } - public void setSeverityLevel( SeverityLevel severityLevel ) - { + public void setSeverityLevel(SeverityLevel severityLevel) { this.severityLevel = severityLevel; } - public boolean isEnableRulesSummary() - { + public boolean isEnableRulesSummary() { return enableRulesSummary; } - public void setEnableRulesSummary( boolean enableRulesSummary ) - { + public void setEnableRulesSummary(boolean enableRulesSummary) { this.enableRulesSummary = enableRulesSummary; } - public boolean isEnableSeveritySummary() - { + public boolean isEnableSeveritySummary() { return enableSeveritySummary; } - public void setEnableSeveritySummary( boolean enableSeveritySummary ) - { + public void setEnableSeveritySummary(boolean enableSeveritySummary) { this.enableSeveritySummary = enableSeveritySummary; } - public boolean isEnableFilesSummary() - { + public boolean isEnableFilesSummary() { return enableFilesSummary; } - public void setEnableFilesSummary( boolean enableFilesSummary ) - { + public void setEnableFilesSummary(boolean enableFilesSummary) { this.enableFilesSummary = enableFilesSummary; } @Deprecated - public boolean isEnableRSS() - { + public boolean isEnableRSS() { return enableRSS; } @Deprecated - public void setEnableRSS( boolean enableRSS ) - { + public void setEnableRSS(boolean enableRSS) { this.enableRSS = enableRSS; } - public String getXrefLocation() - { + public String getXrefLocation() { return xrefLocation; } - public void setXrefLocation( String xrefLocation ) - { + public void setXrefLocation(String xrefLocation) { this.xrefLocation = xrefLocation; } - public String getXrefTestLocation() - { + public String getXrefTestLocation() { return xrefTestLocation; } - public void setXrefTestLocation( String xrefTestLocation ) - { + public void setXrefTestLocation(String xrefTestLocation) { this.xrefTestLocation = xrefTestLocation; } - public List getTestSourceDirectories() - { + public List getTestSourceDirectories() { return testSourceDirectories; } - public void setTestSourceDirectories( List testSourceDirectories ) - { + public void setTestSourceDirectories(List testSourceDirectories) { this.testSourceDirectories = testSourceDirectories; } - public Configuration getCheckstyleConfig() - { + public Configuration getCheckstyleConfig() { return checkstyleConfig; } - public void setCheckstyleConfig( Configuration config ) - { + public void setCheckstyleConfig(Configuration config) { this.checkstyleConfig = config; } - public void setTreeWalkerNames( List treeWalkerNames ) - { + public void setTreeWalkerNames(List treeWalkerNames) { this.treeWalkerNames = treeWalkerNames; } - public List getTreeWalkerNames() - { + public List getTreeWalkerNames() { return treeWalkerNames; } @@ -839,81 +743,75 @@ public List getTreeWalkerNames() * Get the effective Checkstyle version at runtime. * @return the MANIFEST implementation version of Checkstyle API package (can be null) */ - private String getCheckstyleVersion() - { + private String getCheckstyleVersion() { Package checkstyleApiPackage = Configuration.class.getPackage(); - return ( checkstyleApiPackage == null ) ? null : checkstyleApiPackage.getImplementationVersion(); + return (checkstyleApiPackage == null) ? null : checkstyleApiPackage.getImplementationVersion(); } - public List sortConfiguration( CheckstyleResults results ) - { + public List sortConfiguration(CheckstyleResults results) { List result = new ArrayList<>(); - sortConfiguration( result, checkstyleConfig, null, results ); + sortConfiguration(result, checkstyleConfig, null, results); - Collections.sort( result ); + Collections.sort(result); return result; } - private void sortConfiguration( List result, Configuration config, - ChainedItem parent, CheckstyleResults results ) - { - for ( Configuration childConfig : config.getChildren() ) - { + private void sortConfiguration( + List result, + Configuration config, + ChainedItem parent, + CheckstyleResults results) { + for (Configuration childConfig : config.getChildren()) { String ruleName = childConfig.getName(); - if ( treeWalkerNames.contains( ruleName ) ) - { + if (treeWalkerNames.contains(ruleName)) { // special sub-case: TreeWalker is the parent of multiple rules, not an effective rule - sortConfiguration( result, childConfig, new ChainedItem<>( config, parent ), results ); - } - else - { - String fixedmessage = getConfigAttribute( childConfig, null, "message", null ); + sortConfiguration(result, childConfig, new ChainedItem<>(config, parent), results); + } else { + String fixedmessage = getConfigAttribute(childConfig, null, "message", null); // Grab the severity from the rule configuration. Do not set default value here as // it breaks our rule aggregate section entirely. The counts are off but this is // not appropriate fix location per MCHECKSTYLE-365. - String configSeverity = getConfigAttribute( childConfig, null, "severity", null ); + String configSeverity = getConfigAttribute(childConfig, null, "severity", null); // count rule violations long violations = 0; AuditEvent lastMatchedEvent = null; - for ( List errors : results.getFiles().values() ) - { - for ( AuditEvent event : errors ) - { - if ( matchRule( event, ruleName, fixedmessage, configSeverity ) ) - { + for (List errors : results.getFiles().values()) { + for (AuditEvent event : errors) { + if (matchRule(event, ruleName, fixedmessage, configSeverity)) { lastMatchedEvent = event; violations++; } } } - if ( violations > 0 ) // forget rules without violations + if (violations > 0) // forget rules without violations { - String category = RuleUtil.getCategory( lastMatchedEvent ); + String category = RuleUtil.getCategory(lastMatchedEvent); - result.add( new ConfReference( category, childConfig, parent, violations, result.size() ) ); + result.add(new ConfReference(category, childConfig, parent, violations, result.size())); } } } } - private static class ConfReference - implements Comparable - { + private static class ConfReference implements Comparable { private final String category; private final Configuration configuration; private final ChainedItem parentConfiguration; private final long violations; private final int count; - ConfReference( String category, Configuration configuration, - ChainedItem parentConfiguration, long violations, int count ) - { + ConfReference( + String category, + Configuration configuration, + ChainedItem parentConfiguration, + long violations, + int count) { this.category = category; this.configuration = configuration; this.parentConfiguration = parentConfiguration; @@ -921,28 +819,23 @@ private static class ConfReference this.count = count; } - public int compareTo( ConfReference o ) - { - int compare = category.compareTo( o.category ); - if ( compare == 0 ) - { - compare = configuration.getName().compareTo( o.configuration.getName() ); + public int compareTo(ConfReference o) { + int compare = category.compareTo(o.category); + if (compare == 0) { + compare = configuration.getName().compareTo(o.configuration.getName()); } - return ( compare == 0 ) ? ( o.count - count ) : compare; + return (compare == 0) ? (o.count - count) : compare; } } - private static class ChainedItem - { + private static class ChainedItem { private final ChainedItem parent; private final T value; - ChainedItem( T value, ChainedItem parent ) - { + ChainedItem(T value, ChainedItem parent) { this.parent = parent; this.value = value; } } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java index 2659d04c..8a2f1be4 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; @@ -33,6 +32,11 @@ import java.util.List; import java.util.Map; +import com.puppycrawl.tools.checkstyle.DefaultLogger; +import com.puppycrawl.tools.checkstyle.XMLLogger; +import com.puppycrawl.tools.checkstyle.api.AuditListener; +import com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Dependency; @@ -60,12 +64,6 @@ import org.codehaus.plexus.util.xml.pull.XmlPullParser; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import com.puppycrawl.tools.checkstyle.DefaultLogger; -import com.puppycrawl.tools.checkstyle.XMLLogger; -import com.puppycrawl.tools.checkstyle.api.AuditListener; -import com.puppycrawl.tools.checkstyle.api.AutomaticBean.OutputStreamOptions; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; - /** * Performs Checkstyle analysis and outputs violations or a count of violations * to the console, potentially failing the build. @@ -74,11 +72,12 @@ * @author Joakim Erdfelt * */ -@Mojo( name = "check", defaultPhase = LifecyclePhase.VERIFY, requiresDependencyResolution = ResolutionScope.NONE, - threadSafe = true ) -public class CheckstyleViolationCheckMojo - extends AbstractMojo -{ +@Mojo( + name = "check", + defaultPhase = LifecyclePhase.VERIFY, + requiresDependencyResolution = ResolutionScope.NONE, + threadSafe = true) +public class CheckstyleViolationCheckMojo extends AbstractMojo { private static final String JAVA_FILES = "**\\/*.java"; private static final String DEFAULT_CONFIG_LOCATION = "sun_checks.xml"; @@ -88,14 +87,14 @@ public class CheckstyleViolationCheckMojo * of the output file is determined by the outputFileFormat * parameter. */ - @Parameter( property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml" ) + @Parameter(property = "checkstyle.output.file", defaultValue = "${project.build.directory}/checkstyle-result.xml") private File outputFile; /** * Specifies the format of the output to be used when writing to the output * file. Valid values are "plain" and "xml". */ - @Parameter( property = "checkstyle.output.format", defaultValue = "xml" ) + @Parameter(property = "checkstyle.output.format", defaultValue = "xml") private String outputFileFormat; /** @@ -104,7 +103,7 @@ public class CheckstyleViolationCheckMojo * Compare this to {@link #failsOnError} which fails the build immediately * before examining the output log. */ - @Parameter( property = "checkstyle.failOnViolation", defaultValue = "true" ) + @Parameter(property = "checkstyle.failOnViolation", defaultValue = "true") private boolean failOnViolation; /** @@ -113,7 +112,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.3 */ - @Parameter( property = "checkstyle.maxAllowedViolations", defaultValue = "0" ) + @Parameter(property = "checkstyle.maxAllowedViolations", defaultValue = "0") private int maxAllowedViolations; /** @@ -122,7 +121,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.2 */ - @Parameter( property = "checkstyle.violationSeverity", defaultValue = "error" ) + @Parameter(property = "checkstyle.violationSeverity", defaultValue = "error") private String violationSeverity = "error"; /** @@ -131,7 +130,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.13 */ - @Parameter( property = "checkstyle.violation.ignore" ) + @Parameter(property = "checkstyle.violation.ignore") private String violationIgnore; /** @@ -139,7 +138,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.2 */ - @Parameter( property = "checkstyle.skip", defaultValue = "false" ) + @Parameter(property = "checkstyle.skip", defaultValue = "false") private boolean skip; /** @@ -147,7 +146,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.5 */ - @Parameter( property = "checkstyle.skipExec", defaultValue = "false" ) + @Parameter(property = "checkstyle.skipExec", defaultValue = "false") private boolean skipExec; /** @@ -155,7 +154,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.3 */ - @Parameter( property = "checkstyle.console", defaultValue = "true" ) + @Parameter(property = "checkstyle.console", defaultValue = "true") private boolean logViolationsToConsole; /** @@ -163,7 +162,7 @@ public class CheckstyleViolationCheckMojo * * @since 3.0.1 */ - @Parameter( property = "checkstyle.logViolationCount", defaultValue = "true" ) + @Parameter(property = "checkstyle.logViolationCount", defaultValue = "true") private boolean logViolationCountToConsole; /** @@ -171,7 +170,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.11 */ - @Parameter( defaultValue = "${project.resources}", readonly = true ) + @Parameter(defaultValue = "${project.resources}", readonly = true) protected List resources; /** @@ -179,7 +178,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.16 */ - @Parameter( defaultValue = "${project.testResources}", readonly = true ) + @Parameter(defaultValue = "${project.testResources}", readonly = true) protected List testResources; /** @@ -205,7 +204,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.5 */ - @Parameter( property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION ) + @Parameter(property = "checkstyle.config.location", defaultValue = DEFAULT_CONFIG_LOCATION) private String configLocation; /** @@ -224,7 +223,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.5 */ - @Parameter( property = "checkstyle.properties.location" ) + @Parameter(property = "checkstyle.properties.location") private String propertiesLocation; /** @@ -251,13 +250,13 @@ public class CheckstyleViolationCheckMojo * * @since 2.0-beta-2 */ - @Parameter( property = "checkstyle.header.file", defaultValue = "LICENSE.txt" ) + @Parameter(property = "checkstyle.header.file", defaultValue = "LICENSE.txt") private String headerLocation; /** * Specifies the cache file used to speed up Checkstyle on successive runs. */ - @Parameter( defaultValue = "${project.build.directory}/checkstyle-cachefile" ) + @Parameter(defaultValue = "${project.build.directory}/checkstyle-cachefile") private String cacheFile; /** @@ -265,7 +264,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.1 */ - @Parameter( property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file" ) + @Parameter(property = "checkstyle.suppression.expression", defaultValue = "checkstyle.suppressions.file") private String suppressionsFileExpression; /** @@ -282,7 +281,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.0-beta-2 */ - @Parameter( property = "checkstyle.suppressions.location" ) + @Parameter(property = "checkstyle.suppressions.location") private String suppressionsLocation; /** @@ -292,31 +291,31 @@ public class CheckstyleViolationCheckMojo * * @since 2.2 */ - @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}") private String inputEncoding; /** * @since 2.5 */ - @Component( role = CheckstyleExecutor.class, hint = "default" ) + @Component(role = CheckstyleExecutor.class, hint = "default") protected CheckstyleExecutor checkstyleExecutor; /** * Output errors to console. */ - @Parameter( property = "checkstyle.consoleOutput", defaultValue = "false" ) + @Parameter(property = "checkstyle.consoleOutput", defaultValue = "false") private boolean consoleOutput; /** * The Maven Project Object. */ - @Parameter ( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; /** * The Plugin Descriptor */ - @Parameter( defaultValue = "${plugin}", readonly = true, required = true ) + @Parameter(defaultValue = "${plugin}", readonly = true, required = true) private PluginDescriptor plugin; /** @@ -330,13 +329,13 @@ public class CheckstyleViolationCheckMojo * Specifies the names filter of the source files to be excluded for * Checkstyle. */ - @Parameter( property = "checkstyle.excludes" ) + @Parameter(property = "checkstyle.excludes") private String excludes; /** * Specifies the names filter of the source files to be used for Checkstyle. */ - @Parameter( property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true ) + @Parameter(property = "checkstyle.includes", defaultValue = JAVA_FILES, required = true) private String includes; /** @@ -344,14 +343,14 @@ public class CheckstyleViolationCheckMojo * Checkstyle when checking resources. * @since 2.11 */ - @Parameter( property = "checkstyle.resourceExcludes" ) + @Parameter(property = "checkstyle.resourceExcludes") private String resourceExcludes; /** * Specifies the names filter of the files to be used for Checkstyle when checking resources. * @since 2.11 */ - @Parameter( property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true ) + @Parameter(property = "checkstyle.resourceIncludes", defaultValue = "**/*.properties", required = true) private String resourceIncludes; /** @@ -360,7 +359,7 @@ public class CheckstyleViolationCheckMojo * for {@link #logViolationsToConsole}. If you want to use {@link #logViolationsToConsole}, * use {@link #failOnViolation} instead of this. */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean failsOnError; /** @@ -388,7 +387,7 @@ public class CheckstyleViolationCheckMojo * * @since 2.2 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean includeTestSourceDirectory; /** @@ -414,14 +413,14 @@ public class CheckstyleViolationCheckMojo * Whether to apply Checkstyle to resource directories. * @since 2.11 */ - @Parameter( property = "checkstyle.includeResources", defaultValue = "true", required = true ) + @Parameter(property = "checkstyle.includeResources", defaultValue = "true", required = true) private boolean includeResources = true; /** * Whether to apply Checkstyle to test resource directories. * @since 2.11 */ - @Parameter( property = "checkstyle.includeTestResources", defaultValue = "true", required = true ) + @Parameter(property = "checkstyle.includeTestResources", defaultValue = "true", required = true) private boolean includeTestResources = true; /** @@ -454,17 +453,19 @@ public class CheckstyleViolationCheckMojo /** * Dump file for inlined Checkstyle rules. */ - @Parameter( property = "checkstyle.output.rules.file", - defaultValue = "${project.build.directory}/checkstyle-rules.xml" ) + @Parameter( + property = "checkstyle.output.rules.file", + defaultValue = "${project.build.directory}/checkstyle-rules.xml") private File rulesFiles; /** * The header to use for the inline configuration. * Only used when you specify {@code checkstyleRules}. */ - @Parameter( defaultValue = "\n" - + "\n" ) + @Parameter( + defaultValue = "\n" + + "\n") private String checkstyleRulesHeader; /** @@ -473,7 +474,7 @@ public class CheckstyleViolationCheckMojo * * @since 3.0.0 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean omitIgnoredModules; private ByteArrayOutputStream stringOutputStream; @@ -481,221 +482,183 @@ public class CheckstyleViolationCheckMojo private File outputXmlFile; /** {@inheritDoc} */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - checkDeprecatedParameterUsage( sourceDirectory, "sourceDirectory", "sourceDirectories" ); - checkDeprecatedParameterUsage( testSourceDirectory, "testSourceDirectory", "testSourceDirectories" ); - if ( skip ) - { + public void execute() throws MojoExecutionException, MojoFailureException { + checkDeprecatedParameterUsage(sourceDirectory, "sourceDirectory", "sourceDirectories"); + checkDeprecatedParameterUsage(testSourceDirectory, "testSourceDirectory", "testSourceDirectories"); + if (skip) { return; } outputXmlFile = outputFile; - if ( !skipExec ) - { + if (!skipExec) { String effectiveConfigLocation = configLocation; - if ( checkstyleRules != null ) - { - if ( !DEFAULT_CONFIG_LOCATION.equals( configLocation ) ) - { - throw new MojoExecutionException( "If you use inline configuration for rules, don't specify " - + "a configLocation" ); + if (checkstyleRules != null) { + if (!DEFAULT_CONFIG_LOCATION.equals(configLocation)) { + throw new MojoExecutionException( + "If you use inline configuration for rules, don't specify " + "a configLocation"); } - if ( checkstyleRules.getChildCount() > 1 ) - { - throw new MojoExecutionException( "Currently only one root module is supported" ); + if (checkstyleRules.getChildCount() > 1) { + throw new MojoExecutionException("Currently only one root module is supported"); } - PlexusConfiguration checkerModule = checkstyleRules.getChild( 0 ); + PlexusConfiguration checkerModule = checkstyleRules.getChild(0); - try - { - FileUtils.forceMkdir( rulesFiles.getParentFile() ); - FileUtils.fileWrite( rulesFiles, checkstyleRulesHeader + checkerModule.toString() ); - } - catch ( final IOException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try { + FileUtils.forceMkdir(rulesFiles.getParentFile()); + FileUtils.fileWrite(rulesFiles, checkstyleRulesHeader + checkerModule.toString()); + } catch (final IOException e) { + throw new MojoExecutionException(e.getMessage(), e); } effectiveConfigLocation = rulesFiles.getAbsolutePath(); } ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader(); - try - { + try { CheckstyleExecutorRequest request = new CheckstyleExecutorRequest(); - request.setConsoleListener( getConsoleListener() ).setConsoleOutput( consoleOutput ) - .setExcludes( excludes ).setFailsOnError( failsOnError ).setIncludes( includes ) - .setResourceIncludes( resourceIncludes ) - .setResourceExcludes( resourceExcludes ) - .setIncludeResources( includeResources ) - .setIncludeTestResources( includeTestResources ) - .setIncludeTestSourceDirectory( includeTestSourceDirectory ).setListener( getListener() ) - .setProject( project ).setSourceDirectories( getSourceDirectories() ) - .setResources( resources ).setTestResources( testResources ) - .setStringOutputStream( stringOutputStream ).setSuppressionsLocation( suppressionsLocation ) - .setTestSourceDirectories( getTestSourceDirectories() ).setConfigLocation( effectiveConfigLocation ) - .setConfigurationArtifacts( collectArtifacts( "config" ) ) - .setPropertyExpansion( propertyExpansion ) - .setHeaderLocation( headerLocation ).setLicenseArtifacts( collectArtifacts( "license" ) ) - .setCacheFile( cacheFile ).setSuppressionsFileExpression( suppressionsFileExpression ) - .setEncoding( inputEncoding ).setPropertiesLocation( propertiesLocation ) - .setOmitIgnoredModules( omitIgnoredModules ); - checkstyleExecutor.executeCheckstyle( request ); - - } - catch ( CheckstyleException e ) - { - throw new MojoExecutionException( "Failed during checkstyle configuration", e ); - } - catch ( CheckstyleExecutorException e ) - { - throw new MojoExecutionException( "Failed during checkstyle execution", e ); - } - finally - { - //be sure to restore original context classloader - Thread.currentThread().setContextClassLoader( currentClassLoader ); + request.setConsoleListener(getConsoleListener()) + .setConsoleOutput(consoleOutput) + .setExcludes(excludes) + .setFailsOnError(failsOnError) + .setIncludes(includes) + .setResourceIncludes(resourceIncludes) + .setResourceExcludes(resourceExcludes) + .setIncludeResources(includeResources) + .setIncludeTestResources(includeTestResources) + .setIncludeTestSourceDirectory(includeTestSourceDirectory) + .setListener(getListener()) + .setProject(project) + .setSourceDirectories(getSourceDirectories()) + .setResources(resources) + .setTestResources(testResources) + .setStringOutputStream(stringOutputStream) + .setSuppressionsLocation(suppressionsLocation) + .setTestSourceDirectories(getTestSourceDirectories()) + .setConfigLocation(effectiveConfigLocation) + .setConfigurationArtifacts(collectArtifacts("config")) + .setPropertyExpansion(propertyExpansion) + .setHeaderLocation(headerLocation) + .setLicenseArtifacts(collectArtifacts("license")) + .setCacheFile(cacheFile) + .setSuppressionsFileExpression(suppressionsFileExpression) + .setEncoding(inputEncoding) + .setPropertiesLocation(propertiesLocation) + .setOmitIgnoredModules(omitIgnoredModules); + checkstyleExecutor.executeCheckstyle(request); + + } catch (CheckstyleException e) { + throw new MojoExecutionException("Failed during checkstyle configuration", e); + } catch (CheckstyleExecutorException e) { + throw new MojoExecutionException("Failed during checkstyle execution", e); + } finally { + // be sure to restore original context classloader + Thread.currentThread().setContextClassLoader(currentClassLoader); } } - if ( !"xml".equals( outputFileFormat ) && skipExec ) - { - throw new MojoExecutionException( "Output format is '" + outputFileFormat - + "', checkstyle:check requires format to be 'xml' when using skipExec." ); + if (!"xml".equals(outputFileFormat) && skipExec) { + throw new MojoExecutionException("Output format is '" + outputFileFormat + + "', checkstyle:check requires format to be 'xml' when using skipExec."); } - if ( !outputXmlFile.exists() ) - { - getLog().info( "Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile." ); + if (!outputXmlFile.exists()) { + getLog().info("Unable to perform checkstyle:check, unable to find checkstyle:checkstyle outputFile."); return; } - try ( Reader reader = new BufferedReader( ReaderFactory.newXmlReader( outputXmlFile ) ) ) - { + try (Reader reader = new BufferedReader(ReaderFactory.newXmlReader(outputXmlFile))) { XmlPullParser xpp = new MXParser(); - xpp.setInput( reader ); + xpp.setInput(reader); - final List violationsList = getViolations( xpp ); - long violationCount = countViolations( violationsList ); - printViolations( violationsList ); + final List violationsList = getViolations(xpp); + long violationCount = countViolations(violationsList); + printViolations(violationsList); String msg = "You have " + violationCount + " Checkstyle violation" - + ( ( violationCount > 1 || violationCount == 0 ) ? "s" : "" ) + "."; - - if ( violationCount > maxAllowedViolations ) - { - if ( failOnViolation ) - { - if ( maxAllowedViolations > 0 ) - { + + ((violationCount > 1 || violationCount == 0) ? "s" : "") + "."; + + if (violationCount > maxAllowedViolations) { + if (failOnViolation) { + if (maxAllowedViolations > 0) { msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } - throw new MojoFailureException( msg ); + throw new MojoFailureException(msg); } - getLog().warn( "checkstyle:check violations detected but failOnViolation set to false" ); + getLog().warn("checkstyle:check violations detected but failOnViolation set to false"); } - if ( logViolationCountToConsole ) - { - if ( maxAllowedViolations > 0 ) - { - msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; + if (logViolationCountToConsole) { + if (maxAllowedViolations > 0) { + msg += " The maximum number of allowed violations is " + maxAllowedViolations + "."; } - getLog().info( msg ); + getLog().info(msg); } - } - catch ( IOException | XmlPullParserException e ) - { - throw new MojoExecutionException( "Unable to read Checkstyle results xml: " - + outputXmlFile.getAbsolutePath(), e ); + } catch (IOException | XmlPullParserException e) { + throw new MojoExecutionException( + "Unable to read Checkstyle results xml: " + outputXmlFile.getAbsolutePath(), e); } } - private void checkDeprecatedParameterUsage( Object parameter, String name, String replacement ) - throws MojoFailureException - { - if ( parameter != null ) - { - throw new MojoFailureException( "You are using '" + name + "' which has been removed" - + " from the maven-checkstyle-plugin. " + "Please use '" + replacement - + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site." ); + private void checkDeprecatedParameterUsage(Object parameter, String name, String replacement) + throws MojoFailureException { + if (parameter != null) { + throw new MojoFailureException("You are using '" + name + "' which has been removed" + + " from the maven-checkstyle-plugin. " + "Please use '" + replacement + + "' and refer to the >>Major Version Upgrade to version 3.0.0<< " + "on the plugin site."); } } - private List getViolations( XmlPullParser xpp ) - throws XmlPullParserException, IOException - { + private List getViolations(XmlPullParser xpp) throws XmlPullParserException, IOException { List violations = new ArrayList<>(); String basedir = project.getBasedir().getAbsolutePath(); String file = ""; - for ( int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next() ) - { - if ( eventType != XmlPullParser.START_TAG ) - { + for (int eventType = xpp.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = xpp.next()) { + if (eventType != XmlPullParser.START_TAG) { continue; - } - else if ( "file".equals( xpp.getName() ) ) - { - file = PathTool.getRelativeFilePath( basedir, xpp.getAttributeValue( "", "name" ) ); + } else if ("file".equals(xpp.getName())) { + file = PathTool.getRelativeFilePath(basedir, xpp.getAttributeValue("", "name")); continue; - } - else if ( ! "error".equals( xpp.getName() ) ) - { + } else if (!"error".equals(xpp.getName())) { continue; } - String severity = xpp.getAttributeValue( "", "severity" ); - String source = xpp.getAttributeValue( "", "source" ); - String line = xpp.getAttributeValue( "", "line" ); + String severity = xpp.getAttributeValue("", "severity"); + String source = xpp.getAttributeValue("", "source"); + String line = xpp.getAttributeValue("", "line"); /* Nullable */ - String column = xpp.getAttributeValue( "", "column" ); - String message = xpp.getAttributeValue( "", "message" ); - String rule = RuleUtil.getName( source ); - String category = RuleUtil.getCategory( source ); - - Violation violation = new Violation( - source, - file, - line, - severity, - message, - rule, - category - ); - if ( column != null ) - { - violation.setColumn( column ); + String column = xpp.getAttributeValue("", "column"); + String message = xpp.getAttributeValue("", "message"); + String rule = RuleUtil.getName(source); + String category = RuleUtil.getCategory(source); + + Violation violation = new Violation(source, file, line, severity, message, rule, category); + if (column != null) { + violation.setColumn(column); } - violations.add( violation ); + violations.add(violation); } return violations; } - private int countViolations( List violations ) - { - List ignores = violationIgnore == null ? Collections.emptyList() - : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); + private int countViolations(List violations) { + List ignores = violationIgnore == null + ? Collections.emptyList() + : RuleUtil.parseMatchers(violationIgnore.split(",")); int ignored = 0; int countedViolations = 0; - for ( Violation violation : violations ) - { - if ( ! isViolation( violation.getSeverity() ) ) - { + for (Violation violation : violations) { + if (!isViolation(violation.getSeverity())) { continue; } - if ( ignore( ignores, violation.getSource() ) ) - { + if (ignore(ignores, violation.getSource())) { ignored++; continue; } @@ -703,54 +666,46 @@ private int countViolations( List violations ) countedViolations++; } - if ( ignored > 0 ) - { - getLog().info( "Ignored " + ignored + " error" + ( ( ignored > 1L ) ? "s" : "" ) + ", " + countedViolations - + " violation" + ( ( countedViolations > 1 ) ? "s" : "" ) + " remaining." ); + if (ignored > 0) { + getLog().info("Ignored " + ignored + " error" + ((ignored > 1L) ? "s" : "") + ", " + countedViolations + + " violation" + ((countedViolations > 1) ? "s" : "") + " remaining."); } return countedViolations; } - private void printViolations( List violations ) - { - if ( ! logViolationsToConsole ) - { + private void printViolations(List violations) { + if (!logViolationsToConsole) { return; } - List ignores = violationIgnore == null ? Collections.emptyList() - : RuleUtil.parseMatchers( violationIgnore.split( "," ) ); + List ignores = violationIgnore == null + ? Collections.emptyList() + : RuleUtil.parseMatchers(violationIgnore.split(",")); violations.stream() - .filter( violation -> isViolation( violation.getSeverity() ) ) - .filter( violation -> !ignore( ignores, violation.getSource() ) ) - .forEach( violation -> - { - final String message = String.format( "%s:[%s%s] (%s) %s: %s", - violation.getFile(), - violation.getLine(), - ( Violation.NO_COLUMN.equals( violation.getColumn() ) ) ? "" : ( ',' + violation.getColumn() ), - violation.getCategory(), - violation.getRuleName(), - violation.getMessage() ); - log( violation.getSeverity(), message ); - } ); + .filter(violation -> isViolation(violation.getSeverity())) + .filter(violation -> !ignore(ignores, violation.getSource())) + .forEach(violation -> { + final String message = String.format( + "%s:[%s%s] (%s) %s: %s", + violation.getFile(), + violation.getLine(), + (Violation.NO_COLUMN.equals(violation.getColumn())) ? "" : (',' + violation.getColumn()), + violation.getCategory(), + violation.getRuleName(), + violation.getMessage()); + log(violation.getSeverity(), message); + }); } - private void log( String severity, String message ) - { - if ( "info".equals( severity ) ) - { - getLog().info( message ); - } - else if ( "warning".equals( severity ) ) - { - getLog().warn( message ); - } - else - { - getLog().error( message ); + private void log(String severity, String message) { + if ("info".equals(severity)) { + getLog().info(message); + } else if ("warning".equals(severity)) { + getLog().warn(message); + } else { + getLog().error(message); } } @@ -760,183 +715,141 @@ else if ( "warning".equals( severity ) ) * @param severity The severity to check * @return true if the given severity is a violation, otherwise false */ - private boolean isViolation( String severity ) - { - if ( "error".equals( severity ) ) - { - return "error".equals( violationSeverity ) || "warning".equals( violationSeverity ) - || "info".equals( violationSeverity ); - } - else if ( "warning".equals( severity ) ) - { - return "warning".equals( violationSeverity ) || "info".equals( violationSeverity ); - } - else if ( "info".equals( severity ) ) - { - return "info".equals( violationSeverity ); - } - else - { + private boolean isViolation(String severity) { + if ("error".equals(severity)) { + return "error".equals(violationSeverity) + || "warning".equals(violationSeverity) + || "info".equals(violationSeverity); + } else if ("warning".equals(severity)) { + return "warning".equals(violationSeverity) || "info".equals(violationSeverity); + } else if ("info".equals(severity)) { + return "info".equals(violationSeverity); + } else { return false; } } - private boolean ignore( List ignores, String source ) - { - for ( RuleUtil.Matcher ignore : ignores ) - { - if ( ignore.match( source ) ) - { + private boolean ignore(List ignores, String source) { + for (RuleUtil.Matcher ignore : ignores) { + if (ignore.match(source)) { return true; } } return false; } - private DefaultLogger getConsoleListener() - throws MojoExecutionException - { + private DefaultLogger getConsoleListener() throws MojoExecutionException { DefaultLogger consoleListener; - if ( useFile == null ) - { + if (useFile == null) { stringOutputStream = new ByteArrayOutputStream(); - consoleListener = new DefaultLogger( stringOutputStream, OutputStreamOptions.NONE ); - } - else - { - OutputStream out = getOutputStream( useFile ); + consoleListener = new DefaultLogger(stringOutputStream, OutputStreamOptions.NONE); + } else { + OutputStream out = getOutputStream(useFile); - consoleListener = new DefaultLogger( out, OutputStreamOptions.CLOSE ); + consoleListener = new DefaultLogger(out, OutputStreamOptions.CLOSE); } return consoleListener; } - private OutputStream getOutputStream( File file ) - throws MojoExecutionException - { + private OutputStream getOutputStream(File file) throws MojoExecutionException { File parentFile = file.getAbsoluteFile().getParentFile(); - if ( !parentFile.exists() ) - { + if (!parentFile.exists()) { parentFile.mkdirs(); } FileOutputStream fileOutputStream; - try - { - fileOutputStream = new FileOutputStream( file ); - } - catch ( FileNotFoundException e ) - { - throw new MojoExecutionException( "Unable to create output stream: " + file, e ); + try { + fileOutputStream = new FileOutputStream(file); + } catch (FileNotFoundException e) { + throw new MojoExecutionException("Unable to create output stream: " + file, e); } return fileOutputStream; } - private AuditListener getListener() - throws MojoFailureException, MojoExecutionException - { + private AuditListener getListener() throws MojoFailureException, MojoExecutionException { AuditListener listener = null; - if ( StringUtils.isNotEmpty( outputFileFormat ) ) - { + if (StringUtils.isNotEmpty(outputFileFormat)) { File resultFile = outputFile; - OutputStream out = getOutputStream( resultFile ); + OutputStream out = getOutputStream(resultFile); - if ( "xml".equals( outputFileFormat ) ) - { - listener = new XMLLogger( out, OutputStreamOptions.CLOSE ); - } - else if ( "plain".equals( outputFileFormat ) ) - { - try - { + if ("xml".equals(outputFileFormat)) { + listener = new XMLLogger(out, OutputStreamOptions.CLOSE); + } else if ("plain".equals(outputFileFormat)) { + try { // Write a plain output file to the standard output file, // and write an XML output file to the temp directory that can be used to count violations - outputXmlFile = Files.createTempFile( "checkstyle-result", ".xml" ).toFile(); + outputXmlFile = + Files.createTempFile("checkstyle-result", ".xml").toFile(); outputXmlFile.deleteOnExit(); - OutputStream xmlOut = getOutputStream( outputXmlFile ); + OutputStream xmlOut = getOutputStream(outputXmlFile); CompositeAuditListener compoundListener = new CompositeAuditListener(); - compoundListener.addListener( new XMLLogger( xmlOut, OutputStreamOptions.CLOSE ) ); - compoundListener.addListener( new DefaultLogger( out, OutputStreamOptions.CLOSE ) ); + compoundListener.addListener(new XMLLogger(xmlOut, OutputStreamOptions.CLOSE)); + compoundListener.addListener(new DefaultLogger(out, OutputStreamOptions.CLOSE)); listener = compoundListener; + } catch (IOException e) { + throw new MojoExecutionException("Unable to create temporary file", e); } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to create temporary file", e ); - } - } - else - { - throw new MojoFailureException( "Invalid output file format: (" + outputFileFormat - + "). Must be 'plain' or 'xml'." ); + } else { + throw new MojoFailureException( + "Invalid output file format: (" + outputFileFormat + "). Must be 'plain' or 'xml'."); } } return listener; } - private List collectArtifacts( String hint ) - { + private List collectArtifacts(String hint) { List artifacts = new ArrayList<>(); PluginManagement pluginManagement = project.getBuild().getPluginManagement(); - if ( pluginManagement != null ) - { - artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( pluginManagement.getPluginsAsMap(), hint ) ); + if (pluginManagement != null) { + artifacts.addAll(getCheckstylePluginDependenciesAsArtifacts(pluginManagement.getPluginsAsMap(), hint)); } - artifacts.addAll( getCheckstylePluginDependenciesAsArtifacts( project.getBuild().getPluginsAsMap(), hint ) ); + artifacts.addAll( + getCheckstylePluginDependenciesAsArtifacts(project.getBuild().getPluginsAsMap(), hint)); return artifacts; } - private List getCheckstylePluginDependenciesAsArtifacts( Map plugins, String hint ) - { + private List getCheckstylePluginDependenciesAsArtifacts(Map plugins, String hint) { List artifacts = new ArrayList<>(); - Plugin checkstylePlugin = plugins.get( plugin.getGroupId() + ":" + plugin.getArtifactId() ); - if ( checkstylePlugin != null ) - { - for ( Dependency dep : checkstylePlugin.getDependencies() ) - { - // @todo if we can filter on hints, it should be done here... + Plugin checkstylePlugin = plugins.get(plugin.getGroupId() + ":" + plugin.getArtifactId()); + if (checkstylePlugin != null) { + for (Dependency dep : checkstylePlugin.getDependencies()) { + // @todo if we can filter on hints, it should be done here... String depKey = dep.getGroupId() + ":" + dep.getArtifactId(); - artifacts.add( plugin.getArtifactMap().get( depKey ) ); + artifacts.add(plugin.getArtifactMap().get(depKey)); } } return artifacts; } - private List getSourceDirectories() - { - if ( sourceDirectories == null ) - { + private List getSourceDirectories() { + if (sourceDirectories == null) { sourceDirectories = project.getCompileSourceRoots(); } - List sourceDirs = new ArrayList<>( sourceDirectories.size() ); - for ( String sourceDir : sourceDirectories ) - { - sourceDirs.add( FileUtils.resolveFile( project.getBasedir(), sourceDir ) ); + List sourceDirs = new ArrayList<>(sourceDirectories.size()); + for (String sourceDir : sourceDirectories) { + sourceDirs.add(FileUtils.resolveFile(project.getBasedir(), sourceDir)); } return sourceDirs; } - private List getTestSourceDirectories() - { - if ( testSourceDirectories == null ) - { + private List getTestSourceDirectories() { + if (testSourceDirectories == null) { testSourceDirectories = project.getTestCompileSourceRoots(); } - List testSourceDirs = new ArrayList<>( testSourceDirectories.size() ); - for ( String testSourceDir : testSourceDirectories ) - { - testSourceDirs.add( FileUtils.resolveFile( project.getBasedir(), testSourceDir ) ); + List testSourceDirs = new ArrayList<>(testSourceDirectories.size()); + for (String testSourceDir : testSourceDirectories) { + testSourceDirs.add(FileUtils.resolveFile(project.getBasedir(), testSourceDir)); } return testSourceDirs; } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/CompositeAuditListener.java b/src/main/java/org/apache/maven/plugins/checkstyle/CompositeAuditListener.java index 505e63bb..e7a3595b 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/CompositeAuditListener.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/CompositeAuditListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.util.ArrayList; import java.util.List; @@ -28,69 +27,53 @@ /** * AuditListener that forwards events to a list of other AuditListeners */ -public class CompositeAuditListener - implements AuditListener -{ +public class CompositeAuditListener implements AuditListener { private final List delegates = new ArrayList<>(); - public void addListener( AuditListener listener ) - { - delegates.add( listener ); + public void addListener(AuditListener listener) { + delegates.add(listener); } @Override - public void auditStarted( AuditEvent event ) - { - for ( AuditListener listener : delegates ) - { - listener.auditStarted( event ); + public void auditStarted(AuditEvent event) { + for (AuditListener listener : delegates) { + listener.auditStarted(event); } } @Override - public void auditFinished( AuditEvent event ) - { - for ( AuditListener listener : delegates ) - { - listener.auditFinished( event ); + public void auditFinished(AuditEvent event) { + for (AuditListener listener : delegates) { + listener.auditFinished(event); } } @Override - public void fileStarted( AuditEvent event ) - { - for ( AuditListener listener : delegates ) - { - listener.fileStarted( event ); + public void fileStarted(AuditEvent event) { + for (AuditListener listener : delegates) { + listener.fileStarted(event); } } @Override - public void fileFinished( AuditEvent event ) - { - for ( AuditListener listener : delegates ) - { - listener.fileFinished( event ); + public void fileFinished(AuditEvent event) { + for (AuditListener listener : delegates) { + listener.fileFinished(event); } } @Override - public void addError( AuditEvent event ) - { - for ( AuditListener listener : delegates ) - { - listener.addError( event ); + public void addError(AuditEvent event) { + for (AuditListener listener : delegates) { + listener.addError(event); } } @Override - public void addException( AuditEvent event, Throwable throwable ) - { - for ( AuditListener listener : delegates ) - { - listener.addException( event, throwable ); + public void addException(AuditEvent event, Throwable throwable) { + for (AuditListener listener : delegates) { + listener.addException(event, throwable); } } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/IconTool.java b/src/main/java/org/apache/maven/plugins/checkstyle/IconTool.java index c549c5f8..1d65360e 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/IconTool.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/IconTool.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.util.ResourceBundle; @@ -28,8 +27,7 @@ * * @since 2.13 */ -public class IconTool -{ +public class IconTool { public static final String INFO = "info"; public static final String WARNING = "warning"; @@ -45,8 +43,7 @@ public class IconTool private final ResourceBundle bundle; - public IconTool( Sink sink, ResourceBundle bundle ) - { + public IconTool(Sink sink, ResourceBundle bundle) { this.sink = sink; this.bundle = bundle; } @@ -55,9 +52,8 @@ public IconTool( Sink sink, ResourceBundle bundle ) * Render a simple icon of given level. * @param level one of INFO, WARNING or ERROR constants */ - public void iconSeverity( String level ) - { - sink.figureGraphics( "images/icon_" + level + "_sml.gif" ); + public void iconSeverity(String level) { + sink.figureGraphics("images/icon_" + level + "_sml.gif"); } /** @@ -66,24 +62,21 @@ public void iconSeverity( String level ) * @param textType one of NO_TEXT, TEXT_SIMPLE, TEXT_TITLE or * TEXT_ABBREV constants */ - public void iconSeverity( String level, int textType ) - { - sink.figureGraphics( "images/icon_" + level + "_sml.gif" ); + public void iconSeverity(String level, int textType) { + sink.figureGraphics("images/icon_" + level + "_sml.gif"); - if ( textType > 0 ) - { + if (textType > 0) { sink.nonBreakingSpace(); - sink.text( bundle.getString( "report.checkstyle." + level + suffix( textType ) ) ); + sink.text(bundle.getString("report.checkstyle." + level + suffix(textType))); } } /** * Render an info icon. */ - public void iconInfo() - { - iconSeverity( INFO ); + public void iconInfo() { + iconSeverity(INFO); } /** @@ -91,17 +84,15 @@ public void iconInfo() * @param textType one of NO_TEXT, TEXT_SIMPLE, TEXT_TITLE or * TEXT_ABBREV constants */ - public void iconInfo( int textType ) - { - iconSeverity( INFO, textType ); + public void iconInfo(int textType) { + iconSeverity(INFO, textType); } /** * Render a warning icon. */ - public void iconWarning() - { - iconSeverity( WARNING ); + public void iconWarning() { + iconSeverity(WARNING); } /** @@ -109,17 +100,15 @@ public void iconWarning() * @param textType one of NO_TEXT, TEXT_SIMPLE, TEXT_TITLE or * TEXT_ABBREV constants */ - public void iconWarning( int textType ) - { - iconSeverity( WARNING, textType ); + public void iconWarning(int textType) { + iconSeverity(WARNING, textType); } /** * Render an error icon. */ - public void iconError() - { - iconSeverity( ERROR ); + public void iconError() { + iconSeverity(ERROR); } /** @@ -127,15 +116,12 @@ public void iconError() * @param textType one of NO_TEXT, TEXT_SIMPLE, TEXT_TITLE or * TEXT_ABBREV constants */ - public void iconError( int textType ) - { - iconSeverity( ERROR, textType ); + public void iconError(int textType) { + iconSeverity(ERROR, textType); } - private String suffix( int textType ) - { - switch ( textType ) - { + private String suffix(int textType) { + switch (textType) { case TEXT_TITLE: return "s"; case TEXT_ABBREV: diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/ReportResource.java b/src/main/java/org/apache/maven/plugins/checkstyle/ReportResource.java index 0188c80d..557bbde0 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/ReportResource.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/ReportResource.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,59 +16,51 @@ * specific language governing permissions and limitations * under the License. */ - -import org.codehaus.plexus.util.FileUtils; +package org.apache.maven.plugins.checkstyle; import java.io.File; import java.io.IOException; import java.net.URL; +import org.codehaus.plexus.util.FileUtils; + /** * Generic Report Resource management. * * @author Joakim Erdfelt * */ -public class ReportResource -{ +public class ReportResource { private String resourcePathBase; private File outputDirectory; - public ReportResource( String resourcePathBase, File outputDirectory ) - { + public ReportResource(String resourcePathBase, File outputDirectory) { this.resourcePathBase = resourcePathBase; this.outputDirectory = outputDirectory; } - public void copy( String resourceName ) throws IOException - { - File resource = new File( outputDirectory, resourceName ); - if ( !resource.exists() ) - { - URL url = - Thread.currentThread().getContextClassLoader().getResource( resourcePathBase + "/" + resourceName ); - FileUtils.copyURLToFile( url, resource ); + public void copy(String resourceName) throws IOException { + File resource = new File(outputDirectory, resourceName); + if (!resource.exists()) { + URL url = Thread.currentThread().getContextClassLoader().getResource(resourcePathBase + "/" + resourceName); + FileUtils.copyURLToFile(url, resource); } } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } - public String getResourcePathBase() - { + public String getResourcePathBase() { return resourcePathBase; } - public void setResourcePathBase( String resourcePathBase ) - { + public void setResourcePathBase(String resourcePathBase) { this.resourcePathBase = resourcePathBase; } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/RuleUtil.java b/src/main/java/org/apache/maven/plugins/checkstyle/RuleUtil.java index 962d0c49..c26dd546 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/RuleUtil.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/RuleUtil.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,12 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle; import java.util.ArrayList; import java.util.List; import com.puppycrawl.tools.checkstyle.api.AuditEvent; - import org.apache.commons.lang3.StringUtils; /** @@ -32,13 +30,11 @@ * @author Hervé Boutemy * @since 2.13 */ -public final class RuleUtil -{ - private RuleUtil() - { +public final class RuleUtil { + private RuleUtil() { // hide utility class constructor } - + private static final String CHECKSTYLE_PACKAGE = "com.puppycrawl.tools.checkstyle.checks"; /** @@ -47,9 +43,8 @@ private RuleUtil() * @param event the audit event * @return the rule name, which is the class name without package and removed eventual "Check" suffix */ - public static String getName( AuditEvent event ) - { - return getName( event.getSourceName() ); + public static String getName(AuditEvent event) { + return getName(event.getSourceName()); } /** * Get the rule name from an audit event source name. @@ -57,19 +52,16 @@ public static String getName( AuditEvent event ) * @param eventSrcName the audit event source name * @return the rule name, which is the class name without package and removed eventual "Check" suffix */ - public static String getName( String eventSrcName ) - { - if ( eventSrcName == null ) - { + public static String getName(String eventSrcName) { + if (eventSrcName == null) { return null; } - if ( eventSrcName.endsWith( "Check" ) ) - { - eventSrcName = eventSrcName.substring( 0, eventSrcName.length() - 5 ); + if (eventSrcName.endsWith("Check")) { + eventSrcName = eventSrcName.substring(0, eventSrcName.length() - 5); } - return eventSrcName.substring( eventSrcName.lastIndexOf( '.' ) + 1 ); + return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1); } /** @@ -78,9 +70,8 @@ public static String getName( String eventSrcName ) * @param event the audit event * @return the rule category, which is the last package name or "misc" or "extension" */ - public static String getCategory( AuditEvent event ) - { - return getCategory( event.getSourceName() ); + public static String getCategory(AuditEvent event) { + return getCategory(event.getSourceName()); } /** @@ -89,64 +80,47 @@ public static String getCategory( AuditEvent event ) * @param eventSrcName the audit event source name * @return the rule category, which is the last package name or "misc" or "extension" */ - public static String getCategory( String eventSrcName ) - { - if ( eventSrcName == null ) - { + public static String getCategory(String eventSrcName) { + if (eventSrcName == null) { return null; } - int end = eventSrcName.lastIndexOf( '.' ); - eventSrcName = end == -1 ? eventSrcName : eventSrcName.substring( 0, end ); + int end = eventSrcName.lastIndexOf('.'); + eventSrcName = end == -1 ? eventSrcName : eventSrcName.substring(0, end); - if ( CHECKSTYLE_PACKAGE.equals( eventSrcName ) ) - { + if (CHECKSTYLE_PACKAGE.equals(eventSrcName)) { return "misc"; - } - else if ( !eventSrcName.startsWith( CHECKSTYLE_PACKAGE ) ) - { + } else if (!eventSrcName.startsWith(CHECKSTYLE_PACKAGE)) { return "extension"; } - return eventSrcName.substring( eventSrcName.lastIndexOf( '.' ) + 1 ); + return eventSrcName.substring(eventSrcName.lastIndexOf('.') + 1); } - public static List parseMatchers( String[] specs ) - { + public static List parseMatchers(String[] specs) { List matchers = new ArrayList<>(); - for ( String spec : specs ) - { - if ( StringUtils.isBlank( spec ) ) - { + for (String spec : specs) { + if (StringUtils.isBlank(spec)) { continue; } spec = spec.trim(); Matcher matcher; - if ( Character.isUpperCase( spec.charAt( 0 ) ) ) - { + if (Character.isUpperCase(spec.charAt(0))) { // spec starting with uppercase is a rule name - matcher = new RuleMatcher( spec ); - } - else if ( "misc".equals( spec ) ) - { + matcher = new RuleMatcher(spec); + } else if ("misc".equals(spec)) { // "misc" is a special case - matcher = new PackageMatcher( CHECKSTYLE_PACKAGE ); - } - else if ( "extension".equals( spec ) ) - { + matcher = new PackageMatcher(CHECKSTYLE_PACKAGE); + } else if ("extension".equals(spec)) { // "extension" is a special case matcher = new ExtensionMatcher(); - } - else if ( !spec.contains( "." ) ) - { - matcher = new PackageMatcher( CHECKSTYLE_PACKAGE + '.' + spec ); - } - else - { + } else if (!spec.contains(".")) { + matcher = new PackageMatcher(CHECKSTYLE_PACKAGE + '.' + spec); + } else { // by default, spec is a package name - matcher = new PackageMatcher( spec ); + matcher = new PackageMatcher(spec); } - matchers.add( matcher ); + matchers.add(matcher); } return matchers; } @@ -154,58 +128,46 @@ else if ( !spec.contains( "." ) ) /** * Audit event source name matcher. */ - public interface Matcher - { + public interface Matcher { /** * Does the event source name match? * @param eventSrcName the event source name * @return boolean */ - boolean match( String eventSrcName ); + boolean match(String eventSrcName); } - private static class RuleMatcher - implements Matcher - { + private static class RuleMatcher implements Matcher { private final String rule; - RuleMatcher( String rule ) - { + RuleMatcher(String rule) { this.rule = rule; } - public boolean match( String eventSrcName ) - { - return rule.equals( getName( eventSrcName ) ); + public boolean match(String eventSrcName) { + return rule.equals(getName(eventSrcName)); } } - private static class PackageMatcher - implements Matcher - { + private static class PackageMatcher implements Matcher { private final String packageName; - PackageMatcher( String packageName ) - { + PackageMatcher(String packageName) { this.packageName = packageName; } - public boolean match( String eventSrcName ) - { - return eventSrcName.startsWith( packageName ) - && !eventSrcName.substring( packageName.length() + 1 ).contains( "." ); + public boolean match(String eventSrcName) { + return eventSrcName.startsWith(packageName) + && !eventSrcName.substring(packageName.length() + 1).contains("."); } } /** * An extension does not start with Checkstyle package. */ - private static class ExtensionMatcher - implements Matcher - { - public boolean match( String eventSrcName ) - { - return !eventSrcName.startsWith( CHECKSTYLE_PACKAGE ); + private static class ExtensionMatcher implements Matcher { + public boolean match(String eventSrcName) { + return !eventSrcName.startsWith(CHECKSTYLE_PACKAGE); } } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/Violation.java b/src/main/java/org/apache/maven/plugins/checkstyle/Violation.java index e22de2e2..7565601e 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/Violation.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/Violation.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.util.Objects; import java.util.StringJoiner; @@ -25,205 +24,187 @@ /** * Holds data about a single violation and represents the violation itself. */ -class Violation -{ - - /** - * Indicates that a column is not set. - */ - protected static final String NO_COLUMN = "-1"; - - /** The full qualified class name of the checkstyle rule */ - private final String source; - - /** The absolute path of the file containing the violation */ - private final String file; - - private final String line; - - private String column = NO_COLUMN; - - private final String severity; - - private final String message; - - private final String ruleName; - - private final String category; - - // Leaving out column, because there is no CHECKSTYLE:OFF support. - - /** - * Creates a violation instance without a column set. - * - * @param source - * the fully qualified class name of the checkstyle rule - * @param file - * the absolute file path in which the violation occurred - * @param line - * the line in the file on which the violation occurred - * @param severity - * the severity of the violation - * @param message - * the message from checkstyle for this violation - * @param ruleName - * the rule name from which this violation was created - * @param category - * the category of the checkstyle violation - */ - Violation( String source, - String file, - String line, - String severity, - String message, - String ruleName, - String category ) - { - this.source = Objects.requireNonNull( source ); - this.file = file; - this.line = line; - this.severity = Objects.requireNonNull( severity ); - this.message = Objects.requireNonNull( message ); - this.ruleName = Objects.requireNonNull( ruleName ); - this.category = Objects.requireNonNull( category ); - } - - /** - * Returns the fully qualified class name of the checker rule. - * - * @return the fully qualified class name of the checker rule - */ - protected String getSource( ) - { - return source; - } - - /** - * Returns the absolute file path to the checked file. - * - * @return the absolute file path to the checked file - */ - protected String getFile( ) - { - return file; - } - - /** - * Returns the line in the checked file on which the violation occurred. - * - * @return the line in the checked file on which the violation occurred - */ - protected String getLine( ) - { - return line; - } - - /** - * Returns the column in which the violation occurred, if available. - * - * @return the column in which the violation occurred, if available. Otherwise returns {@link #NO_COLUMN}. - */ - protected String getColumn( ) - { - return column; - } - - /** - * Sets the column value for this violation to the given string value. - * @param column the column value to set. May be {@code null}, which will set it to the {@link #NO_COLUMN} value. - */ - protected void setColumn( /* Nullable */ String column ) - { - if ( column == null || column.length() < 1 ) - { - this.column = NO_COLUMN; +class Violation { + + /** + * Indicates that a column is not set. + */ + protected static final String NO_COLUMN = "-1"; + + /** The full qualified class name of the checkstyle rule */ + private final String source; + + /** The absolute path of the file containing the violation */ + private final String file; + + private final String line; + + private String column = NO_COLUMN; + + private final String severity; + + private final String message; + + private final String ruleName; + + private final String category; + + // Leaving out column, because there is no CHECKSTYLE:OFF support. + + /** + * Creates a violation instance without a column set. + * + * @param source + * the fully qualified class name of the checkstyle rule + * @param file + * the absolute file path in which the violation occurred + * @param line + * the line in the file on which the violation occurred + * @param severity + * the severity of the violation + * @param message + * the message from checkstyle for this violation + * @param ruleName + * the rule name from which this violation was created + * @param category + * the category of the checkstyle violation + */ + Violation( + String source, + String file, + String line, + String severity, + String message, + String ruleName, + String category) { + this.source = Objects.requireNonNull(source); + this.file = file; + this.line = line; + this.severity = Objects.requireNonNull(severity); + this.message = Objects.requireNonNull(message); + this.ruleName = Objects.requireNonNull(ruleName); + this.category = Objects.requireNonNull(category); + } + + /** + * Returns the fully qualified class name of the checker rule. + * + * @return the fully qualified class name of the checker rule + */ + protected String getSource() { + return source; + } + + /** + * Returns the absolute file path to the checked file. + * + * @return the absolute file path to the checked file + */ + protected String getFile() { + return file; + } + + /** + * Returns the line in the checked file on which the violation occurred. + * + * @return the line in the checked file on which the violation occurred + */ + protected String getLine() { + return line; + } + + /** + * Returns the column in which the violation occurred, if available. + * + * @return the column in which the violation occurred, if available. Otherwise returns {@link #NO_COLUMN}. + */ + protected String getColumn() { + return column; + } + + /** + * Sets the column value for this violation to the given string value. + * @param column the column value to set. May be {@code null}, which will set it to the {@link #NO_COLUMN} value. + */ + protected void setColumn(/* Nullable */ String column) { + if (column == null || column.length() < 1) { + this.column = NO_COLUMN; + } else { + this.column = column; + } + } + + /** + * Returns the severity of the current violation. + * + * @return the severity of the current violation + */ + protected String getSeverity() { + return severity; + } + + /** + * Returns the message produced by checkstyle for the current violation. + * + * @return the message produced by checkstyle for the current violation + */ + protected String getMessage() { + return message; + } + + /** + * Returns the name of the rule which led to the current violation. + * + * @return the name of the rule which led to the current violation + */ + protected String getRuleName() { + return ruleName; + } + + /** + * Returns the category of the current violation. + * + * @return the category of the current violation + */ + protected String getCategory() { + return category; } - else - { - this.column = column; + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!(other instanceof Violation)) { + return false; + } + Violation violation = (Violation) other; + return Objects.equals(line, violation.line) + && Objects.equals(column, violation.column) + && source.equals(violation.source) + && Objects.equals(file, violation.file) + && severity.equals(violation.severity) + && message.equals(violation.message) + && ruleName.equals(violation.ruleName) + && category.equals(violation.category); } - } - - /** - * Returns the severity of the current violation. - * - * @return the severity of the current violation - */ - protected String getSeverity( ) - { - return severity; - } - - /** - * Returns the message produced by checkstyle for the current violation. - * - * @return the message produced by checkstyle for the current violation - */ - protected String getMessage( ) - { - return message; - } - - /** - * Returns the name of the rule which led to the current violation. - * - * @return the name of the rule which led to the current violation - */ - protected String getRuleName( ) - { - return ruleName; - } - - /** - * Returns the category of the current violation. - * - * @return the category of the current violation - */ - protected String getCategory( ) - { - return category; - } - - @Override - public boolean equals( Object other ) - { - if ( this == other ) - { - return true; + + @Override + public int hashCode() { + return Objects.hash(source, file, line, column, severity, message, ruleName, category); } - if ( !( other instanceof Violation ) ) - { - return false; + + @Override + public String toString() { + return new StringJoiner(", ", Violation.class.getSimpleName() + "[", "]") + .add("source='" + source + "'") + .add("file='" + file + "'") + .add("line=" + line) + .add("column=" + column) + .add("severity='" + severity + "'") + .add("message='" + message + "'") + .add("ruleName='" + ruleName + "'") + .add("category='" + category + "'") + .toString(); } - Violation violation = ( Violation ) other; - return Objects.equals( line, violation.line ) - && Objects.equals( column, violation.column ) - && source.equals( violation.source ) - && Objects.equals( file, violation.file ) - && severity.equals( violation.severity ) - && message.equals( violation.message ) - && ruleName.equals( violation.ruleName ) - && category.equals( violation.category ); - } - - @Override - public int hashCode() - { - return Objects.hash( source, file, line, column, severity, message, ruleName, category ); - } - - @Override - public String toString() - { - return new StringJoiner( ", ", Violation.class.getSimpleName() + "[", "]" ) - .add( "source='" + source + "'" ) - .add( "file='" + file + "'" ) - .add( "line=" + line ) - .add( "column=" + column ) - .add( "severity='" + severity + "'" ) - .add( "message='" + message + "'" ) - .add( "ruleName='" + ruleName + "'" ) - .add( "category='" + category + "'" ) - .toString(); - } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleCheckerListener.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleCheckerListener.java index 85102f5a..ba5d5a1e 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleCheckerListener.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleCheckerListener.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.AuditListener; @@ -25,13 +28,8 @@ import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; - import org.apache.commons.lang3.StringUtils; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - /** * Listener in charge of receiving events from the Checker. * @@ -39,10 +37,7 @@ * @author Vincent Siveton * */ -public class CheckstyleCheckerListener - extends AutomaticBean - implements AuditListener -{ +public class CheckstyleCheckerListener extends AutomaticBean implements AuditListener { private final List sourceDirectories; private CheckstyleResults results; @@ -58,20 +53,18 @@ public class CheckstyleCheckerListener /** * @param sourceDirectory assume that is sourceDirectory is a not null directory and exists */ - public CheckstyleCheckerListener( File sourceDirectory ) - { + public CheckstyleCheckerListener(File sourceDirectory) { this.sourceDirectories = new ArrayList<>(); - this.sourceDirectories.add( sourceDirectory ); + this.sourceDirectories.add(sourceDirectory); } /** * @param sourceDirectory assume that is sourceDirectory is a not null directory and exists * @param configuration Checkstyle configuration * @since 2.5 */ - public CheckstyleCheckerListener( File sourceDirectory, Configuration configuration ) - { + public CheckstyleCheckerListener(File sourceDirectory, Configuration configuration) { this.sourceDirectories = new ArrayList<>(); - this.sourceDirectories.add( sourceDirectory ); + this.sourceDirectories.add(sourceDirectory); this.checkstyleConfiguration = configuration; } @@ -79,8 +72,7 @@ public CheckstyleCheckerListener( File sourceDirectory, Configuration configurat * @param configuration Checkstyle configuration * @since 2.5 */ - public CheckstyleCheckerListener( Configuration configuration ) - { + public CheckstyleCheckerListener(Configuration configuration) { this.sourceDirectories = new ArrayList<>(); this.checkstyleConfiguration = configuration; } @@ -88,118 +80,101 @@ public CheckstyleCheckerListener( Configuration configuration ) /** * @param sourceDirectory assume that is sourceDirectory is a not null directory and exists */ - public void addSourceDirectory( File sourceDirectory ) - { - this.sourceDirectories.add( sourceDirectory ); + public void addSourceDirectory(File sourceDirectory) { + this.sourceDirectories.add(sourceDirectory); } /** * @param severityLevel The severity level of the events to listen to. */ - public void setSeverityLevelFilter( SeverityLevel severityLevel ) - { + public void setSeverityLevelFilter(SeverityLevel severityLevel) { this.severityLevel = severityLevel; } /** * @return The severity level of the events to listen to. */ - public SeverityLevel getSeverityLevelFilter() - { + public SeverityLevel getSeverityLevelFilter() { return severityLevel; } /** {@inheritDoc} */ @Override - public void auditStarted( AuditEvent event ) - { - setResults( new CheckstyleResults() ); + public void auditStarted(AuditEvent event) { + setResults(new CheckstyleResults()); } /** {@inheritDoc} */ @Override - public void auditFinished( AuditEvent event ) - { - //do nothing + public void auditFinished(AuditEvent event) { + // do nothing } /** {@inheritDoc} */ @Override - public void fileStarted( AuditEvent event ) - { - final String fileName = StringUtils.replace( event.getFileName(), "\\", "/" ); - - for ( File sourceDirectory : sourceDirectories ) - { - String sourceDirectoryPath = StringUtils.replace( sourceDirectory.getPath(), "\\", "/" ); - - if ( fileName.startsWith( sourceDirectoryPath + "/" ) ) - { - currentFile = StringUtils.substring( fileName, sourceDirectoryPath.length() + 1 ); - - events = getResults().getFileViolations( currentFile ); - + public void fileStarted(AuditEvent event) { + final String fileName = StringUtils.replace(event.getFileName(), "\\", "/"); + + for (File sourceDirectory : sourceDirectories) { + String sourceDirectoryPath = StringUtils.replace(sourceDirectory.getPath(), "\\", "/"); + + if (fileName.startsWith(sourceDirectoryPath + "/")) { + currentFile = StringUtils.substring(fileName, sourceDirectoryPath.length() + 1); + + events = getResults().getFileViolations(currentFile); + break; } } - if ( events == null ) - { + if (events == null) { events = new ArrayList<>(); } } /** {@inheritDoc} */ @Override - public void fileFinished( AuditEvent event ) - { - getResults().setFileViolations( currentFile, events ); + public void fileFinished(AuditEvent event) { + getResults().setFileViolations(currentFile, events); currentFile = null; } /** {@inheritDoc} */ @Override - public void addError( AuditEvent event ) - { - if ( SeverityLevel.IGNORE.equals( event.getSeverityLevel() ) ) - { + public void addError(AuditEvent event) { + if (SeverityLevel.IGNORE.equals(event.getSeverityLevel())) { return; } - if ( severityLevel == null || severityLevel.equals( event.getSeverityLevel() ) ) - { - events.add( event ); + if (severityLevel == null || severityLevel.equals(event.getSeverityLevel())) { + events.add(event); } } /** {@inheritDoc} */ @Override - public void addException( AuditEvent event, Throwable throwable ) - { - //Do Nothing + public void addException(AuditEvent event, Throwable throwable) { + // Do Nothing } /** {@inheritDoc} */ @Override - protected void finishLocalSetup() throws CheckstyleException - { - //Do Nothing + protected void finishLocalSetup() throws CheckstyleException { + // Do Nothing } /** * @return The results of Checkstyle invocation. */ - public CheckstyleResults getResults() - { - results.setConfiguration( checkstyleConfiguration ); + public CheckstyleResults getResults() { + results.setConfiguration(checkstyleConfiguration); return results; } /** * @param results The results of Checkstyle invocation. */ - public void setResults( CheckstyleResults results ) - { + public void setResults(CheckstyleResults results) { this.results = results; } @@ -207,8 +182,7 @@ public void setResults( CheckstyleResults results ) * @since 2.5 * @return The configuration of Checkstyle to use. */ - public Configuration getCheckstyleConfiguration() - { + public Configuration getCheckstyleConfiguration() { return checkstyleConfiguration; } @@ -216,10 +190,7 @@ public Configuration getCheckstyleConfiguration() * @param checkstyleConfiguration The configuration of Checkstyle to use. * @since 2.5 */ - public void setCheckstyleConfiguration( Configuration checkstyleConfiguration ) - { + public void setCheckstyleConfiguration(Configuration checkstyleConfiguration) { this.checkstyleConfiguration = checkstyleConfiguration; } - } - diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutor.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutor.java index ba7e19e9..583b2ba9 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutor.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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.checkstyle.exec; import com.puppycrawl.tools.checkstyle.api.CheckstyleException; import com.puppycrawl.tools.checkstyle.api.Configuration; @@ -27,8 +26,7 @@ * @since 2.5 * */ -public interface CheckstyleExecutor -{ +public interface CheckstyleExecutor { /** * @param request {@link CheckstyleExecutorRequest} @@ -36,9 +34,8 @@ public interface CheckstyleExecutor * @throws CheckstyleExecutorException in case of an error during plugin execution. * @throws CheckstyleException in case of an error raised by Checkstyle. */ - CheckstyleResults executeCheckstyle( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException, CheckstyleException; + CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request) + throws CheckstyleExecutorException, CheckstyleException; - Configuration getConfiguration( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException; + Configuration getConfiguration(CheckstyleExecutorRequest request) throws CheckstyleExecutorException; } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorException.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorException.java index f60a4af9..d2a6335e 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorException.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorException.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,49 +16,43 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; /** * @author Olivier Lamy * @since 2.5 * */ -public class CheckstyleExecutorException - extends Exception -{ +public class CheckstyleExecutorException extends Exception { private static final long serialVersionUID = 3239899539232498912L; /** - * + * */ - public CheckstyleExecutorException() - { + public CheckstyleExecutorException() { // nothing } /** * @param message Message of the exception. */ - public CheckstyleExecutorException( String message ) - { - super( message ); + public CheckstyleExecutorException(String message) { + super(message); } /** * @param cause Cause of the exception. */ - public CheckstyleExecutorException( Throwable cause ) - { - super( cause ); + public CheckstyleExecutorException(Throwable cause) { + super(cause); } /** * @param message Message of the exception. * @param cause Cause of the exception. */ - public CheckstyleExecutorException( String message, Throwable cause ) - { - super( message, cause ); + public CheckstyleExecutorException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorRequest.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorRequest.java index 39c9f948..c168a2eb 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorRequest.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleExecutorRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,26 +16,25 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.Collection; import java.util.List; +import com.puppycrawl.tools.checkstyle.DefaultLogger; +import com.puppycrawl.tools.checkstyle.api.AuditListener; import org.apache.maven.artifact.Artifact; import org.apache.maven.model.Resource; import org.apache.maven.project.MavenProject; -import com.puppycrawl.tools.checkstyle.DefaultLogger; -import com.puppycrawl.tools.checkstyle.api.AuditListener; - /** * @author Olivier Lamy * @since 2.5 * */ -public class CheckstyleExecutorRequest -{ +public class CheckstyleExecutorRequest { /** * Specifies the names filter of the source files to be used for Checkstyle. @@ -112,7 +109,7 @@ public class CheckstyleExecutorRequest * @since 2.8 */ private List reactorProjects; - + /** * @since 2.12.1 */ @@ -131,9 +128,8 @@ public class CheckstyleExecutorRequest /** * Constructor. */ - public CheckstyleExecutorRequest( ) - { - //nothing + public CheckstyleExecutorRequest() { + // nothing } /** @@ -141,255 +137,209 @@ public CheckstyleExecutorRequest( ) * * @return The includes parameter. */ - public String getIncludes() - { + public String getIncludes() { return includes; } - public CheckstyleExecutorRequest setIncludes( String includes ) - { + public CheckstyleExecutorRequest setIncludes(String includes) { this.includes = includes; return this; } - public String getExcludes() - { + public String getExcludes() { return excludes; } - public CheckstyleExecutorRequest setExcludes( String excludes ) - { + public CheckstyleExecutorRequest setExcludes(String excludes) { this.excludes = excludes; return this; } - public String getResourceIncludes() - { + public String getResourceIncludes() { return resourceIncludes; } - public CheckstyleExecutorRequest setResourceIncludes( String resourceIncludes ) - { + public CheckstyleExecutorRequest setResourceIncludes(String resourceIncludes) { this.resourceIncludes = resourceIncludes; return this; } - public String getResourceExcludes() - { + public String getResourceExcludes() { return resourceExcludes; } - public CheckstyleExecutorRequest setResourceExcludes( String resourceExcludes ) - { + public CheckstyleExecutorRequest setResourceExcludes(String resourceExcludes) { this.resourceExcludes = resourceExcludes; return this; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public CheckstyleExecutorRequest setProject( MavenProject project ) - { + public CheckstyleExecutorRequest setProject(MavenProject project) { this.project = project; return this; } - public String getSuppressionsLocation() - { + public String getSuppressionsLocation() { return suppressionsLocation; } - public CheckstyleExecutorRequest setSuppressionsLocation( String suppressionsLocation ) - { + public CheckstyleExecutorRequest setSuppressionsLocation(String suppressionsLocation) { this.suppressionsLocation = suppressionsLocation; return this; } - public boolean isIncludeTestSourceDirectory() - { + public boolean isIncludeTestSourceDirectory() { return includeTestSourceDirectory; } - public CheckstyleExecutorRequest setIncludeTestSourceDirectory( boolean includeTestSourceDirectory ) - { + public CheckstyleExecutorRequest setIncludeTestSourceDirectory(boolean includeTestSourceDirectory) { this.includeTestSourceDirectory = includeTestSourceDirectory; return this; } - - public Collection getTestSourceDirectories() - { + + public Collection getTestSourceDirectories() { return testSourceDirectories; } - - public CheckstyleExecutorRequest setTestSourceDirectories( Collection testSourceDirectories ) - { + + public CheckstyleExecutorRequest setTestSourceDirectories(Collection testSourceDirectories) { this.testSourceDirectories = testSourceDirectories; return this; } - - public Collection getSourceDirectories() - { + + public Collection getSourceDirectories() { return sourceDirectories; } - - public CheckstyleExecutorRequest setSourceDirectories( Collection sourceDirectories ) - { + + public CheckstyleExecutorRequest setSourceDirectories(Collection sourceDirectories) { this.sourceDirectories = sourceDirectories; return this; } - public List getResources() - { + public List getResources() { return resources; } - public CheckstyleExecutorRequest setResources( List resources ) - { + public CheckstyleExecutorRequest setResources(List resources) { this.resources = resources; return this; } - public List getTestResources() - { + public List getTestResources() { return testResources; } - public CheckstyleExecutorRequest setTestResources( List testResources ) - { + public CheckstyleExecutorRequest setTestResources(List testResources) { this.testResources = testResources; return this; } - public boolean isFailsOnError() - { + public boolean isFailsOnError() { return failsOnError; } - public CheckstyleExecutorRequest setFailsOnError( boolean failsOnError ) - { + public CheckstyleExecutorRequest setFailsOnError(boolean failsOnError) { this.failsOnError = failsOnError; return this; } - public AuditListener getListener() - { + public AuditListener getListener() { return listener; } - public CheckstyleExecutorRequest setListener( AuditListener listener ) - { + public CheckstyleExecutorRequest setListener(AuditListener listener) { this.listener = listener; return this; } - public boolean isConsoleOutput() - { + public boolean isConsoleOutput() { return consoleOutput; } - public CheckstyleExecutorRequest setConsoleOutput( boolean consoleOutput ) - { + public CheckstyleExecutorRequest setConsoleOutput(boolean consoleOutput) { this.consoleOutput = consoleOutput; return this; } - public CheckstyleExecutorRequest setConsoleListener( DefaultLogger defaultLogger ) - { + public CheckstyleExecutorRequest setConsoleListener(DefaultLogger defaultLogger) { this.defaultLogger = defaultLogger; return this; } - public DefaultLogger getConsoleListener() - { + public DefaultLogger getConsoleListener() { return this.defaultLogger; } - public ByteArrayOutputStream getStringOutputStream() - { + public ByteArrayOutputStream getStringOutputStream() { return stringOutputStream; } - public CheckstyleExecutorRequest setStringOutputStream( ByteArrayOutputStream stringOutputStream ) - { + public CheckstyleExecutorRequest setStringOutputStream(ByteArrayOutputStream stringOutputStream) { this.stringOutputStream = stringOutputStream; return this; } - public String getConfigLocation() - { + public String getConfigLocation() { return configLocation; } - public CheckstyleExecutorRequest setConfigLocation( String configLocation ) - { + public CheckstyleExecutorRequest setConfigLocation(String configLocation) { this.configLocation = configLocation; return this; } - public String getPropertyExpansion() - { + public String getPropertyExpansion() { return propertyExpansion; } - public CheckstyleExecutorRequest setPropertyExpansion( String propertyExpansion ) - { + public CheckstyleExecutorRequest setPropertyExpansion(String propertyExpansion) { this.propertyExpansion = propertyExpansion; return this; } - public String getHeaderLocation() - { + public String getHeaderLocation() { return headerLocation; } - public CheckstyleExecutorRequest setHeaderLocation( String headerLocation ) - { + public CheckstyleExecutorRequest setHeaderLocation(String headerLocation) { this.headerLocation = headerLocation; return this; } - public String getCacheFile() - { + public String getCacheFile() { return cacheFile; } - public CheckstyleExecutorRequest setCacheFile( String cacheFile ) - { + public CheckstyleExecutorRequest setCacheFile(String cacheFile) { this.cacheFile = cacheFile; return this; } - public String getSuppressionsFileExpression() - { + public String getSuppressionsFileExpression() { return suppressionsFileExpression; } - public CheckstyleExecutorRequest setSuppressionsFileExpression( String suppressionsFileExpression ) - { + public CheckstyleExecutorRequest setSuppressionsFileExpression(String suppressionsFileExpression) { this.suppressionsFileExpression = suppressionsFileExpression; return this; } - public String getEncoding() - { + public String getEncoding() { return encoding; } - public CheckstyleExecutorRequest setEncoding( String encoding ) - { + public CheckstyleExecutorRequest setEncoding(String encoding) { this.encoding = encoding; return this; } - public String getPropertiesLocation() - { + public String getPropertiesLocation() { return propertiesLocation; } - public CheckstyleExecutorRequest setPropertiesLocation( String propertiesLocation ) - { + public CheckstyleExecutorRequest setPropertiesLocation(String propertiesLocation) { this.propertiesLocation = propertiesLocation; return this; } @@ -399,8 +349,7 @@ public CheckstyleExecutorRequest setPropertiesLocation( String propertiesLocatio * * @return true if the report is aggregated. */ - public boolean isAggregate() - { + public boolean isAggregate() { return aggregate; } @@ -410,8 +359,7 @@ public boolean isAggregate() * @param pAggregate true if an aggregated report is desired. * @return This object. */ - public CheckstyleExecutorRequest setAggregate( boolean pAggregate ) - { + public CheckstyleExecutorRequest setAggregate(boolean pAggregate) { this.aggregate = pAggregate; return this; } @@ -421,8 +369,7 @@ public CheckstyleExecutorRequest setAggregate( boolean pAggregate ) * * @return The reactor projects. */ - public List getReactorProjects() - { + public List getReactorProjects() { return reactorProjects; } @@ -432,58 +379,52 @@ public List getReactorProjects() * @param pReactorProjects The reactor projects. * @return This object. */ - public CheckstyleExecutorRequest setReactorProjects( List pReactorProjects ) - { + public CheckstyleExecutorRequest setReactorProjects(List pReactorProjects) { this.reactorProjects = pReactorProjects; return this; } /** * Returns a list of license artifacts, which may contain the license. - * + * * @return the license artifacts */ - public List getLicenseArtifacts() - { + public List getLicenseArtifacts() { return licenseArtifacts; } /** * Sets a list of license artifacts, which may contain the license. - * + * * @param licenseArtifacts List of license artifacts. * @return This object. */ - public CheckstyleExecutorRequest setLicenseArtifacts( List licenseArtifacts ) - { + public CheckstyleExecutorRequest setLicenseArtifacts(List licenseArtifacts) { this.licenseArtifacts = licenseArtifacts; return this; } - + /** * Returns a list of artifacts, which may contain the checkstyle configuration. - * + * * @return the license artifacts */ - public List getConfigurationArtifacts() - { + public List getConfigurationArtifacts() { return configurationArtifacts; } /** * Sets a list of artifacts, which may contain the checkstyle configuration. - * + * * @param configArtifacts List of artifacts. * @return This object. */ - public CheckstyleExecutorRequest setConfigurationArtifacts( List configArtifacts ) - { + public CheckstyleExecutorRequest setConfigurationArtifacts(List configArtifacts) { this.configurationArtifacts = configArtifacts; return this; } - - public boolean isIncludeResources() - { + + public boolean isIncludeResources() { return includeResources; } @@ -491,14 +432,12 @@ public boolean isIncludeResources() * @param includeResources whether to include the resource directories in the checks. * @return This object. */ - public CheckstyleExecutorRequest setIncludeResources( boolean includeResources ) - { + public CheckstyleExecutorRequest setIncludeResources(boolean includeResources) { this.includeResources = includeResources; return this; } - public boolean isIncludeTestResources() - { + public boolean isIncludeTestResources() { return includeTestResources; } @@ -506,8 +445,7 @@ public boolean isIncludeTestResources() * @param includeTestResources whether to set the test resource directories in the checks. * @return This object. */ - public CheckstyleExecutorRequest setIncludeTestResources( boolean includeTestResources ) - { + public CheckstyleExecutorRequest setIncludeTestResources(boolean includeTestResources) { this.includeTestResources = includeTestResources; return this; } @@ -517,8 +455,7 @@ public CheckstyleExecutorRequest setIncludeTestResources( boolean includeTestRes * * @return true if ignored modules should be omitted. */ - public boolean isOmitIgnoredModules() - { + public boolean isOmitIgnoredModules() { return omitIgnoredModules; } @@ -526,8 +463,7 @@ public boolean isOmitIgnoredModules() * @param omitIgnoredModules Whether to omit ignored modules (modules with severity 'ignore'). * @return This object. */ - public CheckstyleExecutorRequest setOmitIgnoredModules( boolean omitIgnoredModules ) - { + public CheckstyleExecutorRequest setOmitIgnoredModules(boolean omitIgnoredModules) { this.omitIgnoredModules = omitIgnoredModules; return this; } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResults.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResults.java index a82870f9..8db1aea8 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResults.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResults.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,16 +16,17 @@ * specific language governing permissions and limitations * under the License. */ - -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.api.SeverityLevel; +package org.apache.maven.plugins.checkstyle.exec; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; +import com.puppycrawl.tools.checkstyle.api.AuditEvent; +import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.api.SeverityLevel; + /** * Object holding the references to the CheckstyleResults. * TODO: provide fallback to disk based storage if too many results. @@ -35,96 +34,77 @@ * @author Joakim Erdfelt * */ -public class CheckstyleResults -{ +public class CheckstyleResults { private Map> files; private Configuration configuration; - public CheckstyleResults() - { + public CheckstyleResults() { files = new HashMap<>(); } - public List getFileViolations( String file ) - { + public List getFileViolations(String file) { List violations; - if ( this.files.containsKey( file ) ) - { - violations = this.files.get( file ); - } - else - { + if (this.files.containsKey(file)) { + violations = this.files.get(file); + } else { violations = new LinkedList<>(); - if ( file != null ) - { - this.files.put( file, violations ); + if (file != null) { + this.files.put(file, violations); } } return violations; } - public void setFileViolations( String file, List violations ) - { - if ( file != null ) - { - this.files.put( file, violations ); + public void setFileViolations(String file, List violations) { + if (file != null) { + this.files.put(file, violations); } } - public Map> getFiles() - { + public Map> getFiles() { return files; } - public void setFiles( Map> files ) - { + public void setFiles(Map> files) { this.files = files; } - public int getFileCount() - { + public int getFileCount() { return this.files.size(); } - public long getSeverityCount( SeverityLevel level ) - { + public long getSeverityCount(SeverityLevel level) { long count = 0; - for ( List errors : this.files.values() ) - { - count = count + getSeverityCount( errors, level ); + for (List errors : this.files.values()) { + count = count + getSeverityCount(errors, level); } return count; } - public long getSeverityCount( String file, SeverityLevel level ) - { + public long getSeverityCount(String file, SeverityLevel level) { long count = 0; - if ( !this.files.containsKey( file ) ) - { + if (!this.files.containsKey(file)) { return count; } - List violations = this.files.get( file ); + List violations = this.files.get(file); - count = getSeverityCount( violations, level ); + count = getSeverityCount(violations, level); return count; } - public long getSeverityCount( List violations, SeverityLevel level ) - { + public long getSeverityCount(List violations, SeverityLevel level) { long count = 0; - for ( AuditEvent event : violations ) - { - if ( event.getSeverityLevel().equals( level ) ) - { + for (AuditEvent event : violations) { + if (event.getSeverityLevel().equals(level)) { count++; } } @@ -132,13 +112,11 @@ public long getSeverityCount( List violations, SeverityLevel level ) return count; } - public Configuration getConfiguration() - { + public Configuration getConfiguration() { return configuration; } - public void setConfiguration( Configuration configuration ) - { + public void setConfiguration(Configuration configuration) { this.configuration = configuration; } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/exec/DefaultCheckstyleExecutor.java b/src/main/java/org/apache/maven/plugins/checkstyle/exec/DefaultCheckstyleExecutor.java index 46ec912c..ad3a8c46 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/exec/DefaultCheckstyleExecutor.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/exec/DefaultCheckstyleExecutor.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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.checkstyle.exec; import java.io.ByteArrayInputStream; import java.io.File; @@ -34,6 +33,17 @@ import java.util.Properties; import java.util.Set; +import com.puppycrawl.tools.checkstyle.Checker; +import com.puppycrawl.tools.checkstyle.ConfigurationLoader; +import com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions; +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.PackageNamesLoader; +import com.puppycrawl.tools.checkstyle.PropertiesExpander; +import com.puppycrawl.tools.checkstyle.api.AuditListener; +import com.puppycrawl.tools.checkstyle.api.CheckstyleException; +import com.puppycrawl.tools.checkstyle.api.Configuration; +import com.puppycrawl.tools.checkstyle.api.FilterSet; +import com.puppycrawl.tools.checkstyle.filters.SuppressionsLoader; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DependencyResolutionRequiredException; @@ -48,357 +58,293 @@ import org.codehaus.plexus.resource.loader.ResourceNotFoundException; import org.codehaus.plexus.util.FileUtils; -import com.puppycrawl.tools.checkstyle.Checker; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.ConfigurationLoader.IgnoredModulesOptions; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.PackageNamesLoader; -import com.puppycrawl.tools.checkstyle.PropertiesExpander; -import com.puppycrawl.tools.checkstyle.api.AuditListener; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.api.FilterSet; -import com.puppycrawl.tools.checkstyle.filters.SuppressionsLoader; - /** * @author Olivier Lamy * @since 2.5 * */ -@Component( role = CheckstyleExecutor.class, hint = "default", instantiationStrategy = "per-lookup" ) -public class DefaultCheckstyleExecutor - extends AbstractLogEnabled - implements CheckstyleExecutor -{ - @Requirement( hint = "default" ) +@Component(role = CheckstyleExecutor.class, hint = "default", instantiationStrategy = "per-lookup") +public class DefaultCheckstyleExecutor extends AbstractLogEnabled implements CheckstyleExecutor { + @Requirement(hint = "default") private ResourceManager locator; - - @Requirement( hint = "license" ) + + @Requirement(hint = "license") private ResourceManager licenseLocator; - public CheckstyleResults executeCheckstyle( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException, CheckstyleException - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "executeCheckstyle start headerLocation : " + request.getHeaderLocation() ); + public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request) + throws CheckstyleExecutorException, CheckstyleException { + if (getLogger().isDebugEnabled()) { + getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation()); } MavenProject project = request.getProject(); - configureResourceLocator( locator, request, null ); - - configureResourceLocator( licenseLocator, request, request.getLicenseArtifacts() ); + configureResourceLocator(locator, request, null); + + configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts()); // Config is less critical than License, locator can still be used. // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() ); List files; - try - { - files = getFilesToProcess( request ); - } - catch ( IOException e ) - { - throw new CheckstyleExecutorException( "Error getting files to process", e ); + try { + files = getFilesToProcess(request); + } catch (IOException e) { + throw new CheckstyleExecutorException("Error getting files to process", e); } - final String suppressionsFilePath = getSuppressionsFilePath( request ); - FilterSet filterSet = getSuppressionsFilterSet( suppressionsFilePath ); + final String suppressionsFilePath = getSuppressionsFilePath(request); + FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath); Checker checker = new Checker(); // setup classloader, needed to avoid "Unable to get class information for ..." errors List classPathStrings = new ArrayList<>(); List outputDirectories = new ArrayList<>(); - + // stand-alone Collection sourceDirectories = null; Collection testSourceDirectories = request.getTestSourceDirectories(); - + // aggregator Map> sourceDirectoriesByProject = new HashMap<>(); Map> testSourceDirectoriesByProject = new HashMap<>(); - - if ( request.isAggregate() ) - { - for ( MavenProject childProject : request.getReactorProjects() ) - { - sourceDirectories = new ArrayList<>( childProject.getCompileSourceRoots().size() ); + + if (request.isAggregate()) { + for (MavenProject childProject : request.getReactorProjects()) { + sourceDirectories = + new ArrayList<>(childProject.getCompileSourceRoots().size()); List compileSourceRoots = childProject.getCompileSourceRoots(); - for ( String compileSourceRoot : compileSourceRoots ) - { - sourceDirectories.add( new File( compileSourceRoot ) ); + for (String compileSourceRoot : compileSourceRoots) { + sourceDirectories.add(new File(compileSourceRoot)); } - sourceDirectoriesByProject.put( childProject, sourceDirectories ); - - testSourceDirectories = new ArrayList<>( childProject.getTestCompileSourceRoots().size() ); + sourceDirectoriesByProject.put(childProject, sourceDirectories); + + testSourceDirectories = + new ArrayList<>(childProject.getTestCompileSourceRoots().size()); List testCompileSourceRoots = childProject.getTestCompileSourceRoots(); - for ( String testCompileSourceRoot : testCompileSourceRoots ) - { - testSourceDirectories.add( new File( testCompileSourceRoot ) ); + for (String testCompileSourceRoot : testCompileSourceRoots) { + testSourceDirectories.add(new File(testCompileSourceRoot)); } - testSourceDirectoriesByProject.put( childProject, testSourceDirectories ); - - prepareCheckstylePaths( request, childProject, classPathStrings, outputDirectories, - sourceDirectories, testSourceDirectories ); + testSourceDirectoriesByProject.put(childProject, testSourceDirectories); + + prepareCheckstylePaths( + request, + childProject, + classPathStrings, + outputDirectories, + sourceDirectories, + testSourceDirectories); } - } - else - { + } else { sourceDirectories = request.getSourceDirectories(); - prepareCheckstylePaths( request, project, classPathStrings, outputDirectories, sourceDirectories, - testSourceDirectories ); + prepareCheckstylePaths( + request, project, classPathStrings, outputDirectories, sourceDirectories, testSourceDirectories); } - checker.setModuleClassLoader( Thread.currentThread().getContextClassLoader() ); + checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); - if ( filterSet != null ) - { - checker.addFilter( filterSet ); + if (filterSet != null) { + checker.addFilter(filterSet); } - Configuration configuration = getConfiguration( request ); - checker.configure( configuration ); + Configuration configuration = getConfiguration(request); + checker.configure(configuration); AuditListener listener = request.getListener(); - if ( listener != null ) - { - checker.addListener( listener ); + if (listener != null) { + checker.addListener(listener); } - if ( request.isConsoleOutput() ) - { - checker.addListener( request.getConsoleListener() ); + if (request.isConsoleOutput()) { + checker.addListener(request.getConsoleListener()); } - CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener( configuration ); - if ( request.isAggregate() ) - { - for ( MavenProject childProject : request.getReactorProjects() ) - { - sourceDirectories = sourceDirectoriesByProject.get( childProject ); - testSourceDirectories = testSourceDirectoriesByProject.get( childProject ); - addSourceDirectory( checkerListener, sourceDirectories, - testSourceDirectories, - childProject.getResources(), request ); + CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration); + if (request.isAggregate()) { + for (MavenProject childProject : request.getReactorProjects()) { + sourceDirectories = sourceDirectoriesByProject.get(childProject); + testSourceDirectories = testSourceDirectoriesByProject.get(childProject); + addSourceDirectory( + checkerListener, + sourceDirectories, + testSourceDirectories, + childProject.getResources(), + request); } - } - else - { - addSourceDirectory( checkerListener, sourceDirectories, testSourceDirectories, request.getResources(), - request ); + } else { + addSourceDirectory( + checkerListener, sourceDirectories, testSourceDirectories, request.getResources(), request); } - checker.addListener( checkerListener ); + checker.addListener(checkerListener); - int nbErrors = checker.process( files ); + int nbErrors = checker.process(files); checker.destroy(); - if ( request.getStringOutputStream() != null ) - { + if (request.getStringOutputStream() != null) { String message = request.getStringOutputStream().toString().trim(); - if ( message.length() > 0 ) - { - getLogger().info( message ); + if (message.length() > 0) { + getLogger().info(message); } } - if ( nbErrors > 0 ) - { - StringBuilder message = new StringBuilder( "There " ); - if ( nbErrors == 1 ) - { - message.append( "is" ); - } - else - { - message.append( "are" ); + if (nbErrors > 0) { + StringBuilder message = new StringBuilder("There "); + if (nbErrors == 1) { + message.append("is"); + } else { + message.append("are"); } - message.append( " " ); - message.append( nbErrors ); - message.append( " error" ); - if ( nbErrors != 1 ) - { - message.append( "s" ); + message.append(" "); + message.append(nbErrors); + message.append(" error"); + if (nbErrors != 1) { + message.append("s"); } - message.append( " reported by Checkstyle" ); + message.append(" reported by Checkstyle"); String version = getCheckstyleVersion(); - if ( version != null ) - { - message.append( " " ); - message.append( version ); + if (version != null) { + message.append(" "); + message.append(version); } - message.append( " with " ); - message.append( request.getConfigLocation() ); - message.append( " ruleset." ); + message.append(" with "); + message.append(request.getConfigLocation()); + message.append(" ruleset."); - if ( request.isFailsOnError() ) - { + if (request.isFailsOnError()) { // TODO: should be a failure, not an error. Report is not meant to // throw an exception here (so site would // work regardless of config), but should record this information - throw new CheckstyleExecutorException( message.toString() ); - } - else - { - getLogger().info( message.toString() ); + throw new CheckstyleExecutorException(message.toString()); + } else { + getLogger().info(message.toString()); } } return checkerListener.getResults(); } - protected void addSourceDirectory( CheckstyleCheckerListener sinkListener, Collection sourceDirectories, - Collection testSourceDirectories, List resources, - CheckstyleExecutorRequest request ) - { - if ( sourceDirectories != null ) - { - for ( File sourceDirectory : sourceDirectories ) - { - if ( sourceDirectory.exists() ) - { - sinkListener.addSourceDirectory( sourceDirectory ); + protected void addSourceDirectory( + CheckstyleCheckerListener sinkListener, + Collection sourceDirectories, + Collection testSourceDirectories, + List resources, + CheckstyleExecutorRequest request) { + if (sourceDirectories != null) { + for (File sourceDirectory : sourceDirectories) { + if (sourceDirectory.exists()) { + sinkListener.addSourceDirectory(sourceDirectory); } } } - if ( request.isIncludeTestSourceDirectory() && ( testSourceDirectories != null ) ) - { - for ( File testSourceDirectory : testSourceDirectories ) - { - if ( testSourceDirectory.isDirectory() ) - { - sinkListener.addSourceDirectory( testSourceDirectory ); + if (request.isIncludeTestSourceDirectory() && (testSourceDirectories != null)) { + for (File testSourceDirectory : testSourceDirectories) { + if (testSourceDirectory.isDirectory()) { + sinkListener.addSourceDirectory(testSourceDirectory); } } } - if ( resources != null ) - { - for ( Resource resource : resources ) - { - if ( resource.getDirectory() != null ) - { - File resourcesDirectory = new File( resource.getDirectory() ); - if ( resourcesDirectory.exists() && resourcesDirectory.isDirectory() ) - { - sinkListener.addSourceDirectory( resourcesDirectory ); - getLogger().debug( "Added '" + resourcesDirectory.getAbsolutePath() - + "' as a source directory." ); + if (resources != null) { + for (Resource resource : resources) { + if (resource.getDirectory() != null) { + File resourcesDirectory = new File(resource.getDirectory()); + if (resourcesDirectory.exists() && resourcesDirectory.isDirectory()) { + sinkListener.addSourceDirectory(resourcesDirectory); + getLogger() + .debug("Added '" + resourcesDirectory.getAbsolutePath() + "' as a source directory."); } } } } } - public Configuration getConfiguration( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException - { - try - { + public Configuration getConfiguration(CheckstyleExecutorRequest request) throws CheckstyleExecutorException { + try { // Checkstyle will always use the context classloader in order // to load resources (dtds), // so we have to fix it ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader(); - Thread.currentThread().setContextClassLoader( checkstyleClassLoader ); - String configFile = getConfigFile( request ); - Properties overridingProperties = getOverridingProperties( request ); + Thread.currentThread().setContextClassLoader(checkstyleClassLoader); + String configFile = getConfigFile(request); + Properties overridingProperties = getOverridingProperties(request); IgnoredModulesOptions omitIgnoredModules; - if ( request.isOmitIgnoredModules() ) - { + if (request.isOmitIgnoredModules()) { omitIgnoredModules = IgnoredModulesOptions.OMIT; - } - else - { + } else { omitIgnoredModules = IgnoredModulesOptions.EXECUTE; } - Configuration config = - ConfigurationLoader.loadConfiguration( configFile, new PropertiesExpander( overridingProperties ), - omitIgnoredModules ); - String effectiveEncoding = StringUtils.isNotEmpty( request.getEncoding() ) ? request.getEncoding() : System - .getProperty( "file.encoding", "UTF-8" ); - - if ( StringUtils.isEmpty( request.getEncoding() ) ) - { - getLogger().warn( "File encoding has not been set, using platform encoding " + effectiveEncoding - + ", i.e. build is platform dependent!" ); + Configuration config = ConfigurationLoader.loadConfiguration( + configFile, new PropertiesExpander(overridingProperties), omitIgnoredModules); + String effectiveEncoding = StringUtils.isNotEmpty(request.getEncoding()) + ? request.getEncoding() + : System.getProperty("file.encoding", "UTF-8"); + + if (StringUtils.isEmpty(request.getEncoding())) { + getLogger() + .warn("File encoding has not been set, using platform encoding " + effectiveEncoding + + ", i.e. build is platform dependent!"); } - if ( "Checker".equals( config.getName() ) - || "com.puppycrawl.tools.checkstyle.Checker".equals( config.getName() ) ) - { - if ( config instanceof DefaultConfiguration ) - { + if ("Checker".equals(config.getName()) + || "com.puppycrawl.tools.checkstyle.Checker".equals(config.getName())) { + if (config instanceof DefaultConfiguration) { // MCHECKSTYLE-173 Only add the "charset" attribute if it has not been set - addAttributeIfNotExists( (DefaultConfiguration) config, "charset", effectiveEncoding ); - addAttributeIfNotExists( (DefaultConfiguration) config, "cacheFile", request.getCacheFile() ); - } - else - { - getLogger().warn( "Failed to configure file encoding on module " + config ); + addAttributeIfNotExists((DefaultConfiguration) config, "charset", effectiveEncoding); + addAttributeIfNotExists((DefaultConfiguration) config, "cacheFile", request.getCacheFile()); + } else { + getLogger().warn("Failed to configure file encoding on module " + config); } } return config; - } - catch ( CheckstyleException e ) - { - throw new CheckstyleExecutorException( "Failed during checkstyle configuration", e ); + } catch (CheckstyleException e) { + throw new CheckstyleExecutorException("Failed during checkstyle configuration", e); } } - private void addAttributeIfNotExists( DefaultConfiguration config, String name, String value ) - { - try - { + private void addAttributeIfNotExists(DefaultConfiguration config, String name, String value) { + try { // MCHECKSTYLE-132 DefaultConfiguration addAttribute has changed in checkstyle 5.3 - if ( config.getAttribute( name ) == null ) - { - config.addAttribute( name, value ); + if (config.getAttribute(name) == null) { + config.addAttribute(name, value); } - } - catch ( CheckstyleException ex ) - { + } catch (CheckstyleException ex) { // MCHECKSTYLE-159 Checkstyle 5.4+ throws an exception when trying to access an attribute that doesn't exist - config.addAttribute( name, value ); + config.addAttribute(name, value); } } - private void prepareCheckstylePaths( CheckstyleExecutorRequest request, MavenProject project, - List classPathStrings, List outputDirectories, - Collection sourceDirectories, Collection testSourceDirectories ) - throws CheckstyleExecutorException - { - try - { - outputDirectories.add( project.getBuild().getOutputDirectory() ); - - if ( request.isIncludeTestSourceDirectory() && ( testSourceDirectories != null ) - && anyDirectoryExists( testSourceDirectories ) ) - { - classPathStrings.addAll( project.getTestClasspathElements() ); - outputDirectories.add( project.getBuild().getTestOutputDirectory() ); - } - else - { - classPathStrings.addAll( project.getCompileClasspathElements() ); - } - } - catch ( DependencyResolutionRequiredException e ) - { - throw new CheckstyleExecutorException( e.getMessage(), e ); + private void prepareCheckstylePaths( + CheckstyleExecutorRequest request, + MavenProject project, + List classPathStrings, + List outputDirectories, + Collection sourceDirectories, + Collection testSourceDirectories) + throws CheckstyleExecutorException { + try { + outputDirectories.add(project.getBuild().getOutputDirectory()); + + if (request.isIncludeTestSourceDirectory() + && (testSourceDirectories != null) + && anyDirectoryExists(testSourceDirectories)) { + classPathStrings.addAll(project.getTestClasspathElements()); + outputDirectories.add(project.getBuild().getTestOutputDirectory()); + } else { + classPathStrings.addAll(project.getCompileClasspathElements()); + } + } catch (DependencyResolutionRequiredException e) { + throw new CheckstyleExecutorException(e.getMessage(), e); } } - - private boolean anyDirectoryExists( Collection files ) - { - for ( File file : files ) - { - if ( file.isDirectory() ) - { + + private boolean anyDirectoryExists(Collection files) { + for (File file : files) { + if (file.isDirectory()) { return true; } } @@ -411,344 +357,278 @@ private boolean anyDirectoryExists( Collection files ) * *@todo Copied from CheckstyleReportGenerator - move to a utility class */ - private String getCheckstyleVersion() - { + private String getCheckstyleVersion() { Package checkstyleApiPackage = Configuration.class.getPackage(); - return ( checkstyleApiPackage == null ) ? null : checkstyleApiPackage.getImplementationVersion(); + return (checkstyleApiPackage == null) ? null : checkstyleApiPackage.getImplementationVersion(); } - private Properties getOverridingProperties( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException - { + private Properties getOverridingProperties(CheckstyleExecutorRequest request) throws CheckstyleExecutorException { Properties p = new Properties(); - try - { - if ( request.getPropertiesLocation() != null ) - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "request.getPropertiesLocation() " + request.getPropertiesLocation() ); + try { + if (request.getPropertiesLocation() != null) { + if (getLogger().isDebugEnabled()) { + getLogger().debug("request.getPropertiesLocation() " + request.getPropertiesLocation()); } - File propertiesFile = locator.getResourceAsFile( request.getPropertiesLocation(), - "checkstyle-checker.properties" ); + File propertiesFile = + locator.getResourceAsFile(request.getPropertiesLocation(), "checkstyle-checker.properties"); - if ( propertiesFile != null ) - { - try ( InputStream in = new FileInputStream( propertiesFile ) ) - { - p.load( in ); + if (propertiesFile != null) { + try (InputStream in = new FileInputStream(propertiesFile)) { + p.load(in); } } } - if ( StringUtils.isNotEmpty( request.getPropertyExpansion() ) ) - { + if (StringUtils.isNotEmpty(request.getPropertyExpansion())) { String propertyExpansion = request.getPropertyExpansion(); // Convert \ to \\, so that p.load will convert it back properly - propertyExpansion = StringUtils.replace( propertyExpansion, "\\", "\\\\" ); - p.load( new ByteArrayInputStream( propertyExpansion.getBytes() ) ); + propertyExpansion = StringUtils.replace(propertyExpansion, "\\", "\\\\"); + p.load(new ByteArrayInputStream(propertyExpansion.getBytes())); } // Workaround for MCHECKSTYLE-48 // Make sure that "config/maven-header.txt" is the default value // for headerLocation, if configLocation="config/maven_checks.xml" String headerLocation = request.getHeaderLocation(); - if ( "config/maven_checks.xml".equals( request.getConfigLocation() ) ) - { + if ("config/maven_checks.xml".equals(request.getConfigLocation())) { - if ( "LICENSE.txt".equals( request.getHeaderLocation() ) ) - { + if ("LICENSE.txt".equals(request.getHeaderLocation())) { headerLocation = "config/maven-header.txt"; } } - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "headerLocation " + headerLocation ); + if (getLogger().isDebugEnabled()) { + getLogger().debug("headerLocation " + headerLocation); } - if ( StringUtils.isNotEmpty( headerLocation ) ) - { - try - { - File headerFile = licenseLocator.getResourceAsFile( headerLocation, "checkstyle-header.txt" ); + if (StringUtils.isNotEmpty(headerLocation)) { + try { + File headerFile = licenseLocator.getResourceAsFile(headerLocation, "checkstyle-header.txt"); - if ( headerFile != null ) - { - p.setProperty( "checkstyle.header.file", headerFile.getAbsolutePath() ); + if (headerFile != null) { + p.setProperty("checkstyle.header.file", headerFile.getAbsolutePath()); } - } - catch ( FileResourceCreationException | ResourceNotFoundException e ) - { - getLogger().debug( "Unable to process header location: " + headerLocation ); - getLogger().debug( "Checkstyle will throw exception if ${checkstyle.header.file} is used" ); + } catch (FileResourceCreationException | ResourceNotFoundException e) { + getLogger().debug("Unable to process header location: " + headerLocation); + getLogger().debug("Checkstyle will throw exception if ${checkstyle.header.file} is used"); } } - if ( request.getCacheFile() != null ) - { - p.setProperty( "checkstyle.cache.file", request.getCacheFile() ); + if (request.getCacheFile() != null) { + p.setProperty("checkstyle.cache.file", request.getCacheFile()); } + } catch (IOException | ResourceNotFoundException | FileResourceCreationException e) { + throw new CheckstyleExecutorException("Failed to get overriding properties", e); } - catch ( IOException | ResourceNotFoundException | FileResourceCreationException e ) - { - throw new CheckstyleExecutorException( "Failed to get overriding properties", e ); - } - if ( request.getSuppressionsFileExpression() != null ) - { - String suppressionsFilePath = getSuppressionsFilePath( request ); + if (request.getSuppressionsFileExpression() != null) { + String suppressionsFilePath = getSuppressionsFilePath(request); - if ( suppressionsFilePath != null ) - { - p.setProperty( request.getSuppressionsFileExpression(), suppressionsFilePath ); + if (suppressionsFilePath != null) { + p.setProperty(request.getSuppressionsFileExpression(), suppressionsFilePath); } } return p; } - private List getFilesToProcess( CheckstyleExecutorRequest request ) - throws IOException - { + private List getFilesToProcess(CheckstyleExecutorRequest request) throws IOException { StringBuilder excludesStr = new StringBuilder(); - if ( StringUtils.isNotEmpty( request.getExcludes() ) ) - { - excludesStr.append( request.getExcludes() ); + if (StringUtils.isNotEmpty(request.getExcludes())) { + excludesStr.append(request.getExcludes()); } String[] defaultExcludes = FileUtils.getDefaultExcludes(); - for ( String defaultExclude : defaultExcludes ) - { - if ( excludesStr.length() > 0 ) - { - excludesStr.append( "," ); + for (String defaultExclude : defaultExcludes) { + if (excludesStr.length() > 0) { + excludesStr.append(","); } - excludesStr.append( defaultExclude ); + excludesStr.append(defaultExclude); } Set files = new LinkedHashSet<>(); - if ( request.isAggregate() ) - { - for ( MavenProject project : request.getReactorProjects() ) - { + if (request.isAggregate()) { + for (MavenProject project : request.getReactorProjects()) { Set sourceDirectories = new LinkedHashSet<>(); - + // CompileSourceRoots are absolute paths - List compileSourceRoots = project.getCompileSourceRoots(); - for ( String compileSourceRoot : compileSourceRoots ) - { - sourceDirectories.add( new File( compileSourceRoot ) ); + List compileSourceRoots = project.getCompileSourceRoots(); + for (String compileSourceRoot : compileSourceRoots) { + sourceDirectories.add(new File(compileSourceRoot)); } Set testSourceDirectories = new LinkedHashSet<>(); // CompileSourceRoots are absolute paths - List testCompileSourceRoots = project.getTestCompileSourceRoots(); - for ( String testCompileSourceRoot : testCompileSourceRoots ) - { - testSourceDirectories.add( new File( testCompileSourceRoot ) ); + List testCompileSourceRoots = project.getTestCompileSourceRoots(); + for (String testCompileSourceRoot : testCompileSourceRoots) { + testSourceDirectories.add(new File(testCompileSourceRoot)); } - addFilesToProcess( request, sourceDirectories, project.getResources(), project.getTestResources(), - files, testSourceDirectories ); + addFilesToProcess( + request, + sourceDirectories, + project.getResources(), + project.getTestResources(), + files, + testSourceDirectories); } - } - else - { + } else { Collection sourceDirectories = request.getSourceDirectories(); - addFilesToProcess( request, sourceDirectories, request.getResources(), - request.getTestResources(), files, request.getTestSourceDirectories() ); + addFilesToProcess( + request, + sourceDirectories, + request.getResources(), + request.getTestResources(), + files, + request.getTestSourceDirectories()); } - getLogger().debug( "Added " + files.size() + " files to process." ); + getLogger().debug("Added " + files.size() + " files to process."); - return new ArrayList<>( files ); + return new ArrayList<>(files); } - private void addFilesToProcess( CheckstyleExecutorRequest request, Collection sourceDirectories, - List resources, List testResources, Collection files, - Collection testSourceDirectories ) - throws IOException - { - if ( sourceDirectories != null ) - { - for ( File sourceDirectory : sourceDirectories ) - { - if ( sourceDirectory.isDirectory() ) - { + private void addFilesToProcess( + CheckstyleExecutorRequest request, + Collection sourceDirectories, + List resources, + List testResources, + Collection files, + Collection testSourceDirectories) + throws IOException { + if (sourceDirectories != null) { + for (File sourceDirectory : sourceDirectories) { + if (sourceDirectory.isDirectory()) { final List sourceFiles = - FileUtils.getFiles( sourceDirectory, request.getIncludes(), request.getExcludes() ); - files.addAll( sourceFiles ); - getLogger().debug( "Added " + sourceFiles.size() + " source files found in '" - + sourceDirectory.getAbsolutePath() + "'." ); + FileUtils.getFiles(sourceDirectory, request.getIncludes(), request.getExcludes()); + files.addAll(sourceFiles); + getLogger() + .debug("Added " + sourceFiles.size() + " source files found in '" + + sourceDirectory.getAbsolutePath() + "'."); } } } - if ( request.isIncludeTestSourceDirectory() && testSourceDirectories != null ) - { - for ( File testSourceDirectory : testSourceDirectories ) - { - if ( testSourceDirectory.isDirectory() ) - { + if (request.isIncludeTestSourceDirectory() && testSourceDirectories != null) { + for (File testSourceDirectory : testSourceDirectories) { + if (testSourceDirectory.isDirectory()) { final List testSourceFiles = - FileUtils.getFiles( testSourceDirectory, request.getIncludes(), request.getExcludes() ); - - files.addAll( testSourceFiles ); - getLogger().debug( "Added " + testSourceFiles.size() + " test source files found in '" - + testSourceDirectory.getAbsolutePath() + "'." ); + FileUtils.getFiles(testSourceDirectory, request.getIncludes(), request.getExcludes()); + + files.addAll(testSourceFiles); + getLogger() + .debug("Added " + testSourceFiles.size() + " test source files found in '" + + testSourceDirectory.getAbsolutePath() + "'."); } } } - if ( resources != null && request.isIncludeResources() ) - { - addResourceFilesToProcess( request, resources, files ); - } - else - { - getLogger().debug( "No resources found in this project." ); + if (resources != null && request.isIncludeResources()) { + addResourceFilesToProcess(request, resources, files); + } else { + getLogger().debug("No resources found in this project."); } - if ( testResources != null && request.isIncludeTestResources() ) - { - addResourceFilesToProcess( request, testResources, files ); - } - else - { - getLogger().debug( "No test resources found in this project." ); + if (testResources != null && request.isIncludeTestResources()) { + addResourceFilesToProcess(request, testResources, files); + } else { + getLogger().debug("No test resources found in this project."); } } - private void addResourceFilesToProcess( CheckstyleExecutorRequest request, List resources, - Collection files ) - throws IOException - { - for ( Resource resource : resources ) - { - if ( resource.getDirectory() != null ) - { - File resourcesDirectory = new File( resource.getDirectory() ); - if ( resourcesDirectory.isDirectory() ) - { + private void addResourceFilesToProcess( + CheckstyleExecutorRequest request, List resources, Collection files) throws IOException { + for (Resource resource : resources) { + if (resource.getDirectory() != null) { + File resourcesDirectory = new File(resource.getDirectory()); + if (resourcesDirectory.isDirectory()) { String includes = request.getResourceIncludes(); String excludes = request.getResourceExcludes(); // MCHECKSTYLE-214: Only with project-root respect in/excludes, otherwise you'll get every file - if ( resourcesDirectory.equals( request.getProject().getBasedir() ) ) - { - String resourceIncludes = StringUtils.join( resource.getIncludes().iterator(), "," ); - if ( StringUtils.isEmpty( includes ) ) - { + if (resourcesDirectory.equals(request.getProject().getBasedir())) { + String resourceIncludes = + StringUtils.join(resource.getIncludes().iterator(), ","); + if (StringUtils.isEmpty(includes)) { includes = resourceIncludes; - } - else - { + } else { includes += "," + resourceIncludes; } - - String resourceExcludes = StringUtils.join( resource.getExcludes().iterator(), "," ); - if ( StringUtils.isEmpty( excludes ) ) - { + + String resourceExcludes = + StringUtils.join(resource.getExcludes().iterator(), ","); + if (StringUtils.isEmpty(excludes)) { excludes = resourceExcludes; - } - else - { + } else { excludes += "," + resourceExcludes; } } - - List resourceFiles = - FileUtils.getFiles( resourcesDirectory, includes, excludes ); - files.addAll( resourceFiles ); - getLogger().debug( "Added " + resourceFiles.size() + " resource files found in '" - + resourcesDirectory.getAbsolutePath() + "'." ); - } - else - { - getLogger().debug( "The resources directory '" + resourcesDirectory.getAbsolutePath() - + "' does not exist or is not a directory." ); + + List resourceFiles = FileUtils.getFiles(resourcesDirectory, includes, excludes); + files.addAll(resourceFiles); + getLogger() + .debug("Added " + resourceFiles.size() + " resource files found in '" + + resourcesDirectory.getAbsolutePath() + "'."); + } else { + getLogger() + .debug("The resources directory '" + resourcesDirectory.getAbsolutePath() + + "' does not exist or is not a directory."); } } } } - private FilterSet getSuppressionsFilterSet( final String suppressionsFilePath ) - throws CheckstyleExecutorException - { - if ( suppressionsFilePath == null ) - { + private FilterSet getSuppressionsFilterSet(final String suppressionsFilePath) throws CheckstyleExecutorException { + if (suppressionsFilePath == null) { return null; } - try - { - return SuppressionsLoader.loadSuppressions( suppressionsFilePath ); - } - catch ( CheckstyleException ce ) - { - throw new CheckstyleExecutorException( "Failed to load suppressions file from: " - + suppressionsFilePath, ce ); + try { + return SuppressionsLoader.loadSuppressions(suppressionsFilePath); + } catch (CheckstyleException ce) { + throw new CheckstyleExecutorException("Failed to load suppressions file from: " + suppressionsFilePath, ce); } } - private String getSuppressionsFilePath( final CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException - { + private String getSuppressionsFilePath(final CheckstyleExecutorRequest request) throws CheckstyleExecutorException { final String suppressionsLocation = request.getSuppressionsLocation(); - if ( StringUtils.isEmpty( suppressionsLocation ) ) - { + if (StringUtils.isEmpty(suppressionsLocation)) { return null; } - - try - { - File suppressionsFile = locator.getResourceAsFile( suppressionsLocation, "checkstyle-suppressions.xml" ); + + try { + File suppressionsFile = locator.getResourceAsFile(suppressionsLocation, "checkstyle-suppressions.xml"); return suppressionsFile == null ? null : suppressionsFile.getAbsolutePath(); - } - catch ( ResourceNotFoundException e ) - { - throw new CheckstyleExecutorException( "Unable to find suppressions file at location: " - + suppressionsLocation, e ); - } - catch ( FileResourceCreationException e ) - { - throw new CheckstyleExecutorException( "Unable to process suppressions file location: " - + suppressionsLocation, e ); + } catch (ResourceNotFoundException e) { + throw new CheckstyleExecutorException( + "Unable to find suppressions file at location: " + suppressionsLocation, e); + } catch (FileResourceCreationException e) { + throw new CheckstyleExecutorException( + "Unable to process suppressions file location: " + suppressionsLocation, e); } } - private String getConfigFile( CheckstyleExecutorRequest request ) - throws CheckstyleExecutorException - { - try - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( "request.getConfigLocation() " + request.getConfigLocation() ); + private String getConfigFile(CheckstyleExecutorRequest request) throws CheckstyleExecutorException { + try { + if (getLogger().isDebugEnabled()) { + getLogger().debug("request.getConfigLocation() " + request.getConfigLocation()); } - File configFile = locator.getResourceAsFile( request.getConfigLocation(), "checkstyle-checker.xml" ); - if ( configFile == null ) - { - throw new CheckstyleExecutorException( "Unable to process config location: " - + request.getConfigLocation() ); + File configFile = locator.getResourceAsFile(request.getConfigLocation(), "checkstyle-checker.xml"); + if (configFile == null) { + throw new CheckstyleExecutorException( + "Unable to process config location: " + request.getConfigLocation()); } return configFile.getAbsolutePath(); + } catch (ResourceNotFoundException e) { + throw new CheckstyleExecutorException( + "Unable to find configuration file at location: " + request.getConfigLocation(), e); + } catch (FileResourceCreationException e) { + throw new CheckstyleExecutorException( + "Unable to process configuration file at location: " + request.getConfigLocation(), e); } - catch ( ResourceNotFoundException e ) - { - throw new CheckstyleExecutorException( "Unable to find configuration file at location: " - + request.getConfigLocation(), e ); - } - catch ( FileResourceCreationException e ) - { - throw new CheckstyleExecutorException( "Unable to process configuration file at location: " - + request.getConfigLocation(), e ); - } - } /** @@ -757,37 +637,32 @@ private String getConfigFile( CheckstyleExecutorRequest request ) * * @param request executor request data. */ - private void configureResourceLocator( final ResourceManager resourceManager, - final CheckstyleExecutorRequest request, - final List additionalArtifacts ) - { + private void configureResourceLocator( + final ResourceManager resourceManager, + final CheckstyleExecutorRequest request, + final List additionalArtifacts) { final MavenProject project = request.getProject(); - resourceManager.setOutputDirectory( new File( project.getBuild().getDirectory() ) ); + resourceManager.setOutputDirectory(new File(project.getBuild().getDirectory())); // Recurse up the parent hierarchy and add project directories to the search roots MavenProject parent = project; - while ( parent != null && parent.getFile() != null ) - { + while (parent != null && parent.getFile() != null) { // MCHECKSTYLE-131 ( olamy ) I don't like this hack. // (dkulp) Me either. It really pollutes the location stuff // by allowing searches of stuff outside the current module. File dir = parent.getFile().getParentFile(); - resourceManager.addSearchPath( FileResourceLoader.ID, dir.getAbsolutePath() ); + resourceManager.addSearchPath(FileResourceLoader.ID, dir.getAbsolutePath()); parent = parent.getParent(); } - resourceManager.addSearchPath( "url", "" ); - + resourceManager.addSearchPath("url", ""); + // MCHECKSTYLE-225: load licenses from additional artifacts, not from classpath - if ( additionalArtifacts != null ) - { - for ( Artifact licenseArtifact : additionalArtifacts ) - { - try - { - resourceManager.addSearchPath( "jar", "jar:" + licenseArtifact.getFile().toURI().toURL() ); - } - catch ( MalformedURLException e ) - { + if (additionalArtifacts != null) { + for (Artifact licenseArtifact : additionalArtifacts) { + try { + resourceManager.addSearchPath( + "jar", "jar:" + licenseArtifact.getFile().toURI().toURL()); + } catch (MalformedURLException e) { // noop } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/resource/LicenseResourceManager.java b/src/main/java/org/apache/maven/plugins/checkstyle/resource/LicenseResourceManager.java index aa8cefc5..8808867c 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/resource/LicenseResourceManager.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/resource/LicenseResourceManager.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.resource; - /* * 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.checkstyle.resource; import java.util.Map; @@ -35,56 +34,46 @@ * * @since 2.12 */ -@Component( role = ResourceManager.class, hint = "license", instantiationStrategy = "per-lookup" ) -public class LicenseResourceManager - extends DefaultResourceManager -{ +@Component(role = ResourceManager.class, hint = "license", instantiationStrategy = "per-lookup") +public class LicenseResourceManager extends DefaultResourceManager { - @Requirement( role = ResourceLoader.class ) + @Requirement(role = ResourceLoader.class) private Map resourceLoaders; @Override - public void addSearchPath( String id, String path ) - { - ResourceLoader loader = resourceLoaders.get( id ); + public void addSearchPath(String id, String path) { + ResourceLoader loader = resourceLoaders.get(id); - if ( loader == null ) - { - throw new IllegalArgumentException( "unknown resource loader: " + id ); + if (loader == null) { + throw new IllegalArgumentException("unknown resource loader: " + id); } - loader.addSearchPath( path ); + loader.addSearchPath(path); } @Override - public PlexusResource getResource( String name ) - throws ResourceNotFoundException - { - for ( ResourceLoader resourceLoader : resourceLoaders.values() ) - { - if ( resourceLoader instanceof ThreadContextClasspathResourceLoader - && !"config/maven-header.txt".equals( name ) ) - { + public PlexusResource getResource(String name) throws ResourceNotFoundException { + for (ResourceLoader resourceLoader : resourceLoaders.values()) { + if (resourceLoader instanceof ThreadContextClasspathResourceLoader + && !"config/maven-header.txt".equals(name)) { // MCHECKSTYLE-219: Don't load the license from the plugin // classloader, only allow config/maven-header.txt continue; } - try - { - PlexusResource resource = resourceLoader.getResource( name ); + try { + PlexusResource resource = resourceLoader.getResource(name); - getLogger().debug( "The resource '" + name + "' was found as " + resource.getName() + "." ); + getLogger().debug("The resource '" + name + "' was found as " + resource.getName() + "."); return resource; - } - catch ( ResourceNotFoundException e ) - { - getLogger().debug( "The resource '" + name + "' was not found with resourceLoader " - + resourceLoader.getClass().getName() + "." ); + } catch (ResourceNotFoundException e) { + getLogger() + .debug("The resource '" + name + "' was not found with resourceLoader " + + resourceLoader.getClass().getName() + "."); } } - throw new ResourceNotFoundException( name ); + throw new ResourceNotFoundException(name); } } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGenerator.java b/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGenerator.java index c90adc45..125a67a5 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGenerator.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGenerator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.rss; - /* * 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.checkstyle.rss; import org.apache.maven.plugins.checkstyle.exec.CheckstyleResults; import org.apache.maven.reporting.MavenReportException; @@ -27,8 +26,7 @@ * @since 2.4 */ @Deprecated -public interface CheckstyleRssGenerator -{ - void generateRSS( CheckstyleResults results, CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest ) - throws MavenReportException; +public interface CheckstyleRssGenerator { + void generateRSS(CheckstyleResults results, CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest) + throws MavenReportException; } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGeneratorRequest.java b/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGeneratorRequest.java index 8813217a..c95c3c29 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGeneratorRequest.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/rss/CheckstyleRssGeneratorRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.rss; - /* * 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.checkstyle.rss; import java.io.File; @@ -29,8 +28,7 @@ * @since 2.4 */ @Deprecated -public class CheckstyleRssGeneratorRequest -{ +public class CheckstyleRssGeneratorRequest { private MavenProject mavenProject; private String copyright; @@ -39,52 +37,42 @@ public class CheckstyleRssGeneratorRequest private Log log; - public CheckstyleRssGeneratorRequest( MavenProject mavenProject, String copyright, File outputDirectory, Log log ) - { + public CheckstyleRssGeneratorRequest(MavenProject mavenProject, String copyright, File outputDirectory, Log log) { this.mavenProject = mavenProject; this.copyright = copyright; this.outputDirectory = outputDirectory; this.log = log; } - public MavenProject getMavenProject() - { + public MavenProject getMavenProject() { return mavenProject; } - public void setMavenProject( MavenProject mavenProject ) - { + public void setMavenProject(MavenProject mavenProject) { this.mavenProject = mavenProject; } - public String getCopyright() - { + public String getCopyright() { return copyright; } - public void setCopyright( String copyright ) - { + public void setCopyright(String copyright) { this.copyright = copyright; } - public File getOutputDirectory() - { + public File getOutputDirectory() { return outputDirectory; } - public void setOutputDirectory( File outputDirectory ) - { + public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } - public Log getLog() - { + public Log getLog() { return log; } - public void setLog( Log log ) - { + public void setLog(Log log) { this.log = log; } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/rss/DefaultCheckstyleRssGenerator.java b/src/main/java/org/apache/maven/plugins/checkstyle/rss/DefaultCheckstyleRssGenerator.java index c8d03dd1..a5622839 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/rss/DefaultCheckstyleRssGenerator.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/rss/DefaultCheckstyleRssGenerator.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.rss; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,11 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.rss; import java.io.IOException; +import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.checkstyle.CheckstyleReport; import org.apache.maven.plugins.checkstyle.exec.CheckstyleResults; @@ -34,50 +34,41 @@ import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.velocity.VelocityComponent; -import com.puppycrawl.tools.checkstyle.api.SeverityLevel; - /** * @author Olivier Lamy * @since 2.4 */ -@Component( role = CheckstyleRssGenerator.class, hint = "default" ) +@Component(role = CheckstyleRssGenerator.class, hint = "default") @Deprecated -public class DefaultCheckstyleRssGenerator - implements CheckstyleRssGenerator -{ +public class DefaultCheckstyleRssGenerator implements CheckstyleRssGenerator { @Requirement private VelocityComponent velocityComponent; @Override - public void generateRSS( CheckstyleResults results, CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest ) - throws MavenReportException - { + public void generateRSS(CheckstyleResults results, CheckstyleRssGeneratorRequest checkstyleRssGeneratorRequest) + throws MavenReportException { - VelocityTemplate vtemplate = new VelocityTemplate( velocityComponent, CheckstyleReport.PLUGIN_RESOURCES ); - vtemplate.setLog( checkstyleRssGeneratorRequest.getLog() ); + VelocityTemplate vtemplate = new VelocityTemplate(velocityComponent, CheckstyleReport.PLUGIN_RESOURCES); + vtemplate.setLog(checkstyleRssGeneratorRequest.getLog()); Context context = new VelocityContext(); - context.put( "results", results ); - context.put( "project", checkstyleRssGeneratorRequest.getMavenProject() ); - context.put( "copyright", checkstyleRssGeneratorRequest.getCopyright() ); - context.put( "levelInfo", SeverityLevel.INFO ); - context.put( "levelWarning", SeverityLevel.WARNING ); - context.put( "levelError", SeverityLevel.ERROR ); - context.put( "stringutils", new StringUtils() ); + context.put("results", results); + context.put("project", checkstyleRssGeneratorRequest.getMavenProject()); + context.put("copyright", checkstyleRssGeneratorRequest.getCopyright()); + context.put("levelInfo", SeverityLevel.INFO); + context.put("levelWarning", SeverityLevel.WARNING); + context.put("levelError", SeverityLevel.ERROR); + context.put("stringutils", new StringUtils()); - try - { - vtemplate.generate( checkstyleRssGeneratorRequest.getOutputDirectory().getPath() + "/checkstyle.rss", - "checkstyle-rss.vm", context ); - } - catch ( ResourceNotFoundException e ) - { - throw new MavenReportException( "Unable to find checkstyle-rss.vm resource.", e ); - } - catch ( MojoExecutionException | IOException | VelocityException e ) - { - throw new MavenReportException( "Unable to generate checkstyle.rss.", e ); + try { + vtemplate.generate( + checkstyleRssGeneratorRequest.getOutputDirectory().getPath() + "/checkstyle.rss", + "checkstyle-rss.vm", + context); + } catch (ResourceNotFoundException e) { + throw new MavenReportException("Unable to find checkstyle-rss.vm resource.", e); + } catch (MojoExecutionException | IOException | VelocityException e) { + throw new MavenReportException("Unable to generate checkstyle.rss.", e); } } - } diff --git a/src/main/java/org/apache/maven/plugins/checkstyle/rss/VelocityTemplate.java b/src/main/java/org/apache/maven/plugins/checkstyle/rss/VelocityTemplate.java index 0919bd23..758728ba 100644 --- a/src/main/java/org/apache/maven/plugins/checkstyle/rss/VelocityTemplate.java +++ b/src/main/java/org/apache/maven/plugins/checkstyle/rss/VelocityTemplate.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.rss; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.rss; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; @@ -27,13 +33,6 @@ import org.apache.velocity.exception.VelocityException; import org.codehaus.plexus.velocity.VelocityComponent; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.nio.charset.StandardCharsets; - /** *

    * A component to work with Velocity templates from within plugins. @@ -52,27 +51,23 @@ * */ @Deprecated -public class VelocityTemplate -{ +public class VelocityTemplate { private String templateDirectory; private Log log; private VelocityComponent velocity; - public VelocityTemplate( VelocityComponent velocityComponent, String templateBaseDirectory ) - { + public VelocityTemplate(VelocityComponent velocityComponent, String templateBaseDirectory) { this.velocity = velocityComponent; this.templateDirectory = templateBaseDirectory; } - public String getTemplateDirectory() - { + public String getTemplateDirectory() { return templateDirectory; } - public VelocityComponent getVelocity() - { + public VelocityComponent getVelocity() { return velocity; } @@ -86,52 +81,39 @@ public VelocityComponent getVelocity() * @throws MojoExecutionException if merging the velocity template failed * @throws IOException if there was an error writing to the output file */ - public void generate( String outputFilename, String template, Context context ) - throws VelocityException, MojoExecutionException, IOException - { + public void generate(String outputFilename, String template, Context context) + throws VelocityException, MojoExecutionException, IOException { - File outputFile = new File( outputFilename ); - if ( !outputFile.getParentFile().exists() ) - { + File outputFile = new File(outputFilename); + if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } - try ( Writer writer = new OutputStreamWriter( new FileOutputStream( outputFile ), StandardCharsets.UTF_8 ) ) - { - getVelocity().getEngine().mergeTemplate( templateDirectory + "/" + template, context, writer ); - } - catch ( ResourceNotFoundException e ) - { - throw new ResourceNotFoundException( "Template not found: " + templateDirectory + "/" + template, e ); - } - catch ( RuntimeException e ) - { - throw new MojoExecutionException( e.getMessage(), e ); + try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) { + getVelocity().getEngine().mergeTemplate(templateDirectory + "/" + template, context, writer); + } catch (ResourceNotFoundException e) { + throw new ResourceNotFoundException("Template not found: " + templateDirectory + "/" + template, e); + } catch (RuntimeException e) { + throw new MojoExecutionException(e.getMessage(), e); } } - public void setTemplateDirectory( String templateDirectory ) - { + public void setTemplateDirectory(String templateDirectory) { this.templateDirectory = templateDirectory; } - public void setVelocity( VelocityComponent velocity ) - { + public void setVelocity(VelocityComponent velocity) { this.velocity = velocity; } - public Log getLog() - { - if ( this.log == null ) - { + public Log getLog() { + if (this.log == null) { this.log = new SystemStreamLog(); } return log; } - public void setLog( Log log ) - { + public void setLog(Log log) { this.log = log; } - } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleTestCase.java b/src/test/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleTestCase.java index 0d925d35..c7e2fbe4 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleTestCase.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/AbstractCheckstyleTestCase.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.File; import java.io.IOException; @@ -32,16 +31,14 @@ import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingRequest; -import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.DefaultRepositorySystemSession; +import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; /** * Abstract class to test reports generation. */ -public abstract class AbstractCheckstyleTestCase - extends AbstractMojoTestCase -{ +public abstract class AbstractCheckstyleTestCase extends AbstractMojoTestCase { private Locale oldLocale; private ArtifactStubFactory artifactStubFactory; @@ -52,26 +49,22 @@ public abstract class AbstractCheckstyleTestCase private MavenProject testMavenProject; @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { // required for mojo lookups to work super.setUp(); oldLocale = Locale.getDefault(); - Locale.setDefault( Locale.ENGLISH ); + Locale.setDefault(Locale.ENGLISH); - artifactStubFactory = new DependencyArtifactStubFactory( getTestFile( "target" ), true, false ); + artifactStubFactory = new DependencyArtifactStubFactory(getTestFile("target"), true, false); artifactStubFactory.getWorkingDir().mkdirs(); } @Override - protected void tearDown() - throws Exception - { + protected void tearDown() throws Exception { super.tearDown(); - Locale.setDefault( oldLocale ); + Locale.setDefault(oldLocale); oldLocale = null; } @@ -80,8 +73,7 @@ protected void tearDown() * * @return the maven project */ - protected MavenProject getTestMavenProject() - { + protected MavenProject getTestMavenProject() { return testMavenProject; } @@ -92,15 +84,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/test-harness/" + 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/test-harness/" + + getTestMavenProject().getArtifactId(); + + File report = new File(outputDirectory, name); + if (!report.exists()) { + throw new IOException("File not found. Attempted: " + report); } return report; @@ -114,55 +104,48 @@ 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/plugin-configs/" + pluginXml ); - CheckstyleReport 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/plugin-configs/" + pluginXml); + CheckstyleReport mojo = createReportMojo(goal, pluginXmlFile); + return generateReport(mojo, pluginXmlFile); } - protected CheckstyleReport createReportMojo( String goal, File pluginXmlFile ) - throws Exception - { - CheckstyleReport mojo = (CheckstyleReport) lookupMojo( goal, pluginXmlFile ); - assertNotNull( "Mojo not found.", mojo ); + protected CheckstyleReport createReportMojo(String goal, File pluginXmlFile) throws Exception { + CheckstyleReport mojo = (CheckstyleReport) 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( CheckstyleReport mojo, File pluginXmlFile ) - throws Exception - { + protected File generateReport(CheckstyleReport 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 checkstyleTestDir, String fileName ) throws IOException - { - return new String( Files.readAllBytes( checkstyleTestDir.toPath().resolve( fileName ) ) ); + protected String readFile(File checkstyleTestDir, String fileName) throws IOException { + return new String(Files.readAllBytes(checkstyleTestDir.toPath().resolve(fileName))); } - } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleReportTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleReportTest.java index b6575c8b..bf87155c 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleReportTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleReportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - +package org.apache.maven.plugins.checkstyle; import java.io.BufferedReader; import java.io.File; @@ -35,88 +33,62 @@ * @author Edwin Punzalan * */ -public class CheckstyleReportTest - extends AbstractCheckstyleTestCase -{ - public void testNoSource() - throws Exception - { - File generatedReport = generateReport( "checkstyle", "no-source-plugin-config.xml" ); - assertFalse( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); +public class CheckstyleReportTest extends AbstractCheckstyleTestCase { + public void testNoSource() throws Exception { + File generatedReport = generateReport("checkstyle", "no-source-plugin-config.xml"); + assertFalse(FileUtils.fileExists(generatedReport.getAbsolutePath())); } - public void testMinConfiguration() - throws Exception - { - generateReport( "min-plugin-config.xml" ); + public void testMinConfiguration() throws Exception { + generateReport("min-plugin-config.xml"); } - public void testCustomConfiguration() - throws Exception - { - generateReport( "custom-plugin-config.xml" ); + public void testCustomConfiguration() throws Exception { + generateReport("custom-plugin-config.xml"); } - public void testUseFile() - throws Exception - { - generateReport( "useFile-plugin-config.xml" ); + public void testUseFile() throws Exception { + generateReport("useFile-plugin-config.xml"); } - public void testNoRulesSummary() - throws Exception - { - generateReport( "no-rules-plugin-config.xml" ); + public void testNoRulesSummary() throws Exception { + generateReport("no-rules-plugin-config.xml"); } - public void testNoSeveritySummary() - throws Exception - { - generateReport( "no-severity-plugin-config.xml" ); + public void testNoSeveritySummary() throws Exception { + generateReport("no-severity-plugin-config.xml"); } - public void testNoFilesSummary() - throws Exception - { - generateReport( "no-files-plugin-config.xml" ); + public void testNoFilesSummary() throws Exception { + generateReport("no-files-plugin-config.xml"); } - public void testFailOnError() - { - try - { - generateReport( "fail-on-error-plugin-config.xml" ); + public void testFailOnError() { + try { + generateReport("fail-on-error-plugin-config.xml"); - fail( "Must throw exception on errors" ); - } - catch ( Exception e ) - { + fail("Must throw exception on errors"); + } catch (Exception e) { // expected } } - public void testDependencyResolutionException() - { - try - { - generateReport( "dep-resolution-exception-plugin-config.xml" ); + public void testDependencyResolutionException() { + try { + generateReport("dep-resolution-exception-plugin-config.xml"); - fail( "Must throw exception on errors" ); - } - catch ( Exception e ) - { - if ( !( e.getCause().getCause().getCause() instanceof DependencyResolutionRequiredException ) ) - { + fail("Must throw exception on errors"); + } catch (Exception e) { + if (!(e.getCause().getCause().getCause() instanceof DependencyResolutionRequiredException)) { e.printStackTrace(); - fail( "Must throw exception DependencyResolutionRequiredException on errors and not " + e.getClass().getName() + ", " + e.getMessage() ); + fail("Must throw exception DependencyResolutionRequiredException on errors and not " + + e.getClass().getName() + ", " + e.getMessage()); } } } - public void testTestSourceDirectory() - throws Exception - { - generateReport( "test-source-directory-plugin-config.xml" ); + public void testTestSourceDirectory() throws Exception { + generateReport("test-source-directory-plugin-config.xml"); } /** @@ -126,104 +98,84 @@ public void testTestSourceDirectory() * @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(); } - private void generateReport( String pluginXml ) - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/" + pluginXml ); + private void generateReport(String pluginXml) throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/" + pluginXml); ResourceBundle bundle = - ResourceBundle.getBundle( "checkstyle-report", Locale.getDefault(), this.getClassLoader() ); + ResourceBundle.getBundle("checkstyle-report", Locale.getDefault(), this.getClassLoader()); - CheckstyleReport mojo = createReportMojo( "checkstyle", pluginXmlFile ); + CheckstyleReport mojo = createReportMojo("checkstyle", pluginXmlFile); PluginDescriptor descriptorStub = new PluginDescriptor(); - descriptorStub.setGroupId( "org.apache.maven.plugins" ); - descriptorStub.setArtifactId( "maven-checkstyle-plugin" ); - setVariableValueToObject( mojo, "plugin", descriptorStub ); + descriptorStub.setGroupId("org.apache.maven.plugins"); + descriptorStub.setArtifactId("maven-checkstyle-plugin"); + setVariableValueToObject(mojo, "plugin", descriptorStub); - File generatedReport = generateReport( mojo, pluginXmlFile ); - assertTrue( FileUtils.fileExists( generatedReport.getAbsolutePath() ) ); + File generatedReport = generateReport(mojo, pluginXmlFile); + assertTrue(FileUtils.fileExists(generatedReport.getAbsolutePath())); - File outputFile = (File) getVariableValueFromObject( mojo, "outputFile" ); - assertNotNull( "Test output file", outputFile ); - assertTrue( "Test output file exists", outputFile.exists() ); + File outputFile = (File) getVariableValueFromObject(mojo, "outputFile"); + assertNotNull("Test output file", outputFile); + assertTrue("Test output file exists", outputFile.exists()); - String cacheFile = (String) getVariableValueFromObject( mojo, "cacheFile" ); - if ( cacheFile != null ) - { - assertTrue( "Test cache file exists", new File( cacheFile ).exists() ); + String cacheFile = (String) getVariableValueFromObject(mojo, "cacheFile"); + if (cacheFile != null) { + assertTrue("Test cache file exists", new File(cacheFile).exists()); } File outputDir = mojo.getReportOutputDirectory(); - Boolean rss = (Boolean) getVariableValueFromObject( mojo, "enableRSS" ); - if (rss) - { - File rssFile = new File( outputDir, "checkstyle.rss" ); - assertTrue( "Test rss file exists", rssFile.exists() ); + Boolean rss = (Boolean) getVariableValueFromObject(mojo, "enableRSS"); + if (rss) { + File rssFile = new File(outputDir, "checkstyle.rss"); + assertTrue("Test rss file exists", rssFile.exists()); } - File useFile = (File) getVariableValueFromObject( mojo, "useFile" ); - if ( useFile != null ) - { - assertTrue( "Test useFile exists", useFile.exists() ); + File useFile = (File) getVariableValueFromObject(mojo, "useFile"); + if (useFile != null) { + assertTrue("Test useFile exists", useFile.exists()); } - String str = readFile( generatedReport ); + String str = readFile(generatedReport); - boolean searchHeaderFound = - str.contains( getHtmlHeader( bundle.getString( "report.checkstyle.rules" ) ) ); - Boolean rules = (Boolean) getVariableValueFromObject( mojo, "enableRulesSummary" ); - if (rules) - { - assertTrue( "Test for Rules Summary", searchHeaderFound ); - } - else - { - assertFalse( "Test for Rules Summary", searchHeaderFound ); + boolean searchHeaderFound = str.contains(getHtmlHeader(bundle.getString("report.checkstyle.rules"))); + Boolean rules = (Boolean) getVariableValueFromObject(mojo, "enableRulesSummary"); + if (rules) { + assertTrue("Test for Rules Summary", searchHeaderFound); + } else { + assertFalse("Test for Rules Summary", searchHeaderFound); } - searchHeaderFound = str.contains( getHtmlHeader( bundle.getString( "report.checkstyle.summary" ) ) ); - Boolean severity = (Boolean) getVariableValueFromObject( mojo, "enableSeveritySummary" ); - if (severity) - { - assertTrue( "Test for Severity Summary", searchHeaderFound ); - } - else - { - assertFalse( "Test for Severity Summary", searchHeaderFound ); + searchHeaderFound = str.contains(getHtmlHeader(bundle.getString("report.checkstyle.summary"))); + Boolean severity = (Boolean) getVariableValueFromObject(mojo, "enableSeveritySummary"); + if (severity) { + assertTrue("Test for Severity Summary", searchHeaderFound); + } else { + assertFalse("Test for Severity Summary", searchHeaderFound); } - searchHeaderFound = str.contains( getHtmlHeader( bundle.getString( "report.checkstyle.files" ) ) ); - Boolean files = (Boolean) getVariableValueFromObject( mojo, "enableFilesSummary" ); - if (files) - { - assertTrue( "Test for Files Summary", searchHeaderFound ); - } - else - { - assertFalse( "Test for Files Summary", searchHeaderFound ); + searchHeaderFound = str.contains(getHtmlHeader(bundle.getString("report.checkstyle.files"))); + Boolean files = (Boolean) getVariableValueFromObject(mojo, "enableFilesSummary"); + if (files) { + assertTrue("Test for Files Summary", searchHeaderFound); + } else { + assertFalse("Test for Files Summary", searchHeaderFound); } } - private static String getHtmlHeader( String s ) - { + private static String getHtmlHeader(String s) { return ">" + s + ""; } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojoTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojoTest.java index 49923678..8ab86449 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/CheckstyleViolationCheckMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; import java.io.File; import java.util.Arrays; @@ -34,164 +33,134 @@ * @author Edwin Punzalan * */ -public class CheckstyleViolationCheckMojoTest - extends AbstractMojoTestCase -{ - public void testDefaultConfig() - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml" ); +public class CheckstyleViolationCheckMojoTest extends AbstractMojoTestCase { + public void testDefaultConfig() throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml"); - CheckstyleViolationCheckMojo mojo = (CheckstyleViolationCheckMojo) lookupMojo( "check", pluginXmlFile ); + CheckstyleViolationCheckMojo mojo = (CheckstyleViolationCheckMojo) lookupMojo("check", pluginXmlFile); - mojoSetup( mojo ); + mojoSetup(mojo); - assertNotNull( "Mojo not found.", mojo ); + assertNotNull("Mojo not found.", mojo); - assertNotNull( "project null.", mojo.project ); + assertNotNull("project null.", mojo.project); - try - { + try { mojo.execute(); - fail( "Must throw an exception on violations" ); - } - catch ( MojoFailureException e ) - { - //expected + fail("Must throw an exception on violations"); + } catch (MojoFailureException e) { + // expected } } - public void testInvalidFormatWithSkipExec() - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml" ); + public void testInvalidFormatWithSkipExec() throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml"); - Mojo mojo = lookupMojo( "check", pluginXmlFile ); + Mojo mojo = lookupMojo("check", pluginXmlFile); - assertNotNull( "Mojo not found.", mojo ); + assertNotNull("Mojo not found.", mojo); - mojoSetup( mojo ); + mojoSetup(mojo); - setVariableValueToObject( mojo, "outputFileFormat", "plain" ); + setVariableValueToObject(mojo, "outputFileFormat", "plain"); - try - { + try { mojo.execute(); - fail( "Must throw an exception invalid format: plain" ); - } - catch ( MojoExecutionException e ) - { - //expected + fail("Must throw an exception invalid format: plain"); + } catch (MojoExecutionException e) { + // expected } } - public void testNoOutputFile() - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml" ); + public void testNoOutputFile() throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml"); - Mojo mojo = lookupMojo( "check", pluginXmlFile ); + Mojo mojo = lookupMojo("check", pluginXmlFile); - assertNotNull( "Mojo not found.", mojo ); + assertNotNull("Mojo not found.", mojo); - mojoSetup( mojo ); + mojoSetup(mojo); - setVariableValueToObject( mojo, "outputFile", new File( "target/NoSuchFile.xml" ) ); + setVariableValueToObject(mojo, "outputFile", new File("target/NoSuchFile.xml")); mojo.execute(); } - private void doTestPlainOutputFile( boolean failsOnError ) - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/check-plugin-plain-output.xml" ); + private void doTestPlainOutputFile(boolean failsOnError) throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/check-plugin-plain-output.xml"); - Mojo mojo = lookupMojo( "check", pluginXmlFile ); + Mojo mojo = lookupMojo("check", pluginXmlFile); - assertNotNull( "Mojo not found.", mojo ); + assertNotNull("Mojo not found.", mojo); PluginDescriptor descriptorStub = new PluginDescriptor(); - descriptorStub.setGroupId( "org.apache.maven.plugins" ); - descriptorStub.setArtifactId( "maven-checkstyle-plugin" ); - setVariableValueToObject( mojo, "plugin", descriptorStub ); + descriptorStub.setGroupId("org.apache.maven.plugins"); + descriptorStub.setArtifactId("maven-checkstyle-plugin"); + setVariableValueToObject(mojo, "plugin", descriptorStub); - setVariableValueToObject( mojo, "failsOnError", failsOnError ); + setVariableValueToObject(mojo, "failsOnError", failsOnError); mojo.execute(); } - public void testPlainOutputFileFailOnError() - throws Exception - { - try - { - doTestPlainOutputFile( true ); + public void testPlainOutputFileFailOnError() throws Exception { + try { + doTestPlainOutputFile(true); - fail( "Must fail on violations" ); - } - catch ( MojoExecutionException e ) - { + fail("Must fail on violations"); + } catch (MojoExecutionException e) { // expected } } - public void testPlainOutputFile() - throws Exception - { - doTestPlainOutputFile( false ); + public void testPlainOutputFile() throws Exception { + doTestPlainOutputFile(false); } - public void testNoFail() - throws Exception - { - File pluginXmlFile = new File( getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml" ); + public void testNoFail() throws Exception { + File pluginXmlFile = new File(getBasedir(), "src/test/resources/plugin-configs/check-plugin-config.xml"); - Mojo mojo = lookupMojo( "check", pluginXmlFile ); + Mojo mojo = lookupMojo("check", pluginXmlFile); - assertNotNull( "Mojo not found.", mojo ); + assertNotNull("Mojo not found.", mojo); - mojoSetup( mojo ); + mojoSetup(mojo); - setVariableValueToObject( mojo, "failOnViolation", Boolean.FALSE ); + setVariableValueToObject(mojo, "failOnViolation", Boolean.FALSE); mojo.execute(); } - protected void mojoSetup( Mojo mojo ) - throws Exception - { + protected void mojoSetup(Mojo mojo) throws Exception { // mojo setup - setVariableValueToObject( mojo, "project", new MavenProjectStub() - { + setVariableValueToObject(mojo, "project", new MavenProjectStub() { - public File getFile() - { - return new File( getBasedir(), "target/classes" ); + public File getFile() { + return new File(getBasedir(), "target/classes"); } - public Build getBuild() - { - return new Build() - { + public Build getBuild() { + return new Build() { private static final long serialVersionUID = -743084937617131258L; - public String getDirectory() - { + public String getDirectory() { return getBasedir() + "/target/classes"; } }; } - - } ); - - setVariableValueToObject( mojo, "configLocation", "sun_checks.xml" ); - setVariableValueToObject( mojo, "cacheFile", getBasedir() + "/target/classes/checkstyle-cachefile" ); - setVariableValueToObject( mojo, "sourceDirectories", Arrays.asList( getBasedir() + "/src/test/plugin-configs/src" ));// new File( getBasedir() + "/target" ) ); - setVariableValueToObject( mojo, "inputEncoding", "UTF-8" ); - setVariableValueToObject( mojo, "skipExec", Boolean.TRUE ); - + }); + + setVariableValueToObject(mojo, "configLocation", "sun_checks.xml"); + setVariableValueToObject(mojo, "cacheFile", getBasedir() + "/target/classes/checkstyle-cachefile"); + setVariableValueToObject( + mojo, + "sourceDirectories", + Arrays.asList( + getBasedir() + "/src/test/plugin-configs/src")); // new File( getBasedir() + "/target" ) ); + setVariableValueToObject(mojo, "inputEncoding", "UTF-8"); + setVariableValueToObject(mojo, "skipExec", Boolean.TRUE); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/DependencyArtifactStubFactory.java b/src/test/java/org/apache/maven/plugins/checkstyle/DependencyArtifactStubFactory.java index 5a15a42e..aa7a5e32 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/DependencyArtifactStubFactory.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/DependencyArtifactStubFactory.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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.checkstyle; 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/checkstyle/ReportResourceTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/ReportResourceTest.java index 1c31ca11..f6252ea6 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/ReportResourceTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/ReportResourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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,46 +16,40 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle; -import junit.framework.TestCase; +import java.io.File; +import junit.framework.TestCase; import org.codehaus.plexus.PlexusTestCase; -import java.io.File; - /** * @author Edwin Punzalan * */ -public class ReportResourceTest - extends TestCase -{ - private File outputDir = new File( PlexusTestCase.getBasedir(), "target/unit-test/ReportResource" ); - - public void testConstructor() - { - ReportResource reportResource = new ReportResource( "reportbase", outputDir ); - assertEquals( "Test resourcePathBase", "reportbase", reportResource.getResourcePathBase() ); - assertEquals( "Test outputDirectory", outputDir, reportResource.getOutputDirectory() ); +public class ReportResourceTest extends TestCase { + private File outputDir = new File(PlexusTestCase.getBasedir(), "target/unit-test/ReportResource"); + + public void testConstructor() { + ReportResource reportResource = new ReportResource("reportbase", outputDir); + assertEquals("Test resourcePathBase", "reportbase", reportResource.getResourcePathBase()); + assertEquals("Test outputDirectory", outputDir, reportResource.getOutputDirectory()); } - public void testSetters() - { - ReportResource reportResource = new ReportResource( null, null ); - reportResource.setResourcePathBase( "reportbase" ); - reportResource.setOutputDirectory( outputDir ); + public void testSetters() { + ReportResource reportResource = new ReportResource(null, null); + reportResource.setResourcePathBase("reportbase"); + reportResource.setOutputDirectory(outputDir); - assertEquals( "Test resourcePathBase", "reportbase", reportResource.getResourcePathBase() ); - assertEquals( "Test outputDirectory", outputDir, reportResource.getOutputDirectory() ); + assertEquals("Test resourcePathBase", "reportbase", reportResource.getResourcePathBase()); + assertEquals("Test outputDirectory", outputDir, reportResource.getOutputDirectory()); } - public void testCopy() - throws Exception - { - ReportResource reportResource = new ReportResource( "META-INF/plexus", outputDir ); - reportResource.copy( "components.xml" ); + public void testCopy() throws Exception { + ReportResource reportResource = new ReportResource("META-INF/plexus", outputDir); + reportResource.copy("components.xml"); - File copiedFile = new File( outputDir, "components.xml" ); - assertTrue( "Test copied file exists", copiedFile.exists() ); + File copiedFile = new File(outputDir, "components.xml"); + assertTrue("Test copied file exists", copiedFile.exists()); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/RuleUtilTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/RuleUtilTest.java index a7dddd4f..f2a68ead 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/RuleUtilTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/RuleUtilTest.java @@ -1,9 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - -import java.util.List; - -import junit.framework.TestCase; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -13,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 @@ -22,58 +16,60 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle; + +import java.util.List; + +import junit.framework.TestCase; -public class RuleUtilTest - extends TestCase -{ +public class RuleUtilTest extends TestCase { private static final String CHECKSTYLE_PACKAGE = "com.puppycrawl.tools.checkstyle.checks"; - public void testGetName() - { - assertEquals( "FinalParameters", RuleUtil.getName( CHECKSTYLE_PACKAGE + ".FinalParameters" ) ); - assertEquals( "FinalParameters", RuleUtil.getName( CHECKSTYLE_PACKAGE + ".FinalParametersCheck" ) ); - assertNull( RuleUtil.getName( (String) null ) ); + public void testGetName() { + assertEquals("FinalParameters", RuleUtil.getName(CHECKSTYLE_PACKAGE + ".FinalParameters")); + assertEquals("FinalParameters", RuleUtil.getName(CHECKSTYLE_PACKAGE + ".FinalParametersCheck")); + assertNull(RuleUtil.getName((String) null)); } - public void testGetCategory() - { - assertEquals( "misc", RuleUtil.getCategory( CHECKSTYLE_PACKAGE + ".FinalParametersCheck" ) ); - assertEquals( "test", RuleUtil.getCategory( CHECKSTYLE_PACKAGE + ".test.FinalParametersCheck" ) ); - assertEquals( "extension", RuleUtil.getCategory( "test.FinalParametersCheck" ) ); - assertEquals( "extension", RuleUtil.getCategory( "copyright" ) ); - assertNull( RuleUtil.getCategory( (String) null ) ); + public void testGetCategory() { + assertEquals("misc", RuleUtil.getCategory(CHECKSTYLE_PACKAGE + ".FinalParametersCheck")); + assertEquals("test", RuleUtil.getCategory(CHECKSTYLE_PACKAGE + ".test.FinalParametersCheck")); + assertEquals("extension", RuleUtil.getCategory("test.FinalParametersCheck")); + assertEquals("extension", RuleUtil.getCategory("copyright")); + assertNull(RuleUtil.getCategory((String) null)); } - public void testMatcher() - { - String[] specs = ( "misc, test, extension, Header, " + CHECKSTYLE_PACKAGE + ".test2" ).split( "," ); - String[] eventSrcNames = - new String[] { CHECKSTYLE_PACKAGE + ".FinalParametersCheck", - CHECKSTYLE_PACKAGE + ".test.FinalParametersCheck", "test.FinalParametersCheck", - CHECKSTYLE_PACKAGE + ".whitespace.HeaderCheck", CHECKSTYLE_PACKAGE + ".test2.FinalParametersCheck" }; + public void testMatcher() { + String[] specs = ("misc, test, extension, Header, " + CHECKSTYLE_PACKAGE + ".test2").split(","); + String[] eventSrcNames = new String[] { + CHECKSTYLE_PACKAGE + ".FinalParametersCheck", + CHECKSTYLE_PACKAGE + ".test.FinalParametersCheck", + "test.FinalParametersCheck", + CHECKSTYLE_PACKAGE + ".whitespace.HeaderCheck", + CHECKSTYLE_PACKAGE + ".test2.FinalParametersCheck" + }; - List matchers = RuleUtil.parseMatchers( specs ); + List matchers = RuleUtil.parseMatchers(specs); - for ( int i = 0; i < matchers.size(); i++ ) - { + for (int i = 0; i < matchers.size(); i++) { String spec = specs[i]; - RuleUtil.Matcher matcher = matchers.get( i ); - for ( int j = 0; j < matchers.size(); j++ ) - { + RuleUtil.Matcher matcher = matchers.get(i); + for (int j = 0; j < matchers.size(); j++) { String eventSrcName = eventSrcNames[j]; - assertEquals( spec + " should" + ( ( i == j ) ? " " : " not " ) + "match " + eventSrcName, i == j, - matcher.match( eventSrcName ) ); + assertEquals( + spec + " should" + ((i == j) ? " " : " not ") + "match " + eventSrcName, + i == j, + matcher.match(eventSrcName)); } } } - public void testMatcherWithBlankStrings() - { - String[] specs = ( " ,,foo, " ).split( "," ); + public void testMatcherWithBlankStrings() { + String[] specs = (" ,,foo, ").split(","); - List matchers = RuleUtil.parseMatchers( specs ); + List matchers = RuleUtil.parseMatchers(specs); - assertEquals( 1, matchers.size() ); - assertTrue( matchers.get( 0 ).match( CHECKSTYLE_PACKAGE + ".foo.SomeCheck" ) ); + assertEquals(1, matchers.size()); + assertTrue(matchers.get(0).match(CHECKSTYLE_PACKAGE + ".foo.SomeCheck")); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/ViolationTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/ViolationTest.java index 41abb5cd..f13eff9d 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/ViolationTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/ViolationTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle; - /* * 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,16 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle; import junit.framework.TestCase; -public class ViolationTest - extends TestCase -{ - public void testEquals() - { - Violation v1 = new Violation( "", null, null, "", "", "", "" ); - Violation v2 = new Violation( "", null, null, "", "", "", "" ); - assertEquals( v1, v2 ); +public class ViolationTest extends TestCase { + public void testEquals() { + Violation v1 = new Violation("", null, null, "", "", "", ""); + Violation v2 = new Violation("", null, null, "", "", "", ""); + assertEquals(v1, v2); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerMultiSourceTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerMultiSourceTest.java index 0befa3b9..d248ae7e 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerMultiSourceTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerMultiSourceTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * 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,166 +16,154 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.Violation; - import junit.framework.TestCase; -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -public class CheckstyleReportListenerMultiSourceTest - extends TestCase -{ +public class CheckstyleReportListenerMultiSourceTest extends TestCase { private Map listenerMap; /** * {@inheritDoc} */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { listenerMap = new HashMap<>(); - CheckstyleCheckerListener listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.addSourceDirectory( new File( "/source/path2" ) ); - listener.setSeverityLevelFilter( SeverityLevel.INFO ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); - - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.addSourceDirectory( new File( "/source/path2" ) ); - listener.setSeverityLevelFilter( SeverityLevel.WARNING ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); - - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.addSourceDirectory( new File( "/source/path2" ) ); - listener.setSeverityLevelFilter( SeverityLevel.ERROR ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); - - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.addSourceDirectory( new File( "/source/path2" ) ); - listener.setSeverityLevelFilter( SeverityLevel.IGNORE ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); + CheckstyleCheckerListener listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.addSourceDirectory(new File("/source/path2")); + listener.setSeverityLevelFilter(SeverityLevel.INFO); + listenerMap.put(listener.getSeverityLevelFilter(), listener); + + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.addSourceDirectory(new File("/source/path2")); + listener.setSeverityLevelFilter(SeverityLevel.WARNING); + listenerMap.put(listener.getSeverityLevelFilter(), listener); + + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.addSourceDirectory(new File("/source/path2")); + listener.setSeverityLevelFilter(SeverityLevel.ERROR); + listenerMap.put(listener.getSeverityLevelFilter(), listener); + + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.addSourceDirectory(new File("/source/path2")); + listener.setSeverityLevelFilter(SeverityLevel.IGNORE); + listenerMap.put(listener.getSeverityLevelFilter(), listener); } - public void testListeners() - { - fireAuditStarted( null ); - - AuditEvent event = new AuditEvent( this, "/source/path/file1", null ); - fireFileStarted( event ); - Violation message = - new Violation( 0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file1", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path2/file2", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path2/file2", message ) ); - fireAddError( new AuditEvent( this, "/source/path2/file2", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path/file3", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path2/file4", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path2/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path2/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path2/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path2/file4", message ) ); - fireFileFinished( event ); - - fireAuditFinished( null ); - - CheckstyleCheckerListener listener = listenerMap.get( SeverityLevel.INFO ); + public void testListeners() { + fireAuditStarted(null); + + AuditEvent event = new AuditEvent(this, "/source/path/file1", null); + fireFileStarted(event); + Violation message = new Violation(0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file1", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path2/file2", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path2/file2", message)); + fireAddError(new AuditEvent(this, "/source/path2/file2", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path/file3", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path2/file4", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path2/file4", message)); + fireAddError(new AuditEvent(this, "/source/path2/file4", message)); + fireAddError(new AuditEvent(this, "/source/path2/file4", message)); + fireAddError(new AuditEvent(this, "/source/path2/file4", message)); + fireFileFinished(event); + + fireAuditFinished(null); + + CheckstyleCheckerListener listener = listenerMap.get(SeverityLevel.INFO); CheckstyleResults results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 1, results.getFileViolations( "file1" ).size() ); - assertEquals( "test file severities", 1, results.getSeverityCount( "file1", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.WARNING ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 1, results.getFileViolations("file1").size()); + assertEquals("test file severities", 1, results.getSeverityCount("file1", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.WARNING); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 2, results.getFileViolations( "file2" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 2, results.getSeverityCount( "file2", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.ERROR ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 2, results.getFileViolations("file2").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.INFO)); + assertEquals("test file severities", 2, results.getSeverityCount("file2", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.ERROR); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 3, results.getFileViolations( "file3" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 3, results.getSeverityCount( "file3", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.IGNORE ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 3, results.getFileViolations("file3").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.WARNING)); + assertEquals("test file severities", 3, results.getSeverityCount("file3", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.IGNORE); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 0, results.getFileViolations( "file4" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.IGNORE ) ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 0, results.getFileViolations("file4").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.IGNORE)); } - private void fireAuditStarted( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.auditStarted( event ); + private void fireAuditStarted(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.auditStarted(event); } } - private void fireAuditFinished( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.auditFinished( event ); + private void fireAuditFinished(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.auditFinished(event); } } - private void fireFileStarted( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.fileStarted( event ); + private void fireFileStarted(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.fileStarted(event); } } - private void fireFileFinished( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.fileFinished( event ); + private void fireFileFinished(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.fileFinished(event); } } - private void fireAddError( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.addError( event ); + private void fireAddError(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.addError(event); } } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerTest.java index a6e48e0f..62df6536 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleReportListenerTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * 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,164 +16,152 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; import com.puppycrawl.tools.checkstyle.api.AuditEvent; import com.puppycrawl.tools.checkstyle.api.SeverityLevel; import com.puppycrawl.tools.checkstyle.api.Violation; - - import junit.framework.TestCase; -import java.io.File; -import java.util.HashMap; -import java.util.Map; - /** * @author Edwin Punzalan * */ -public class CheckstyleReportListenerTest - extends TestCase -{ +public class CheckstyleReportListenerTest extends TestCase { private Map listenerMap; /** {@inheritDoc} */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { listenerMap = new HashMap<>(); - CheckstyleCheckerListener listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.setSeverityLevelFilter( SeverityLevel.INFO ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); + CheckstyleCheckerListener listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.setSeverityLevelFilter(SeverityLevel.INFO); + listenerMap.put(listener.getSeverityLevelFilter(), listener); - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.setSeverityLevelFilter( SeverityLevel.WARNING ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.setSeverityLevelFilter(SeverityLevel.WARNING); + listenerMap.put(listener.getSeverityLevelFilter(), listener); - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.setSeverityLevelFilter( SeverityLevel.ERROR ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.setSeverityLevelFilter(SeverityLevel.ERROR); + listenerMap.put(listener.getSeverityLevelFilter(), listener); - listener = new CheckstyleCheckerListener( new File( "/source/path" ) ); - listener.setSeverityLevelFilter( SeverityLevel.IGNORE ); - listenerMap.put( listener.getSeverityLevelFilter(), listener ); + listener = new CheckstyleCheckerListener(new File("/source/path")); + listener.setSeverityLevelFilter(SeverityLevel.IGNORE); + listenerMap.put(listener.getSeverityLevelFilter(), listener); } - public void testListeners() - { - fireAuditStarted( null ); - - AuditEvent event = new AuditEvent( this, "/source/path/file1", null ); - fireFileStarted( event ); - Violation message = new Violation( 0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file1", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path/file2", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file2", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file2", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path/file3", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file3", message ) ); - fireFileFinished( event ); - - event = new AuditEvent( this, "/source/path/file4", null ); - fireFileStarted( event ); - message = new Violation( 0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null ); - fireAddError( new AuditEvent( this, "/source/path/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file4", message ) ); - fireAddError( new AuditEvent( this, "/source/path/file4", message ) ); - fireFileFinished( event ); - - fireAuditFinished( null ); - - CheckstyleCheckerListener listener = listenerMap.get( SeverityLevel.INFO ); + public void testListeners() { + fireAuditStarted(null); + + AuditEvent event = new AuditEvent(this, "/source/path/file1", null); + fireFileStarted(event); + Violation message = new Violation(0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file1", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path/file2", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file2", message)); + fireAddError(new AuditEvent(this, "/source/path/file2", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path/file3", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireAddError(new AuditEvent(this, "/source/path/file3", message)); + fireFileFinished(event); + + event = new AuditEvent(this, "/source/path/file4", null); + fireFileStarted(event); + message = new Violation(0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null); + fireAddError(new AuditEvent(this, "/source/path/file4", message)); + fireAddError(new AuditEvent(this, "/source/path/file4", message)); + fireAddError(new AuditEvent(this, "/source/path/file4", message)); + fireAddError(new AuditEvent(this, "/source/path/file4", message)); + fireFileFinished(event); + + fireAuditFinished(null); + + CheckstyleCheckerListener listener = listenerMap.get(SeverityLevel.INFO); CheckstyleResults results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 1, results.getFileViolations( "file1" ).size() ); - assertEquals( "test file severities", 1, results.getSeverityCount( "file1", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.WARNING ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 1, results.getFileViolations("file1").size()); + assertEquals("test file severities", 1, results.getSeverityCount("file1", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.WARNING); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 2, results.getFileViolations( "file2" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 2, results.getSeverityCount( "file2", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.ERROR ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 2, results.getFileViolations("file2").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.INFO)); + assertEquals("test file severities", 2, results.getSeverityCount("file2", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.ERROR); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 3, results.getFileViolations( "file3" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 3, results.getSeverityCount( "file3", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.IGNORE ) ); - - listener = listenerMap.get( SeverityLevel.IGNORE ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 3, results.getFileViolations("file3").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.WARNING)); + assertEquals("test file severities", 3, results.getSeverityCount("file3", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.IGNORE)); + + listener = listenerMap.get(SeverityLevel.IGNORE); results = listener.getResults(); - assertEquals( "Test total files", 4, results.getFiles().size() ); - assertEquals( "Test file count", 4, results.getFileCount() ); - assertEquals( "test file violations", 0, results.getFileViolations( "file4" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.IGNORE ) ); + assertEquals("Test total files", 4, results.getFiles().size()); + assertEquals("Test file count", 4, results.getFileCount()); + assertEquals( + "test file violations", 0, results.getFileViolations("file4").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.IGNORE)); } - private void fireAuditStarted( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.auditStarted( event ); + private void fireAuditStarted(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.auditStarted(event); } } - private void fireAuditFinished( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.auditFinished( event ); + private void fireAuditFinished(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.auditFinished(event); } } - private void fireFileStarted( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.fileStarted( event ); + private void fireFileStarted(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.fileStarted(event); } } - private void fireFileFinished( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.fileFinished( event ); + private void fireFileFinished(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.fileFinished(event); } } - private void fireAddError( AuditEvent event ) - { - for ( CheckstyleCheckerListener listener : listenerMap.values() ) - { - listener.addError( event ); + private void fireAddError(AuditEvent event) { + for (CheckstyleCheckerListener listener : listenerMap.values()) { + listener.addError(event); } } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResultsTest.java b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResultsTest.java index 513457f6..3550bbd4 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResultsTest.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/exec/CheckstyleResultsTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.exec; - /* * 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,128 +16,128 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.exec; -import junit.framework.TestCase; - -import com.puppycrawl.tools.checkstyle.api.SeverityLevel; -import com.puppycrawl.tools.checkstyle.api.AuditEvent; -import com.puppycrawl.tools.checkstyle.api.Violation; - +import java.util.ArrayList; import java.util.Collections; -import java.util.Map; import java.util.HashMap; import java.util.List; -import java.util.ArrayList; +import java.util.Map; + +import com.puppycrawl.tools.checkstyle.api.AuditEvent; +import com.puppycrawl.tools.checkstyle.api.SeverityLevel; +import com.puppycrawl.tools.checkstyle.api.Violation; +import junit.framework.TestCase; /** * @author Edwin Punzalan * */ -public class CheckstyleResultsTest - extends TestCase -{ +public class CheckstyleResultsTest extends TestCase { private CheckstyleResults results; /** {@inheritDoc} */ - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { results = new CheckstyleResults(); } /** {@inheritDoc} */ - protected void tearDown() - throws Exception - { + protected void tearDown() throws Exception { results = null; } - public void testEmptyResults() - { - assertEquals( "test total files", 0, results.getFiles().size() ); + public void testEmptyResults() { + assertEquals("test total files", 0, results.getFiles().size()); - assertEquals( "test file count", 0, results.getFileCount() ); + assertEquals("test file count", 0, results.getFileCount()); - assertEquals( "test zero file violations", 0, results.getFileViolations( "filename" ).size() ); + assertEquals( + "test zero file violations", + 0, + results.getFileViolations("filename").size()); - assertEquals( "test INFO severity count", 0, results.getSeverityCount( SeverityLevel.INFO ) ); + assertEquals("test INFO severity count", 0, results.getSeverityCount(SeverityLevel.INFO)); - assertEquals( "test WARNING severity count", 0, results.getSeverityCount( SeverityLevel.WARNING ) ); + assertEquals("test WARNING severity count", 0, results.getSeverityCount(SeverityLevel.WARNING)); - assertEquals( "test ERROR severity count", 0, results.getSeverityCount( SeverityLevel.ERROR ) ); + assertEquals("test ERROR severity count", 0, results.getSeverityCount(SeverityLevel.ERROR)); - assertEquals( "test IGNORE severity count", 0, results.getSeverityCount( SeverityLevel.IGNORE ) ); + assertEquals("test IGNORE severity count", 0, results.getSeverityCount(SeverityLevel.IGNORE)); } - public void testResults() - { + public void testResults() { Map> files = new HashMap<>(); - Violation message = new Violation( 0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null ); - AuditEvent event = new AuditEvent( this, "file1", message ); - files.put( "file1", Collections.singletonList( event ) ); + Violation message = new Violation(0, 0, "", "", null, SeverityLevel.INFO, null, getClass(), null); + AuditEvent event = new AuditEvent(this, "file1", message); + files.put("file1", Collections.singletonList(event)); - message = new Violation( 0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null ); + message = new Violation(0, 0, "", "", null, SeverityLevel.WARNING, null, getClass(), null); List events = new ArrayList<>(); - events.add( new AuditEvent( this, "file2", message ) ); - events.add( new AuditEvent( this, "file2", message ) ); - files.put( "file2", events ); + events.add(new AuditEvent(this, "file2", message)); + events.add(new AuditEvent(this, "file2", message)); + files.put("file2", events); - message = new Violation( 0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null ); + message = new Violation(0, 0, "", "", null, SeverityLevel.ERROR, null, getClass(), null); events = new ArrayList<>(); - events.add( new AuditEvent( this, "file3", message ) ); - events.add( new AuditEvent( this, "file3", message ) ); - events.add( new AuditEvent( this, "file3", message ) ); - files.put( "file3", events ); + events.add(new AuditEvent(this, "file3", message)); + events.add(new AuditEvent(this, "file3", message)); + events.add(new AuditEvent(this, "file3", message)); + files.put("file3", events); - message = new Violation( 0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null ); + message = new Violation(0, 0, "", "", null, SeverityLevel.IGNORE, null, getClass(), null); events = new ArrayList<>(); - events.add( new AuditEvent( this, "file4", message ) ); - events.add( new AuditEvent( this, "file4", message ) ); - events.add( new AuditEvent( this, "file4", message ) ); - events.add( new AuditEvent( this, "file4", message ) ); - files.put( "file4", events ); - - results.setFiles( files ); - - assertEquals( "test total files", 4, results.getFiles().size() ); - assertEquals( "test file count", 4, results.getFileCount() ); - - assertEquals( "test file severities", 0, results.getSeverityCount( "file0", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file0", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file0", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file0", SeverityLevel.IGNORE ) ); - - assertEquals( "test file violations", 1, results.getFileViolations( "file1" ).size() ); - assertEquals( "test file severities", 1, results.getSeverityCount( "file1", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file1", SeverityLevel.IGNORE ) ); - - assertEquals( "test file violations", 2, results.getFileViolations( "file2" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 2, results.getSeverityCount( "file2", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file2", SeverityLevel.IGNORE ) ); - - assertEquals( "test file violations", 3, results.getFileViolations( "file3" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 3, results.getSeverityCount( "file3", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file3", SeverityLevel.IGNORE ) ); - - assertEquals( "test file violations", 4, results.getFileViolations( "file4" ).size() ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.INFO ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.WARNING ) ); - assertEquals( "test file severities", 0, results.getSeverityCount( "file4", SeverityLevel.ERROR ) ); - assertEquals( "test file severities", 4, results.getSeverityCount( "file4", SeverityLevel.IGNORE ) ); - - assertEquals( "test INFO severity count", 1, results.getSeverityCount( SeverityLevel.INFO ) ); - assertEquals( "test WARNING severity count", 2, results.getSeverityCount( SeverityLevel.WARNING ) ); - assertEquals( "test ERROR severity count", 3, results.getSeverityCount( SeverityLevel.ERROR ) ); - assertEquals( "test IGNORE severity count", 4, results.getSeverityCount( SeverityLevel.IGNORE ) ); - - results.setFileViolations( "file", Collections.emptyList() ); - assertEquals( "test file violations", 0, results.getFileViolations( "file" ).size() ); + events.add(new AuditEvent(this, "file4", message)); + events.add(new AuditEvent(this, "file4", message)); + events.add(new AuditEvent(this, "file4", message)); + events.add(new AuditEvent(this, "file4", message)); + files.put("file4", events); + + results.setFiles(files); + + assertEquals("test total files", 4, results.getFiles().size()); + assertEquals("test file count", 4, results.getFileCount()); + + assertEquals("test file severities", 0, results.getSeverityCount("file0", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file0", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file0", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file0", SeverityLevel.IGNORE)); + + assertEquals( + "test file violations", 1, results.getFileViolations("file1").size()); + assertEquals("test file severities", 1, results.getSeverityCount("file1", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file1", SeverityLevel.IGNORE)); + + assertEquals( + "test file violations", 2, results.getFileViolations("file2").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.INFO)); + assertEquals("test file severities", 2, results.getSeverityCount("file2", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file2", SeverityLevel.IGNORE)); + + assertEquals( + "test file violations", 3, results.getFileViolations("file3").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.WARNING)); + assertEquals("test file severities", 3, results.getSeverityCount("file3", SeverityLevel.ERROR)); + assertEquals("test file severities", 0, results.getSeverityCount("file3", SeverityLevel.IGNORE)); + + assertEquals( + "test file violations", 4, results.getFileViolations("file4").size()); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.INFO)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.WARNING)); + assertEquals("test file severities", 0, results.getSeverityCount("file4", SeverityLevel.ERROR)); + assertEquals("test file severities", 4, results.getSeverityCount("file4", SeverityLevel.IGNORE)); + + assertEquals("test INFO severity count", 1, results.getSeverityCount(SeverityLevel.INFO)); + assertEquals("test WARNING severity count", 2, results.getSeverityCount(SeverityLevel.WARNING)); + assertEquals("test ERROR severity count", 3, results.getSeverityCount(SeverityLevel.ERROR)); + assertEquals("test IGNORE severity count", 4, results.getSeverityCount(SeverityLevel.IGNORE)); + + results.setFileViolations("file", Collections.emptyList()); + assertEquals( + "test file violations", 0, results.getFileViolations("file").size()); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/CheckstyleProjectStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/CheckstyleProjectStub.java index 528a00f2..82e3d040 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/CheckstyleProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/CheckstyleProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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.checkstyle.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 CheckstyleProjectStub - extends MavenProjectStub -{ +public abstract class CheckstyleProjectStub 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); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithExceptionsStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithExceptionsStub.java index 67799085..5be94b6c 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithExceptionsStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithExceptionsStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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,23 +16,20 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.stubs; + +import java.util.List; import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.plugin.testing.stubs.ArtifactStub; -import java.util.List; - /** * @author Edwin Punzalan * */ -public class MavenProjectWithExceptionsStub - extends MinMavenProjectStub -{ +public class MavenProjectWithExceptionsStub extends MinMavenProjectStub { /** {@inheritDoc} */ - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { - throw new DependencyResolutionRequiredException( new ArtifactStub() ); + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { + throw new DependencyResolutionRequiredException(new ArtifactStub()); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithNoJxrPluginStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithNoJxrPluginStub.java index 1c5c2f2c..463c9253 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithNoJxrPluginStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MavenProjectWithNoJxrPluginStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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,9 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.stubs; -import java.util.List; import java.util.Collections; +import java.util.List; import org.apache.maven.model.ReportPlugin; @@ -28,18 +27,14 @@ * @author Edwin Punzalan * */ -public class MavenProjectWithNoJxrPluginStub - extends MinMavenProjectStub -{ +public class MavenProjectWithNoJxrPluginStub extends MinMavenProjectStub { /** {@inheritDoc} */ - public String getInceptionYear() - { + public String getInceptionYear() { return "2005"; } /** {@inheritDoc} */ - public List getReportPlugins() - { + public List getReportPlugins() { return Collections.emptyList(); } } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MinMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MinMavenProjectStub.java index ab838019..aaaaf5dc 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MinMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MinMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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,101 +16,88 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Build; import org.apache.maven.model.Organization; import org.apache.maven.model.ReportPlugin; -import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.codehaus.plexus.PlexusTestCase; -import java.util.ArrayList; -import java.util.List; -import java.util.Collections; -import java.io.File; - /** * @author Edwin Punzalan * */ -public class MinMavenProjectStub - extends CheckstyleProjectStub -{ +public class MinMavenProjectStub extends CheckstyleProjectStub { /** {@inheritDoc} */ - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { return getCompileSourceRoots(); } /** {@inheritDoc} */ - public List getTestClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getCompileClasspathElements() ); - list.add( PlexusTestCase.getBasedir() + "/target/test-classes" ); + public List getTestClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getCompileClasspathElements()); + list.add(PlexusTestCase.getBasedir() + "/target/test-classes"); return list; } /** {@inheritDoc} */ - public List getCompileSourceRoots() - { - return Collections.singletonList( PlexusTestCase.getBasedir() + "/target/classes" ); + public List getCompileSourceRoots() { + return Collections.singletonList(PlexusTestCase.getBasedir() + "/target/classes"); } /** {@inheritDoc} */ - public List getTestCompileSourceRoots() - { - List list = new ArrayList<>( getCompileSourceRoots() ); - list.add( PlexusTestCase.getBasedir() + "/target/test-classes" ); + public List getTestCompileSourceRoots() { + List list = new ArrayList<>(getCompileSourceRoots()); + list.add(PlexusTestCase.getBasedir() + "/target/test-classes"); return list; } /** {@inheritDoc} */ - public File getBasedir() - { - return new File( PlexusTestCase.getBasedir() ); + public File getBasedir() { + return new File(PlexusTestCase.getBasedir()); } /** {@inheritDoc} */ - public List getReportPlugins() - { + public List getReportPlugins() { ReportPlugin jxrPlugin = new ReportPlugin(); - jxrPlugin.setArtifactId( "maven-jxr-plugin" ); + jxrPlugin.setArtifactId("maven-jxr-plugin"); - return Collections.singletonList( jxrPlugin ); + return Collections.singletonList(jxrPlugin); } /** {@inheritDoc} */ - public Organization getOrganization() - { + public Organization getOrganization() { Organization organization = new Organization(); - organization.setName( "maven-plugin-tests" ); + organization.setName("maven-plugin-tests"); return organization; } /** {@inheritDoc} */ - public String getInceptionYear() - { + public String getInceptionYear() { return "2006"; } /** {@inheritDoc} */ - public Build getBuild() - { + public Build getBuild() { Build build = new Build(); - build.setDirectory( PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/min" ); + build.setDirectory(PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/min"); return build; } /** {@inheritDoc} */ - public File getFile() - { - File file = new File( getBasedir(), "pom.xml" ); + public File getFile() { + File file = new File(getBasedir(), "pom.xml"); return file; } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/ModuleMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/ModuleMavenProjectStub.java index 5c92929a..b879a3b2 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/ModuleMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/ModuleMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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,104 +16,91 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.checkstyle.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.apache.maven.model.Build; import org.apache.maven.model.Organization; import org.apache.maven.model.ReportPlugin; -import org.apache.maven.artifact.DependencyResolutionRequiredException; import org.codehaus.plexus.PlexusTestCase; -import java.util.ArrayList; -import java.util.List; -import java.util.Collections; -import java.io.File; - /** * @author Edwin Punzalan * */ -public class ModuleMavenProjectStub - extends CheckstyleProjectStub -{ +public class ModuleMavenProjectStub extends CheckstyleProjectStub { /** {@inheritDoc} */ - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { return getCompileSourceRoots(); } /** {@inheritDoc} */ - public List getTestClasspathElements() - throws DependencyResolutionRequiredException - { - List list = new ArrayList<>( getCompileClasspathElements() ); - list.add( PlexusTestCase.getBasedir() + "/target/test-classes" ); + public List getTestClasspathElements() throws DependencyResolutionRequiredException { + List list = new ArrayList<>(getCompileClasspathElements()); + list.add(PlexusTestCase.getBasedir() + "/target/test-classes"); return list; } /** {@inheritDoc} */ - public List getCompileSourceRoots() - { - return Collections.singletonList( PlexusTestCase.getBasedir() + "/target/classes" ); + public List getCompileSourceRoots() { + return Collections.singletonList(PlexusTestCase.getBasedir() + "/target/classes"); } /** {@inheritDoc} */ - public List getTestCompileSourceRoots() - { - List list = new ArrayList<>( getCompileSourceRoots() ); - list.add( PlexusTestCase.getBasedir() + "/target/test-classes" ); + public List getTestCompileSourceRoots() { + List list = new ArrayList<>(getCompileSourceRoots()); + list.add(PlexusTestCase.getBasedir() + "/target/test-classes"); return list; } /** {@inheritDoc} */ - public File getBasedir() - { - return new File( PlexusTestCase.getBasedir() ); + public File getBasedir() { + return new File(PlexusTestCase.getBasedir()); } /** {@inheritDoc} */ - public List getReportPlugins() - { + public List getReportPlugins() { ReportPlugin jxrPlugin = new ReportPlugin(); - jxrPlugin.setArtifactId( "maven-jxr-plugin" ); + jxrPlugin.setArtifactId("maven-jxr-plugin"); - return Collections.singletonList( jxrPlugin ); + return Collections.singletonList(jxrPlugin); } /** {@inheritDoc} */ - public Organization getOrganization() - { + public Organization getOrganization() { Organization organization = new Organization(); - organization.setName( "maven-plugin-tests" ); + organization.setName("maven-plugin-tests"); return organization; } /** {@inheritDoc} */ - public String getInceptionYear() - { + public String getInceptionYear() { return "2006"; } /** {@inheritDoc} */ - public Build getBuild() - { + public Build getBuild() { Build build = new Build(); - build.setDirectory( PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/multi" ); - build.setSourceDirectory( PlexusTestCase.getBasedir() + "/src/test/test-sources" ); - build.setTestSourceDirectory( PlexusTestCase.getBasedir() + "/src/test/java" ); + build.setDirectory(PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/multi"); + build.setSourceDirectory(PlexusTestCase.getBasedir() + "/src/test/test-sources"); + build.setTestSourceDirectory(PlexusTestCase.getBasedir() + "/src/test/java"); return build; } /** {@inheritDoc} */ - public File getFile() - { - File file = new File( getBasedir(), "pom.xml" ); + public File getFile() { + File file = new File(getBasedir(), "pom.xml"); return file; } diff --git a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MultiMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MultiMavenProjectStub.java index b39d9e02..63e4abef 100644 --- a/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MultiMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/checkstyle/stubs/MultiMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.checkstyle.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.checkstyle.stubs; import java.io.File; import java.util.Collections; @@ -33,93 +32,77 @@ /** * */ -public class MultiMavenProjectStub - extends CheckstyleProjectStub -{ +public class MultiMavenProjectStub extends CheckstyleProjectStub { - public MultiMavenProjectStub() - { - setExecutionRoot( true ); + public MultiMavenProjectStub() { + setExecutionRoot(true); } @Override - public MavenProject getExecutionProject() - { + public MavenProject getExecutionProject() { return this; } /** {@inheritDoc} */ - public List getCompileClasspathElements() - throws DependencyResolutionRequiredException - { + public List getCompileClasspathElements() throws DependencyResolutionRequiredException { return Collections.emptyList(); } /** {@inheritDoc} */ - public List getTestClasspathElements() - throws DependencyResolutionRequiredException - { + public List getTestClasspathElements() throws DependencyResolutionRequiredException { return Collections.emptyList(); } /** {@inheritDoc} */ - public List getCompileSourceRoots() - { + public List getCompileSourceRoots() { return Collections.emptyList(); } /** {@inheritDoc} */ - public List getTestCompileSourceRoots() - { + public List getTestCompileSourceRoots() { return Collections.emptyList(); } /** {@inheritDoc} */ - public File getBasedir() - { - return new File( PlexusTestCase.getBasedir() ); + public File getBasedir() { + return new File(PlexusTestCase.getBasedir()); } /** {@inheritDoc} */ - public List getReportPlugins() - { + public List getReportPlugins() { ReportPlugin jxrPlugin = new ReportPlugin(); - jxrPlugin.setArtifactId( "maven-jxr-plugin" ); + jxrPlugin.setArtifactId("maven-jxr-plugin"); - return Collections.singletonList( jxrPlugin ); + return Collections.singletonList(jxrPlugin); } /** {@inheritDoc} */ - public Organization getOrganization() - { + public Organization getOrganization() { Organization organization = new Organization(); - organization.setName( "maven-plugin-tests" ); + organization.setName("maven-plugin-tests"); return organization; } /** {@inheritDoc} */ - public String getInceptionYear() - { + public String getInceptionYear() { return "2006"; } /** {@inheritDoc} */ - public Build getBuild() - { + public Build getBuild() { Build build = new Build(); - build.setDirectory( PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/multi" ); + build.setDirectory(PlexusTestCase.getBasedir() + "/target/test-harness/checkstyle/multi"); return build; } /** {@inheritDoc} */ - public File getFile() - { - File file = new File( getBasedir(), "pom.xml" ); + public File getFile() { + File file = new File(getBasedir(), "pom.xml"); return file; }