aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAurimas Liutikas <aurimas@google.com>2018-01-27 17:00:40 -0800
committerAurimas Liutikas <aurimas@google.com>2018-01-27 17:01:41 -0800
commit0d3be72607b72301b708dca56e3afc3299fd2126 (patch)
treee58fd83708211220003af021e3345f001413cc48
parentb4aec831a096b89efed151c9b2c5754d9491e6ea (diff)
parent5f62e6406680bb91ef505b9a1932e398bf42532d (diff)
downloadcheckstyle-master.tar.gz
Merge Checkstyle 8.7 into aosp/masterHEADmastermain
Merged commit 5f62e6406680bb91ef505b9a1932e398bf42532d Test: None
-rwxr-xr-x.ci/check-only-javadoc-error.sh2
-rwxr-xr-x.ci/idea_inspection.sh4
-rwxr-xr-x.ci/run-link-check-plugin.sh2
-rwxr-xr-x.ci/sonar.sh2
-rwxr-xr-x.ci/travis/travis.sh76
-rwxr-xr-x.ci/travis/xtr_releasenotes-gen.sh4
-rwxr-xr-x.ci/wercker.sh200
-rw-r--r--.travis.yml48
-rw-r--r--README.md4
-rw-r--r--appveyor.yml3
-rw-r--r--circle.yml6
-rw-r--r--config/ant-phase-verify.xml2
-rw-r--r--config/catalog.xml2
-rw-r--r--config/checkstyle_checks.xml12
-rw-r--r--config/findbugs-exclude.xml67
-rw-r--r--config/import-control.xml10
-rw-r--r--config/intellij-idea-inspections.xml5
-rw-r--r--config/pmd-test.xml1
-rw-r--r--config/pmd.xml4
-rw-r--r--config/suppressions-xpath.xml21
-rw-r--r--config/suppressions.xml16
-rw-r--r--config/version-number-rules.xml31
-rw-r--r--distelli-manifest.yml2
-rw-r--r--pom.xml137
-rwxr-xr-xrelease.sh6
-rw-r--r--shippable.yml75
-rw-r--r--src/it/java/com/google/checkstyle/test/base/AbstractModuleTestSupport.java27
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/Checker.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java27
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java12
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/FileStatefulCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/GlobalStatefulCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java3
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java8
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.java8
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java22
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java (renamed from src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractLoader.java)14
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java25
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java5
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/Context.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java14
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java1
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java17
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java24
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java7
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java122
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java24
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java26
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java8
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java19
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java3
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java12
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.java1
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.java9
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java8
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java8
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java5
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java42
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java349
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java6
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java4
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java51
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilter.java48
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtility.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.java50
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java2
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtils.java45
-rw-r--r--src/main/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtils.java7
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_zh.properties3
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/messages_zh.properties6
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd18
-rw-r--r--src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd25
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java36
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java18
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java18
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java171
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java8
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java13
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java125
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java38
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java202
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/XmlLoaderTest.java (renamed from src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractLoaderTest.java)12
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java8
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java9
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java6
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java12
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java21
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java25
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java15
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java65
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java20
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java25
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java55
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java54
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java55
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java8
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java37
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java18
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java18
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java36
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java7
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java21
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java11
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java59
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java6
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java10
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java55
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java487
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java14
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java13
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java32
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java48
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java8
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java9
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java2
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java8
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java7
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java6
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java14
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java16
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java3
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java58
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java5
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java1
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java28
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java14
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java46
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java63
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java4
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java9
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java45
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java82
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java6
-rw-r--r--src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/fallthrough/InputFallThrough.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalType.java2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/modifiedcontrolvariable/InputModifiedControlVariableBothForLoops.java10
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/multiplevariabledeclarations/InputMultipleVariableDeclarations.java4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/nestedfordepth/InputNestedForDepth.java3
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineSingleLine.java7
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/parameterassignment/InputParameterAssignmentWithUnchecked.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisAnnotationInterface.java9
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisCatchVariables.java40
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumConstant.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumInnerClassesAndBugs.java40
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisFor.java23
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMethodReferences.java (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMetodReferences.java)6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/returncount/InputReturnCountVoid.java8
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/unnecessaryparentheses/InputUnnecessaryParenthesesOperatorsAndCasts.java8
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistance.java11
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceAnonymous.java22
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceLabels.java22
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMethodWithAnnotation.java (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMwthodWithAnnotation.java)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderCompareImports.java10
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderFindBetterPatternMatch.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetition.java (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetiton.java)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative2.java15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeparated.java (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeperated.java)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationAnnotationIncorrect.java24
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java20
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPosition.java39
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPositionWithSinglelineComments.java26
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodTags.java8
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/nonemptyatclausedescription/InputNonEmptyAtclauseDescription.java27
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/booleanexpressioncomplexity/InputBooleanExpressionComplexity.java12
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityPackageName.java7
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/npathcomplexity/InputNPathComplexityDefault.java13
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierFinalInEnumStaticMethods.java16
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameEqualClassName.java4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverriddenMethods.java (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverridenMethods.java)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/ExpectedTranslationLog.xml15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckLinux.xml15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckMacOS.xml15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckWindows.xml15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfter.java4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations.java4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations2.java8
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistentProperty.xml (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistingProperty.xml)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderMultiple.xml5
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderXpathCorrect.xml5
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.js7
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.properties4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.sql5
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.xml11
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java15
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterSuppressById.java16
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java14
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java12
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname-ignore.xml (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname-ignore.xml)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname.xml (renamed from src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname.xml)2
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnAnnotationField.java25
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnMethod.java7
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLogger.xml5
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerEmpty.xml3
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerError.xml6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorModuleId.xml4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorNullFileName.xml4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorZeroColumn.xml6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException.xml4
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException2.xml6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException3.xml6
-rw-r--r--src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerExceptionNullFileName.xml4
-rw-r--r--src/xdocs/config.xml14
-rw-r--r--src/xdocs/config_coding.xml4
-rw-r--r--src/xdocs/config_filters.xml542
-rw-r--r--src/xdocs/config_javadoc.xml62
-rw-r--r--src/xdocs/index.xml.vm6
-rw-r--r--src/xdocs/releasenotes.xml125
-rw-r--r--src/xdocs/writingjavadocchecks.xml.vm63
-rw-r--r--wercker.yml212
278 files changed, 4919 insertions, 1315 deletions
diff --git a/.ci/check-only-javadoc-error.sh b/.ci/check-only-javadoc-error.sh
index 78fc12819..ad0e48053 100755
--- a/.ci/check-only-javadoc-error.sh
+++ b/.ci/check-only-javadoc-error.sh
@@ -7,7 +7,7 @@ set -e
uname -a
mvn --version
-mvn clean install -Pno-validations
+mvn -e clean install -Pno-validations
git clone https://github.com/checkstyle/contribution && cd contribution/checkstyle-tester
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties
diff --git a/.ci/idea_inspection.sh b/.ci/idea_inspection.sh
index a548569f7..b85a8402c 100755
--- a/.ci/idea_inspection.sh
+++ b/.ci/idea_inspection.sh
@@ -29,7 +29,7 @@ if [[ -z $IDEA_PATH ]]; then
fi
#Execute compilation of Checkstyle to generate all source files
-mvn compile
+mvn -e compile
mkdir -p $RESULTS_DIR
rm -rf $RESULTS_DIR/*
@@ -42,7 +42,7 @@ echo $IDEA_OUTPUT
if [[ $IDEA_OUTPUT == "Already running" ]]; then
echo "It might be that Intellij Idea is running, please close it."
exit 1;
-else
+fi
echo "Checking results ..."
if [[ $(grep -R "<problems" $RESULTS_DIR/ | cat | wc -l ) > 0 ]]; then
diff --git a/.ci/run-link-check-plugin.sh b/.ci/run-link-check-plugin.sh
index 434df02a6..c6bac1397 100755
--- a/.ci/run-link-check-plugin.sh
+++ b/.ci/run-link-check-plugin.sh
@@ -8,7 +8,7 @@ set -e
uname -a
mvn --version
curl -I https://sourceforge.net/projects/checkstyle/
-mvn clean site -Dcheckstyle.ant.skip=true -DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dcheckstyle.skip=true
+mvn -e clean site -Dcheckstyle.ant.skip=true -DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dcheckstyle.skip=true
echo "------------ grep of linkcheck.html--BEGIN"
# "grep ... | cat" is required command is running in "set -e" mode and grep could return exit code 1 if nothing is matching
grep externalLink target/site/linkcheck.html | cat
diff --git a/.ci/sonar.sh b/.ci/sonar.sh
index 9172697e4..e594b4ac1 100755
--- a/.ci/sonar.sh
+++ b/.ci/sonar.sh
@@ -4,7 +4,7 @@
curl -X POST -u admin:admin -F 'backup=@config/default_sonar_profile.xml' -v http://localhost:9000/api/profiles/restore
#execute inspection
-mvn sonar:sonar -P sonar -Dsonar.language=java -Dsonar.profile=checksyle-profile
+mvn -e sonar:sonar -P sonar -Dsonar.language=java -Dsonar.profile=checksyle-profile
# Uncomment following to get HTML report.
# mvn sonar:sonar -Dsonar.analysis.mode=preview -Dsonar.issuesReport.html.enable=true \
diff --git a/.ci/travis/travis.sh b/.ci/travis/travis.sh
index 474703c5b..8de2b864f 100755
--- a/.ci/travis/travis.sh
+++ b/.ci/travis/travis.sh
@@ -5,17 +5,37 @@ set -e
case $1 in
nondex)
- mvn --fail-never clean nondex:nondex -DargLine='-Xms1024m -Xmx2048m'
+ mvn -e --fail-never clean nondex:nondex -DargLine='-Xms1024m -Xmx2048m'
cat `grep -RlE 'td class=.x' .nondex/ | cat` < /dev/null > output.txt
RESULT=$(cat output.txt | wc -c)
cat output.txt
echo 'Size of output:'$RESULT
- if [[ $RESULT != 0 ]]; then false; fi
+ if [[ $RESULT != 0 ]]; then sleep 5s; false; fi
+ ;;
+
+versions)
+ if [[ -v TRAVIS_EVENT_TYPE && $TRAVIS_EVENT_TYPE != "cron" ]]; then exit 0; fi
+ mvn -e clean versions:dependency-updates-report versions:plugin-updates-report
+ if [ $(grep "<nextVersion>" target/*-updates-report.xml | cat | wc -l) -gt 0 ]; then
+ echo "Version reports (dependency-updates-report.xml):"
+ cat target/dependency-updates-report.xml
+ echo "Version reports (plugin-updates-report.xml):"
+ cat target/plugin-updates-report.xml
+ echo "New dependency versions:"
+ grep -B 7 -A 7 "<nextVersion>" target/dependency-updates-report.xml | cat
+ echo "New plugin versions:"
+ grep -B 4 -A 7 "<nextVersion>" target/plugin-updates-report.xml | cat
+ echo "Verification is failed."
+ sleep 5s
+ false
+ else
+ echo "No new versions found"
+ fi
;;
assembly-run-all-jar)
- mvn clean package -Passembly
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ mvn -e clean package -Passembly
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
echo version:$CS_POM_VERSION
java -jar target/checkstyle-$CS_POM_VERSION-all.jar -c /google_checks.xml \
src/it/resources/com/google/checkstyle/test/chapter3filestructure/rule332nolinewrap/InputNoLineWrapGood.java > output.log
@@ -26,10 +46,11 @@ assembly-run-all-jar)
sonarqube)
# token could be generated at https://sonarcloud.io/account/security/
# executon on local: SONAR_TOKEN=xxxxxxxxxx ./.ci/travis/travis.sh sonarqube
- if [[ $TRAVIS_PULL_REQUEST && $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi
+ if [[ -v TRAVIS_PULL_REQUEST && $TRAVIS_PULL_REQUEST && $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi
+ if [[ -z $SONAR_TOKEN ]]; then echo "SONAR_TOKEN is not set"; sleep 5s; exit 1; fi
export MAVEN_OPTS='-Xmx2000m'
- mvn clean package cobertura:cobertura sonar:sonar \
- -Dsonar.host.url=https://sonarqube.com \
+ mvn -e clean package cobertura:cobertura sonar:sonar \
+ -Dsonar.host.url=https://sonarcloud.io \
-Dsonar.login=$SONAR_TOKEN \
-Dcobertura.report.format=xml -Dmaven.test.failure.ignore=true \
-Dcheckstyle.skip=true -Dpmd.skip=true -Dcheckstyle.ant.skip=true
@@ -37,7 +58,7 @@ sonarqube)
release-dry-run)
if [ $(git log -1 | grep -E "\[maven-release-plugin\] prepare release" | cat | wc -l) -lt 1 ]; then
- mvn release:prepare -DdryRun=true --batch-mode -Darguments='-DskipTests -DskipITs \
+ mvn -e release:prepare -DdryRun=true --batch-mode -Darguments='-DskipTests -DskipITs \
-Dcobertura.skip=true -Dpmd.skip=true -Dfindbugs.skip=true -Dxml.skip=true \
-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true -Dgpg.skip=true'
fi
@@ -68,9 +89,9 @@ all-sevntu-checks)
;;
no-error-test-sbe)
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
echo version:$CS_POM_VERSION
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
git clone https://github.com/real-logic/simple-binary-encoding.git
cd simple-binary-encoding
git checkout 963814f8ca1456de9daaf67e78663e7d877871a9
@@ -85,7 +106,7 @@ no-exception-test-checkstyle-sevntu-checkstyle)
sed -i.'' 's/#checkstyle/checkstyle/' projects-to-test-on.properties
sed -i.'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -97,7 +118,7 @@ no-exception-test-guava)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -109,7 +130,7 @@ no-exception-test-guava-with-google-checks)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
sed -i.'' 's/warning/ignore/' src/main/resources/google_checks.xml
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
@@ -122,7 +143,7 @@ no-exception-test-hibernate)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -134,7 +155,7 @@ no-exception-test-findbugs)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#findbugs/findbugs/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -146,7 +167,7 @@ no-exception-test-spring-framework)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -158,7 +179,7 @@ no-exception-test-hbase)
sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -172,7 +193,7 @@ no-exception-test-Pmd-elasticsearch-lombok-ast)
sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties
sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -189,7 +210,7 @@ no-exception-test-alot-of-project1)
sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties
sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties
cd ../../
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
cd contribution/checkstyle-tester
export MAVEN_OPTS="-Xmx2048m"
groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
@@ -197,14 +218,18 @@ no-exception-test-alot-of-project1)
cobertura-check)
set +e
- mvn clean compile cobertura:cobertura cobertura:check -DargLine='-Xms1024m -Xmx2048m' > mvn-log.log
+ echo "Output and Error output will be redirected to mvn-log.log file ..."
+ mvn -e clean compile cobertura:cobertura cobertura:check -DargLine='-Xms1024m -Xmx2048m' &> mvn-log.log
+ echo "Printing mvn-log.log file:"
cat mvn-log.log
+ sleep 5s
set -e
echo "Grep for hidden errors (due to quiet=true mode in pom.xml):"
grep -R "<td class=\"nbHitsUncovered\"" target/site/cobertura/* --exclude=*grammars* | cat > mvn-log-grep.log
cat mvn-log-grep.log
if [[ $(cat mvn-log-grep.log | wc -l) -gt 0 ]]; then
- exit 1
+ sleep 5s
+ false
fi
echo "Checking that all classes are covered:"
xmlstarlet sel -t -m "//class" -v "@name" -n target/site/cobertura/coverage.xml | sed "s/\./\//g" | sed "/^$/d" | sort | uniq > cobertura_classes.log
@@ -215,22 +240,23 @@ cobertura-check)
sed -i'' "s/com\/puppycrawl\/tools\/checkstyle\/gui\/BaseCellEditor/\ncom\/puppycrawl\/tools\/checkstyle\/gui\/BaseCellEditor/" cobertura_excluded_classes.log
grep -Fxvf cobertura_classes.log target_classes.log > missed_classes_with_excludes.log
grep -Fvf cobertura_excluded_classes.log missed_classes_with_excludes.log > missed_classes_without_excludes.log | cat > output.log
- echo "output.log"
+ echo "output.log content:"
cat output.log
if [[ -s missed_classes_without_excludes.log ]] ; then
echo "Classes which are missed in Cobertura coverage report:"
cat missed_classes_without_excludes.log
- exit 1;
+ sleep 5s
+ false
else
echo "All classes are present in Cobertura coverage report."
- exit 0;
fi
;;
*)
echo "Unexpected argument: $1"
- exit 1
+ sleep 5s
+ false
;;
esac
diff --git a/.ci/travis/xtr_releasenotes-gen.sh b/.ci/travis/xtr_releasenotes-gen.sh
index 6b1af3cfd..c7f48fcb9 100755
--- a/.ci/travis/xtr_releasenotes-gen.sh
+++ b/.ci/travis/xtr_releasenotes-gen.sh
@@ -5,14 +5,14 @@ set -e
if [[ $TRAVIS_PULL_REQUEST =~ ^([0-9]*)$ ]]; then exit 0; fi
git clone https://github.com/checkstyle/contribution
cd contribution/releasenotes-builder
-mvn clean compile package
+mvn -e clean compile package
cd ../../
# we need to do full clone as Travis do "git clone --depth=50"
git clone https://github.com/checkstyle/checkstyle
cd checkstyle
LATEST_RELEASE_TAG=$(git describe $(git rev-list --tags --max-count=1))
cd ../
-CS_RELEASE_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | sed 's/-SNAPSHOT//' )
+CS_RELEASE_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | sed 's/-SNAPSHOT//' )
echo LATEST_RELEASE_TAG=$LATEST_RELEASE_TAG
echo CS_RELEASE_VERSION=$CS_RELEASE_VERSION
java -jar contribution/releasenotes-builder/target/releasenotes-builder-1.0-all.jar \
diff --git a/.ci/wercker.sh b/.ci/wercker.sh
new file mode 100755
index 000000000..0de1a200e
--- /dev/null
+++ b/.ci/wercker.sh
@@ -0,0 +1,200 @@
+#!/bin/bash
+# Attention, there is no "-x" to avoid problems on Wercker
+set -e
+
+case $1 in
+
+no-error-pgjdbc)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/pgjdbc/pgjdbc.git && break || sleep 15; done
+ cd pgjdbc/pgjdbc
+ mvn -e checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
+ cd ../../
+ rm -rf pgjdbc
+ ;;
+
+no-error-orekit)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/Hipparchus-Math/hipparchus.git && break || sleep 15; done
+ cd hipparchus
+ git checkout 905006092493e350dcd68dd7b2ec1dedaf4983b7
+ mvn -e clean install -DskipTests
+ cd ../
+ for i in 1 2 3 4 5; do git clone https://github.com/CS-SI/Orekit.git && break || sleep 15; done
+ cd Orekit
+ # Orekit use 'develop' branch as target for PullRequest merges
+ git checkout develop
+ mvn -e compile checkstyle:check -Dorekit.checkstyle.version=${CS_POM_VERSION}
+ cd ../
+ rm -rf hipparchus Orekit
+ ;;
+
+no-error-xwiki)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/xwiki/xwiki-commons/ && break || sleep 15; done
+ cd xwiki-commons
+ git checkout 44b0c0048c516dae20cf5f8a71181af836549484
+ mvn -e install -DskipTests -Dxwiki.clirr.skip=true checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
+ cd ../../
+ rm -rf xwiki-commons
+ ;;
+
+no-error-apex-core)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/apache/incubator-apex-core/ && break || sleep 15; done
+ cd incubator-apex-core
+ mvn -e compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
+ cd ../
+ rm -rf incubator-apex-core
+ ;;
+
+no-error-hibernate-search)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/hibernate/hibernate-search.git && break || sleep 15; done
+ cd hibernate-search
+ mvn -e -s settings-example.xml clean install -DskipTests=true -Dtest.elasticsearch.host.provided=true -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION}
+ mvn -e -s settings-example.xml checkstyle:check -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION}
+ cd ../
+ rm -rf hibernate-search
+ ;;
+
+no-error-htmlunit)
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ echo "checkouting project sources ..."
+ svn -q export https://svn.code.sf.net/p/htmlunit/code/trunk/htmlunit@r14923 htmlunit
+ cd htmlunit
+ sed -i "s/ <version>2.28-SNAPSHOT/ <version>2.28-20171106.080245-12/" pom.xml
+ echo "Running checkstyle validation ..."
+ mvn -e compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
+ cd ../
+ rm -rf htmlunit
+ ;;
+
+no-error-checkstyles-sevntu)
+ set -e
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ mvn -e compile verify -Dmaven.sevntu-checkstyle-check.checkstyle.version=${CS_POM_VERSION} -Dmaven.test.skip=true -Dcheckstyle.ant.skip=true -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dforbiddenapis.skip=true -Dxml.skip=true
+ ;;
+
+no-error-sevntu-checks)
+ set -e
+ CS_POM_VERSION=$(mvn -e -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
+ echo CS_version: ${CS_POM_VERSION}
+ for i in 1 2 3 4 5; do git clone https://github.com/sevntu-checkstyle/sevntu.checkstyle && break || sleep 15; done
+ cd sevntu.checkstyle/sevntu-checks
+ mvn -e -Pno-validations verify -Dcheckstyle.skip=false -Dcheckstyle.version=${CS_POM_VERSION} -Dcheckstyle.configLocation=../../config/checkstyle_checks.xml
+ ;;
+
+no-exception-struts)
+ for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
+ cd contribution/checkstyle-tester
+ sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
+ sed -i'' 's/#apache-struts/apache-struts/' projects-for-wercker.properties
+ groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-checkstyle-sevntu)
+ set -e
+ for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
+ cd contribution/checkstyle-tester
+ sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
+ sed -i'' 's/#checkstyle/checkstyle/' projects-for-wercker.properties
+ sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-for-wercker.properties
+ groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-guava)
+ for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
+ cd contribution/checkstyle-tester
+ sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
+ sed -i'' 's/#guava/guava/' projects-for-wercker.properties
+ groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-hibernate-orm)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#hibernate-orm/hibernate-orm/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-findbugs)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#findbugs/findbugs/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-spring-framework)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#spring-framework/spring-framework/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-hbase)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#Hbase/Hbase/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-Pmd-elasticsearch-lombok-ast)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#pmd/pmd/' projects-to-test-on.properties
+ sed -i.'' 's/#elasticsearch/elasticsearch/' projects-to-test-on.properties
+ sed -i.'' 's/#lombok-ast/lombok-ast/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+no-exception-alot-of-projects)
+ git clone https://github.com/checkstyle/contribution
+ cd contribution/checkstyle-tester
+ sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties
+ sed -i.'' 's/#RxJava/RxJava/' projects-to-test-on.properties
+ sed -i.'' 's/#java-design-patterns/java-design-patterns/' projects-to-test-on.properties
+ sed -i.'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-to-test-on.properties
+ sed -i.'' 's/#apache-ant/apache-ant/' projects-to-test-on.properties
+ sed -i.'' 's/#apache-jsecurity/apache-jsecurity/' projects-to-test-on.properties
+ sed -i.'' 's/#android-launcher/android-launcher/' projects-to-test-on.properties
+ groovy ./launch.groovy --listOfProjects projects-to-test-on.properties --config checks-nonjavadoc-error.xml
+ cd ../../
+ rm -rf contribution
+ ;;
+
+*)
+ echo "Unexpected argument: $1"
+ sleep 5s
+ false
+ ;;
+
+esac
diff --git a/.travis.yml b/.travis.yml
index ee0a9c8bc..44478c705 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -18,11 +18,7 @@ branches:
- master
install:
- - |
- if [ "${TRAVIS_OS_NAME}" == "osx" ]; then
- # https://github.com/travis-ci/travis-ci/issues/6307#issuecomment-233315824
- rvm get head
- fi
+ -
matrix:
fast_finish: true
@@ -36,14 +32,14 @@ matrix:
- jdk: oraclejdk8
env:
- DESC="tests and deploy"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Xms1024m -Xmx2048m'"
- DEPLOY="true"
# checkstyle (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="checkstyle and sevntu-checkstyle"
- - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn clean verify -DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true"
+ - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn -e clean verify -DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true"
# cobertura and codecov (oraclejdk8)
- jdk: oraclejdk8
@@ -56,13 +52,13 @@ matrix:
- jdk: oraclejdk8
env:
- DESC="findbugs,spotbugs,pmd"
- - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn clean compile pmd:check findbugs:check spotbugs:check"
+ - CMD="export MAVEN_OPTS='-Xmx2000m' && mvn -e clean compile pmd:check findbugs:check spotbugs:check"
# eclipse static analysis
- jdk: oraclejdk8
env:
- DESC="eclipse static analysis"
- - CMD="mvn clean compile exec:exec -Peclipse-compiler"
+ - CMD="mvn -e clean compile exec:exec -Peclipse-compiler"
# Releasenotes generation - validaton
- jdk: oraclejdk8
@@ -81,7 +77,7 @@ matrix:
#- jdk: oraclejdk8
# env:
# - DESC="site"
- # - CMD1="mvn clean site -Dlinkcheck.skip=true -DskipTests -DskipITs "
+ # - CMD1="mvn -e clean site -Dlinkcheck.skip=true -DskipTests -DskipITs "
# - CMD2=" -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true "
# - CMD3=" -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true"
# - CMD=$CMD1$CMD2$CMD3
@@ -91,42 +87,42 @@ matrix:
- jdk: oraclejdk8
env:
- DESC="tests de"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=de -Duser.country=DE -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=de -Duser.country=DE -Xms1024m -Xmx2048m'"
# unit tests in Spanish locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests es"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=es -Duser.country=ES -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=es -Duser.country=ES -Xms1024m -Xmx2048m'"
# unit tests in Finnish locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests fi"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=fi -Duser.country=FI -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=fi -Duser.country=FI -Xms1024m -Xmx2048m'"
# unit tests in French locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests fr"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=fr -Duser.country=FR -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=fr -Duser.country=FR -Xms1024m -Xmx2048m'"
# unit tests in Chinese locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests zh"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=zh -Duser.country=CN -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=zh -Duser.country=CN -Xms1024m -Xmx2048m'"
# unit tests in Japanese locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests ja"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=ja -Duser.country=JP -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=ja -Duser.country=JP -Xms1024m -Xmx2048m'"
# unit tests in Portuguese locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests pt"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=pt -Duser.country=PT -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=pt -Duser.country=PT -Xms1024m -Xmx2048m'"
# unit tests in Turkish locale (oraclejdk8)
- jdk: oraclejdk8
env:
- DESC="tests tr"
- - CMD="mvn clean integration-test failsafe:verify -DargLine='-Duser.language=tr -Duser.country=TR -Xms1024m -Xmx2048m'"
+ - CMD="mvn -e clean integration-test failsafe:verify -DargLine='-Duser.language=tr -Duser.country=TR -Xms1024m -Xmx2048m'"
# assembly (oraclejdk8)
- jdk: oraclejdk8
@@ -161,12 +157,12 @@ matrix:
- os: osx
env:
- DESC="MacOS verify, site, assembly"
- - CMD="export JAVA_HOME=$(/usr/libexec/java_home) && mvn package -Dlinkcheck.skip=true && mvn package -Passembly "
+ - CMD="export JAVA_HOME=$(/usr/libexec/java_home) && mvn -e package -Dlinkcheck.skip=true && mvn -e package -Passembly "
- # https://sonarqube.com (oraclejdk8)
+ # https://sonarcloud.io (oraclejdk8)
- jdk: oraclejdk8
env:
- - DESC="sonarqube.com"
+ - DESC="sonarcloud.io"
- CMD="./.ci/travis/travis.sh sonarqube"
# No error testing - simple-binary-encoding
@@ -175,8 +171,14 @@ matrix:
- DESC="no error test on simple-binary-encoding"
- CMD="./.ci/travis/travis.sh no-error-test-sbe"
+ # versions to update
+ - jdk: oraclejdk8
+ env:
+ - DESC="print versions to update"
+ - CMD="./.ci/travis/travis.sh versions"
+
script:
- - SKIP_FILES=".github|appveyor.yml|circle.yml|distelli-manifest.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|shippable.yml|wercker.yml|intellij-idea-inspections.xml"
+ - SKIP_FILES=".github|appveyor.yml|circle.yml|distelli-manifest.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|shippable.yml|wercker.yml|wercker.sh|intellij-idea-inspections.xml"
- SKIP_CI=$(if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" | cat | wc -c | sed 's/^ *//' ) > 0 ]]; then echo false; else echo true; fi;)
- echo "SKIP_CI="$SKIP_CI
- |
@@ -208,6 +210,6 @@ after_success:
&& $SKIP_DEPLOY == 'false'
]];
then
- mvn -s config/deploy-settings.xml -Pno-validations deploy;
+ mvn -e -s config/deploy-settings.xml -Pno-validations deploy;
echo "deploy to maven snapshot repository is finished";
fi
diff --git a/README.md b/README.md
index 85850830b..d01f5c5bf 100644
--- a/README.md
+++ b/README.md
@@ -73,8 +73,8 @@ directory.
[appveyor]:https://ci.appveyor.com/project/checkstyle/checkstyle/history
[appveyor img]:https://ci.appveyor.com/api/projects/status/rw6bw3dl9kph6ucc?svg=true
-[sonar]:https://sonarqube.com/dashboard?id=com.puppycrawl.tools%3Acheckstyle
-[sonar img]:https://sonarqube.com/api/badges/measure?key=com.puppycrawl.tools:checkstyle&metric=sqale_debt_ratio
+[sonar]:https://sonarcloud.io/dashboard?id=com.puppycrawl.tools%3Acheckstyle
+[sonar img]:https://sonarcloud.io/api/badges/measure?key=com.puppycrawl.tools:checkstyle&metric=sqale_debt_ratio
[codacy]:https://www.codacy.com/app/checkstyle/checkstyle
[codacy img]:https://api.codacy.com/project/badge/3adf12d434314ba8b38277ea46d3c44b
diff --git a/appveyor.yml b/appveyor.yml
index 5f607ca36..288e0cec6 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -14,7 +14,8 @@ skip_commits:
- release.sh
- RIGHTS.antlr
- shippable.yml
- -wercker.yml
+ - wercker.yml
+ - wercker.sh
clone_depth: 10
branches:
only:
diff --git a/circle.yml b/circle.yml
index 595964e03..2db6ea56e 100644
--- a/circle.yml
+++ b/circle.yml
@@ -7,9 +7,9 @@ dependencies:
pre:
- if [ ! -d groovy-2.4.7 ]; then wget https://dl.bintray.com/groovy/maven/apache-groovy-binary-2.4.7.zip && unzip apache-groovy-binary-2.4.7.zip; fi
- # we to override as 'mvn dependecy:go-ofline' does not download all dependencies
+ # we to override as 'mvn -e dependecy:go-ofline' does not download all dependencies
override:
- - mvn install -Pno-validations
+ - mvn -e install -Pno-validations
- eval $TESTER_DEPENDENCIES
machine:
java:
@@ -45,7 +45,7 @@ machine:
TEST_3: $CMD1$CMD2$TAPESTRY$STORM$CASSANDRA$CMD3
# Test over apache-commons, hadoop, scouter, groovy
TEST_4: $CMD1$CMD2$COMMONS$HADOOP$SCOUTER$GROOVY$CMD3
- SKIP_FILES: ".github|appveyor.yml|.travis.yml|.ci|distelli-manifest.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|shippable.yml|wercker.yml|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
+ SKIP_FILES: ".github|appveyor.yml|.travis.yml|.ci|distelli-manifest.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|shippable.yml|wercker.yml|wercker.sh|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
test:
override:
- if [ $(git diff --name-only HEAD HEAD~1 | grep -vE $SKIP_FILES | wc -c) -gt 0 ] ; then case $CIRCLE_NODE_INDEX in 0) eval $TEST_1 ;; 1) eval $TEST_2 ;; 2) eval $TEST_3 ;; 3) eval $TEST_4 ;; esac; fi:
diff --git a/config/ant-phase-verify.xml b/config/ant-phase-verify.xml
index b9a2331a4..feba93f94 100644
--- a/config/ant-phase-verify.xml
+++ b/config/ant-phase-verify.xml
@@ -38,6 +38,8 @@
<property key="checkstyle.importcontroltest.file" file="config/import-control-test.xml"/>
<property key="checkstyle.suppressions.file"
file="config/suppressions.xml"/>
+ <property key="checkstyle.suppressions-xpath.file"
+ file="config/suppressions-xpath.xml"/>
</checkstyle>
<tstamp>
diff --git a/config/catalog.xml b/config/catalog.xml
index 896f017a7..20ce70769 100644
--- a/config/catalog.xml
+++ b/config/catalog.xml
@@ -8,7 +8,9 @@
<system systemId="http://checkstyle.sourceforge.net/dtds/packages_1_0.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/packages_1_0.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/suppressions_1_0.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_0.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/suppressions_1_1.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_1.dtd"/>
+ <system systemId="http://checkstyle.sourceforge.net/dtds/suppressions_1_2.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/suppressions_1_1_xpath_experimental.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_1_xpath_experimental.dtd"/>
+ <system systemId="http://checkstyle.sourceforge.net/dtds/suppressions_1_2_xpath_experimental.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/import_control_1_0.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_0.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/import_control_1_1.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_1.dtd"/>
<system systemId="http://checkstyle.sourceforge.net/dtds/import_control_1_2.dtd" uri="./../src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/import_control_1_2.dtd"/>
diff --git a/config/checkstyle_checks.xml b/config/checkstyle_checks.xml
index c94e8f5c9..1f5dce734 100644
--- a/config/checkstyle_checks.xml
+++ b/config/checkstyle_checks.xml
@@ -35,6 +35,15 @@
<property name="file" value="${checkstyle.suppressions.file}"/>
</module>
<module name="SuppressWarningsFilter"/>
+ <module name="SuppressWithPlainTextCommentFilter">
+ <!--
+ Use suppressions.xml for suppressions, this is only example.
+ checkFormat will prevent suppression comments from being valid.
+ -->
+ <property name="checkFormat" value="IGNORETHIS"/>
+ <property name="offCommentFormat" value="CSOFF\: .*"/>
+ <property name="onCommentFormat" value="CSON\: .*"/>
+ </module>
<!-- Headers -->
<module name="Header">
@@ -312,6 +321,9 @@
<property name="offCommentFormat" value="CSOFF\: .*"/>
<property name="onCommentFormat" value="CSON\: .*"/>
</module>
+ <module name="SuppressionXpathFilter">
+ <property name="file" value="${checkstyle.suppressions-xpath.file}"/>
+ </module>
<module name="SuppressWithNearbyCommentFilter">
<property name="commentFormat" value="-@cs\[(\w{8,}(\|\w{8,})*)\] \w[\(\)\-\.\'\`\,\:\;\w ]{10,}"/>
<property name="checkFormat" value="$1"/>
diff --git a/config/findbugs-exclude.xml b/config/findbugs-exclude.xml
index 0f4b8a21f..e9898d1df 100644
--- a/config/findbugs-exclude.xml
+++ b/config/findbugs-exclude.xml
@@ -91,16 +91,69 @@
<Bug pattern="NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE" />
</Match>
<Match>
- <!-- Temporary disabled. Have to deal with Javadoc nodes as well
- See https://github.com/checkstyle/checkstyle/issues/3432-->
- <Class name="com.puppycrawl.tools.checkstyle.gui.TreeTable" />
- <Method name="makeCodeSelection"/>
- <Bug pattern="RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT"/>
- </Match>
- <Match>
<!-- false-positive. Bugs reported even though casting is done only after verification using instanceof -->
<Class name="com.puppycrawl.tools.checkstyle.JavadocDetailNodeParser"/>
<Method name="parseJavadocAsDetailNode"/>
<Bug pattern="BC_UNCONFIRMED_CAST_OF_RETURN_VALUE"/>
</Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.Main"/>
+ <Method name="loadProperties"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.PackageNamesLoader"/>
+ <Method name="processFile"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.PropertyCacheFile"/>
+ <Method name="flushAndCloseOutStream"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.PropertyCacheFile"/>
+ <Method name="load"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.checks.header.AbstractHeaderCheck"/>
+ <Method name="loadHeaderFile"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.ant.CheckstyleAntTask"/>
+ <Method name="createOverridingProperties"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.PropertyCacheFile"/>
+ <Method name="persist"/>
+ <Bug pattern="NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.PropertyCacheFile"/>
+ <Method name="persist"/>
+ <Bug pattern="NP_NULL_PARAM_DEREF"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
+ <Method name="getTranslationKeys"/>
+ <Bug pattern="NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH"/>
+ </Match>
+ <Match>
+ <!-- false-positive. See details at https://github.com/checkstyle/checkstyle/pull/5403 -->
+ <Class name="com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheck"/>
+ <Method name="processFiltered"/>
+ <Bug pattern="NP_GUARANTEED_DEREF_ON_EXCEPTION_PATH"/>
+ </Match>
</FindBugsFilter>
diff --git a/config/import-control.xml b/config/import-control.xml
index 126d2fcc3..2a9ce1b7f 100644
--- a/config/import-control.xml
+++ b/config/import-control.xml
@@ -95,11 +95,6 @@
local-only="true"/>
<allow pkg="org.antlr.v4.runtime" local-only="true"/>
- <!-- allowed till https://github.com/checkstyle/checkstyle/issues/3455 -->
- <allow class="com.google.common.io.Closeables" local-only="true"/>
- <allow class="com.google.common.collect.ImmutableCollection" local-only="true"/>
- <allow class="com.google.common.collect.ImmutableMap" local-only="true"/>
-
<allow class="com.puppycrawl.tools.checkstyle.Checker" local-only="true"/>
<!-- allowed till https://github.com/checkstyle/checkstyle/issues/3817 -->
<allow pkg="com.puppycrawl.tools.checkstyle.utils"/>
@@ -120,6 +115,9 @@
<allow class="com.google.common.collect.Multiset.Entry" local-only="true"/>
<allow class="com.google.common.collect.SetMultimap" local-only="true"/>
+ <subpackage name="imports">
+ <allow class="com.puppycrawl.tools.checkstyle.XmlLoader" local-only="true"/>
+ </subpackage>
<subpackage name="indentation">
<allow pkg="java.lang.reflect"/>
</subpackage>
@@ -154,9 +152,11 @@
<allow class="java.lang.ref.WeakReference" local-only="true"/>
<allow class="com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent" local-only="true"/>
<allow class="com.puppycrawl.tools.checkstyle.TreeWalkerFilter" local-only="true"/>
+ <allow class="com.puppycrawl.tools.checkstyle.XmlLoader" local-only="true"/>
<disallow pkg="com\.puppycrawl\.tools\.checkstyle\.checks\.[^.]+" regex="true"/>
<allow pkg="com.puppycrawl.tools.checkstyle.utils"/>
<allow pkg="com.puppycrawl.tools.checkstyle.xpath"/>
+ <allow class="java.nio.charset.StandardCharsets" local-only="true"/>
</subpackage>
<subpackage name="gui" strategyOnMismatch="disallowed">
diff --git a/config/intellij-idea-inspections.xml b/config/intellij-idea-inspections.xml
index c35ca4569..33d284fd8 100644
--- a/config/intellij-idea-inspections.xml
+++ b/config/intellij-idea-inspections.xml
@@ -3,8 +3,7 @@
<option name="myName" value="Checkstyle" />
<inspection_tool class="AbsoluteAlignmentInUserInterface" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="AbstractBeanReferencesInspection" enabled="true" level="WARNING" enabled_by_default="true" />
- <!-- till https://github.com/checkstyle/checkstyle/issues/4716 -->
- <inspection_tool class="AbstractClassExtendsConcreteClass" enabled="false" level="ERROR" enabled_by_default="false" />
+ <inspection_tool class="AbstractClassExtendsConcreteClass" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="AbstractClassNamingConvention" enabled="true" level="WARNING" enabled_by_default="true">
<option name="m_regex" value="[A-Z][A-Za-z\d]*|Check" />
<option name="m_minLength" value="5" />
@@ -2091,8 +2090,6 @@ isolated classes and we cannot put them to separate package as it will affect us
See https://github.com/checkstyle/checkstyle/issues/2285-->
<option value="ProhibitedExceptionThrown" />
<option value="MismatchedQueryAndUpdateOfCollection" />
- <!-- Till https://github.com/checkstyle/checkstyle/issues/3066 -->
- <option value="ProhibitedExceptionCaught" />
<!-- No way to split apart huge if/else branches in test. -->
<option value="IfStatementWithTooManyBranches" />
<!-- we have to catch Exception in Checker and rethrow it -->
diff --git a/config/pmd-test.xml b/config/pmd-test.xml
index a444b6073..13141609c 100644
--- a/config/pmd-test.xml
+++ b/config/pmd-test.xml
@@ -94,6 +94,7 @@
| //ClassOrInterfaceDeclaration[@Image='AstRegressionTest']//MethodDeclarator[@Image='testImpossibleValid']
| //ClassOrInterfaceDeclaration[@Image='AllChecksTest']//MethodDeclarator[@Image='testAllModulesAreReferencedInConfigFile']
| //ClassOrInterfaceDeclaration[@Image='DetailASTTest']//MethodDeclarator[@Image='testTreeStructure']
+ | //ClassOrInterfaceDeclaration[@Image='SuppressWithPlainTextCommentFilterTest']//MethodDeclarator[@Image='testEqualsAndHashCodeOfTagClass']
"/>
</properties>
</rule>
diff --git a/config/pmd.xml b/config/pmd.xml
index cebf840ab..01eb897c9 100644
--- a/config/pmd.xml
+++ b/config/pmd.xml
@@ -184,7 +184,7 @@
<properties>
<!-- Can not change API -->
<property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='AbstractFileSetCheck'
- or @Image='AbstractCheck' or @Image='AbstractJavadocCheck' or @Image='AbstractNode']"/>
+ or @Image='AbstractCheck' or @Image='AbstractJavadocCheck' or @Image='AbstractNode' or @Image='AbstractViolationReporter']"/>
</properties>
</rule>
@@ -264,7 +264,7 @@
<rule ref="rulesets/java/naming.xml/AbstractNaming">
<properties>
<!-- We can not brake compatibility with previous versions -->
- <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='AbstractClassNameCheck']"/>
+ <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='AbstractClassNameCheck' or @Image='AutomaticBean']"/>
</properties>
</rule>
<rule ref="rulesets/java/naming.xml/LongVariable">
diff --git a/config/suppressions-xpath.xml b/config/suppressions-xpath.xml
new file mode 100644
index 000000000..65fba6de6
--- /dev/null
+++ b/config/suppressions-xpath.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0"?>
+
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2_xpath_experimental.dtd">
+
+<suppressions>
+ <!-- Tone down the checking for test code -->
+ <suppress-xpath checks="NPathComplexity"
+ query="/CLASS_DEF[@text='XdocsPagesTest']
+ //METHOD_DEF[@text='validateCheckSection']"/>
+
+ <suppress-xpath checks="CyclomaticComplexity"
+ query="/CLASS_DEF[@text='XdocsPagesTest']//METHOD_DEF"/>
+
+ <!-- Suppressions from PMD configuration-->
+ <!-- JavadocMethodCheck, JavadocStyleCheck, JavadocUtils.getJavadocTags() - deprecated -->
+ <suppress-xpath checks="CyclomaticComplexity"
+ query="/CLASS_DEF[@text='JavadocMethodCheck' or @text='JavadocStyleCheck'
+ or @text='CustomImportOrderCheck']//METHOD_DEF"/>
+</suppressions>
diff --git a/config/suppressions.xml b/config/suppressions.xml
index 1273406df..aeb9c3300 100644
--- a/config/suppressions.xml
+++ b/config/suppressions.xml
@@ -1,8 +1,8 @@
<?xml version="1.0"?>
<!DOCTYPE suppressions PUBLIC
- "-//Puppy Crawl//DTD Suppressions 1.1//EN"
- "http://checkstyle.sourceforge.net/dtds/suppressions_1_1.dtd">
+ "-//Puppy Crawl//DTD Suppressions 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress checks="FileLength"
@@ -21,14 +21,12 @@
files="AbstractClassNameCheck.java"/>
<!-- test should be named as their main class -->
<suppress checks="AbstractClassNameCheck"
- files="AbstractCheckTest.java|AbstractClassNameCheckTest.java|AbstractTypeAwareCheckTest.java|AbstractJavadocCheckTest.java|AbstractViolationReporterTest.java|AbstractFileSetCheckTest.java|AbstractLoaderTest.java|AbstractNodeTest.java"/>
+ files="AbstractCheckTest.java|AbstractClassNameCheckTest.java|AbstractTypeAwareCheckTest.java|AbstractJavadocCheckTest.java|AbstractViolationReporterTest.java|AbstractFileSetCheckTest.java|AbstractNodeTest.java"/>
<!-- Tone down the checking for test code -->
- <suppress checks="CyclomaticComplexity" files="[\\/]XdocsPagesTest\.java"/>
- <suppress checks="NPathComplexity" files="[\\/]XdocsPagesTest\.java"/>
<suppress checks="IllegalCatch" files="[\\/]internal[\\/].*[\\/]\w+Util\.java"/>
<suppress checks="EmptyBlock" files=".*[\\/]src[\\/]test[\\/]"/>
- <suppress checks="Javadoc" files=".*[\\/]src[\\/](test|it)[\\/]"/>
+ <suppress message="Missing a Javadoc comment|Missing package-info.java file|Expected @throws tag for|missing an @author tag" files=".*[\\/]src[\\/](test|it)[\\/]"/>
<suppress checks="MagicNumber" files=".*[\\/]src[\\/](test|it)[\\/]"/>
<suppress checks="AvoidStaticImport" files=".*[\\/]src[\\/](test|it)[\\/]"/>
<suppress checks="ClassDataAbstractionCoupling" files="[\\/]IndentationCheckTest.java$|[\\/]SuppressWithNearbyCommentFilterTest.java$|[\\/]SuppressionCommentFilterTest.java|[\\/]DetailASTTest.java$"/>
@@ -85,12 +83,6 @@
<!-- Should be fixed after moving https://github.com/sevntu-checkstyle/sevntu.checkstyle/blob/master/sevntu-checks/src/main/java/com/github/sevntu/checkstyle/checks/coding/ReturnCountExtendedCheck.java into the main repo, to allow skip guard sentences(or by topLinesToIgnoreCount) -->
<suppress checks="ReturnCount" files="(ConfigurationLoader|LambdaHandler)\.java"/>
- <!-- Suppressions from PMD configuration-->
- <!-- JavadocMethodCheck, JavadocStyleCheck, JavadocUtils.getJavadocTags() - deprecated -->
- <suppress checks="CyclomaticComplexity" files="JavadocMethodCheck\.java"/>
- <suppress checks="CyclomaticComplexity" files="JavadocStyleCheck\.java"/>
- <suppress checks="CyclomaticComplexity" files="CustomImportOrderCheck\.java"/>
-
<!-- HandlerFactory crosses allowed limit for executable statements -->
<suppress checks="ExecutableStatementCount" files="HandlerFactory\.java"/>
</suppressions>
diff --git a/config/version-number-rules.xml b/config/version-number-rules.xml
new file mode 100644
index 000000000..ab7b21a73
--- /dev/null
+++ b/config/version-number-rules.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ruleset xmlns="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ comparisonMethod="maven" xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 https://mojo.codehaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd">
+
+ <ignoreVersions>
+ <ignoreVersion type="regex">.*[-_\.](alpha|Alpha|ALPHA|beta|Beta|BETA|rc|RC|M|EA)[-_\.]?[0-9]?.*</ignoreVersion>
+ </ignoreVersions>
+ <rules>
+ <rule groupId="com.google.guava" artifactId="guava">
+ <ignoreVersions>
+ <ignoreVersion type="regex">.*-android</ignoreVersion>
+ </ignoreVersions>
+ </rule>
+ <rule groupId="antlr" artifactId="antlr">
+ <ignoreVersions>
+ <!-- this is really old version before versioning become semantic -->
+ <ignoreVersion type="regex">20030911</ignoreVersion>
+ </ignoreVersions>
+ </rule>
+ <rule groupId="org.apache.maven.plugins" artifactId="maven-release-plugin">
+ <ignoreVersions>
+ <!-- we use 2.1 version that is defined at our parent
+ http://central.maven.org/maven2/org/sonatype/oss/oss-parent/9/oss-parent-9.pom
+ It is better to use same version as in parent, we have to use such parent
+ to use nexus-staging-maven-plugin to deploy maven central
+ -->
+ <ignoreVersion type="regex">.*</ignoreVersion>
+ </ignoreVersions>
+ </rule>
+ </rules>
+</ruleset>
diff --git a/distelli-manifest.yml b/distelli-manifest.yml
index aa2042a20..283876063 100644
--- a/distelli-manifest.yml
+++ b/distelli-manifest.yml
@@ -2,7 +2,7 @@
checkstyle/checkstyle:
Build:
- set -e
- - SKIP_FILES="appveyor.yml|circle.yml|shippable.yml|.travis.yml|wercker.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
+ - SKIP_FILES="appveyor.yml|circle.yml|shippable.yml|.travis.yml|wercker.yml|wercker.sh|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
- SKIP_CI=$(if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" | cat | wc -c) > 0 ]]; then echo false; else echo true; fi;)
- echo "SKIP_CI="$SKIP_CI
- |
diff --git a/pom.xml b/pom.xml
index 0c1538273..244454d06 100644
--- a/pom.xml
+++ b/pom.xml
@@ -22,7 +22,7 @@
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
- <version>8.5</version>
+ <version>8.7</version>
<packaging>jar</packaging>
<name>checkstyle</name>
@@ -211,22 +211,22 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<projectVersion>${project.version}</projectVersion>
- <antlr4.version>4.7</antlr4.version>
+ <antlr4.version>4.7.1</antlr4.version>
<maven.site.plugin.version>3.6</maven.site.plugin.version>
<maven.findbugs.plugin.version>3.0.5</maven.findbugs.plugin.version>
<maven.spotbugs.plugin.version>3.0.6</maven.spotbugs.plugin.version>
<maven.pmd.plugin.version>3.8</maven.pmd.plugin.version>
<pmd.version>5.8.1</pmd.version>
<maven.jacoco.plugin.version>0.7.9</maven.jacoco.plugin.version>
- <saxon.version>9.8.0-5</saxon.version>
+ <saxon.version>9.8.0-7</saxon.version>
<maven.checkstyle.plugin.version>2.17</maven.checkstyle.plugin.version>
<maven.sevntu.checkstyle.plugin.version>1.25.0</maven.sevntu.checkstyle.plugin.version>
- <maven.sevntu-checkstyle-check.checkstyle.version>8.4</maven.sevntu-checkstyle-check.checkstyle.version>
+ <maven.sevntu-checkstyle-check.checkstyle.version>8.6</maven.sevntu-checkstyle-check.checkstyle.version>
<maven.versions.plugin.version>2.5</maven.versions.plugin.version>
<java.version>1.8</java.version>
<tools.jar.version>${java.version}.0</tools.jar.version>
<tools.jar.path>${java.home}/../lib/tools.jar</tools.jar.path>
- <pitest.plugin.version>1.2.4</pitest.plugin.version>
+ <pitest.plugin.version>1.3.1</pitest.plugin.version>
<pitest.plugin.timeout.factor>10</pitest.plugin.timeout.factor>
<pitest.plugin.timeout.constant>50000</pitest.plugin.timeout.constant>
<pitest.plugin.threads>4</pitest.plugin.threads>
@@ -271,7 +271,7 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
- <version>23.2-jre</version>
+ <version>23.6-jre</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
@@ -290,13 +290,13 @@
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
- <version>1.16.1</version>
+ <version>1.17.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.jqno.equalsverifier</groupId>
<artifactId>equalsverifier</artifactId>
- <version>2.3.3</version>
+ <version>2.4</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -314,13 +314,13 @@
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
- <version>2.5</version>
+ <version>2.6</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
- <version>4.9.0.201710071750-r</version>
+ <version>4.9.2.201712150930-r</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -346,10 +346,50 @@
<build>
<pluginManagement>
<plugins>
+ <!-- from super-pom http://maven.apache.org/ref/3.5.2/maven-model-builder/super-pom.html BEGIN -->
+ <!-- we need to override just make "mvn versions:plugin-updates-report" see no old versions -->
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <version>1.8</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>3.1.0</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <version>3.0.2</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-release-plugin</artifactId>
+ <!-- version is same as in supper-pom as it is better to use same version as in sonatype-nexus-staging -->
+ <version>2.1</version>
+ </plugin>
+ <!-- from super-pom END -->
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>2.7</version>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>sonar-maven-plugin</artifactId>
+ <version>3.4.0.905</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.1.0</version>
+ </plugin>
+ <plugin>
+ <groupId>org.pitest</groupId>
+ <artifactId>pitest-maven</artifactId>
+ <version>${pitest.plugin.version}</version>
+ </plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
- <version>2.10.4</version>
+ <version>3.0.0</version>
<configuration>
<source>${java.version}</source>
<failOnError>true</failOnError>
@@ -680,6 +720,11 @@
<version>${maven.versions.plugin.version}</version>
<configuration>
<generateBackupPoms>false</generateBackupPoms>
+ <rulesUri>file://${basedir}/config/version-number-rules.xml</rulesUri>
+ <formats>
+ <format>xml</format>
+ <format>html</format>
+ </formats>
</configuration>
</plugin>
<plugin>
@@ -1086,8 +1131,7 @@
<!-- generated classes, unfortunately use problematic api -->
<exclude>**/GeneratedJavaLexer.class</exclude>
<exclude>**/JavadocParser.class</exclude>
- <!-- excluded till https://github.com/policeman-tools/forbidden-apis/issues/108-->
- <exclude>**/checks/annotation/annotationlocation/InputAnnotationLocationDeprecatedAndCustom*</exclude>
+ <exclude>**/Input*</exclude>
</excludes>
</configuration>
<executions>
@@ -1148,7 +1192,6 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
- <version>2.7</version>
<reportSets>
<reportSet>
<reports>
@@ -1232,7 +1275,7 @@
<artifactId>maven-report</artifactId>
<version>0.1</version>
<configuration>
- <sonarHostURL>https://sonarqube.com</sonarHostURL>
+ <sonarHostURL>https://sonarcloud.io</sonarHostURL>
</configuration>
</plugin>
@@ -1305,6 +1348,7 @@
<excludedLink>http://search.maven.org/*</excludedLink>
<!-- codehaus does not exists anymore -->
<excludedLink>http://sonar-plugins.codehaus.org/maven-report</excludedLink>
+ <excludedLink>http://www.mojohaus.org/sonar-maven-plugin/sonar-maven-plugin</excludedLink>
<!-- this plugin does not have site at all -->
<excludedLink>http://hazendaz.github.io/findbugs-maven-plugin/</excludedLink>
<!-- SSLHandshakeException but page is opening -->
@@ -1336,7 +1380,7 @@
by sonar's developers. It is not allowed to open issue against sonar's maven report plugin
at sonar's issue tracker: http://jira.codehaus.org/browse/MSONAR
Sonar's mailing lists: http://www.mojohaus.org/sonar-maven-plugin/mail-lists.html-->
- <excludedLink>https://sonarqube.com/project/index/com.puppycrawl.tools:checkstyle</excludedLink>
+ <excludedLink>https://sonarcloud.io/project/index/com.puppycrawl.tools:checkstyle</excludedLink>
<!-- SSL error, skip validating released "-all" jar on sourceforge as it is uploaded after site generation-->
<excludedLink>http://downloads.sourceforge.net/project/checkstyle/checkstyle/*/checkstyle-*-all.jar</excludedLink>
@@ -1348,6 +1392,8 @@
<excludedLink>https://github.com/search*</excludedLink>
<!-- till https://github.com/apache/maven-plugins/pull/81 -->
<excludedLink>http://git-scm.com*</excludedLink>
+ <!-- links works but not in linkcheck -->
+ <excludedLink>https://marketplace.visualstudio.com/items?itemName=shengchen.vscode-checkstyle</excludedLink>
<!-- reason described at https://github.com/checkstyle/checkstyle/issues/3080 -->
<excludedLink>https://www.scm-manager.org/</excludedLink>
@@ -1384,6 +1430,8 @@
<!-- permanent: avax.net.ssl.SSLException : Received fatal alert: internal_error -->
<excludedLink>https://salt.bountysource.com/teams/checkstyle</excludedLink>
<excludedLink>https://www.bountysource.com/teams/checkstyle/issues</excludedLink>
+ <!-- javax.net.ssl.SSLHandshakeException : Received fatal alert: handshake_failure -->
+ <excludedLink>https://eclipse.org</excludedLink>
</excludedLinks>
</configuration>
</plugin>
@@ -1488,7 +1536,6 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
- <version>3.1.0</version>
<executions>
<execution>
<phase>package</phase>
@@ -1521,7 +1568,6 @@
<!-- Creates the binary and source distributions -->
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
- <version>3.1.0</version>
<configuration>
<descriptors>
<descriptor>config/assembly-bin.xml</descriptor>
@@ -1551,7 +1597,6 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
- <version>3.3.0.603</version>
</plugin>
</plugins>
</build>
@@ -1567,7 +1612,6 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
- <version>2.7</version>
<configuration>
<quiet>true</quiet>
<formats>
@@ -1684,7 +1728,8 @@
<param>com.puppycrawl.tools.checkstyle.checks.UniquePropertiesCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.UpperEllCheckTest</param>
</targetTests>
- <mutationThreshold>99</mutationThreshold>
+ <coverageThreshold>100</coverageThreshold>
+ <mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
<threads>${pitest.plugin.threads}</threads>
@@ -1723,6 +1768,7 @@
<param>com.puppycrawl.tools.checkstyle.checks.annotation.PackageAnnotationCheckTest</param>
<param>com.puppycrawl.tools.checkstyle.checks.annotation.SuppressWarningsCheckTest</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1750,6 +1796,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.blocks.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>97</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1777,7 +1824,8 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.coding.*</param>
</targetTests>
- <mutationThreshold>97</mutationThreshold>
+ <coverageThreshold>100</coverageThreshold>
+ <mutationThreshold>98</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
<threads>${pitest.plugin.threads}</threads>
@@ -1804,6 +1852,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.design.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1831,6 +1880,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.header.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1858,6 +1908,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.imports.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>96</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1885,6 +1936,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.indentation.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>94</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1912,6 +1964,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.javadoc.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>95</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1939,7 +1992,8 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.metrics.*</param>
</targetTests>
- <mutationThreshold>97</mutationThreshold>
+ <coverageThreshold>100</coverageThreshold>
+ <mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
<threads>${pitest.plugin.threads}</threads>
@@ -1966,6 +2020,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.modifier.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -1997,6 +2052,7 @@
<!-- deprecated class -->
<param>com.puppycrawl.tools.checkstyle.checks.naming.AbstractTypeParameterNameCheck</param>
</excludedClasses>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2024,6 +2080,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.regexp.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2051,6 +2108,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.sizes.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2078,7 +2136,8 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.checks.whitespace.*</param>
</targetTests>
- <mutationThreshold>99</mutationThreshold>
+ <coverageThreshold>100</coverageThreshold>
+ <mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
<threads>${pitest.plugin.threads}</threads>
@@ -2130,6 +2189,7 @@
<param>com.puppycrawl.tools.checkstyle.doclets.*</param>
<param>com.puppycrawl.tools.checkstyle.ThreadModeSettingsTest</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2154,6 +2214,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.MainTest</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2199,6 +2260,7 @@
to remove all of them as they are chained together, so we just exclude it from pitest check. -->
<param>destroy</param>
</excludedMethods>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2238,8 +2300,9 @@
</excludedMethods>
<avoidCallsTo>
<!--cause of https://github.com/checkstyle/checkstyle/issues/3605-->
- <avoidCallsTo>com.puppycrawl.tools.checkstyle.api.AbstractLoader$FeaturesForVerySecureJavaInstallations</avoidCallsTo>
+ <avoidCallsTo>com.puppycrawl.tools.checkstyle.XmlLoader$FeaturesForVerySecureJavaInstallations</avoidCallsTo>
</avoidCallsTo>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2266,6 +2329,7 @@
<param>com.puppycrawl.tools.checkstyle.filefilters.*</param>
<param>com.puppycrawl.tools.checkstyle.filters.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2289,23 +2353,18 @@
</targetClasses>
<targetTests>
<param>com.puppycrawl.tools.checkstyle.utils.*</param>
- <param>com.puppycrawl.tools.checkstyle.checks.coding.*</param>
+ <!-- 12% mutation in CommonUtils, 3% coverage in CommonUtils, 2% coverage in JavadocUtils -->
<param>com.puppycrawl.tools.checkstyle.AstTreeStringPrinterTest</param>
- <param>com.puppycrawl.tools.checkstyle.ConfigurationLoaderTest</param>
+ <!-- 2% mutation in CommonUtils -->
<param>com.puppycrawl.tools.checkstyle.DetailNodeTreeStringPrinterTest</param>
+ <!-- ModuleReflectionUtils -->
<param>com.puppycrawl.tools.checkstyle.PackageObjectFactoryTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.FinalParametersCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.TranslationCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.blocks.RightCurlyCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.coding.MultipleVariableDeclarationsCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.design.FinalClassCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.javadoc.*</param>
- <param>com.puppycrawl.tools.checkstyle.checks.regexp.RegexpOnFilenameCheckTest</param>
- <param>com.puppycrawl.tools.checkstyle.checks.whitespace.*</param>
- <param>com.puppycrawl.tools.checkstyle.filters.SuppressionCommentFilter</param>
- <param>com.puppycrawl.tools.checkstyle.filters.SuppressWithNearbyCommentFilterTest</param>
- <param>com.puppycrawl.tools.checkstyle.internal.AllChecksTest</param>
+ <!-- 3% coverage in BlockCommentPosition, 11% mutation in JavadocUtils, 10% coverage in JavadocUtils, ScopeUtils -->
+ <param>com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheckTest</param>
+ <param>com.puppycrawl.tools.checkstyle.checks.javadoc.SingleLineJavadocCheckTest</param>
+ <param>com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocVariableCheckTest</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2330,6 +2389,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.gui.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>30</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
@@ -2380,6 +2440,7 @@
<targetTests>
<param>com.puppycrawl.tools.checkstyle.xpath.*</param>
</targetTests>
+ <coverageThreshold>100</coverageThreshold>
<mutationThreshold>100</mutationThreshold>
<timeoutFactor>${pitest.plugin.timeout.factor}</timeoutFactor>
<timeoutConstant>${pitest.plugin.timeout.constant}</timeoutConstant>
diff --git a/release.sh b/release.sh
index 8690ef7bd..2465a4bb4 100755
--- a/release.sh
+++ b/release.sh
@@ -25,10 +25,10 @@ echo "Please provide password for $SF_USER,checkstyle@shell.sourceforge.net"
echo "exit" | ssh -t $SF_USER,checkstyle@shell.sourceforge.net create
# Version bump in pom.xml - https://github.com/checkstyle/checkstyle/commits/master
-mvn -Pgpg release:prepare -B -Darguments="-DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true -Dxml.skip=true"
+mvn -e -Pgpg release:prepare -B -Darguments="-DskipTests -DskipITs -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true -Dxml.skip=true"
# deployment of jars to maven central and publication of site to http://checkstyle.sourceforge.net/new-site/
-mvn -Pgpg release:perform -Darguments='-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true'
+mvn -e -Pgpg release:perform -Darguments='-Dcheckstyle.ant.skip=true -Dcheckstyle.skip=true'
#############################
@@ -53,7 +53,7 @@ EOF
git checkout checkstyle-$RELEASE
#Generate all binaries
-mvn -Passembly clean package
+mvn -e -Passembly clean package
#Publish them to sourceforce
FRS_PATH=/home/frs/project/checkstyle/checkstyle/$RELEASE
diff --git a/shippable.yml b/shippable.yml
index 63c28d088..7b2587940 100644
--- a/shippable.yml
+++ b/shippable.yml
@@ -6,26 +6,26 @@ jdk:
env:
matrix:
- - PROFILE="-Ppitest-checkstyle-xpath,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checkstyle-filters,no-validations"; POST_ACTION=check_survived
+ - PROFILE="-Ppitest-checkstyle-xpath,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checkstyle-filters,no-validations"; POST_ACTION=check_survived_uncovered
- PROFILE="-Ppitest-checks-javadoc,no-validations"
- - PROFILE="-Ppitest-checks-imports,no-validations"; POST_ACTION=check_survived_imports
- - PROFILE="-Ppitest-checks-metrics,no-validations"
- - PROFILE="-Ppitest-checks-regexp,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-sizes,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-whitespace,no-validations"; POST_ACTION=check_survived_whitespace
- - PROFILE="-Ppitest-checks-misc,no-validations"; POST_ACTION=check_survived_misc
+ - PROFILE="-Ppitest-checks-imports,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-metrics,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-regexp,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-sizes,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-whitespace,no-validations"; POST_ACTION=check_survived
+ - PROFILE="-Ppitest-checks-misc,no-validations"; POST_ACTION=check_survived_uncovered
- PROFILE="-Ppitest-checks-blocks,no-validations"; POST_ACTION=check_survived_blocks
- PROFILE="-Ppitest-checks-coding,no-validations"; POST_ACTION=check_survived_coding
- - PROFILE="-Ppitest-checks-design,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-annotation,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-header,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-modifier,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checks-naming,no-validations"; POST_ACTION=check_survived
+ - PROFILE="-Ppitest-checks-design,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-annotation,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-header,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-modifier,no-validations"; POST_ACTION=check_survived_uncovered
+ - PROFILE="-Ppitest-checks-naming,no-validations"; POST_ACTION=check_survived_uncovered
- PROFILE="-Ppitest-checks-indentation,no-validations"
- - PROFILE="-Ppitest-checkstyle-tree-walker,no-validations"; POST_ACTION=check_survived
+ - PROFILE="-Ppitest-checkstyle-tree-walker,no-validations"; POST_ACTION=check_survived_uncovered
- PROFILE="-Ppitest-checkstyle-common,no-validations"; POST_ACTION=check_survived
- - PROFILE="-Ppitest-checkstyle-main,no-validations"; POST_ACTION=check_survived
+ - PROFILE="-Ppitest-checkstyle-main,no-validations"; POST_ACTION=check_survived_uncovered
- PROFILE="-Ppitest-checkstyle-api,no-validations"; POST_ACTION=check_survived
- PROFILE="-Ppitest-checkstyle-utils,no-validations"; POST_ACTION=check_survived
- PROFILE="-Ppitest-checkstyle-gui,no-validations"
@@ -43,31 +43,24 @@ build:
# we skip PRs and commits that are not for Issues, as pitest is too time consuming
- |
set -e
- SKIP_FILES="appveyor.yml|circle.yml|distelli-manifest.yml|.travis.yml|wercker.yml|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
+ SKIP_FILES="appveyor.yml|circle.yml|distelli-manifest.yml|.travis.yml|wercker.yml|wercker.sh|fast-forward-merge.sh|LICENSE|LICENSE.apache20|README.md|release.sh|RIGHTS.antlr|intellij-idea-inspections.xml|org.eclipse.jdt.core.prefs"
SKIP_CI=$(if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" | cat | wc -c) > 0 ]]; then echo false; else echo true; fi;)
echo "SKIP_CI="$SKIP_CI
echo "POST_ACTION="$POST_ACTION
if [[ $SKIP_CI == 'false' ]];
then
- mvn $PROFILE clean verify org.pitest:pitest-maven:mutationCoverage;
+ mvn -e $PROFILE clean verify org.pitest:pitest-maven:mutationCoverage;
- if [[ $POST_ACTION == 'check_survived' && $(grep -RE "class='survived'" target/ | cat | wc -l) > 0 ]]; then
+ if [[ $POST_ACTION == 'check_survived_uncovered' \
+ && ( $(grep -RE "class='survived'" target/ | cat | wc -l) > 0 \
+ || $(grep -RE "class='uncovered'" target/ | cat | wc -l) > 0) ]]; then
echo "Survived items:"$(grep -RE "class='survived'" target/ | cat)
- echo "Survived items found in reports, build will be failed"
- exit 1
- fi
- if [[ $POST_ACTION == 'check_survived_whitespace' && $(grep -RE "class='survived'" --exclude="NoWhitespaceAfterCheck.*" --exclude="ParenPadCheck.*" --exclude="SingleSpaceSeparatorCheck.*" target/ | cat | wc -l) > 0 ]]; then
- echo "Survived items:"$(grep -RE "class='survived'" --exclude="NoWhitespaceAfterCheck.*" --exclude="ParenPadCheck.*" --exclude="SingleSpaceSeparatorCheck.*" target/ | cat)
- echo "Survived items found in reports, build will be failed"
+ echo "Uncovered items:"$(grep -RE "class='uncovered'" target/ | cat)
+ echo "Survived/Uncovered items found in reports, build will be failed"
exit 1
fi
- if [[ $POST_ACTION == 'check_survived_imports' && $(grep -RE "class='survived'" --exclude="CustomImportOrderCheck.*" target/ | cat | wc -l) > 0 ]]; then
- echo "Survived items:"$(grep -RE "class='survived'" --exclude="CustomImportOrderCheck.*" --exclude="ImportOrderCheck.*" target/ | cat)
- echo "Survived items found in reports, build will be failed"
- exit 1
- fi
- if [[ $POST_ACTION == 'check_survived_misc' && $(grep -RE "class='survived'" --exclude="TranslationCheck.*" target/ | cat | wc -l) > 0 ]]; then
- echo "Survived items:"$(grep -RE "class='survived'" --exclude="TranslationCheck.*" target/ | cat)
+ if [[ $POST_ACTION == 'check_survived' && $(grep -RE "class='survived'" target/ | cat | wc -l) > 0 ]]; then
+ echo "Survived items:"$(grep -RE "class='survived'" target/ | cat)
echo "Survived items found in reports, build will be failed"
exit 1
fi
@@ -77,17 +70,17 @@ build:
exit 1
fi
if [[ $POST_ACTION == 'check_survived_coding'
- && $(grep -RE "class='survived'" --exclude="AbstractSuperCheck.*" --exclude="DeclarationOrderCheck.*" --exclude="EqualsAvoidNullCheck.*" \
- --exclude="EqualsHashCodeCheck.*" --exclude="FallThroughCheck.*" --exclude="HiddenFieldCheck.*" --exclude="IllegalInstantiationCheck.*" \
- --exclude="IllegalTokenTextCheck.*" --exclude="IllegalTypeCheck.*" --exclude="MagicNumberCheck.*" --exclude="ModifiedControlVariableCheck.*" \
- --exclude="MultipleStringLiteralsCheck.*" --exclude="MultipleVariableDeclarationsCheck.*" --exclude="NestedForDepthCheck.*" \
- --exclude="OneStatementPerLineCheck.*" --exclude="ParameterAssignmentCheck.*" --exclude="RequireThisCheck.*" --exclude="ReturnCountCheck.*" \
+ && $(grep -RE "class='survived'" --exclude="EqualsAvoidNullCheck.*" \
+ --exclude="FallThroughCheck.*" --exclude="HiddenFieldCheck.*" --exclude="IllegalInstantiationCheck.*" \
+ --exclude="IllegalTypeCheck.*" \
+ --exclude="MultipleVariableDeclarationsCheck.*" \
+ --exclude="RequireThisCheck.*" \
--exclude="UnnecessaryParenthesesCheck.*" --exclude="VariableDeclarationUsageDistanceCheck.*" target/ | cat | wc -l) > 0 ]]; then
- echo "Survived items:"$(grep -RE "class='survived'" --exclude="AbstractSuperCheck.*" --exclude="DeclarationOrderCheck.*" --exclude="EqualsAvoidNullCheck.*" \
- --exclude="EqualsHashCodeCheck.*" --exclude="FallThroughCheck.*" --exclude="HiddenFieldCheck.*" --exclude="IllegalInstantiationCheck.*" \
- --exclude="IllegalTokenTextCheck.*" --exclude="IllegalTypeCheck.*" --exclude="MagicNumberCheck.*" --exclude="ModifiedControlVariableCheck.*" \
- --exclude="MultipleStringLiteralsCheck.*" --exclude="MultipleVariableDeclarationsCheck.*" --exclude="NestedForDepthCheck.*" \
- --exclude="OneStatementPerLineCheck.*" --exclude="ParameterAssignmentCheck.*" --exclude="RequireThisCheck.*" --exclude="ReturnCountCheck.*" \
+ echo "Survived items:"$(grep -RE "class='survived'" --exclude="EqualsAvoidNullCheck.*" \
+ --exclude="FallThroughCheck.*" --exclude="HiddenFieldCheck.*" --exclude="IllegalInstantiationCheck.*" \
+ --exclude="IllegalTypeCheck.*" \
+ --exclude="MultipleVariableDeclarationsCheck.*" \
+ --exclude="RequireThisCheck.*" \
--exclude="UnnecessaryParenthesesCheck.*" --exclude="VariableDeclarationUsageDistanceCheck.*" target/ | cat)
echo "Survived items found in reports, build will be failed"
exit 1
diff --git a/src/it/java/com/google/checkstyle/test/base/AbstractModuleTestSupport.java b/src/it/java/com/google/checkstyle/test/base/AbstractModuleTestSupport.java
index 946f79760..d23a3e099 100644
--- a/src/it/java/com/google/checkstyle/test/base/AbstractModuleTestSupport.java
+++ b/src/it/java/com/google/checkstyle/test/base/AbstractModuleTestSupport.java
@@ -87,7 +87,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* Returns test logger.
* @return logger test logger
*/
- public BriefUtLogger getBriefUtLogger() {
+ public final BriefUtLogger getBriefUtLogger() {
return new BriefUtLogger(stream);
}
@@ -122,7 +122,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @return {@link Checker} instance based on the given {@link Configuration} instance.
* @throws Exception if an exception occurs during checker configuration.
*/
- public Checker createChecker(Configuration moduleConfig)
+ public final Checker createChecker(Configuration moduleConfig)
throws Exception {
if (checkstyleModules == null) {
checkstyleModules = CheckUtil.getCheckstyleModules();
@@ -134,7 +134,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
for (Class<?> moduleClass : checkstyleModules) {
if (moduleClass.getSimpleName().equals(name)
|| moduleClass.getSimpleName().equals(name + "Check")) {
- if (ModuleReflectionUtils.isCheckstyleCheck(moduleClass)
+ if (ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(moduleClass)
|| ModuleReflectionUtils.isTreeWalkerFilterModule(moduleClass)) {
moduleCreationOption = ModuleCreationOption.IN_TREEWALKER;
}
@@ -151,9 +151,9 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param moduleCreationOption {@code IN_TREEWALKER} if the {@code moduleConfig} should be added
* under {@link TreeWalker}.
* @return {@link Checker} instance.
- * @throws CheckstyleException if an exception occurs during checker configuration.
+ * @throws Exception if an exception occurs during checker configuration.
*/
- protected Checker createChecker(Configuration moduleConfig,
+ protected final Checker createChecker(Configuration moduleConfig,
ModuleCreationOption moduleCreationOption)
throws Exception {
final DefaultConfiguration dc;
@@ -183,7 +183,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param config {@link Configuration} instance.
* @return {@link DefaultConfiguration} for the {@link Checker}.
*/
- protected DefaultConfiguration createTreeWalkerConfig(Configuration config) {
+ protected static DefaultConfiguration createTreeWalkerConfig(Configuration config) {
final DefaultConfiguration dc =
new DefaultConfiguration("configuration");
final DefaultConfiguration twConf = createModuleConfig(TreeWalker.class);
@@ -199,7 +199,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param config {@link Configuration} instance.
* @return {@link DefaultConfiguration} for the given {@link Configuration} instance.
*/
- protected DefaultConfiguration createRootConfig(Configuration config) {
+ protected static DefaultConfiguration createRootConfig(Configuration config) {
final DefaultConfiguration dc = new DefaultConfiguration("root");
dc.addChild(config);
return dc;
@@ -218,7 +218,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param warnsExpected an array of expected warning numbers.
* @throws Exception if exception occurs during verification process.
*/
- protected void verify(Configuration config, String fileName, String[] expected,
+ protected final void verify(Configuration config, String fileName, String[] expected,
Integer... warnsExpected) throws Exception {
verify(createChecker(config),
new File[] {new File(fileName)},
@@ -234,7 +234,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param warnsExpected an array of expected warning line numbers.
* @throws Exception if exception occurs during verification process.
*/
- protected void verify(Checker checker,
+ protected final void verify(Checker checker,
File[] processedFiles,
String messageFileName,
String[] expected,
@@ -281,10 +281,12 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
+ * @param aClass The package the message is located in.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
+ * @return The message of the check with the arguments applied.
*/
- protected String getCheckMessage(Class<? extends AbstractViolationReporter> aClass,
+ protected static String getCheckMessage(Class<? extends AbstractViolationReporter> aClass,
String messageKey, Object... arguments) {
String checkMessage;
try {
@@ -302,10 +304,12 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
/**
* Gets the check message 'as is' from appropriate 'messages.properties' file.
+ * @param messages The map of messages to scan.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
+ * @return The message of the check with the arguments applied.
*/
- protected String getCheckMessage(Map<String, String> messages, String messageKey,
+ protected static String getCheckMessage(Map<String, String> messages, String messageKey,
Object... arguments) {
String checkMessage = null;
for (Map.Entry<String, String> entry : messages.entrySet()) {
@@ -333,6 +337,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* Returns {@link Configuration} instance for the given module name.
* This implementation uses {@link AbstractModuleTestSupport#getConfiguration()} method inside.
* @param moduleName module name.
+ * @param moduleId module id.
* @return {@link Configuration} instance for the given module name.
* @throws CheckstyleException if exception occurs during configuration loading.
*/
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/Checker.java b/src/main/java/com/puppycrawl/tools/checkstyle/Checker.java
index 80cff6205..9ecc9eff1 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/Checker.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/Checker.java
@@ -413,7 +413,7 @@ public class Checker extends AutomaticBean implements MessageDispatcher, RootMod
}
@Override
- public void finishLocalSetup() throws CheckstyleException {
+ protected void finishLocalSetup() throws CheckstyleException {
final Locale locale = new Locale(localeLanguage, localeCountry);
LocalizedMessage.setLocale(locale);
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
index c37302c5f..059e93c98 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/ConfigurationLoader.java
@@ -40,7 +40,6 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
-import com.puppycrawl.tools.checkstyle.api.AbstractLoader;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Configuration;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
@@ -76,7 +75,7 @@ public final class ConfigurationLoader {
"-//Puppy Crawl//DTD Check Configuration 1.0//EN";
/** The resource for version 1_0 of the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_0 =
+ private static final String DTD_CONFIGURATION_NAME_1_0 =
"com/puppycrawl/tools/checkstyle/configuration_1_0.dtd";
/** The public ID for version 1_1 of the configuration dtd. */
@@ -84,7 +83,7 @@ public final class ConfigurationLoader {
"-//Puppy Crawl//DTD Check Configuration 1.1//EN";
/** The resource for version 1_1 of the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_1 =
+ private static final String DTD_CONFIGURATION_NAME_1_1 =
"com/puppycrawl/tools/checkstyle/configuration_1_1.dtd";
/** The public ID for version 1_2 of the configuration dtd. */
@@ -92,7 +91,7 @@ public final class ConfigurationLoader {
"-//Puppy Crawl//DTD Check Configuration 1.2//EN";
/** The resource for version 1_2 of the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_2 =
+ private static final String DTD_CONFIGURATION_NAME_1_2 =
"com/puppycrawl/tools/checkstyle/configuration_1_2.dtd";
/** The public ID for version 1_3 of the configuration dtd. */
@@ -100,7 +99,7 @@ public final class ConfigurationLoader {
"-//Puppy Crawl//DTD Check Configuration 1.3//EN";
/** The resource for version 1_3 of the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_3 =
+ private static final String DTD_CONFIGURATION_NAME_1_3 =
"com/puppycrawl/tools/checkstyle/configuration_1_3.dtd";
/** Prefix for the exception when unable to parse resource. */
@@ -166,10 +165,10 @@ public final class ConfigurationLoader {
*/
private static Map<String, String> createIdToResourceNameMap() {
final Map<String, String> map = new HashMap<>();
- map.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0);
- map.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1);
- map.put(DTD_PUBLIC_ID_1_2, DTD_RESOURCE_NAME_1_2);
- map.put(DTD_PUBLIC_ID_1_3, DTD_RESOURCE_NAME_1_3);
+ map.put(DTD_PUBLIC_ID_1_0, DTD_CONFIGURATION_NAME_1_0);
+ map.put(DTD_PUBLIC_ID_1_1, DTD_CONFIGURATION_NAME_1_1);
+ map.put(DTD_PUBLIC_ID_1_2, DTD_CONFIGURATION_NAME_1_2);
+ map.put(DTD_PUBLIC_ID_1_3, DTD_CONFIGURATION_NAME_1_3);
return map;
}
@@ -224,7 +223,7 @@ public final class ConfigurationLoader {
* 'ignore' should be omitted, {@code false} otherwise
* @return the check configurations
* @throws CheckstyleException if an error occurs
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter
*/
@Deprecated
@@ -245,7 +244,7 @@ public final class ConfigurationLoader {
* @param threadModeSettings the thread mode configuration
* @return the check configurations
* @throws CheckstyleException if an error occurs
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter, WeakerAccess
*/
@Deprecated
@@ -297,7 +296,7 @@ public final class ConfigurationLoader {
* 'ignore' should be omitted, {@code false} otherwise
* @return the check configurations
* @throws CheckstyleException if an error occurs
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter
*/
@Deprecated
@@ -320,7 +319,7 @@ public final class ConfigurationLoader {
* @param threadModeSettings the thread mode configuration
* @return the check configurations
* @throws CheckstyleException if an error occurs
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter, WeakerAccess
*/
@Deprecated
@@ -580,7 +579,7 @@ public final class ConfigurationLoader {
* appear in the public API of the ConfigurationLoader.
*/
private final class InternalLoader
- extends AbstractLoader {
+ extends XmlLoader {
/** Module elements. */
private static final String MODULE = "module";
/** Name attribute. */
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java b/src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java
index e110b0229..23cd2ff83 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/DefaultLogger.java
@@ -28,6 +28,7 @@ import java.nio.charset.StandardCharsets;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
@@ -77,7 +78,7 @@ public class DefaultLogger extends AutomaticBean implements AuditListener {
* Creates a new {@code DefaultLogger} instance.
* @param outputStream where to log infos and errors
* @param closeStreamsAfterUse if oS should be closed in auditFinished()
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter
*/
@Deprecated
@@ -92,7 +93,7 @@ public class DefaultLogger extends AutomaticBean implements AuditListener {
* @param closeInfoAfterUse auditFinished should close infoStream.
* @param errorStream the {@code OutputStream} for error messages.
* @param closeErrorAfterUse auditFinished should close errorStream
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter
*/
@Deprecated
@@ -112,7 +113,7 @@ public class DefaultLogger extends AutomaticBean implements AuditListener {
* @param errorStream the {@code OutputStream} for error messages
* @param closeErrorAfterUse auditFinished should close errorStream
* @param messageFormatter formatter for the log message.
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter, WeakerAccess
*/
@Deprecated
@@ -193,6 +194,11 @@ public class DefaultLogger extends AutomaticBean implements AuditListener {
formatter = messageFormatter;
}
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
/**
* Print an Emacs compliant line on the error stream.
* If the column number is non zero, then also display it.
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/FileStatefulCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/FileStatefulCheck.java
index 7f4c60e77..2c67438d4 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/FileStatefulCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/FileStatefulCheck.java
@@ -34,7 +34,7 @@ import java.lang.annotation.Target;
* Checker guarantees that each check instance processes only one file at the same time.
* Checker guarantees that all check instances have equal (but not the same) configuration.
* It means, that if a check holds a property of type "array of strings",
- * the property value will not be shared accross check instances.
+ * the property value will not be shared across check instances.
* Instead, each check instance will hold its own array instance.
* Checker does not guarantee that each file will have it's own thread -
* there might be a list of files, which will be executed on the same thread.
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/GlobalStatefulCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/GlobalStatefulCheck.java
index 52cc1f185..9fd6d7408 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/GlobalStatefulCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/GlobalStatefulCheck.java
@@ -35,7 +35,7 @@ import java.lang.annotation.Target;
* The check methods and fields should be thread safe, because they may be accessed from others
* threads at the same time.
* Checker guarantees that there will be exactly one check instance
- * This is simular to multi-file validation, which checkstyle does not support fully yet.
+ * This is similar to multi-file validation, which checkstyle does not support fully yet.
* Please refer to https://github.com/checkstyle/checkstyle/issues/3540 for details.
* @author Andrew Kuchev
* @noinspection AnnotationClass, ClassIndependentOfModule, unused
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java
index 4c5cf4efd..9b6b0cc57 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/PackageNamesLoader.java
@@ -37,7 +37,6 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.google.common.io.Closeables;
-import com.puppycrawl.tools.checkstyle.api.AbstractLoader;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -46,7 +45,7 @@ import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
* @author Rick Giles
*/
public final class PackageNamesLoader
- extends AbstractLoader {
+ extends XmlLoader {
/** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID =
"-//Puppy Crawl//DTD Package Names 1.0//EN";
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java b/src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java
index 2465edcab..630709739 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/PackageObjectFactory.java
@@ -55,7 +55,7 @@ public class PackageObjectFactory implements ModuleFactory {
*/
public enum ModuleLoadOption {
/**
- * Searching from registred checkstyle modules and from packages given in countructor.
+ * Searching from registered checkstyle modules and from packages given in constructor.
**/
SEARCH_REGISTERED_PACKAGES,
/**
@@ -73,7 +73,7 @@ public class PackageObjectFactory implements ModuleFactory {
public static final String UNABLE_TO_INSTANTIATE_EXCEPTION_MESSAGE =
"PackageObjectFactory.unableToInstantiateExceptionMessage";
- /** Exception message when there is ambigugous module name in config file. */
+ /** Exception message when there is ambiguous module name in config file. */
public static final String AMBIGUOUS_MODULE_NAME_EXCEPTION_MESSAGE =
"PackageObjectFactory.ambiguousModuleNameExceptionMessage";
@@ -354,7 +354,7 @@ public class PackageObjectFactory implements ModuleFactory {
}
/**
- * Searching to class with given name (or name concatinated with &quot;Check&quot;) in existing
+ * Searching to class with given name (or name concatenated with &quot;Check&quot;) in existing
* packages. Returns instance if class found or, otherwise, null.
* @param name the name of a class.
* @return the {@code Object} created by loader.
@@ -820,6 +820,8 @@ public class PackageObjectFactory implements ModuleFactory {
BASE_PACKAGE + ".filters.IntRangeFilter");
NAME_TO_FULL_MODULE_NAME.put("SeverityMatchFilter",
BASE_PACKAGE + ".filters.SeverityMatchFilter");
+ NAME_TO_FULL_MODULE_NAME.put("SuppressWithPlainTextCommentFilter",
+ BASE_PACKAGE + ".filters.SuppressWithPlainTextCommentFilter");
NAME_TO_FULL_MODULE_NAME.put("SuppressionCommentFilter",
BASE_PACKAGE + ".filters.SuppressionCommentFilter");
NAME_TO_FULL_MODULE_NAME.put("SuppressionFilter",
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java b/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
index 2a0ae4dc2..cd42699dd 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/PropertyCacheFile.java
@@ -239,7 +239,7 @@ final class PropertyCacheFile {
/**
* Serializes object to output stream.
- * @param object object to be erialized
+ * @param object object to be serialized
* @param outputStream serialization stream
* @throws IOException if an error occurs
*/
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.java b/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.java
index 629c680f6..a881efb6c 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/TreeWalkerAuditEvent.java
@@ -105,6 +105,14 @@ public class TreeWalkerAuditEvent {
}
/**
+ * Gets the column char index associated with the message.
+ * @return the column char index associated with the message
+ */
+ public int getColumnCharIndex() {
+ return localizedMessage.getColumnCharIndex();
+ }
+
+ /**
* Returns id of module.
* @return the identifier of the module that generated the event. Can return
* null.
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java b/src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java
index 0a0095418..10037c524 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/XMLLogger.java
@@ -35,6 +35,7 @@ import java.util.concurrent.ConcurrentHashMap;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AuditListener;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -81,7 +82,7 @@ public class XMLLogger
* Sets the output to a defined stream.
* @param outputStream the stream to write logs to.
* @param closeStream close oS in auditFinished
- * @deprecated in order to fullfil demands of BooleanParameter IDEA check.
+ * @deprecated in order to fulfill demands of BooleanParameter IDEA check.
* @noinspection BooleanParameter
*/
@Deprecated
@@ -102,6 +103,11 @@ public class XMLLogger
}
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ @Override
public void auditStarted(AuditEvent event) {
writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
@@ -115,8 +121,6 @@ public class XMLLogger
@Override
public void auditFinished(AuditEvent event) {
- fileMessages.forEach(this::writeFileMessages);
-
writer.println("</checkstyle>");
if (closeStream) {
writer.close();
@@ -180,21 +184,20 @@ public class XMLLogger
public void addError(AuditEvent event) {
if (event.getSeverityLevel() != SeverityLevel.IGNORE) {
final String fileName = event.getFileName();
- if (fileName == null) {
+ if (fileName == null || !fileMessages.containsKey(fileName)) {
synchronized (writerLock) {
writeFileError(event);
}
}
else {
- final FileMessages messages = fileMessages.computeIfAbsent(
- fileName, name -> new FileMessages());
+ final FileMessages messages = fileMessages.get(fileName);
messages.addError(event);
}
}
}
/**
- * Outputs the given envet to the writer.
+ * Outputs the given event to the writer.
* @param event An event to print.
*/
private void writeFileError(AuditEvent event) {
@@ -221,14 +224,13 @@ public class XMLLogger
@Override
public void addException(AuditEvent event, Throwable throwable) {
final String fileName = event.getFileName();
- if (fileName == null) {
+ if (fileName == null || !fileMessages.containsKey(fileName)) {
synchronized (writerLock) {
writeException(throwable);
}
}
else {
- final FileMessages messages = fileMessages.computeIfAbsent(
- fileName, name -> new FileMessages());
+ final FileMessages messages = fileMessages.get(fileName);
messages.addException(throwable);
}
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java
index e0a83f334..5a410f045 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/XmlLoader.java
@@ -17,7 +17,7 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
-package com.puppycrawl.tools.checkstyle.api;
+package com.puppycrawl.tools.checkstyle;
import java.io.IOException;
import java.io.InputStream;
@@ -48,7 +48,7 @@ import org.xml.sax.helpers.DefaultHandler;
* @author Oliver Burn
* @noinspection ThisEscapedInObjectConstruction
*/
-public abstract class AbstractLoader
+public class XmlLoader
extends DefaultHandler {
/** Maps public id to resolve to resource name for the DTD. */
private final Map<String, String> publicIdToResourceNameMap;
@@ -62,7 +62,7 @@ public abstract class AbstractLoader
* @throws SAXException if an error occurs
* @throws ParserConfigurationException if an error occurs
*/
- protected AbstractLoader(String publicId, String dtdResourceName)
+ protected XmlLoader(String publicId, String dtdResourceName)
throws SAXException, ParserConfigurationException {
this(new HashMap<>(1));
publicIdToResourceNameMap.put(publicId, dtdResourceName);
@@ -74,7 +74,7 @@ public abstract class AbstractLoader
* @throws SAXException if an error occurs
* @throws ParserConfigurationException if an error occurs
*/
- protected AbstractLoader(Map<String, String> publicIdToResourceNameMap)
+ protected XmlLoader(Map<String, String> publicIdToResourceNameMap)
throws SAXException, ParserConfigurationException {
this.publicIdToResourceNameMap = new HashMap<>(publicIdToResourceNameMap);
final SAXParserFactory factory = SAXParserFactory.newInstance();
@@ -145,9 +145,9 @@ public abstract class AbstractLoader
}
/**
- * Configures SAXParserFactory with features requered
- * for exectution on very secured environments.
- * @param factory factory to be configured with spectial features
+ * Configures SAXParserFactory with features required
+ * for execution on very secured environments.
+ * @param factory factory to be configured with special features
* @throws SAXException if an error occurs
* @throws ParserConfigurationException if an error occurs
*/
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java
index 1739b6bd5..fa57d7d7b 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractViolationReporter.java
@@ -27,6 +27,7 @@ import java.util.Map;
* {@link LocalizedMessage localized messages} that are created by the module.
*
* @author lkuehne
+ * @noinspection NoopMethodInAbstractClass
*/
public abstract class AbstractViolationReporter
extends AutomaticBean {
@@ -134,6 +135,11 @@ public abstract class AbstractViolationReporter
return messageBundle;
}
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
/**
* Log a message that has no column information.
*
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java
index 7e977eaa7..e7a35f69f 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/AutomaticBean.java
@@ -53,7 +53,8 @@ import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
* calling the bean's setters for all configuration attributes.
* @author lkuehne
*/
-public class AutomaticBean
+// -@cs[AbstractClassName] We can not brake compatibility with previous versions.
+public abstract class AutomaticBean
implements Configurable, Contextualizable {
/**
@@ -78,6 +79,16 @@ public class AutomaticBean
private Configuration configuration;
/**
+ * Provides a hook to finish the part of this component's setup that
+ * was not handled by the bean introspection.
+ * <p>
+ * The default implementation does nothing.
+ * </p>
+ * @throws CheckstyleException if there is a configuration error.
+ */
+ protected abstract void finishLocalSetup() throws CheckstyleException;
+
+ /**
* Creates a BeanUtilsBean that is configured to use
* type converters that throw a ConversionException
* instead of using the default value when something
@@ -259,18 +270,6 @@ public class AutomaticBean
}
/**
- * Provides a hook to finish the part of this component's setup that
- * was not handled by the bean introspection.
- * <p>
- * The default implementation does nothing.
- * </p>
- * @throws CheckstyleException if there is a configuration error.
- */
- protected void finishLocalSetup() throws CheckstyleException {
- // No code by default, should be overridden only by demand at subclasses
- }
-
- /**
* Called by configure() for every child of this component's Configuration.
* <p>
* The default implementation throws {@link CheckstyleException} if
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java
index e4fc7191b..c50b2d1f0 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java
@@ -20,8 +20,7 @@
package com.puppycrawl.tools.checkstyle.api;
import java.io.Serializable;
-
-import com.google.common.collect.ImmutableMap;
+import java.util.Map;
/**
* A Configuration is used to configure a Configurable component. The general
@@ -61,5 +60,5 @@ public interface Configuration extends Serializable {
* for this configuration.
* @return unmodifiable map containing custom messages
*/
- ImmutableMap<String, String> getMessages();
+ Map<String, String> getMessages();
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/Context.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/Context.java
index 795de7058..e96c66352 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/Context.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/Context.java
@@ -19,7 +19,7 @@
package com.puppycrawl.tools.checkstyle.api;
-import com.google.common.collect.ImmutableCollection;
+import java.util.Collection;
/**
* A context to be used in subcomponents. The general idea of
@@ -40,5 +40,5 @@ public interface Context {
* Returns the names of all attributes of this context.
* @return the names of all attributes of this context.
*/
- ImmutableCollection<String> getAttributeNames();
+ Collection<String> getAttributeNames();
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java
index ca9a5b363..6aa0ad823 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/FileContents.java
@@ -23,12 +23,12 @@ import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
-import com.google.common.collect.ImmutableMap;
import com.puppycrawl.tools.checkstyle.grammars.CommentListener;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -165,7 +165,7 @@ public final class FileContents implements CommentListener {
* @deprecated Use {@link #getSingleLineComments()} instead.
*/
@Deprecated
- public ImmutableMap<Integer, TextBlock> getCppComments() {
+ public Map<Integer, TextBlock> getCppComments() {
return getSingleLineComments();
}
@@ -174,8 +174,8 @@ public final class FileContents implements CommentListener {
* the value is the comment {@link TextBlock} at the line.
* @return the Map of comments
*/
- public ImmutableMap<Integer, TextBlock> getSingleLineComments() {
- return ImmutableMap.copyOf(cppComments);
+ public Map<Integer, TextBlock> getSingleLineComments() {
+ return Collections.unmodifiableMap(cppComments);
}
/**
@@ -202,7 +202,7 @@ public final class FileContents implements CommentListener {
*/
// -@cs[AbbreviationAsWordInName] Can't change yet since class is API.
@Deprecated
- public ImmutableMap<Integer, List<TextBlock>> getCComments() {
+ public Map<Integer, List<TextBlock>> getCComments() {
return getBlockComments();
}
@@ -212,8 +212,8 @@ public final class FileContents implements CommentListener {
* that start at that line.
* @return the map of comments
*/
- public ImmutableMap<Integer, List<TextBlock>> getBlockComments() {
- return ImmutableMap.copyOf(clangComments);
+ public Map<Integer, List<TextBlock>> getBlockComments() {
+ return Collections.unmodifiableMap(clangComments);
}
/**
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java
index 3b12ffe20..64e919541 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/FileText.java
@@ -37,7 +37,7 @@ import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import com.google.common.io.Closeables;
+import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* Represents the text contents of a file of arbitrary plain text type.
@@ -139,7 +139,7 @@ public final class FileText {
lines = textLines.toArray(new String[textLines.size()]);
}
finally {
- Closeables.closeQuietly(reader);
+ CommonUtils.close(reader);
}
}
@@ -209,7 +209,7 @@ public final class FileText {
}
}
finally {
- Closeables.closeQuietly(reader);
+ CommonUtils.close(reader);
}
return buf.toString();
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java
index 5b45f5d22..8adc69c73 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java
@@ -30,6 +30,7 @@ import com.puppycrawl.tools.checkstyle.grammars.GeneratedJavaTokenTypes;
*
* @author Oliver Burn
* @author <a href="mailto:dobratzp@ele.uri.edu">Peter Dobratz</a>
+ * @noinspection ClassWithTooManyDependents
*/
public final class TokenTypes {
// The following three types are never part of an AST,
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java
index 56303a33b..76601aeae 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheck.java
@@ -47,6 +47,7 @@ import com.puppycrawl.tools.checkstyle.Definitions;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import com.puppycrawl.tools.checkstyle.api.FileText;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
+import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
@@ -132,19 +133,19 @@ public class TranslationCheck extends AbstractFileSetCheck {
private static final String DEFAULT_TRANSLATION_REGEXP = "^.+\\..+$";
/**
- * Regexp pattern for bundles names wich end with language code, followed by country code and
+ * Regexp pattern for bundles names which end with language code, followed by country code and
* variant suffix. For example, messages_es_ES_UNIX.properties.
*/
private static final Pattern LANGUAGE_COUNTRY_VARIANT_PATTERN =
CommonUtils.createPattern("^.+\\_[a-z]{2}\\_[A-Z]{2}\\_[A-Za-z]+\\..+$");
/**
- * Regexp pattern for bundles names wich end with language code, followed by country code
+ * Regexp pattern for bundles names which end with language code, followed by country code
* suffix. For example, messages_es_ES.properties.
*/
private static final Pattern LANGUAGE_COUNTRY_PATTERN =
CommonUtils.createPattern("^.+\\_[a-z]{2}\\_[A-Z]{2}\\..+$");
/**
- * Regexp pattern for bundles names wich end with language code suffix.
+ * Regexp pattern for bundles names which end with language code suffix.
* For example, messages_es.properties.
*/
private static final Pattern LANGUAGE_PATTERN =
@@ -325,9 +326,11 @@ public class TranslationCheck extends AbstractFileSetCheck {
* @param fileName file name.
*/
private void logMissingTranslation(String filePath, String fileName) {
+ final MessageDispatcher dispatcher = getMessageDispatcher();
+ dispatcher.fireFileStarted(filePath);
log(0, MSG_KEY_MISSING_TRANSLATION_FILE, fileName);
fireErrors(filePath);
- getMessageDispatcher().fireFileFinished(filePath);
+ dispatcher.fireFileFinished(filePath);
}
/**
@@ -454,6 +457,9 @@ public class TranslationCheck extends AbstractFileSetCheck {
private void checkFilesForConsistencyRegardingTheirKeys(SetMultimap<File, String> fileKeys,
Set<String> keysThatMustExist) {
for (File currentFile : fileKeys.keySet()) {
+ final MessageDispatcher dispatcher = getMessageDispatcher();
+ final String path = currentFile.getPath();
+ dispatcher.fireFileStarted(path);
final Set<String> currentFileKeys = fileKeys.get(currentFile);
final Set<String> missingKeys = keysThatMustExist.stream()
.filter(e -> !currentFileKeys.contains(e)).collect(Collectors.toSet());
@@ -462,9 +468,8 @@ public class TranslationCheck extends AbstractFileSetCheck {
log(0, MSG_KEY, key);
}
}
- final String path = currentFile.getPath();
fireErrors(path);
- getMessageDispatcher().fireFileFinished(path);
+ dispatcher.fireFileFinished(path);
}
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java
index b20f5b96e..ffe0bd9cd 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheck.java
@@ -113,7 +113,7 @@ public class UniquePropertiesCheck extends AbstractFileSetCheck {
}
++lineNumber;
}
- // -1 as check seeks for the first duplicate occurance in file,
+ // -1 as check seeks for the first duplicate occurrence in file,
// so it cannot be the last line.
if (lineNumber > fileText.size() - 1) {
lineNumber = 0;
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java
index 0fc040f7c..326cc8109 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/EqualsAvoidNullCheck.java
@@ -483,7 +483,7 @@ public class EqualsAvoidNullCheck extends AbstractCheck {
// The minimal distance between objCalledOn and field (of type String) initialization
// is calculated as follows:
// String(6) + space(1) + variableName(1) + assign(1) +
- // anotherStringVariableName(1) + semicolumn(1) = 11
+ // anotherStringVariableName(1) + semicolon(1) = 11
// Example: length of "String s=d;" is 11 symbols.
final int minimumSymbolsBetween = 11;
if (field.getLineNo() < objCalledOn.getLineNo()
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java
index 03977238b..679d79a17 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/FinalLocalVariableCheck.java
@@ -251,7 +251,7 @@ public class FinalLocalVariableCheck extends AbstractCheck {
case TokenTypes.SLIST:
// -@cs[MoveVariableInsideIf] assignment value is modified later so it can't be
// moved
- final Deque<DetailAST> prevScopeUnitializedVariableData =
+ final Deque<DetailAST> prevScopeUninitializedVariableData =
prevScopeUninitializedVariables.peek();
boolean containsBreak = false;
if (ast.getParent().getType() != TokenTypes.CASE_GROUP
@@ -263,7 +263,7 @@ public class FinalLocalVariableCheck extends AbstractCheck {
}
final DetailAST parent = ast.getParent();
if (containsBreak || shouldUpdateUninitializedVariables(parent)) {
- updateAllUninitializedVariables(prevScopeUnitializedVariableData);
+ updateAllUninitializedVariables(prevScopeUninitializedVariableData);
}
updateCurrentScopeAssignedVariables();
break;
@@ -348,35 +348,35 @@ public class FinalLocalVariableCheck extends AbstractCheck {
*/
private void storePrevScopeUninitializedVariableData() {
final ScopeData scopeData = scopeStack.peek();
- final Deque<DetailAST> prevScopeUnitializedVariableData =
+ final Deque<DetailAST> prevScopeUninitializedVariableData =
new ArrayDeque<>();
- scopeData.uninitializedVariables.forEach(prevScopeUnitializedVariableData::push);
- prevScopeUninitializedVariables.push(prevScopeUnitializedVariableData);
+ scopeData.uninitializedVariables.forEach(prevScopeUninitializedVariableData::push);
+ prevScopeUninitializedVariables.push(prevScopeUninitializedVariableData);
}
/**
* Update current scope data uninitialized variable according to the whole scope data.
- * @param prevScopeUnitializedVariableData variable for previous stack of uninitialized
+ * @param prevScopeUninitializedVariableData variable for previous stack of uninitialized
* variables
+ * @noinspection MethodParameterNamingConvention
*/
- // -@cs[CyclomaticComplexity] Breaking apart will damage encapsulation.
private void updateAllUninitializedVariables(
- Deque<DetailAST> prevScopeUnitializedVariableData) {
+ Deque<DetailAST> prevScopeUninitializedVariableData) {
// Check for only previous scope
- updateUninitializedVariables(prevScopeUnitializedVariableData);
+ updateUninitializedVariables(prevScopeUninitializedVariableData);
// Check for rest of the scope
prevScopeUninitializedVariables.forEach(this::updateUninitializedVariables);
}
/**
* Update current scope data uninitialized variable according to the specific scope data.
- * @param scopeUnitializedVariableData variable for specific stack of uninitialized variables
+ * @param scopeUninitializedVariableData variable for specific stack of uninitialized variables
*/
- private void updateUninitializedVariables(Deque<DetailAST> scopeUnitializedVariableData) {
+ private void updateUninitializedVariables(Deque<DetailAST> scopeUninitializedVariableData) {
final Iterator<DetailAST> iterator = currentScopeAssignedVariables.peek().iterator();
while (iterator.hasNext()) {
final DetailAST assignedVariable = iterator.next();
- for (DetailAST variable : scopeUnitializedVariableData) {
+ for (DetailAST variable : scopeUninitializedVariableData) {
for (ScopeData scopeData : scopeStack) {
final FinalVariableCandidate candidate =
scopeData.scope.get(variable.getText());
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java
index 75b1284ed..bcdb895b1 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalInstantiationCheck.java
@@ -116,7 +116,6 @@ public class IllegalInstantiationCheck
@Override
public void beginTree(DetailAST rootAST) {
- super.beginTree(rootAST);
pkgName = null;
imports.clear();
instantiations.clear();
@@ -328,7 +327,7 @@ public class IllegalInstantiationCheck
* @return true if type is standard
*/
private boolean isStandardClass(String className, String illegal) {
- boolean isStandardCalss = false;
+ boolean isStandardClass = false;
// class from java.lang
if (illegal.length() - JAVA_LANG.length() == className.length()
&& illegal.endsWith(className)
@@ -343,10 +342,10 @@ public class IllegalInstantiationCheck
final boolean isSamePackage = isSamePackage(className);
if (!isSameFile && !isSamePackage) {
- isStandardCalss = true;
+ isStandardClass = true;
}
}
- return isStandardCalss;
+ return isStandardClass;
}
/**
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java
index edcb1a0b4..ef2891c81 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheck.java
@@ -98,8 +98,6 @@ public final class IllegalTypeCheck extends AbstractCheck {
*/
public static final String MSG_KEY = "illegal.type";
- /** Abstract classes legal by default. */
- private static final String[] DEFAULT_LEGAL_ABSTRACT_NAMES = {};
/** Types illegal by default. */
private static final String[] DEFAULT_ILLEGAL_TYPES = {
"HashSet",
@@ -144,7 +142,6 @@ public final class IllegalTypeCheck extends AbstractCheck {
/** Creates new instance of the check. */
public IllegalTypeCheck() {
setIllegalClassNames(DEFAULT_ILLEGAL_TYPES);
- setLegalAbstractClassNames(DEFAULT_LEGAL_ABSTRACT_NAMES);
setIgnoredMethodNames(DEFAULT_IGNORED_METHOD_NAMES);
}
@@ -450,7 +447,6 @@ public final class IllegalTypeCheck extends AbstractCheck {
* @noinspection WeakerAccess
*/
public void setLegalAbstractClassNames(String... classNames) {
- legalAbstractClassNames.clear();
Collections.addAll(legalAbstractClassNames, classNames);
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java
index c2e3de96e..58e5f7b3d 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheck.java
@@ -91,6 +91,7 @@ import com.puppycrawl.tools.checkstyle.utils.TokenUtils;
* @author o_sukhodolsky
* @author Andrei Selkin
*/
+// -@cs[ClassDataAbstractionCoupling] This check requires to work with and identify many frames.
@FileStatefulCheck
public class RequireThisCheck extends AbstractCheck {
@@ -113,6 +114,7 @@ public class RequireThisCheck extends AbstractCheck {
TokenTypes.METHOD_DEF,
TokenTypes.CLASS_DEF,
TokenTypes.ENUM_DEF,
+ TokenTypes.ANNOTATION_DEF,
TokenTypes.INTERFACE_DEF,
TokenTypes.PARAMETER_DEF,
TokenTypes.TYPE_ARGUMENT,
@@ -145,12 +147,12 @@ public class RequireThisCheck extends AbstractCheck {
TokenTypes.BXOR_ASSIGN,
}).collect(Collectors.toSet()));
+ /** Frame for the currently processed AST. */
+ private final Deque<AbstractFrame> current = new ArrayDeque<>();
+
/** Tree of all the parsed frames. */
private Map<DetailAST, AbstractFrame> frames;
- /** Frame for the currently processed AST. */
- private AbstractFrame current;
-
/** Whether we should check fields usage. */
private boolean checkFields = true;
/** Whether we should check methods usage. */
@@ -193,8 +195,10 @@ public class RequireThisCheck extends AbstractCheck {
TokenTypes.CLASS_DEF,
TokenTypes.INTERFACE_DEF,
TokenTypes.ENUM_DEF,
+ TokenTypes.ANNOTATION_DEF,
TokenTypes.CTOR_DEF,
TokenTypes.METHOD_DEF,
+ TokenTypes.LITERAL_FOR,
TokenTypes.SLIST,
TokenTypes.IDENT,
};
@@ -208,7 +212,7 @@ public class RequireThisCheck extends AbstractCheck {
@Override
public void beginTree(DetailAST rootAST) {
frames = new HashMap<>();
- current = null;
+ current.clear();
final Deque<AbstractFrame> frameStack = new LinkedList<>();
DetailAST curNode = rootAST;
@@ -239,7 +243,26 @@ public class RequireThisCheck extends AbstractCheck {
case TokenTypes.SLIST :
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
- current = frames.get(ast);
+ case TokenTypes.LITERAL_FOR :
+ current.push(frames.get(ast));
+ break;
+ default :
+ // do nothing
+ }
+ }
+
+ @Override
+ public void leaveToken(DetailAST ast) {
+ switch (ast.getType()) {
+ case TokenTypes.CLASS_DEF :
+ case TokenTypes.INTERFACE_DEF :
+ case TokenTypes.ENUM_DEF :
+ case TokenTypes.ANNOTATION_DEF :
+ case TokenTypes.SLIST :
+ case TokenTypes.METHOD_DEF :
+ case TokenTypes.CTOR_DEF :
+ case TokenTypes.LITERAL_FOR:
+ current.pop();
break;
default :
// do nothing
@@ -252,7 +275,12 @@ public class RequireThisCheck extends AbstractCheck {
* @param ast IDENT to check.
*/
private void processIdent(DetailAST ast) {
- final int parentType = ast.getParent().getType();
+ int parentType = ast.getParent().getType();
+ if (parentType == TokenTypes.EXPR
+ && ast.getParent().getParent().getParent().getType()
+ == TokenTypes.ANNOTATION_FIELD_DEF) {
+ parentType = TokenTypes.ANNOTATION_FIELD_DEF;
+ }
switch (parentType) {
case TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR:
case TokenTypes.ANNOTATION:
@@ -328,6 +356,7 @@ public class RequireThisCheck extends AbstractCheck {
* @param frameStack stack containing the FrameTree being built.
* @param ast AST to parse.
*/
+ // -@cs[JavaNCSS] This method is a big switch and is too hard to remove.
private static void collectDeclarations(Deque<AbstractFrame> frameStack, DetailAST ast) {
final AbstractFrame frame = frameStack.peek();
switch (ast.getType()) {
@@ -336,7 +365,8 @@ public class RequireThisCheck extends AbstractCheck {
break;
case TokenTypes.PARAMETER_DEF :
if (!CheckUtils.isReceiverParameter(ast)
- && !isLambdaParameter(ast)) {
+ && !isLambdaParameter(ast)
+ && ast.getParent().getType() != TokenTypes.LITERAL_CATCH) {
final DetailAST parameterIdent = ast.findFirstToken(TokenTypes.IDENT);
frame.addIdent(parameterIdent);
}
@@ -366,6 +396,20 @@ public class RequireThisCheck extends AbstractCheck {
final DetailAST ctorFrameNameIdent = ast.findFirstToken(TokenTypes.IDENT);
frameStack.addFirst(new ConstructorFrame(frame, ctorFrameNameIdent));
break;
+ case TokenTypes.ENUM_CONSTANT_DEF :
+ final DetailAST ident = ast.findFirstToken(TokenTypes.IDENT);
+ ((ClassFrame) frame).addStaticMember(ident);
+ break;
+ case TokenTypes.LITERAL_CATCH:
+ final AbstractFrame catchFrame = new CatchFrame(frame, ast);
+ catchFrame.addIdent(ast.findFirstToken(TokenTypes.PARAMETER_DEF).findFirstToken(
+ TokenTypes.IDENT));
+ frameStack.addFirst(catchFrame);
+ break;
+ case TokenTypes.LITERAL_FOR:
+ final AbstractFrame forFrame = new ForFrame(frame, ast);
+ frameStack.addFirst(forFrame);
+ break;
case TokenTypes.LITERAL_NEW:
if (isAnonymousClassDef(ast)) {
frameStack.addFirst(new AnonymousClassFrame(frame,
@@ -414,6 +458,8 @@ public class RequireThisCheck extends AbstractCheck {
case TokenTypes.SLIST :
case TokenTypes.METHOD_DEF :
case TokenTypes.CTOR_DEF :
+ case TokenTypes.LITERAL_CATCH :
+ case TokenTypes.LITERAL_FOR :
frames.put(ast, frameStack.poll());
break;
case TokenTypes.LITERAL_NEW :
@@ -581,7 +627,8 @@ public class RequireThisCheck extends AbstractCheck {
private boolean canBeReferencedFromStaticContext(DetailAST ident) {
AbstractFrame variableDeclarationFrame = findFrame(ident, false);
boolean staticInitializationBlock = false;
- while (variableDeclarationFrame.getType() == FrameType.BLOCK_FRAME) {
+ while (variableDeclarationFrame.getType() == FrameType.BLOCK_FRAME
+ || variableDeclarationFrame.getType() == FrameType.FOR_FRAME) {
final DetailAST blockFrameNameIdent = variableDeclarationFrame.getFrameNameIdent();
final DetailAST definitionToken = blockFrameNameIdent.getParent();
if (definitionToken.getType() == TokenTypes.STATIC_INIT) {
@@ -824,7 +871,7 @@ public class RequireThisCheck extends AbstractCheck {
* @return AbstractFrame containing declaration or null.
*/
private AbstractFrame findClassFrame(DetailAST name, boolean lookForMethod) {
- AbstractFrame frame = current;
+ AbstractFrame frame = current.peek();
while (true) {
frame = findFrame(frame, name, lookForMethod);
@@ -846,7 +893,7 @@ public class RequireThisCheck extends AbstractCheck {
* @return AbstractFrame containing declaration or null.
*/
private AbstractFrame findFrame(DetailAST name, boolean lookForMethod) {
- return findFrame(current, name, lookForMethod);
+ return findFrame(current.peek(), name, lookForMethod);
}
/**
@@ -858,14 +905,7 @@ public class RequireThisCheck extends AbstractCheck {
*/
private static AbstractFrame findFrame(AbstractFrame frame, DetailAST name,
boolean lookForMethod) {
- final AbstractFrame result;
- if (frame == null) {
- result = null;
- }
- else {
- result = frame.getIfContains(name, lookForMethod);
- }
- return result;
+ return frame.getIfContains(name, lookForMethod);
}
/**
@@ -900,7 +940,7 @@ public class RequireThisCheck extends AbstractCheck {
* @return the name of the nearest parent ClassFrame.
*/
private String getNearestClassFrameName() {
- AbstractFrame frame = current;
+ AbstractFrame frame = current.peek();
while (frame.getType() != FrameType.CLASS_FRAME) {
frame = frame.getParent();
}
@@ -952,6 +992,10 @@ public class RequireThisCheck extends AbstractCheck {
METHOD_FRAME,
/** Block frame type. */
BLOCK_FRAME,
+ /** Catch frame type. */
+ CATCH_FRAME,
+ /** Lambda frame type. */
+ FOR_FRAME,
}
/**
@@ -1357,4 +1401,44 @@ public class RequireThisCheck extends AbstractCheck {
return FrameType.BLOCK_FRAME;
}
}
+
+ /**
+ * A frame initiated on entering a catch block; holds local catch variable names.
+ * @author Richard Veach
+ */
+ public static class CatchFrame extends AbstractFrame {
+ /**
+ * Creates catch frame.
+ * @param parent parent frame.
+ * @param ident ident frame name ident.
+ */
+ protected CatchFrame(AbstractFrame parent, DetailAST ident) {
+ super(parent, ident);
+ }
+
+ @Override
+ public FrameType getType() {
+ return FrameType.CATCH_FRAME;
+ }
+ }
+
+ /**
+ * A frame initiated on entering a for block; holds local for variable names.
+ * @author Richard Veach
+ */
+ public static class ForFrame extends AbstractFrame {
+ /**
+ * Creates for frame.
+ * @param parent parent frame.
+ * @param ident ident frame name ident.
+ */
+ protected ForFrame(AbstractFrame parent, DetailAST ident) {
+ super(parent, ident);
+ }
+
+ @Override
+ public FrameType getType() {
+ return FrameType.FOR_FRAME;
+ }
+ }
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java
index 231fcd8fd..fcdcdda9d 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheck.java
@@ -60,6 +60,11 @@ public final class ReturnCountCheck extends AbstractCheck {
* file.
*/
public static final String MSG_KEY = "return.count";
+ /**
+ * A key pointing to the warning message text in "messages.properties"
+ * file.
+ */
+ public static final String MSG_KEY_VOID = "return.countVoid";
/** Stack of method contexts. */
private final Deque<Context> contextStack = new ArrayDeque<>();
@@ -199,10 +204,10 @@ public final class ReturnCountCheck extends AbstractCheck {
// we can't identify which max to use for lambdas, so we can only assign
// after the first return statement is seen
if (ast.getFirstChild().getType() == TokenTypes.SEMI) {
- context.visitLiteralReturn(maxForVoid);
+ context.visitLiteralReturn(maxForVoid, true);
}
else {
- context.visitLiteralReturn(max);
+ context.visitLiteralReturn(max, false);
}
}
@@ -217,6 +222,8 @@ public final class ReturnCountCheck extends AbstractCheck {
private int count;
/** Maximum allowed number of return statements. */
private Integer maxAllowed;
+ /** Identifies if context is void. */
+ private boolean isVoidContext;
/**
* Creates new method context.
@@ -227,10 +234,12 @@ public final class ReturnCountCheck extends AbstractCheck {
}
/**
- * Increase the number of return statements.
+ * Increase the number of return statements and set context return type.
* @param maxAssigned Maximum allowed number of return statements.
+ * @param voidReturn Identifies if context is void.
*/
- public void visitLiteralReturn(int maxAssigned) {
+ public void visitLiteralReturn(int maxAssigned, Boolean voidReturn) {
+ isVoidContext = voidReturn;
if (maxAllowed == null) {
maxAllowed = maxAssigned;
}
@@ -245,7 +254,12 @@ public final class ReturnCountCheck extends AbstractCheck {
*/
public void checkCount(DetailAST ast) {
if (checking && maxAllowed != null && count > maxAllowed) {
- log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY, count, maxAllowed);
+ if (isVoidContext) {
+ log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY_VOID, count, maxAllowed);
+ }
+ else {
+ log(ast.getLineNo(), ast.getColumnNo(), MSG_KEY, count, maxAllowed);
+ }
}
}
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java
index 0e7d9fd07..f13541ef8 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheck.java
@@ -424,8 +424,13 @@ public class VariableDeclarationUsageDistanceCheck extends AbstractCheck {
*/
private static int getDistToVariableUsageInChildNode(DetailAST childNode, DetailAST varIdent,
int currentDistToVarUsage) {
+ DetailAST examineNode = childNode;
+ if (examineNode.getType() == TokenTypes.LABELED_STAT) {
+ examineNode = examineNode.getFirstChild().getNextSibling();
+ }
+
int resultDist = currentDistToVarUsage;
- switch (childNode.getType()) {
+ switch (examineNode.getType()) {
case TokenTypes.VARIABLE_DEF:
resultDist++;
break;
@@ -437,7 +442,7 @@ public class VariableDeclarationUsageDistanceCheck extends AbstractCheck {
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF:
case TokenTypes.LITERAL_SWITCH:
- if (isVariableInOperatorExpr(childNode, varIdent)) {
+ if (isVariableInOperatorExpr(examineNode, varIdent)) {
resultDist++;
}
else {
@@ -447,11 +452,11 @@ public class VariableDeclarationUsageDistanceCheck extends AbstractCheck {
}
break;
default:
- if (childNode.branchContains(TokenTypes.SLIST)) {
- resultDist = 0;
+ if (examineNode.findFirstToken(TokenTypes.SLIST) == null) {
+ resultDist++;
}
else {
- resultDist++;
+ resultDist = 0;
}
}
return resultDist;
@@ -522,16 +527,17 @@ public class VariableDeclarationUsageDistanceCheck extends AbstractCheck {
variableUsageAst = exprWithVariableUsage;
}
}
+
+ // If there's no any variable usage, then distance = 0.
+ else if (variableUsageExpressions.isEmpty()) {
+ variableUsageAst = null;
+ }
// If variable usage exists in different scopes, then distance =
// distance until variable first usage.
- else if (variableUsageExpressions.size() > 1) {
+ else {
dist++;
variableUsageAst = variableUsageExpressions.get(0);
}
- // If there's no any variable usage, then distance = 0.
- else {
- variableUsageAst = null;
- }
}
return new SimpleEntry<>(variableUsageAst, dist);
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java
index cc32ef218..c4d2d6d57 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheck.java
@@ -436,7 +436,6 @@ public class CustomImportOrderCheck extends AbstractCheck {
* user value.
*/
public final void setCustomImportOrderRules(final String inputCustomImportOrder) {
- customImportOrderRules.clear();
for (String currentState : GROUP_SEPARATOR_PATTERN.split(inputCustomImportOrder)) {
addRulesToList(currentState);
}
@@ -636,7 +635,7 @@ public class CustomImportOrderCheck extends AbstractCheck {
}
if (SPECIAL_IMPORTS_RULE_GROUP.equals(group)) {
bestMatch = findBetterPatternMatch(importPath,
- SPECIAL_IMPORTS_RULE_GROUP, specialImportsRegExp, bestMatch);
+ group, specialImportsRegExp, bestMatch);
}
}
}
@@ -691,7 +690,7 @@ public class CustomImportOrderCheck extends AbstractCheck {
final String separator = "\\.";
final String[] import1Tokens = import1.split(separator);
final String[] import2Tokens = import2.split(separator);
- for (int i = 0; i < import1Tokens.length && i != import2Tokens.length; i++) {
+ for (int i = 0; i != import1Tokens.length && i != import2Tokens.length; i++) {
final String import1Token = import1Tokens[i];
final String import2Token = import2Tokens[i];
result = import1Token.compareTo(import2Token);
@@ -699,6 +698,9 @@ public class CustomImportOrderCheck extends AbstractCheck {
break;
}
}
+ if (result == 0) {
+ result = Integer.compare(import1Tokens.length, import2Tokens.length);
+ }
return result;
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
index f6e78691d..93a442b24 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlLoader.java
@@ -34,14 +34,14 @@ import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
-import com.puppycrawl.tools.checkstyle.api.AbstractLoader;
+import com.puppycrawl.tools.checkstyle.XmlLoader;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
/**
* Responsible for loading the contents of an import control configuration file.
* @author Oliver Burn
*/
-final class ImportControlLoader extends AbstractLoader {
+final class ImportControlLoader extends XmlLoader {
/** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID_1_0 =
"-//Puppy Crawl//DTD Import Control 1.0//EN";
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java
index a6f08bf1d..f769c754c 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheck.java
@@ -392,6 +392,10 @@ public class ImportOrderCheck
}
doVisitToken(ident, isStatic, isStaticAndNotLastImport);
+ if (isStaticAndNotLastImport && !beforeFirstImport) {
+ log(ident.getLineNo(), MSG_ORDERING, ident.getText());
+ }
+
}
else if (option == ImportOrderOption.BOTTOM) {
@@ -401,6 +405,10 @@ public class ImportOrderCheck
}
doVisitToken(ident, isStatic, isLastImportAndNonStatic);
+ if (isLastImportAndNonStatic) {
+ log(ident.getLineNo(), MSG_ORDERING, ident.getText());
+ }
+
}
else if (option == ImportOrderOption.ABOVE) {
// previous non-static but current is static
@@ -440,14 +448,15 @@ public class ImportOrderCheck
final int groupIdx = getGroupNumber(name);
final int line = ident.getLineNo();
- if (isInSameGroup(groupIdx, isStatic)) {
- doVisitTokenInSameGroup(isStatic, previous, name, line);
- }
- else if (groupIdx > lastGroup) {
- if (!beforeFirstImport && separated && line - lastImportLine < 2) {
+ if (groupIdx > lastGroup) {
+ if (!beforeFirstImport && separated && line - lastImportLine < 2
+ && !isInSameGroup(groupIdx, isStatic)) {
log(line, MSG_SEPARATION, name);
}
}
+ else if (isInSameGroup(groupIdx, isStatic)) {
+ doVisitTokenInSameGroup(isStatic, previous, name, line);
+ }
else {
log(line, MSG_ORDERING, name);
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java
index f8af0a778..39f2b9ce6 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/LineWrappingHandler.java
@@ -262,7 +262,8 @@ public class LineWrappingHandler {
if (isCurrentNodeCloseAnnotationAloneInLine
|| node.getType() == TokenTypes.AT
&& (parentNode.getParent().getType() == TokenTypes.MODIFIERS
- || parentNode.getParent().getType() == TokenTypes.ANNOTATIONS)) {
+ || parentNode.getParent().getType() == TokenTypes.ANNOTATIONS)
+ || node.getLineNo() == atNode.getLineNo()) {
logWarningMessage(node, firstNodeIndent);
}
else {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java
index 1b91a5775..eb80609f5 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/TryHandler.java
@@ -129,9 +129,9 @@ public class TryHandler extends BlockParentHandler {
*/
private void checkTryResources(final DetailAST resourcesSpecAst) {
final DetailAST resourcesAst = resourcesSpecAst.findFirstToken(TokenTypes.RESOURCES);
- final int indetation = getIndent().getFirstIndentLevel()
+ final int indentation = getIndent().getFirstIndentLevel()
+ getIndentCheck().getLineWrappingIndentation();
- final IndentLevel expectedResourceIndent = new IndentLevel(indetation);
+ final IndentLevel expectedResourceIndent = new IndentLevel(indentation);
final String subType = "resource";
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
index 2e0d95e75..ca3aec832 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java
@@ -100,12 +100,12 @@ public class JavadocMethodCheck extends AbstractTypeAwareCheck {
public static final String MSG_DUPLICATE_TAG = "javadoc.duplicateTag";
/** Compiled regexp to match Javadoc tags that take an argument. */
- private static final Pattern MATCH_JAVADOC_ARG =
- CommonUtils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s+\\S*");
+ private static final Pattern MATCH_JAVADOC_ARG = CommonUtils.createPattern(
+ "^\\s*(?>\\*|\\/\\*\\*)?\\s*@(throws|exception|param)\\s+(\\S+)\\s+\\S*");
/** Compiled regexp to match first part of multilineJavadoc tags. */
- private static final Pattern MATCH_JAVADOC_ARG_MULTILINE_START =
- CommonUtils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s*$");
+ private static final Pattern MATCH_JAVADOC_ARG_MULTILINE_START = CommonUtils.createPattern(
+ "^\\s*(?>\\*|\\/\\*\\*)?\\s*@(throws|exception|param)\\s+(\\S+)\\s*$");
/** Compiled regexp to look for a continuation of the comment. */
private static final Pattern MATCH_JAVADOC_MULTILINE_CONT =
@@ -118,10 +118,10 @@ public class JavadocMethodCheck extends AbstractTypeAwareCheck {
/** Compiled regexp to match Javadoc tags with no argument. */
private static final Pattern MATCH_JAVADOC_NOARG =
- CommonUtils.createPattern("@(return|see)\\s+\\S");
+ CommonUtils.createPattern("^\\s*(?>\\*|\\/\\*\\*)?\\s*@(return|see)\\s+\\S");
/** Compiled regexp to match first part of multilineJavadoc tags. */
private static final Pattern MATCH_JAVADOC_NOARG_MULTILINE_START =
- CommonUtils.createPattern("@(return|see)\\s*$");
+ CommonUtils.createPattern("^\\s*(?>\\*|\\/\\*\\*)?\\s*@(return|see)\\s*$");
/** Compiled regexp to match Javadoc tags with no argument and {}. */
private static final Pattern MATCH_JAVADOC_NOARG_CURLY =
CommonUtils.createPattern("\\{\\s*@(inheritDoc)\\s*\\}");
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.java
index 77516206b..73e46a097 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheck.java
@@ -48,6 +48,7 @@ public class NonEmptyAtclauseDescriptionCheck extends AbstractJavadocCheck {
JavadocTokenTypes.PARAM_LITERAL,
JavadocTokenTypes.RETURN_LITERAL,
JavadocTokenTypes.THROWS_LITERAL,
+ JavadocTokenTypes.EXCEPTION_LITERAL,
JavadocTokenTypes.DEPRECATED_LITERAL,
};
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java
index a0498fc24..293cd4aaa 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/AbstractClassCouplingCheck.java
@@ -140,7 +140,7 @@ public abstract class AbstractClassCouplingCheck extends AbstractCheck {
}
/**
- * Sets user-excluded pakcages to ignore. All exlcuded packages should end with a period,
+ * Sets user-excluded packages to ignore. All excluded packages should end with a period,
* so it also appends a dot to a package name.
* @param excludedPackages the list of packages to ignore.
*/
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.java
index b960dd5a9..8c41a8c2e 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheck.java
@@ -59,14 +59,7 @@ public final class ClassDataAbstractionCouplingCheck
@Override
public int[] getAcceptableTokens() {
- return new int[] {
- TokenTypes.PACKAGE_DEF,
- TokenTypes.IMPORT,
- TokenTypes.CLASS_DEF,
- TokenTypes.INTERFACE_DEF,
- TokenTypes.ENUM_DEF,
- TokenTypes.LITERAL_NEW,
- };
+ return getRequiredTokens();
}
// -@cs[SimpleAccessorNameNotation] Overrides method from the base class.
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java
index 5f62d2c5d..b07268cd4 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheck.java
@@ -337,7 +337,7 @@ public final class NPathComplexityCheck extends AbstractCheck {
}
/**
- * Calculates number of conditional operators, including inline ternary operatior, for a token.
+ * Calculates number of conditional operators, including inline ternary operator, for a token.
* @param ast inspected token.
* @return number of conditional operators.
* @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.23">
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java
index cc8d1b6b0..5db77a317 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheck.java
@@ -289,11 +289,11 @@ public class RedundantModifierCheck
modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null;
// declared in a final class?
DetailAST parent = ast.getParent();
- while (parent != null) {
+ while (parent != null && !checkFinal) {
if (parent.getType() == TokenTypes.CLASS_DEF) {
final DetailAST classModifiers =
parent.findFirstToken(TokenTypes.MODIFIERS);
- checkFinal = checkFinal || classModifiers.findFirstToken(TokenTypes.FINAL) != null;
+ checkFinal = classModifiers.findFirstToken(TokenTypes.FINAL) != null;
parent = null;
}
else if (parent.getType() == TokenTypes.LITERAL_NEW
@@ -301,6 +301,10 @@ public class RedundantModifierCheck
checkFinal = true;
parent = null;
}
+ else if (parent.getType() == TokenTypes.ENUM_DEF) {
+ checkFinal = modifiers.findFirstToken(TokenTypes.LITERAL_STATIC) != null;
+ parent = null;
+ }
else {
parent = parent.getParent();
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java
index c7876e2e2..b82985bbd 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpSinglelineJavaCheck.java
@@ -62,15 +62,15 @@ public class RegexpSinglelineJavaCheck extends AbstractCheck {
@Override
public void beginTree(DetailAST rootAST) {
- MatchSuppressor supressor = null;
+ MatchSuppressor suppressor = null;
if (ignoreComments) {
- supressor = new CommentSuppressor(getFileContents());
+ suppressor = new CommentSuppressor(getFileContents());
}
final DetectorOptions options = DetectorOptions.newBuilder()
.reporter(this)
.compileFlags(0)
- .suppressor(supressor)
+ .suppressor(suppressor)
.format(format)
.message(message)
.minimum(minimum)
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java
index d31c52586..e9ce934e4 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/sizes/MethodCountCheck.java
@@ -112,7 +112,7 @@ public final class MethodCountCheck extends AbstractCheck {
@Override
public void visitToken(DetailAST ast) {
if (ast.getType() == TokenTypes.METHOD_DEF) {
- if (isInLastestScopeDefinition(ast)) {
+ if (isInLatestScopeDefinition(ast)) {
raiseCounter(ast);
}
}
@@ -134,11 +134,11 @@ public final class MethodCountCheck extends AbstractCheck {
* Checks if there is a scope definition to check and that the method is found inside that scope
* (class, enum, etc.).
* @param methodDef
- * The method to analzye.
+ * The method to analyze.
* @return {@code true} if the method is part of the latest scope definition and should be
* counted.
*/
- private boolean isInLastestScopeDefinition(DetailAST methodDef) {
+ private boolean isInLatestScopeDefinition(DetailAST methodDef) {
boolean result = false;
if (!counters.isEmpty()) {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java
index 44a3118fc..4d9562015 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheck.java
@@ -390,8 +390,12 @@ public class NoWhitespaceAfterCheck extends AbstractCheck {
}
//ident and lastTypeNode lay on one line
else {
- if (ident.getColumnNo() >= ast.getColumnNo() + 1
- || lastTypeNode.getColumnNo() > ident.getColumnNo()) {
+ final int instanceOfSize = 13;
+ // +2 because ast has `[]` after the ident
+ if (ident.getColumnNo() >= ast.getColumnNo() + 2
+ // +13 because ident (at most 1 character) is followed by
+ // ' instanceof ' (12 characters)
+ || lastTypeNode.getColumnNo() >= ident.getColumnNo() + instanceOfSize) {
previousElement = lastTypeNode;
}
else {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java
index 39dea8fb9..77fe7c4cd 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filefilters/BeforeExecutionExclusionFileFilter.java
@@ -83,6 +83,11 @@ public final class BeforeExecutionExclusionFileFilter extends AutomaticBean
}
@Override
+ protected void finishLocalSetup() {
+ // No code by default
+ }
+
+ @Override
public boolean accept(String uri) {
return fileNamePattern == null || !fileNamePattern.matcher(uri).find();
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java
index db2aa9216..9642ee7d3 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilter.java
@@ -21,6 +21,7 @@ package com.puppycrawl.tools.checkstyle.filters;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
@@ -59,6 +60,11 @@ public class SeverityMatchFilter
}
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ @Override
public boolean accept(AuditEvent event) {
final boolean severityMatches = severity == event.getSeverityLevel();
return acceptOnMatch == severityMatches;
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java
index ad2d6d23e..21c17eea1 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressElement.java
@@ -24,7 +24,6 @@ import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.Filter;
-import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* This filter processes {@link AuditEvent}
@@ -53,6 +52,12 @@ public class SuppressElement
/** The pattern for check class names. */
private final String checkPattern;
+ /** The regexp to match message names against. */
+ private final Pattern messageRegexp;
+
+ /** The pattern for message names. */
+ private final String messagePattern;
+
/** Module id filter. */
private final String moduleId;
@@ -74,20 +79,33 @@ public class SuppressElement
*
* @param files regular expression for names of filtered files.
* @param checks regular expression for filtered check classes.
+ * @param message regular expression for messages.
* @param modId the id
* @param lines lines CSV values and ranges for line number filtering.
* @param columns columns CSV values and ranges for column number filtering.
*/
public SuppressElement(String files, String checks,
- String modId, String lines, String columns) {
+ String message, String modId, String lines, String columns) {
filePattern = files;
- fileRegexp = Pattern.compile(files);
+ if (files == null) {
+ fileRegexp = null;
+ }
+ else {
+ fileRegexp = Pattern.compile(files);
+ }
checkPattern = checks;
if (checks == null) {
checkRegexp = null;
}
else {
- checkRegexp = CommonUtils.createPattern(checks);
+ checkRegexp = Pattern.compile(checks);
+ }
+ messagePattern = message;
+ if (message == null) {
+ messageRegexp = null;
+ }
+ else {
+ messageRegexp = Pattern.compile(message);
}
moduleId = modId;
linesCsv = lines;
@@ -109,6 +127,7 @@ public class SuppressElement
@Override
public boolean accept(AuditEvent event) {
return isFileNameAndModuleNotMatching(event)
+ || !isMessageNameMatching(event)
|| isLineAndColumnMatch(event);
}
@@ -119,13 +138,22 @@ public class SuppressElement
*/
private boolean isFileNameAndModuleNotMatching(AuditEvent event) {
return event.getFileName() == null
- || !fileRegexp.matcher(event.getFileName()).find()
+ || fileRegexp != null && !fileRegexp.matcher(event.getFileName()).find()
|| event.getLocalizedMessage() == null
|| moduleId != null && !moduleId.equals(event.getModuleId())
|| checkRegexp != null && !checkRegexp.matcher(event.getSourceName()).find();
}
/**
+ * Is matching by message.
+ * @param event event
+ * @return true is matching or not set.
+ */
+ private boolean isMessageNameMatching(AuditEvent event) {
+ return messageRegexp == null || messageRegexp.matcher(event.getMessage()).find();
+ }
+
+ /**
* Whether line and column match.
* @param event event to process.
* @return true if line and column match.
@@ -138,7 +166,8 @@ public class SuppressElement
@Override
public int hashCode() {
- return Objects.hash(filePattern, checkPattern, moduleId, linesCsv, columnsCsv);
+ return Objects.hash(filePattern, checkPattern, messagePattern, moduleId, linesCsv,
+ columnsCsv);
}
@Override
@@ -152,6 +181,7 @@ public class SuppressElement
final SuppressElement suppressElement = (SuppressElement) other;
return Objects.equals(filePattern, suppressElement.filePattern)
&& Objects.equals(checkPattern, suppressElement.checkPattern)
+ && Objects.equals(messagePattern, suppressElement.messagePattern)
&& Objects.equals(moduleId, suppressElement.moduleId)
&& Objects.equals(linesCsv, suppressElement.linesCsv)
&& Objects.equals(columnsCsv, suppressElement.columnsCsv);
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.java
index 4e2c6bb5b..f2577138c 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWarningsFilter.java
@@ -21,6 +21,7 @@ package com.puppycrawl.tools.checkstyle.filters;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.Filter;
import com.puppycrawl.tools.checkstyle.checks.SuppressWarningsHolder;
@@ -33,6 +34,11 @@ public class SuppressWarningsFilter
extends AutomaticBean
implements Filter {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ @Override
public boolean accept(AuditEvent event) {
return !SuppressWarningsHolder.isSuppressed(event);
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java
index 85a387b64..d3fa968ce 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithNearbyCommentFilter.java
@@ -31,6 +31,7 @@ import java.util.regex.PatternSyntaxException;
import com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent;
import com.puppycrawl.tools.checkstyle.TreeWalkerFilter;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -183,6 +184,11 @@ public class SuppressWithNearbyCommentFilter
}
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ @Override
public boolean accept(TreeWalkerAuditEvent event) {
boolean accepted = true;
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java
new file mode 100644
index 000000000..ad380845e
--- /dev/null
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilter.java
@@ -0,0 +1,349 @@
+////////////////////////////////////////////////////////////////////////////////
+// checkstyle: Checks Java source code for adherence to a set of rules.
+// Copyright (C) 2001-2017 the original author or authors.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+////////////////////////////////////////////////////////////////////////////////
+
+package com.puppycrawl.tools.checkstyle.filters;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+import com.puppycrawl.tools.checkstyle.api.AuditEvent;
+import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
+import com.puppycrawl.tools.checkstyle.api.FileText;
+import com.puppycrawl.tools.checkstyle.api.Filter;
+import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
+
+/**
+ * <p>
+ * A filter that uses comments to suppress audit events.
+ * The filter can be used only to suppress audit events received from
+ * {@link com.puppycrawl.tools.checkstyle.api.FileSetCheck} checks.
+ * SuppressWithPlainTextCommentFilter knows nothing about AST,
+ * it treats only plain text comments and extracts the information required for suppression from
+ * the plain text comments. Currently the filter supports only single line comments.
+ * </p>
+ * <p>
+ * Rationale:
+ * Sometimes there are legitimate reasons for violating a check. When
+ * this is a matter of the code in question and not personal
+ * preference, the best place to override the policy is in the code
+ * itself. Semi-structured comments can be associated with the check.
+ * This is sometimes superior to a separate suppressions file, which
+ * must be kept up-to-date as the source file is edited.
+ * </p>
+ * @author Andrei Selkin
+ */
+public class SuppressWithPlainTextCommentFilter extends AutomaticBean implements Filter {
+
+ /** Comment format which turns checkstyle reporting off. */
+ private static final String DEFAULT_OFF_FORMAT = "// CHECKSTYLE:OFF";
+
+ /** Comment format which turns checkstyle reporting on. */
+ private static final String DEFAULT_ON_FORMAT = "// CHECKSTYLE:ON";
+
+ /** Default check format to suppress. By default the filter suppress all checks. */
+ private static final String DEFAULT_CHECK_FORMAT = ".*";
+
+ /** Regexp which turns checkstyle reporting off. */
+ private Pattern offCommentFormat = CommonUtils.createPattern(DEFAULT_OFF_FORMAT);
+
+ /** Regexp which turns checkstyle reporting on. */
+ private Pattern onCommentFormat = CommonUtils.createPattern(DEFAULT_ON_FORMAT);
+
+ /** The check format to suppress. */
+ private String checkFormat = DEFAULT_CHECK_FORMAT;
+
+ /** The message format to suppress.*/
+ private String messageFormat;
+
+ /**
+ * Sets an off comment format pattern.
+ * @param pattern off comment format pattern.
+ */
+ public final void setOffCommentFormat(Pattern pattern) {
+ offCommentFormat = pattern;
+ }
+
+ /**
+ * Sets an on comment format pattern.
+ * @param pattern on comment format pattern.
+ */
+ public final void setOnCommentFormat(Pattern pattern) {
+ onCommentFormat = pattern;
+ }
+
+ /**
+ * Sets a pattern for check format.
+ * @param format pattern for check format.
+ */
+ public final void setCheckFormat(String format) {
+ checkFormat = format;
+ }
+
+ /**
+ * Sets a pattern for message format.
+ * @param format pattern for message format.
+ */
+ public final void setMessageFormat(String format) {
+ messageFormat = format;
+ }
+
+ @Override
+ public boolean accept(AuditEvent event) {
+ boolean accepted = true;
+ if (event.getLocalizedMessage() != null) {
+ final FileText fileText = getFileText(event.getFileName());
+ if (fileText != null) {
+ final List<Suppression> suppressions = getSuppressions(fileText);
+ accepted = getNearestSuppression(suppressions, event) == null;
+ }
+ }
+ return accepted;
+ }
+
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ /**
+ * Returns {@link FileText} instance created based on the given file name.
+ * @param fileName the name of the file.
+ * @return {@link FileText} instance.
+ */
+ private static FileText getFileText(String fileName) {
+ final File file = new File(fileName);
+ FileText result = null;
+
+ // some violations can be on a directory, instead of a file
+ if (!file.isDirectory()) {
+ try {
+ result = new FileText(file, StandardCharsets.UTF_8.name());
+ }
+ catch (IOException ex) {
+ throw new IllegalStateException("Cannot read source file: " + fileName, ex);
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the list of {@link Suppression} instances retrieved from the given {@link FileText}.
+ * @param fileText {@link FileText} instance.
+ * @return list of {@link Suppression} instances.
+ */
+ private List<Suppression> getSuppressions(FileText fileText) {
+ final List<Suppression> suppressions = new ArrayList<>();
+ for (int lineNo = 0; lineNo < fileText.size(); lineNo++) {
+ final Optional<Suppression> suppression = getSuppression(fileText, lineNo);
+ suppression.ifPresent(suppressions::add);
+ }
+ return suppressions;
+ }
+
+ /**
+ * Tries to extract the suppression from the given line.
+ * @param fileText {@link FileText} instance.
+ * @param lineNo line number.
+ * @return {@link Optional} of {@link Suppression}.
+ */
+ private Optional<Suppression> getSuppression(FileText fileText, int lineNo) {
+ final String line = fileText.get(lineNo);
+ final Matcher onCommentMatcher = onCommentFormat.matcher(line);
+ final Matcher offCommentMatcher = offCommentFormat.matcher(line);
+
+ Suppression suppression = null;
+ if (onCommentMatcher.find()) {
+ suppression = new Suppression(onCommentMatcher.group(0),
+ lineNo + 1, onCommentMatcher.start(), SuppressionType.ON, this);
+ }
+ if (offCommentMatcher.find()) {
+ suppression = new Suppression(offCommentMatcher.group(0),
+ lineNo + 1, offCommentMatcher.start(), SuppressionType.OFF, this);
+ }
+
+ return Optional.ofNullable(suppression);
+ }
+
+ /**
+ * Finds the nearest {@link Suppression} instance which can suppress
+ * the given {@link AuditEvent}. The nearest suppression is the suppression which scope
+ * is before the line and column of the event.
+ * @param suppressions {@link Suppression} instance.
+ * @param event {@link AuditEvent} instance.
+ * @return {@link Suppression} instance.
+ */
+ private static Suppression getNearestSuppression(List<Suppression> suppressions,
+ AuditEvent event) {
+ return suppressions
+ .stream()
+ .filter(suppression -> suppression.isMatch(event))
+ .reduce((first, second) -> second)
+ .filter(suppression -> suppression.suppressionType != SuppressionType.ON)
+ .orElse(null);
+ }
+
+ /** Enum which represents the type of the suppression. */
+ private enum SuppressionType {
+
+ /** On suppression type. */
+ ON,
+ /** Off suppression type. */
+ OFF
+
+ }
+
+ /** The class which represents the suppression. */
+ public static class Suppression {
+
+ /** The regexp which is used to match the event source.*/
+ private final Pattern eventSourceRegexp;
+ /** The regexp which is used to match the event message.*/
+ private final Pattern eventMessageRegexp;
+
+ /** Suppression text.*/
+ private final String text;
+ /** Suppression line.*/
+ private final int lineNo;
+ /** Suppression column number.*/
+ private final int columnNo;
+ /** Suppression type. */
+ private final SuppressionType suppressionType;
+
+ /**
+ * Creates new suppression instance.
+ * @param text suppression text.
+ * @param lineNo suppression line number.
+ * @param columnNo suppression column number.
+ * @param suppressionType suppression type.
+ * @param filter the {@link SuppressWithPlainTextCommentFilter} with the context.
+ */
+ protected Suppression(
+ String text,
+ int lineNo,
+ int columnNo,
+ SuppressionType suppressionType,
+ SuppressWithPlainTextCommentFilter filter
+ ) {
+ this.text = text;
+ this.lineNo = lineNo;
+ this.columnNo = columnNo;
+ this.suppressionType = suppressionType;
+
+ //Expand regexp for check and message
+ //Does not intern Patterns with Utils.getPattern()
+ String format = "";
+ try {
+ if (this.suppressionType == SuppressionType.ON) {
+ format = CommonUtils.fillTemplateWithStringsByRegexp(
+ filter.checkFormat, text, filter.onCommentFormat);
+ eventSourceRegexp = Pattern.compile(format);
+ if (filter.messageFormat == null) {
+ eventMessageRegexp = null;
+ }
+ else {
+ format = CommonUtils.fillTemplateWithStringsByRegexp(
+ filter.messageFormat, text, filter.onCommentFormat);
+ eventMessageRegexp = Pattern.compile(format);
+ }
+ }
+ else {
+ format = CommonUtils.fillTemplateWithStringsByRegexp(
+ filter.checkFormat, text, filter.offCommentFormat);
+ eventSourceRegexp = Pattern.compile(format);
+ if (filter.messageFormat == null) {
+ eventMessageRegexp = null;
+ }
+ else {
+ format = CommonUtils.fillTemplateWithStringsByRegexp(
+ filter.messageFormat, text, filter.offCommentFormat);
+ eventMessageRegexp = Pattern.compile(format);
+ }
+ }
+ }
+ catch (final PatternSyntaxException ex) {
+ throw new IllegalArgumentException(
+ "unable to parse expanded comment " + format, ex);
+ }
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ }
+ if (other == null || getClass() != other.getClass()) {
+ return false;
+ }
+ final Suppression suppression = (Suppression) other;
+ return Objects.equals(lineNo, suppression.lineNo)
+ && Objects.equals(columnNo, suppression.columnNo)
+ && Objects.equals(suppressionType, suppression.suppressionType)
+ && Objects.equals(text, suppression.text)
+ && Objects.equals(eventSourceRegexp, suppression.eventSourceRegexp)
+ && Objects.equals(eventMessageRegexp, suppression.eventMessageRegexp);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(
+ text, lineNo, columnNo, suppressionType, eventSourceRegexp, eventMessageRegexp);
+ }
+
+ /**
+ * Checks whether the suppression matches the given {@link AuditEvent}.
+ * @param event {@link AuditEvent} instance.
+ * @return true if the suppression matches {@link AuditEvent}.
+ */
+ private boolean isMatch(AuditEvent event) {
+ boolean match = false;
+ if (isInScopeOfSuppression(event)) {
+ final Matcher sourceNameMatcher = eventSourceRegexp.matcher(event.getSourceName());
+ if (sourceNameMatcher.find()) {
+ match = eventMessageRegexp == null
+ || eventMessageRegexp.matcher(event.getMessage()).find();
+ }
+ else {
+ match = event.getModuleId() != null
+ && eventSourceRegexp.matcher(event.getModuleId()).find();
+ }
+ }
+ return match;
+ }
+
+ /**
+ * Checks whether {@link AuditEvent} is in the scope of the suppression.
+ * @param event {@link AuditEvent} instance.
+ * @return true if {@link AuditEvent} is in the scope of the suppression.
+ */
+ private boolean isInScopeOfSuppression(AuditEvent event) {
+ return lineNo <= event.getLine();
+ }
+ }
+
+}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java
index e87139594..386964a8a 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilter.java
@@ -32,6 +32,7 @@ import java.util.regex.PatternSyntaxException;
import com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent;
import com.puppycrawl.tools.checkstyle.TreeWalkerFilter;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -179,6 +180,11 @@ public class SuppressionCommentFilter
}
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
+ @Override
public boolean accept(TreeWalkerAuditEvent event) {
boolean accepted = true;
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java
index 814ea3173..35e59834e 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilter.java
@@ -42,7 +42,7 @@ import com.puppycrawl.tools.checkstyle.utils.FilterUtils;
*/
public class SuppressionFilter extends AutomaticBean implements Filter, ExternalResourceHolder {
- /** Filename of supression file. */
+ /** Filename of suppression file. */
private String file;
/** Tells whether config file existence is optional. */
private boolean optional;
@@ -50,7 +50,7 @@ public class SuppressionFilter extends AutomaticBean implements Filter, External
private FilterSet filters = new FilterSet();
/**
- * Sets name of the supression file.
+ * Sets name of the suppression file.
* @param fileName name of the suppressions file.
*/
public void setFile(String fileName) {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java
index f4b254074..9363ed5ca 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilter.java
@@ -41,7 +41,7 @@ import com.puppycrawl.tools.checkstyle.utils.FilterUtils;
public class SuppressionXpathFilter extends AutomaticBean implements
TreeWalkerFilter, ExternalResourceHolder {
- /** Filename of supression file. */
+ /** Filename of suppression file. */
private String file;
/** Tells whether config file existence is optional. */
private boolean optional;
@@ -49,7 +49,7 @@ public class SuppressionXpathFilter extends AutomaticBean implements
private Set<TreeWalkerFilter> filters = new HashSet<>();
/**
- * Sets name of the supression file.
+ * Sets name of the suppression file.
* @param fileName name of the suppressions file.
*/
public void setFile(String fileName) {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java
index ee3c66ed8..ced67bc97 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoader.java
@@ -36,7 +36,7 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.puppycrawl.tools.checkstyle.TreeWalkerFilter;
-import com.puppycrawl.tools.checkstyle.api.AbstractLoader;
+import com.puppycrawl.tools.checkstyle.XmlLoader;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.FilterSet;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -46,25 +46,37 @@ import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
* @author Rick Giles
*/
public final class SuppressionsLoader
- extends AbstractLoader {
+ extends XmlLoader {
/** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID_1_0 =
"-//Puppy Crawl//DTD Suppressions 1.0//EN";
/** The resource for the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_0 =
+ private static final String DTD_SUPPRESSIONS_NAME_1_0 =
"com/puppycrawl/tools/checkstyle/suppressions_1_0.dtd";
/** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID_1_1 =
"-//Puppy Crawl//DTD Suppressions 1.1//EN";
/** The resource for the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_1 =
+ private static final String DTD_SUPPRESSIONS_NAME_1_1 =
"com/puppycrawl/tools/checkstyle/suppressions_1_1.dtd";
/** The public ID for the configuration dtd. */
+ private static final String DTD_PUBLIC_ID_1_2 =
+ "-//Puppy Crawl//DTD Suppressions 1.2//EN";
+ /** The resource for the configuration dtd. */
+ private static final String DTD_SUPPRESSIONS_NAME_1_2 =
+ "com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd";
+ /** The public ID for the configuration dtd. */
private static final String DTD_PUBLIC_ID_1_1_XPATH =
"-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.1//EN";
/** The resource for the configuration dtd. */
- private static final String DTD_RESOURCE_NAME_1_1_XPATH =
+ private static final String DTD_SUPPRESSIONS_NAME_1_1_XPATH =
"com/puppycrawl/tools/checkstyle/suppressions_1_1_xpath_experimental.dtd";
+ /** The public ID for the configuration dtd. */
+ private static final String DTD_PUBLIC_ID_1_2_XPATH =
+ "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN";
+ /** The resource for the configuration dtd. */
+ private static final String DTD_SUPPRESSIONS_NAME_1_2_XPATH =
+ "com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd";
/** File search error message. **/
private static final String UNABLE_TO_FIND_ERROR_MESSAGE = "Unable to find: ";
/** String literal for attribute name. **/
@@ -72,6 +84,8 @@ public final class SuppressionsLoader
/** String literal for attribute name. **/
private static final String ATTRIBUTE_NAME_CHECKS = "checks";
/** String literal for attribute name. **/
+ private static final String ATTRIBUTE_NAME_MESSAGE = "message";
+ /** String literal for attribute name. **/
private static final String ATTRIBUTE_NAME_ID = "id";
/** String literal for attribute name. **/
private static final String ATTRIBUTE_NAME_QUERY = "query";
@@ -128,20 +142,21 @@ public final class SuppressionsLoader
private static SuppressElement getSuppressElement(Attributes attributes) throws SAXException {
final String checks = attributes.getValue(ATTRIBUTE_NAME_CHECKS);
final String modId = attributes.getValue(ATTRIBUTE_NAME_ID);
- if (checks == null && modId == null) {
+ final String message = attributes.getValue(ATTRIBUTE_NAME_MESSAGE);
+ if (checks == null && modId == null && message == null) {
// -@cs[IllegalInstantiation] SAXException is in the overridden method signature
- throw new SAXException("missing checks and id attribute");
+ throw new SAXException("missing checks or id or message attribute");
}
final SuppressElement suppress;
try {
final String files = attributes.getValue(ATTRIBUTE_NAME_FILES);
final String lines = attributes.getValue(ATTRIBUTE_NAME_LINES);
final String columns = attributes.getValue(ATTRIBUTE_NAME_COLUMNS);
- suppress = new SuppressElement(files, checks, modId, lines, columns);
+ suppress = new SuppressElement(files, checks, message, modId, lines, columns);
}
catch (final PatternSyntaxException ex) {
// -@cs[IllegalInstantiation] SAXException is in the overridden method signature
- throw new SAXException("invalid files or checks format", ex);
+ throw new SAXException("invalid files or checks or message format", ex);
}
return suppress;
}
@@ -156,19 +171,21 @@ public final class SuppressionsLoader
private static XpathFilter getXpathFilter(Attributes attributes) throws SAXException {
final String checks = attributes.getValue(ATTRIBUTE_NAME_CHECKS);
final String modId = attributes.getValue(ATTRIBUTE_NAME_ID);
- if (checks == null && modId == null) {
+ final String message = attributes.getValue(ATTRIBUTE_NAME_MESSAGE);
+ if (checks == null && modId == null && message == null) {
// -@cs[IllegalInstantiation] SAXException is in the overridden method signature
- throw new SAXException("missing checks and id attribute for suppress-xpath");
+ throw new SAXException("missing checks or id or message attribute for suppress-xpath");
}
final XpathFilter filter;
try {
final String files = attributes.getValue(ATTRIBUTE_NAME_FILES);
final String xpathQuery = attributes.getValue(ATTRIBUTE_NAME_QUERY);
- filter = new XpathFilter(files, checks, modId, xpathQuery);
+ filter = new XpathFilter(files, checks, message, modId, xpathQuery);
}
catch (final PatternSyntaxException ex) {
// -@cs[IllegalInstantiation] SAXException is in the overridden method signature
- throw new SAXException("invalid files or checks format for suppress-xpath", ex);
+ throw new SAXException("invalid files or checks or message format for suppress-xpath",
+ ex);
}
return filter;
}
@@ -266,9 +283,11 @@ public final class SuppressionsLoader
*/
private static Map<String, String> createIdToResourceNameMap() {
final Map<String, String> map = new HashMap<>();
- map.put(DTD_PUBLIC_ID_1_0, DTD_RESOURCE_NAME_1_0);
- map.put(DTD_PUBLIC_ID_1_1, DTD_RESOURCE_NAME_1_1);
- map.put(DTD_PUBLIC_ID_1_1_XPATH, DTD_RESOURCE_NAME_1_1_XPATH);
+ map.put(DTD_PUBLIC_ID_1_0, DTD_SUPPRESSIONS_NAME_1_0);
+ map.put(DTD_PUBLIC_ID_1_1, DTD_SUPPRESSIONS_NAME_1_1);
+ map.put(DTD_PUBLIC_ID_1_2, DTD_SUPPRESSIONS_NAME_1_2);
+ map.put(DTD_PUBLIC_ID_1_1_XPATH, DTD_SUPPRESSIONS_NAME_1_1_XPATH);
+ map.put(DTD_PUBLIC_ID_1_2_XPATH, DTD_SUPPRESSIONS_NAME_1_2_XPATH);
return map;
}
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilter.java b/src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilter.java
index 8079be3df..600340404 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilter.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/filters/XpathFilter.java
@@ -53,6 +53,12 @@ public class XpathFilter implements TreeWalkerFilter {
/** The pattern for check class names. */
private final String checkPattern;
+ /** The regexp to match message names against. */
+ private final Pattern messageRegexp;
+
+ /** The pattern for message names. */
+ private final String messagePattern;
+
/** Module id filter. */
private final String moduleId;
@@ -66,13 +72,19 @@ public class XpathFilter implements TreeWalkerFilter {
* Creates a {@code XpathElement} instance.
* @param files regular expression for names of filtered files
* @param checks regular expression for filtered check classes
+ * @param message regular expression for messages.
* @param moduleId the module id
* @param query the xpath query
*/
public XpathFilter(String files, String checks,
- String moduleId, String query) {
+ String message, String moduleId, String query) {
filePattern = files;
- fileRegexp = Pattern.compile(files);
+ if (files == null) {
+ fileRegexp = null;
+ }
+ else {
+ fileRegexp = Pattern.compile(files);
+ }
checkPattern = checks;
if (checks == null) {
checkRegexp = null;
@@ -80,6 +92,13 @@ public class XpathFilter implements TreeWalkerFilter {
else {
checkRegexp = CommonUtils.createPattern(checks);
}
+ messagePattern = message;
+ if (message == null) {
+ messageRegexp = null;
+ }
+ else {
+ messageRegexp = Pattern.compile(message);
+ }
this.moduleId = moduleId;
xpathQuery = query;
if (xpathQuery == null) {
@@ -99,6 +118,7 @@ public class XpathFilter implements TreeWalkerFilter {
@Override
public boolean accept(TreeWalkerAuditEvent event) {
return !isFileNameAndModuleAndCheckNameMatching(event)
+ || !isMessageNameMatching(event)
|| !isXpathQueryMatching(event);
}
@@ -109,26 +129,39 @@ public class XpathFilter implements TreeWalkerFilter {
*/
private boolean isFileNameAndModuleAndCheckNameMatching(TreeWalkerAuditEvent event) {
return event.getFileName() != null
- && fileRegexp.matcher(event.getFileName()).find()
+ && (fileRegexp == null || fileRegexp.matcher(event.getFileName()).find())
&& event.getLocalizedMessage() != null
&& (moduleId == null || moduleId.equals(event.getModuleId()))
&& (checkRegexp == null || checkRegexp.matcher(event.getSourceName()).find());
}
/**
+ * Is matching by message.
+ * @param event event
+ * @return true is matching or not set.
+ */
+ private boolean isMessageNameMatching(TreeWalkerAuditEvent event) {
+ return messageRegexp == null || messageRegexp.matcher(event.getMessage()).find();
+ }
+
+ /**
* Is matching by xpath query.
* @param event event
* @return true is matching
*/
private boolean isXpathQueryMatching(TreeWalkerAuditEvent event) {
- boolean isMatching = false;
- if (xpathExpression != null) {
+ boolean isMatching;
+ if (xpathExpression == null) {
+ isMatching = true;
+ }
+ else {
+ isMatching = false;
final List<Item> items = getItems(event);
for (Item item : items) {
final AbstractNode abstractNode = (AbstractNode) item;
isMatching = abstractNode.getTokenType() == event.getTokenType()
&& abstractNode.getLineNumber() == event.getLine()
- && abstractNode.getColumnNumber() == event.getColumn();
+ && abstractNode.getColumnNumber() == event.getColumnCharIndex();
if (isMatching) {
break;
}
@@ -165,7 +198,7 @@ public class XpathFilter implements TreeWalkerFilter {
@Override
public int hashCode() {
- return Objects.hash(filePattern, checkPattern, moduleId, xpathQuery);
+ return Objects.hash(filePattern, checkPattern, messagePattern, moduleId, xpathQuery);
}
@Override
@@ -179,6 +212,7 @@ public class XpathFilter implements TreeWalkerFilter {
final XpathFilter xpathFilter = (XpathFilter) other;
return Objects.equals(filePattern, xpathFilter.filePattern)
&& Objects.equals(checkPattern, xpathFilter.checkPattern)
+ && Objects.equals(messagePattern, xpathFilter.messagePattern)
&& Objects.equals(moduleId, xpathFilter.moduleId)
&& Objects.equals(xpathQuery, xpathFilter.xpathQuery);
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtility.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtility.java
index bb673e99b..a36d6092d 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtility.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtility.java
@@ -155,7 +155,7 @@ public final class AnnotationUtility {
for (DetailAST child = holder.getFirstChild();
child != null; child = child.getNextSibling()) {
if (child.getType() == TokenTypes.ANNOTATION) {
- final DetailAST firstChild = child.getFirstChild();
+ final DetailAST firstChild = child.findFirstToken(TokenTypes.AT);
final String name =
FullIdent.createFullIdent(firstChild.getNextSibling()).getText();
if (annotation.equals(name)) {
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.java
index f35404e7e..5d4934261 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPosition.java
@@ -36,6 +36,18 @@ public final class BlockCommentPosition {
}
/**
+ * Node is on type definition.
+ * @param blockComment DetailAST
+ * @return true if node is before class, interface, enum or annotation.
+ */
+ public static boolean isOnType(DetailAST blockComment) {
+ return isOnClass(blockComment)
+ || isOnInterface(blockComment)
+ || isOnEnum(blockComment)
+ || isOnAnnotationDef(blockComment);
+ }
+
+ /**
* Node is on class definition.
* @param blockComment DetailAST
* @return true if node is before class
@@ -80,6 +92,20 @@ public final class BlockCommentPosition {
}
/**
+ * Node is on type member declaration.
+ * @param blockComment DetailAST
+ * @return true if node is before method, field, constructor, enum constant
+ * or annotation field
+ */
+ public static boolean isOnMember(DetailAST blockComment) {
+ return isOnMethod(blockComment)
+ || isOnField(blockComment)
+ || isOnConstructor(blockComment)
+ || isOnEnumConstant(blockComment)
+ || isOnAnnotationField(blockComment);
+ }
+
+ /**
* Node is on method declaration.
* @param blockComment DetailAST
* @return true if node is before method
@@ -130,6 +156,17 @@ public final class BlockCommentPosition {
}
/**
+ * Node is on annotation field declaration.
+ * @param blockComment DetailAST
+ * @return true if node is before annotation field
+ */
+ public static boolean isOnAnnotationField(DetailAST blockComment) {
+ return isOnPlainClassMember(blockComment, TokenTypes.ANNOTATION_FIELD_DEF)
+ || isOnTokenWithModifiers(blockComment, TokenTypes.ANNOTATION_FIELD_DEF)
+ || isOnTokenWithAnnotation(blockComment, TokenTypes.ANNOTATION_FIELD_DEF);
+ }
+
+ /**
* Checks that block comment is on specified token without any modifiers.
* @param blockComment block comment start DetailAST
* @param parentTokenType parent token type
@@ -179,11 +216,16 @@ public final class BlockCommentPosition {
* @return true if block comment is on specified token without modifiers
*/
private static boolean isOnPlainClassMember(DetailAST blockComment, int memberType) {
- return blockComment.getParent() != null
- && blockComment.getParent().getType() == TokenTypes.TYPE
- && blockComment.getParent().getParent().getType() == memberType
+ DetailAST parent = blockComment.getParent();
+ // type could be in fully qualified form, so we go up to Type token
+ while (parent != null && parent.getType() == TokenTypes.DOT) {
+ parent = parent.getParent();
+ }
+ return parent != null
+ && parent.getType() == TokenTypes.TYPE
+ && parent.getParent().getType() == memberType
// previous parent sibling is always TokenTypes.MODIFIERS
- && blockComment.getParent().getPreviousSibling().getChildCount() == 0;
+ && parent.getPreviousSibling().getChildCount() == 0;
}
/**
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java
index 14b3e03b5..122c6f277 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/CommonUtils.java
@@ -129,7 +129,7 @@ public final class CommonUtils {
commentContent.setText("*" + content);
commentContent.setLineNo(0);
// javadoc should starts at 0 column, so COMMENT_CONTENT node
- // that contains javadoc identificator has -1 column
+ // that contains javadoc identifier has -1 column
commentContent.setColumnNo(-1);
final DetailAST blockCommentEnd = new DetailAST();
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtils.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtils.java
index b744167cd..947760370 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtils.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtils.java
@@ -30,6 +30,7 @@ import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.DetailNode;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.checks.javadoc.InvalidJavadocTag;
import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTag;
import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo;
@@ -176,8 +177,8 @@ public final class JavadocUtils {
boolean result = false;
if (!commentContent.isEmpty()) {
- final char docCommentIdentificator = commentContent.charAt(0);
- result = docCommentIdentificator == '*';
+ final char docCommentIdentifier = commentContent.charAt(0);
+ result = docCommentIdentifier == '*';
}
return result;
@@ -400,24 +401,40 @@ public final class JavadocUtils {
/**
* Checks Javadoc comment it's in right place.
- * From Javadoc util documentation:
+ * <p>From Javadoc util documentation:
* "Placement of comments - Documentation comments are recognized only when placed
- * immediately before class, interface, constructor, method, or field
+ * immediately before class, interface, constructor, method, field or annotation field
* declarations -- see the class example, method example, and field example.
- * Documentation comments placed in the body of a method are ignored. Only one
- * documentation comment per declaration statement is recognized by the Javadoc tool."
+ * Documentation comments placed in the body of a method are ignored."</p>
+ * <p>If there are many documentation comments per declaration statement,
+ * only the last one will be recognized.</p>
*
* @param blockComment Block comment AST
* @return true if Javadoc is in right place
+ * @see <a href="https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javadoc.html">
+ * Javadoc util documentation</a>
*/
private static boolean isCorrectJavadocPosition(DetailAST blockComment) {
- return BlockCommentPosition.isOnClass(blockComment)
- || BlockCommentPosition.isOnInterface(blockComment)
- || BlockCommentPosition.isOnEnum(blockComment)
- || BlockCommentPosition.isOnMethod(blockComment)
- || BlockCommentPosition.isOnField(blockComment)
- || BlockCommentPosition.isOnConstructor(blockComment)
- || BlockCommentPosition.isOnEnumConstant(blockComment)
- || BlockCommentPosition.isOnAnnotationDef(blockComment);
+ // We must be sure that after this one there are no other documentation comments.
+ DetailAST sibling = blockComment.getNextSibling();
+ while (sibling != null) {
+ if (sibling.getType() == TokenTypes.BLOCK_COMMENT_BEGIN) {
+ if (isJavadocComment(getBlockCommentContent(sibling))) {
+ // Found another javadoc comment, so this one should be ignored.
+ break;
+ }
+ sibling = sibling.getNextSibling();
+ }
+ else if (sibling.getType() == TokenTypes.SINGLE_LINE_COMMENT) {
+ sibling = sibling.getNextSibling();
+ }
+ else {
+ // Annotation, declaration or modifier is here. Do not check further.
+ sibling = null;
+ }
+ }
+ return sibling == null
+ && (BlockCommentPosition.isOnType(blockComment)
+ || BlockCommentPosition.isOnMember(blockComment));
}
}
diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtils.java b/src/main/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtils.java
index c05c21c0c..d52f7041c 100644
--- a/src/main/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtils.java
+++ b/src/main/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtils.java
@@ -73,7 +73,7 @@ public final class ModuleReflectionUtils {
*/
public static boolean isCheckstyleModule(Class<?> clazz) {
return isValidCheckstyleClass(clazz)
- && (isCheckstyleCheck(clazz)
+ && (isCheckstyleTreeWalkerCheck(clazz)
|| isFileSetModule(clazz)
|| isFilterModule(clazz)
|| isFileFilterModule(clazz)
@@ -111,12 +111,13 @@ public final class ModuleReflectionUtils {
}
/**
- * Checks whether a class may be considered as the checkstyle check.
+ * Checks whether a class may be considered as the checkstyle check
+ * which has TreeWalker as a parent.
* Checkstyle's checks are classes which implement 'AbstractCheck' interface.
* @param clazz class to check.
* @return true if a class may be considered as the checkstyle check.
*/
- public static boolean isCheckstyleCheck(Class<?> clazz) {
+ public static boolean isCheckstyleTreeWalkerCheck(Class<?> clazz) {
return AbstractCheck.class.isAssignableFrom(clazz);
}
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties
index 64b56e1a2..7a2168816 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Overload methods should not be split. Previous over
parameter.assignment=Assignment of parameter ''{0}'' is not allowed.
require.this.method=Method call to ''{0}'' needs \"{1}this.\".
require.this.variable=Reference to instance variable ''{0}'' needs \"{1}this.\".
-return.count=Return count is {0,number,integer} (max allowed is {1,number,integer}).
+return.count=Return count is {0,number,integer} (max allowed for non-void methods/lambdas is {1,number,integer}).
+return.countVoid=Return count is {0,number,integer} (max allowed for void methods/constructors/lambdas is {1,number,integer}).
simplify.boolReturn=Conditional logic can be removed.
simplify.expression=Expression can be simplified.
string.literal.equality=Literal Strings should be compared using equals(), not ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties
index bb1308e27..6e46475d4 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_de.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Die Definition der überladene Methoden steht nicht
parameter.assignment=Die Zuweisung des Parameters ''{0}'' ist nicht erlaubt.
require.this.method=Der Methodenaufruf ''{0}'' erfordert ein vorangestelltes \"{1}this.\".
require.this.variable=Der Instanzvariablenzugriff ''{0}'' erfordert ein vorangestelltes \"{1}this.\".
-return.count=Die Methode hat insgesamt {0,number,integer} return-Anweisungen (Obergrenze ist {1,number,integer}).
+return.count=Die Methode hat insgesamt {0,number,integer} return-Anweisungen (max erlaubt für nicht void Methoden / Lambdas ist ist {1,number,integer}).
+return.countVoid=Die Methode hat insgesamt {0,number,integer} return-Anweisungen (max erlaubt für void Methoden / Konstruktoren / Lambdas ist {1,number,integer}).
simplify.boolReturn=Die Verzweigungslogik kann entfernt werden.
simplify.expression=Der Ausdruck kann vereinfacht werden.
string.literal.equality=Der Vergleich von String-Literalen sollte mit equals() erfolgen, nicht mit ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties
index 1a97e0017..3f7b7f6a8 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_es.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Métodos de sobrecarga no deben ser divididos. Mét
parameter.assignment=No esta permitida la asignación del parámetro ''{0}''.
require.this.method=La llamada al método ''{0}'' necesita \"{1}this.\".
require.this.variable=La referencia a la variable de instancia ''{0}'' necesita \"{1}this.\".
-return.count=El número de sentencias return es {0,number,integer} (máximo permitido es {1,number,integer}).
+return.count=El número de sentencias return es {0,number,integer} (max permitido para métodos no vacíos / lambdas es {1,number,integer}).
+return.countVoid=El número de sentencias return es {0,number,integer} (max permitido para métodos / constructores / lambdas vacíos {1,number,integer}).
simplify.boolReturn=Se puede eliminar la lógica condicional.
simplify.expression=Se puede simplificar la expresión.
string.literal.equality=Las cadenas literales deben compararse usando equals(), no ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties
index b28e231c1..1246514af 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fi.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Ylikuormitus menetelmiä ei tulisi jakaa. Edellinen
parameter.assignment=Tehtävä parametrin ''{0}'' ei ole sallittu.
require.this.method=Menetelmä kehotus ''{0}'' tarvitsee \"{1}this.\".
require.this.variable=Viittaus Esimerkiksi muuttuja ''{0}'' tarvitsee \"{1}this.\".
-return.count=Paluu määrä on {0, number, integer} (max sallittu on {1, number, integer}).
+return.count=Paluu määrä on {0, number, integer} (max sallittu ei-tyhjiin menetelmiin / lambdas {1, number, integer}).
+return.countVoid=Paluu määrä on {0, number, integer} (max sallittu menetelmät / konstruktorit / lambdas ovat {1, number, integer}).
simplify.boolReturn=Konditionaalilogiikan voisi poistaa.
simplify.expression=Ilmaisua voisi yksinkertaistaa.
string.literal.equality=Kirjaimellinen Strings pitäisi verrata käyttämällä tasavertaisten (), ei ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties
index 7ae8de9d5..a1d712fbf 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_fr.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Les méthodes de surcharge ne doivent pas être sé
parameter.assignment=Il est interdit d''affecter une valeur au paramètre ''{0}''.
require.this.method=L''appel à la méthode ''{0}'' nécessite l''utilisation de \"{1}this.\".
require.this.variable=La référence à la variable d''instance ''{0}'' doit utiliser \"{1}this.\".
-return.count=Le nombre de return est de {0,number,integer} alors que le maximum autorisé est de {1,number,integer}.
+return.count=Le nombre de return est de {0,number,integer} alors que le maximum méthodes non-nulles/lambdas {1,number,integer}.
+return.countVoid=Le nombre de return est de {0,number,integer} alors que le maximum autorisé void methods/constructors/lambdas est de {1,number,integer}.
simplify.boolReturn=Le test peut être supprimé et l''expression directement retournée.
simplify.expression=L''expression peut être simplifiée.
string.literal.equality=Les chaines de caractères littérales devraient être comparées avec la méthode equals() et pas avec ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties
index 98adfa1fa..ae74664c6 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_ja.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=オーバーロードされているメソッドは
parameter.assignment=パラメータ ''{0}'' への代入は許可されていません。
require.this.method=メソッド ''{0}'' への呼び出しは、 \"{1}this.\" が必要です。
require.this.variable=インスタンス変数 ''{0}'' への参照には \"{1}this.\" が必要です。
-return.count=return が {0,number,integer} 個所あります(最大 {1,number,integer} まで)。
+return.count=return が {0,number,integer} 個所あります(非無効メソッド/ ラムダに許される最大値は {1,number,integer} まで)。
+return.countVoid=return が {0,number,integer} 個所あります(無効メソッド/コンストラクタ/ ラムダメソッドに許可される最大値は {1,number,integer} まで)。
simplify.boolReturn=条件ロジックはなくせます。
simplify.expression=表現は簡潔にできます。
string.literal.equality=リテラルの文字列は ''{0}'' ではなく、 equals() を使用して比較するべきです。
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties
index 73fb2cc7c..da79ad8de 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_pt.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=Métodos de sobrecarga não devem ser separados. O
parameter.assignment=A atribuição ao parâmetro ''{0}'' não é permitda.
require.this.method=A chamada de método no ''{0}'' precisa de \"{1}this.\".
require.this.variable=A referência à variável de instância ''{0}'' precisa de \"{1}this.\".
-return.count=O número de \"return\"s é {0,number,integer} (o máximo permitido é {1,number,integer}).
+return.count=O número de \"return\"s é {0,number,integer} (o máximo permitido para métodos não vazios/lambdas é {1,number,integer}).
+return.countVoid=O número de \"return\"s é {0,number,integer} (o máximo permitido para vazios métodos/construtores/lambdas é {1,number,integer}).
simplify.boolReturn=A lógica condicional pode ser removida.
simplify.expression=A expressão pode ser simplicada.
string.literal.equality=Literais de String deveriam ser comparados com \"equals()\", não com ''{0}''.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties
index da4f29763..4e278314c 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_tr.properties
@@ -45,7 +45,8 @@ overload.methods.declaration=Aşırı yük yöntemleri bölünmüş olmamalıdı
parameter.assignment=''{0}'' parametresine atama yapılamaz.
require.this.method=''{0}'' metoduna erişim \"{1}this.\" kullanılarak yapılmalıdır.
require.this.variable=''{0}'' değişkenine erişim \"{1}this.\" kullanılarak yapılmalıdır.
-return.count=Kullanılan ''return'' sayısı {0,number,integer} (maksimum izin verilen değer {1,number,integer}).
+return.count=Kullanılan ''return'' sayısı {0,number,integer} (void olmayan yöntemler / lambdas için izin verilen maksimum sayı {1,number,integer}).
+return.countVoid=Kullanılan ''return'' sayısı {0,number,integer} (void yöntemleri / kurucu / lambdas için izin verilen maksimum sayı {1,number,integer}).
simplify.boolReturn=Koşul mantığı kaldırılabilir.
simplify.expression=İfade sadeleştirilebilir.
string.literal.equality=''String'' ifadeleri ''{0}'' kullanarak değil, equals() metodu kullanarak karşılaştırılmalı.
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_zh.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_zh.properties
index 5bc59c5a1..51bf29a60 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_zh.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/coding/messages_zh.properties
@@ -44,7 +44,8 @@ overload.methods.declaration=重载方法应写在一起,上一个重载方法
parameter.assignment=不应对方法参数''{0}''赋值。
require.this.method=对方法 ''{0}'' 的调用需要 \"{1}this.\"。
require.this.variable=对实例属性 ''{0}'' 的引用需要 \"{1}this.\"。
-return.count=Return 次数 {0,number,integer} 次(最多: {1,number,integer} 次)。
+return.count=Return 次数 {0,number,integer} 次(最大允许非空虚方法/ 拉姆达: {1,number,integer} 次)。
+return.countVoid=Return 次数 {0,number,integer} 次(最大允許為void方法/構造函數/ 拉姆达: {1,number,integer} 次)。
simplify.boolReturn=不必要的条件逻辑。
simplify.expression=表达式可被简化。
string.literal.equality=字符串应使用equals()方法进行比较,而非''{0}''。
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/messages_zh.properties b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/messages_zh.properties
index 5298c0e5d..0132462d5 100644
--- a/src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/messages_zh.properties
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/checks/imports/messages_zh.properties
@@ -9,10 +9,10 @@ import.control.disallowed=不允许的导入: {0} 。
import.control.missing.file=找不到导入控制文件。
import.control.unknown.pkg=导入控制文件并未处理此包。
import.duplicate=第{0,number,integer}行重复导入:{1} 。
-import.groups.separated.internally=進口組以前的額外分離 ''{0}''。
-import.illegal=非法进口: {0} 。
+import.groups.separated.internally=导入组之前的额外空行 ''{0}''。
+import.illegal=非法导入: {0} 。
import.lang=不需要从 java.lang 包导入: {0} 。
import.ordering=导入 ''{0}'' 顺序错误。
-import.same=额外 import 当前包下内容:{0} 。
+import.same=额外导入当前包下内容:{0} 。
import.separation=''{0}'' 应与之前的导入语句通过空行隔开。
import.unused=无用导入 - {0} 。
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd b/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd
new file mode 100644
index 000000000..56498682e
--- /dev/null
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!-- Add the following to any file that is to be validated against this DTD:
+
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2.dtd">
+-->
+
+<!ELEMENT suppressions (suppress*)>
+
+<!ELEMENT suppress EMPTY>
+<!ATTLIST suppress files CDATA #IMPLIED
+ checks CDATA #IMPLIED
+ message CDATA #IMPLIED
+ id CDATA #IMPLIED
+ lines CDATA #IMPLIED
+ columns CDATA #IMPLIED>
diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd b/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd
new file mode 100644
index 000000000..f424d8e20
--- /dev/null
+++ b/src/main/resources/com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd
@@ -0,0 +1,25 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!-- Add the following to any file that is to be validated against this DTD:
+
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2_xpath_experimental.dtd">
+-->
+
+<!ELEMENT suppressions (suppress|suppress-xpath)*>
+
+<!ELEMENT suppress EMPTY>
+<!ATTLIST suppress files CDATA #IMPLIED
+ checks CDATA #IMPLIED
+ message CDATA #IMPLIED
+ id CDATA #IMPLIED
+ lines CDATA #IMPLIED
+ columns CDATA #IMPLIED>
+
+<!ELEMENT suppress-xpath EMPTY>
+<!ATTLIST suppress-xpath files CDATA #IMPLIED
+ checks CDATA #IMPLIED
+ message CDATA #IMPLIED
+ id CDATA #IMPLIED
+ query CDATA #IMPLIED>
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java
index b3e708a0c..5b008cf2e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractModuleTestSupport.java
@@ -81,7 +81,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* Returns test logger.
* @return logger for tests
*/
- public BriefUtLogger getBriefUtLogger() {
+ public final BriefUtLogger getBriefUtLogger() {
return new BriefUtLogger(stream);
}
@@ -95,7 +95,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @return {@link Checker} instance based on the given {@link Configuration} instance.
* @throws Exception if an exception occurs during checker configuration.
*/
- public Checker createChecker(Configuration moduleConfig)
+ public final Checker createChecker(Configuration moduleConfig)
throws Exception {
ModuleCreationOption moduleCreationOption = ModuleCreationOption.IN_CHECKER;
@@ -103,7 +103,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
if (!ROOT_MODULE_NAME.equals(moduleName)) {
try {
final Class<?> moduleClass = Class.forName(moduleName);
- if (ModuleReflectionUtils.isCheckstyleCheck(moduleClass)
+ if (ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(moduleClass)
|| ModuleReflectionUtils.isTreeWalkerFilterModule(moduleClass)) {
moduleCreationOption = ModuleCreationOption.IN_TREEWALKER;
}
@@ -124,7 +124,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @return {@link Checker} instance based on the given {@link Configuration} instance.
* @throws Exception if an exception occurs during checker configuration.
*/
- public Checker createChecker(Configuration moduleConfig,
+ public final Checker createChecker(Configuration moduleConfig,
ModuleCreationOption moduleCreationOption)
throws Exception {
final Checker checker = new Checker();
@@ -150,9 +150,9 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* based on the given {@link Configuration} instance.
* @param config {@link Configuration} instance.
* @return {@link DefaultConfiguration} for the {@link TreeWalker}
- * based on the given {@link Configuration} instance.
+ * based on the given {@link Configuration} instance.
*/
- protected DefaultConfiguration createTreeWalkerConfig(Configuration config) {
+ protected static DefaultConfiguration createTreeWalkerConfig(Configuration config) {
final DefaultConfiguration dc =
new DefaultConfiguration("configuration");
final DefaultConfiguration twConf = createModuleConfig(TreeWalker.class);
@@ -168,7 +168,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param config {@link Configuration} instance.
* @return {@link DefaultConfiguration} for the given {@link Configuration} instance.
*/
- protected DefaultConfiguration createRootConfig(Configuration config) {
+ protected static DefaultConfiguration createRootConfig(Configuration config) {
final DefaultConfiguration dc = new DefaultConfiguration(ROOT_MODULE_NAME);
if (config != null) {
dc.addChild(config);
@@ -198,7 +198,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param filename file name.
* @return URI-representation of the path for the file with the given file name.
*/
- protected String getUriString(String filename) {
+ protected final String getUriString(String filename) {
return new File("src/test/resources/" + getPackageLocation() + "/" + filename).toURI()
.toString();
}
@@ -213,7 +213,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
- protected void verify(Configuration aConfig, String fileName, String... expected)
+ protected final void verify(Configuration aConfig, String fileName, String... expected)
throws Exception {
verify(createChecker(aConfig), fileName, fileName, expected);
}
@@ -246,7 +246,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param expected an array of expected messages.
* @throws Exception if exception occurs during verification process.
*/
- protected void verify(Checker checker,
+ protected final void verify(Checker checker,
String processedFilename,
String messageFileName,
String... expected)
@@ -257,8 +257,13 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
}
/**
- * We keep two verify methods with separate logic only for convenience of debugging
- * We have minimum amount of multi-file test cases
+ * We keep two verify methods with separate logic only for convenience of debugging.
+ * We have minimum amount of multi-file test cases.
+ * @param checker {@link Checker} instance.
+ * @param processedFiles list of files to verify.
+ * @param messageFileName message file name.
+ * @param expected an array of expected messages.
+ * @throws Exception if exception occurs during verification process.
*/
protected void verify(Checker checker,
File[] processedFiles,
@@ -299,7 +304,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param expectedViolations a map of expected violations per files.
* @throws Exception if exception occurs during verification process.
*/
- protected void verify(Checker checker,
+ protected final void verify(Checker checker,
File[] processedFiles,
Map<String, List<String>> expectedViolations)
throws Exception {
@@ -383,8 +388,9 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
*
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
+ * @return The message of the check with the arguments applied.
*/
- protected String getCheckMessage(String messageKey, Object... arguments) {
+ protected final String getCheckMessage(String messageKey, Object... arguments) {
return internalGetCheckMessage(getMessageBundle(), messageKey, arguments);
}
@@ -395,6 +401,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param clazz the related check class.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
+ * @return The message of the check with the arguments applied.
*/
protected static String getCheckMessage(
Class<?> clazz, String messageKey, Object... arguments) {
@@ -408,6 +415,7 @@ public abstract class AbstractModuleTestSupport extends AbstractPathTestSupport
* @param messageBundle the bundle name.
* @param messageKey the key of message in 'messages.properties' file.
* @param arguments the arguments of message in 'messages.properties' file.
+ * @return The message of the check with the arguments applied.
*/
private static String internalGetCheckMessage(
String messageBundle, String messageKey, Object... arguments) {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java
index 9b79d8f59..849cf8981 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java
@@ -21,8 +21,15 @@ package com.puppycrawl.tools.checkstyle;
import java.io.File;
import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
public abstract class AbstractPathTestSupport {
+ protected static final String LF_REGEX = "\\\\n";
+
+ protected static final String CRLF_REGEX = "\\\\r\\\\n";
+
/**
* Returns the exact location for the package where the file is present.
* @return path for the package name for the file.
@@ -46,4 +53,15 @@ public abstract class AbstractPathTestSupport {
protected final String getResourcePath(String filename) {
return "/" + getPackageLocation() + "/" + filename;
}
+
+ /** Reads the contents of a file.
+ * @param filename the name of the file whose contents are to be read
+ * @return contents of the file with all {@code \r\n} replaced by {@code \n}
+ * @throws IOException if I/O exception occurs while reading
+ */
+ protected static String readFile(String filename) throws IOException {
+ return new String(Files.readAllBytes(
+ Paths.get(filename)), StandardCharsets.UTF_8)
+ .replaceAll(CRLF_REGEX, LF_REGEX);
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java
index dd676666b..01113fa95 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractTreeTestSupport.java
@@ -23,16 +23,9 @@ import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Paths;
public abstract class AbstractTreeTestSupport extends AbstractPathTestSupport {
- protected static final String LF_REGEX = "\\\\n";
-
- protected static final String CRLF_REGEX = "\\\\r\\\\n";
-
/**
* Returns canonical path for the file with the given file name.
* The path is formed base on the non-compilable resources location.
@@ -118,15 +111,4 @@ public abstract class AbstractTreeTestSupport extends AbstractPathTestSupport {
assertEquals("Generated tree from the javadoc file should match the pre-defined tree",
expectedContents, actualContents);
}
-
- /** Reads the contents of a file.
- * @param filename the name of the file whose contents are to be read
- * @return contents of the file with all {@code \r\n} replaced by {@code \n}
- * @throws IOException if I/O exception occurs while reading
- */
- protected static String readFile(String filename) throws IOException {
- return new String(Files.readAllBytes(
- Paths.get(filename)), StandardCharsets.UTF_8)
- .replaceAll(CRLF_REGEX, LF_REGEX);
- }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java
new file mode 100644
index 000000000..9387ec28b
--- /dev/null
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractXmlTestSupport.java
@@ -0,0 +1,171 @@
+////////////////////////////////////////////////////////////////////////////////
+// checkstyle: Checks Java source code for adherence to a set of rules.
+// Copyright (C) 2001-2017 the original author or authors.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+////////////////////////////////////////////////////////////////////////////////
+
+package com.puppycrawl.tools.checkstyle;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Set;
+import java.util.function.BiPredicate;
+
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.junit.Assert;
+import org.w3c.dom.Document;
+import org.w3c.dom.NamedNodeMap;
+import org.w3c.dom.Node;
+
+import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil;
+
+public abstract class AbstractXmlTestSupport extends AbstractModuleTestSupport {
+
+ protected static Document getOutputStreamXml(ByteArrayOutputStream outputStream)
+ throws ParserConfigurationException {
+ final String xml = new String(outputStream.toByteArray(), StandardCharsets.UTF_8);
+
+ return XmlUtil.getRawXml("audit output", xml, xml);
+ }
+
+ protected static void verifyXml(String expectedOutputFile,
+ ByteArrayOutputStream actualOutputStream, String... messages) throws Exception {
+ verifyXml(expectedOutputFile, actualOutputStream, null, messages);
+ }
+
+ protected static void verifyXml(String expectedOutputFile,
+ ByteArrayOutputStream actualOutputStream,
+ BiPredicate<Node, Node> ordered, String... messages) throws Exception {
+ String expectedContents = readFile(expectedOutputFile);
+
+ for (int i = 0; i < messages.length; i++) {
+ expectedContents = expectedContents.replace("$" + i, messages[i]);
+ }
+
+ final Document expectedDocument = XmlUtil.getRawXml("audit output", expectedContents,
+ expectedContents);
+ final Document actualDocument = getOutputStreamXml(actualOutputStream);
+
+ verifyXmlNode(expectedDocument, actualDocument, "/", ordered);
+ }
+
+ private static void verifyXmlNodes(Node expected, Node actual, String path,
+ BiPredicate<Node, Node> ordered) {
+ final Node expectedFirstChild = expected.getFirstChild();
+ final Node actualFirstChild = actual.getFirstChild();
+
+ if (expectedFirstChild == null) {
+ Assert.assertNull("no children nodes should exist: " + path, actualFirstChild);
+ Assert.assertEquals("text should be the same: " + path, expected.getNodeValue(),
+ actual.getNodeValue());
+ }
+ else {
+ Assert.assertNotNull("children nodes should exist: " + path, actualFirstChild);
+
+ if (ordered == null) {
+ Node actualChild = actualFirstChild;
+
+ for (Node expectedChild = expectedFirstChild; expectedChild != null;
+ expectedChild = expectedChild.getNextSibling()) {
+ verifyXmlNode(expectedChild, actualChild, path, ordered);
+
+ actualChild = actualChild.getNextSibling();
+ }
+
+ Assert.assertNull("node have same number of children: " + path, actualChild);
+ }
+ else {
+ final Set<Node> expectedChildren = XmlUtil.getChildrenElements(expected);
+ final Set<Node> actualChildren = XmlUtil.getChildrenElements(actual);
+
+ Assert.assertEquals("node have same number of children: " + path,
+ expectedChildren.size(), actualChildren.size());
+
+ for (Node expectedChild : expectedChildren) {
+ Node foundChild = null;
+
+ for (Node actualChild : actualChildren) {
+ if (ordered.test(expectedChild, actualChild)) {
+ foundChild = actualChild;
+ break;
+ }
+ }
+
+ Assert.assertNotNull("node should exist: " + path + expectedChild.getNodeName()
+ + "/", foundChild);
+
+ verifyXmlNode(expectedChild, foundChild, path, ordered);
+ }
+ }
+ }
+ }
+
+ private static void verifyXmlNode(Node expected, Node actual, String path,
+ BiPredicate<Node, Node> ordered) {
+ if (expected == null) {
+ if (actual != null) {
+ Assert.fail("no node should exist: " + path + actual.getNodeName() + "/");
+ }
+ }
+ else {
+ final String newPath = path + expected.getNodeName() + "/";
+
+ Assert.assertNotNull("node should exist: " + newPath, actual);
+ Assert.assertEquals("node should have same name: " + newPath, expected.getNodeName(),
+ actual.getNodeName());
+ Assert.assertEquals("node should have same type: " + newPath, expected.getNodeType(),
+ actual.getNodeType());
+
+ verifyXmlAttributes(expected.getAttributes(), actual.getAttributes(), newPath);
+
+ verifyXmlNodes(expected, actual, newPath, ordered);
+ }
+ }
+
+ private static void verifyXmlAttributes(NamedNodeMap expected, NamedNodeMap actual,
+ String path) {
+ if (expected == null) {
+ Assert.assertNull("no attributes should exist: " + path, actual);
+ }
+ else {
+ Assert.assertNotNull("attributes should exist: " + path, actual);
+
+ for (int i = 0; i < expected.getLength(); i++) {
+ verifyXmlAttribute(expected.item(i), actual.item(i), path);
+ }
+
+ Assert.assertEquals("node have same number of attributes: " + path,
+ expected.getLength(), actual.getLength());
+ }
+ }
+
+ private static void verifyXmlAttribute(Node expected, Node actual, String path) {
+ final String expectedName = expected.getNodeName();
+
+ Assert.assertNotNull("attribute value for '" + expectedName + "' should not be null: "
+ + path, actual);
+
+ Assert.assertEquals("attribute name should match: " + path, expectedName,
+ actual.getNodeName());
+
+ // ignore checkstyle version in xml as it changes each release
+ if (!"/#document/checkstyle".equals(path) && !"version".equals(expectedName)) {
+ Assert.assertEquals("attribute value for '" + expectedName + "' should match: " + path,
+ expected.getNodeValue(), actual.getNodeValue());
+ }
+ }
+}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
index 876492e7f..a59c27ea0 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/CheckerTest.java
@@ -415,7 +415,7 @@ public class CheckerTest extends AbstractModuleTestSupport {
assertEquals("Charset was different than expected",
System.getProperty("file.encoding", StandardCharsets.UTF_8.name()),
context.get("charset"));
- assertEquals("Was used unsufficient classloader",
+ assertEquals("Was used insufficient classloader",
contextClassLoader, context.get("classLoader"));
assertEquals("Severity is set to unexpected value",
"error", context.get("severity"));
@@ -1079,7 +1079,7 @@ public class CheckerTest extends AbstractModuleTestSupport {
@Override
public Set<String> getExternalResourceLocations() {
final Set<String> externalResourceLocation = new HashSet<>(1);
- externalResourceLocation.add("non_existing_external_resource.xml");
+ externalResourceLocation.add("non_existent_external_resource.xml");
return externalResourceLocation;
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
index 3e43563e2..909fed3ee 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/ConfigurationLoaderTest.java
@@ -511,16 +511,16 @@ public class ConfigurationLoaderTest extends AbstractPathTestSupport {
}
@Test
- public void testNonExistingPropertyName() throws Exception {
+ public void testNonExistentPropertyName() throws Exception {
try {
- loadConfiguration("InputConfigurationLoaderNonexistingProperty.xml");
+ loadConfiguration("InputConfigurationLoaderNonexistentProperty.xml");
fail("exception in expected");
}
catch (CheckstyleException ex) {
assertEquals("Invalid exception message",
"unable to parse configuration stream", ex.getMessage());
assertEquals("Invalid exception cause message",
- "Property ${nonexisting} has not been set",
+ "Property ${nonexistent} has not been set",
ex.getCause().getMessage());
}
}
@@ -619,7 +619,7 @@ public class ConfigurationLoaderTest extends AbstractPathTestSupport {
/**
* This SuppressWarning("unchecked") required to suppress
- * "Unchecked generics array creation for varargs parameter" during mock
+ * "Unchecked generics array creation for varargs parameter" during mock.
* @throws Exception could happen from PowerMokito calls and getAttribute
*/
@SuppressWarnings("unchecked")
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java
index de4d5a975..07ede0057 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultConfigurationTest.java
@@ -32,18 +32,18 @@ public class DefaultConfigurationTest {
public void testRemoveChild() {
final DefaultConfiguration config = new DefaultConfiguration("MyConfig");
final DefaultConfiguration configChild = new DefaultConfiguration("childConfig");
- assertEquals("Invalid cildren count", 0, config.getChildren().length);
+ assertEquals("Invalid children count", 0, config.getChildren().length);
config.addChild(configChild);
- assertEquals("Invalid cildren count", 1, config.getChildren().length);
+ assertEquals("Invalid children count", 1, config.getChildren().length);
config.removeChild(configChild);
- assertEquals("Invalid cildren count", 0, config.getChildren().length);
+ assertEquals("Invalid children count", 0, config.getChildren().length);
}
@Test
- public void testExceptionForNonExistingAttribute() {
+ public void testExceptionForNonExistentAttribute() {
final String name = "MyConfig";
final DefaultConfiguration config = new DefaultConfiguration(name);
- final String attributeName = "NonExisting#$%";
+ final String attributeName = "NonExistent#$%";
try {
config.getAttribute(attributeName);
fail("Exception is expected");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
index 654da102d..a339424a0 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java
@@ -19,6 +19,7 @@
package com.puppycrawl.tools.checkstyle;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
@@ -33,6 +34,7 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@@ -114,4 +116,15 @@ public class DefaultLoggerTest {
assertTrue("Message should contain exception info, but was " + infoStream,
infoStream.toString().contains("java.lang.IllegalStateException: upsss"));
}
+
+ @Test
+ public void testFinishLocalSetup() throws CheckstyleException {
+ final OutputStream infoStream = new ByteArrayOutputStream();
+ final DefaultLogger dl = new DefaultLogger(infoStream,
+ AutomaticBean.OutputStreamOptions.CLOSE);
+ dl.finishLocalSetup();
+ dl.auditStarted(null);
+ dl.auditFinished(null);
+ assertNotNull("instance should not be null", dl);
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java
index e6f46a06a..6d77ef350 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/DetailNodeTreeStringPrinterTest.java
@@ -77,7 +77,7 @@ public class DetailNodeTreeStringPrinterTest extends AbstractTreeTestSupport {
}
@Test
- public void testNoUnnecessaryTextinJavadocAst() throws Exception {
+ public void testNoUnnecessaryTextInJavadocAst() throws Exception {
verifyJavadocTree(
getPath("ExpectedDetailNodeTreeStringPrinterNoUnnecessaryTextInJavadocAst.txt"),
getPath("InputDetailNodeTreeStringPrinterNoUnnecessaryTextInJavadocAst.javadoc"));
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
index 77b8d4a30..a29340b4a 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java
@@ -173,7 +173,7 @@ public class MainTest {
throws Exception {
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log",
+ assertEquals("Unexpected output log",
"Checkstyle version: null" + System.lineSeparator(),
systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
@@ -188,7 +188,7 @@ public class MainTest {
exit.checkAssertionAfterwards(() -> {
final String usage = "Unrecognized option: -w" + EOL
+ USAGE;
- assertEquals("Unexpected ouput log", usage, systemOut.getLog());
+ assertEquals("Unexpected output log", usage, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-w");
@@ -199,7 +199,7 @@ public class MainTest {
throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log",
+ assertEquals("Unexpected output log",
"Must specify a config XML file." + System.lineSeparator(),
systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
@@ -208,36 +208,36 @@ public class MainTest {
}
@Test
- public void testNonExistingTargetFile()
+ public void testNonExistentTargetFile()
throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Files to process must be specified, found 0."
+ assertEquals("Unexpected output log", "Files to process must be specified, found 0."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
- Main.main("-c", "/google_checks.xml", "NonExistingFile.java");
+ Main.main("-c", "/google_checks.xml", "NonExistentFile.java");
}
@Test
- public void testNonExistingConfigFile()
+ public void testNonExistentConfigFile()
throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Could not find config XML file "
- + "'src/main/resources/non_existing_config.xml'." + EOL,
+ assertEquals("Unexpected output log", "Could not find config XML file "
+ + "'src/main/resources/non_existent_config.xml'." + EOL,
systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
- Main.main("-c", "src/main/resources/non_existing_config.xml",
+ Main.main("-c", "src/main/resources/non_existent_config.xml",
getPath("InputMain.java"));
}
@Test
- public void testNonExistingOutputFormat() throws Exception {
+ public void testNonExistentOutputFormat() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Invalid output format. "
+ assertEquals("Unexpected output log", "Invalid output format. "
+ "Found 'xmlp' but expected 'plain' or 'xml'." + EOL, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -246,19 +246,18 @@ public class MainTest {
}
@Test
- public void testNonExistingClass() throws Exception {
+ public void testNonExistentClass() throws Exception {
exit.expectSystemExitWithStatus(-2);
exit.checkAssertionAfterwards(() -> {
- final String expectedExceptionMessage = errorCounterOneMessage.getMessage()
- + EOL;
- assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog());
+ final String expectedExceptionMessage = errorCounterOneMessage.getMessage() + EOL;
+ assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog());
final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:"
+ " cannot initialize module TreeWalker - ";
assertTrue("Unexpected system error log", systemErr.getLog().startsWith(cause));
});
- Main.main("-c", getPath("InputMainConfig-non-existing-classname.xml"),
+ Main.main("-c", getPath("InputMainConfig-non-existent-classname.xml"),
getPath("InputMain.java"));
}
@@ -266,7 +265,7 @@ public class MainTest {
public void testExistingTargetFile() throws Exception {
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL
+ assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL
+ auditFinishMessage.getMessage() + EOL,
systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
@@ -284,7 +283,7 @@ public class MainTest {
ResourceBundle.getBundle("checkstylecompilation", Locale.ROOT);
final String version = compilationProperties
.getString("checkstyle.compile.version");
- assertEquals("Unexpected ouput log", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + EOL
+ assertEquals("Unexpected output log", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + EOL
+ "<checkstyle version=\"" + version + "\">" + EOL
+ "<file name=\"" + expectedPath + "\">" + EOL
+ "</file>" + EOL
@@ -300,7 +299,7 @@ public class MainTest {
public void testExistingTargetFilePlainOutput() throws Exception {
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL
+ assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL
+ auditFinishMessage.getMessage() + EOL, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -321,7 +320,7 @@ public class MainTest {
"name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"},
null, getClass(), null);
final String expectedPath = getFilePath("InputMain.java");
- assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL
+ assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL
+ "[WARN] " + expectedPath + ":3:14: "
+ invalidPatternMessageMain.getMessage()
+ " [TypeName]" + EOL
@@ -352,7 +351,7 @@ public class MainTest {
"name.invalidPattern", new String[] {"InputMainInner", "^[a-z0-9]*$"},
null, getClass(), null);
final String expectedPath = getFilePath("InputMain.java");
- assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL
+ assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL
+ "[ERROR] " + expectedPath + ":3:14: "
+ invalidPatternMessageMain.getMessage() + " [TypeName]" + EOL
+ "[ERROR] " + expectedPath + ":5:7: "
@@ -367,11 +366,11 @@ public class MainTest {
}
@Test
- public void testExistingTargetFilePlainOutputToNonExistingFile()
+ public void testExistentTargetFilePlainOutputToNonExistentFile()
throws Exception {
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-c", getPath("InputMainConfig-classname.xml"),
@@ -385,7 +384,7 @@ public class MainTest {
throws Exception {
final File file = temporaryFolder.newFile("file.output");
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-c", getPath("InputMainConfig-classname.xml"),
@@ -395,8 +394,8 @@ public class MainTest {
}
@Test
- public void testCreateNonExistingOutputFile() throws Exception {
- final String outputFile = temporaryFolder.getRoot().getCanonicalPath() + "nonexisting.out";
+ public void testCreateNonExistentOutputFile() throws Exception {
+ final String outputFile = temporaryFolder.getRoot().getCanonicalPath() + "nonexistent.out";
assertFalse("File must not exist", new File(outputFile).exists());
Main.main("-c", getPath("InputMainConfig-classname.xml"),
"-f", "plain",
@@ -413,7 +412,7 @@ public class MainTest {
//exit.expectSystemExitWithStatus(0);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", auditStartMessage.getMessage() + EOL
+ assertEquals("Unexpected output log", auditStartMessage.getMessage() + EOL
+ auditFinishMessage.getMessage() + EOL, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -426,16 +425,16 @@ public class MainTest {
}
@Test
- public void testExistingTargetFilePlainOutputNonexistingProperties()
+ public void testExistingTargetFilePlainOutputNonexistentProperties()
throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Could not find file 'nonexisting.properties'."
+ assertEquals("Unexpected output log", "Could not find file 'nonexistent.properties'."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-c", getPath("InputMainConfig-classname-prop.xml"),
- "-p", "nonexisting.properties",
+ "-p", "nonexistent.properties",
getPath("InputMain.java"));
}
@@ -445,7 +444,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-2);
exit.checkAssertionAfterwards(() -> {
final String output = errorCounterOneMessage.getMessage() + EOL;
- assertEquals("Unexpected ouput log", output, systemOut.getLog());
+ assertEquals("Unexpected output log", output, systemOut.getLog());
final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
+ "CheckstyleException: unable to parse configuration stream - ";
assertTrue("Unexpected system error log", systemErr.getLog().startsWith(errorOutput));
@@ -460,7 +459,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-2);
exit.checkAssertionAfterwards(() -> {
final String output = errorCounterOneMessage.getMessage() + EOL;
- assertEquals("Unexpected ouput log", output, systemOut.getLog());
+ assertEquals("Unexpected output log", output, systemOut.getLog());
final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
+ "CheckstyleException: cannot initialize module RegexpSingleline"
+ " - RegexpSingleline is not allowed as a child in RegexpSingleline";
@@ -476,7 +475,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-2);
exit.checkAssertionAfterwards(() -> {
final String output = errorCounterOneMessage.getMessage() + EOL;
- assertEquals("Unexpected ouput log", output, systemOut.getLog());
+ assertEquals("Unexpected output log", output, systemOut.getLog());
final String errorOutput = "com.puppycrawl.tools.checkstyle.api."
+ "CheckstyleException: cannot initialize module TreeWalker"
+ " - JavadocVariable is not allowed as a child in JavadocMethod";
@@ -521,12 +520,12 @@ public class MainTest {
final boolean samePrefix = causeMessage.substring(0, causeMessage.indexOf(' '))
.equals(localizedMessage
.substring(0, localizedMessage.indexOf(' ')));
- final boolean sameSufix =
+ final boolean sameSuffix =
causeMessage.substring(causeMessage.lastIndexOf(' '), causeMessage.length())
.equals(localizedMessage
.substring(localizedMessage.lastIndexOf(' '),
localizedMessage.length()));
- assertTrue("Invalid error message", samePrefix || sameSufix);
+ assertTrue("Invalid error message", samePrefix || sameSuffix);
assertTrue("Invalid error message",
causeMessage.contains(":invalid"));
}
@@ -614,7 +613,7 @@ public class MainTest {
}
sb.append(auditFinishMessage.getMessage())
.append(EOL);
- assertEquals("Unexpected ouput log", sb.toString(), systemOut.getLog());
+ assertEquals("Unexpected output log", sb.toString(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -659,7 +658,7 @@ public class MainTest {
exit.checkAssertionAfterwards(() -> {
final String expectedExceptionMessage = auditStartMessage.getMessage() + EOL
+ errorCounterOneMessage.getMessage() + EOL;
- assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog());
+ assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog());
final String exceptionFirstLine = "com.puppycrawl.tools.checkstyle.api."
+ "CheckstyleException: Exception was thrown while processing "
@@ -669,7 +668,7 @@ public class MainTest {
systemErr.getLog().startsWith(exceptionFirstLine));
});
- // We put xml as source to cause parse excepion
+ // We put xml as source to cause parse exception
Main.main("-c", getPath("InputMainConfig-classname.xml"),
getNonCompilablePath("InputMainIncorrectClass.java"));
}
@@ -679,7 +678,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Printing AST is allowed for only one file."
+ assertEquals("Unexpected output log", "Printing AST is allowed for only one file."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -718,7 +717,7 @@ public class MainTest {
+ " `--RCURLY -> } [6:0]" + EOL;
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", expected, systemOut.getLog());
+ assertEquals("Unexpected output log", expected, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-t", getPath("InputMain.java"));
@@ -758,7 +757,7 @@ public class MainTest {
+ " `--RCURLY -> } [6:0]" + EOL;
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", expected, systemOut.getLog());
+ assertEquals("Unexpected output log", expected, systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
Main.main("-T", getPath("InputMain.java"));
@@ -771,7 +770,7 @@ public class MainTest {
.replaceAll("\\\\r\\\\n", "\\\\n");
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log",
+ assertEquals("Unexpected output log",
expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n"));
assertEquals("Unexpected system error log",
"", systemErr.getLog());
@@ -786,7 +785,7 @@ public class MainTest {
StandardCharsets.UTF_8).replaceAll("\\\\r\\\\n", "\\\\n");
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log",
+ assertEquals("Unexpected output log",
expected, systemOut.getLog().replaceAll("\\\\r\\\\n", "\\\\n"));
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -798,7 +797,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options."
+ assertEquals("Unexpected output log", "Option '-t' cannot be used with other options."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -811,7 +810,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options."
+ assertEquals("Unexpected output log", "Option '-t' cannot be used with other options."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -824,7 +823,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options."
+ assertEquals("Unexpected output log", "Option '-t' cannot be used with other options."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -838,7 +837,7 @@ public class MainTest {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Option '-t' cannot be used with other options."
+ assertEquals("Unexpected output log", "Option '-t' cannot be used with other options."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -857,7 +856,7 @@ public class MainTest {
public void testExcludeOption() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Files to process must be specified, found 0."
+ assertEquals("Unexpected output log", "Files to process must be specified, found 0."
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -868,9 +867,9 @@ public class MainTest {
public void testExcludeRegexpOption() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Files to process must be specified, found 0."
+ assertEquals("Unexpected output log", "Files to process must be specified, found 0."
+ System.lineSeparator(), systemOut.getLog());
- assertEquals("Unexpected ouput log", "", systemErr.getLog());
+ assertEquals("Unexpected output log", "", systemErr.getLog());
});
Main.main("-c", "/google_checks.xml", getFilePath(""), "-x", ".");
}
@@ -893,7 +892,7 @@ public class MainTest {
TestRootModuleChecker.reset();
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
assertTrue("Invalid Checker state", TestRootModuleChecker.isProcessed());
});
@@ -916,7 +915,7 @@ public class MainTest {
+ "TestRootModuleCheckerCheck, " + checkstylePackage
+ "TestRootModuleCheckerCheck"},
null, getClass(), null);
- assertEquals("Unexpected ouput log", errorCounterOneMessage.getMessage() + EOL,
+ assertEquals("Unexpected output log", errorCounterOneMessage.getMessage() + EOL,
systemOut.getLog());
assertTrue("Unexpected system error log",
systemErr.getLog().startsWith(checkstylePackage + "api.CheckstyleException: "
@@ -932,14 +931,14 @@ public class MainTest {
exit.expectSystemExitWithStatus(-2);
exit.checkAssertionAfterwards(() -> {
final String expectedExceptionMessage = errorCounterOneMessage.getMessage() + EOL;
- assertEquals("Unexpected ouput log", expectedExceptionMessage, systemOut.getLog());
+ assertEquals("Unexpected output log", expectedExceptionMessage, systemOut.getLog());
final String cause = "com.puppycrawl.tools.checkstyle.api.CheckstyleException:"
+ " cannot initialize module TreeWalker - ";
assertTrue("Unexpected system error log", systemErr.getLog().startsWith(cause));
});
- Main.main("-c", getPath("InputMainConfig-non-existing-classname-ignore.xml"),
+ Main.main("-c", getPath("InputMainConfig-non-existent-classname-ignore.xml"),
"-executeIgnoredModules",
getPath("InputMain.java"));
}
@@ -948,7 +947,7 @@ public class MainTest {
public void testInvalidCheckerThreadsNumber() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Invalid Checker threads number"
+ assertEquals("Unexpected output log", "Invalid Checker threads number"
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -959,7 +958,7 @@ public class MainTest {
public void testInvalidTreeWalkerThreadsNumber() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Invalid TreeWalker threads number"
+ assertEquals("Unexpected output log", "Invalid TreeWalker threads number"
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -970,7 +969,7 @@ public class MainTest {
public void testZeroCheckerThreadsNumber() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "Checker threads number must be greater than zero"
+ assertEquals("Unexpected output log", "Checker threads number must be greater than zero"
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
});
@@ -981,7 +980,7 @@ public class MainTest {
public void testZeroTreeWalkerThreadsNumber() throws Exception {
exit.expectSystemExitWithStatus(-1);
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log",
+ assertEquals("Unexpected output log",
"TreeWalker threads number must be greater than zero"
+ System.lineSeparator(), systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
@@ -994,7 +993,7 @@ public class MainTest {
TestRootModuleChecker.reset();
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed());
final DefaultConfiguration config =
@@ -1014,7 +1013,7 @@ public class MainTest {
TestRootModuleChecker.reset();
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed());
final DefaultConfiguration config =
@@ -1034,7 +1033,7 @@ public class MainTest {
TestRootModuleChecker.reset();
exit.checkAssertionAfterwards(() -> {
- assertEquals("Unexpected ouput log", "", systemOut.getLog());
+ assertEquals("Unexpected output log", "", systemOut.getLog());
assertEquals("Unexpected system error log", "", systemErr.getLog());
assertTrue("Invalid checker state", TestRootModuleChecker.isProcessed());
final DefaultConfiguration config =
@@ -1049,7 +1048,7 @@ public class MainTest {
.getChildren()[0];
assertEquals("Invalid checker name", "Checker", checkerConfiguration.getName());
final Configuration treeWalkerConfig = checkerConfiguration.getChildren()[0];
- assertEquals("Invalid checker childs name", "TreeWalker", treeWalkerConfig.getName());
+ assertEquals("Invalid checker children name", "TreeWalker", treeWalkerConfig.getName());
});
Main.main("-C", "1", "-W", "1", "-c", getPath("InputMainConfig-multi-thread-mode.xml"),
getPath("InputMain.java"));
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
index d391e64ea..cf9823825 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/PropertyCacheFileTest.java
@@ -109,11 +109,11 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
final String filePath = temporaryFolder.newFile().getPath();
final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
cache.put("myFile", 1);
- assertTrue("Should return true wnen file is in cache",
+ assertTrue("Should return true when file is in cache",
cache.isInCache("myFile", 1));
- assertFalse("Should return false wnen file is not in cache",
+ assertFalse("Should return false when file is not in cache",
cache.isInCache("myFile", 2));
- assertFalse("Should return false wnen file is not in cache",
+ assertFalse("Should return false when file is not in cache",
cache.isInCache("myFile1", 1));
}
@@ -216,7 +216,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
}
@Test
- public void testExternalResourseIsSavedInCache() throws Exception {
+ public void testExternalResourceIsSavedInCache() throws Exception {
final Configuration config = new DefaultConfiguration("myName");
final String filePath = temporaryFolder.newFile().getPath();
final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
@@ -245,12 +245,12 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
/**
* This SuppressWarning("unchecked") required to suppress
- * "Unchecked generics array creation for varargs parameter" during mock
+ * "Unchecked generics array creation for varargs parameter" during mock.
* @throws IOException when smth wrong with file creation or cache.load
*/
@SuppressWarnings("unchecked")
@Test
- public void testNonExistingResource() throws IOException {
+ public void testNonExistentResource() throws IOException {
final Configuration config = new DefaultConfiguration("myName");
final String filePath = temporaryFolder.newFile().getPath();
final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
@@ -358,10 +358,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
}
@Test
- public void testPutNonExsistingExternalResourceSameExceptionBetweenRuns() throws Exception {
+ public void testPutNonExistentExternalResourceSameExceptionBetweenRuns() throws Exception {
final File cacheFile = temporaryFolder.newFile();
- // We mock getUriByFilename method of CommonUtils to garantee that it will
+ // We mock getUriByFilename method of CommonUtils to guarantee that it will
// throw CheckstyleException with the specific content.
mockStatic(CommonUtils.class);
final CheckstyleException mockException =
@@ -370,7 +370,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
.thenThrow(mockException);
// We invoke 'putExternalResources' twice to invalidate cache
- // and have two identical exceptions whith the equal content
+ // and have two identical exceptions which the equal content
final int numberOfRuns = 2;
final String[] configHashes = new String[numberOfRuns];
final String[] externalResourceHashes = new String[numberOfRuns];
@@ -382,10 +382,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
assertNotNull("Config hash key should not be null", configHashes[i]);
- final Set<String> nonExistingExternalResources = new HashSet<>();
- final String externalResourceFileName = "non_existing_file.xml";
- nonExistingExternalResources.add(externalResourceFileName);
- cache.putExternalResources(nonExistingExternalResources);
+ final Set<String> nonExistentExternalResources = new HashSet<>();
+ final String externalResourceFileName = "non_existent_file.xml";
+ nonExistentExternalResources.add(externalResourceFileName);
+ cache.putExternalResources(nonExistentExternalResources);
externalResourceHashes[i] = cache.get(PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX
+ externalResourceFileName);
@@ -412,7 +412,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
* @noinspection InstanceMethodNamingConvention
*/
@Test
- public void testPutNonExsistingExternalResourceDifferentExceptionsBetweenRuns()
+ public void testPutNonExistentExternalResourceDifferentExceptionsBetweenRuns()
throws Exception {
final File cacheFile = temporaryFolder.newFile();
@@ -426,7 +426,7 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
final Configuration config = new DefaultConfiguration("myConfig");
final PropertyCacheFile cache = new PropertyCacheFile(config, cacheFile.getPath());
- // We mock getUriByFilename method of CommonUtils to garantee that it will
+ // We mock getUriByFilename method of CommonUtils to guarantee that it will
// throw CheckstyleException with the specific content.
mockStatic(CommonUtils.class);
final CheckstyleException mockException = new CheckstyleException("Exception #" + i);
@@ -438,10 +438,10 @@ public class PropertyCacheFileTest extends AbstractPathTestSupport {
configHashes[i] = cache.get(PropertyCacheFile.CONFIG_HASH_KEY);
assertNotNull("Config hash key should not be null", configHashes[i]);
- final Set<String> nonExistingExternalResources = new HashSet<>();
- final String externalResourceFileName = "non_existing_file.xml";
- nonExistingExternalResources.add(externalResourceFileName);
- cache.putExternalResources(nonExistingExternalResources);
+ final Set<String> nonExistentExternalResources = new HashSet<>();
+ final String externalResourceFileName = "non_existent_file.xml";
+ nonExistentExternalResources.add(externalResourceFileName);
+ cache.putExternalResources(nonExistentExternalResources);
externalResourceHashes[i] = cache.get(PropertyCacheFile.EXTERNAL_RESOURCE_KEY_PREFIX
+ externalResourceFileName);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java
index 91464a9e8..cfb14357d 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/XMLLoggerTest.java
@@ -24,34 +24,32 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
-import java.io.InputStreamReader;
import java.io.PrintWriter;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.AutomaticBean;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
import com.puppycrawl.tools.checkstyle.internal.utils.CloseAndFlushTestByteArrayOutputStream;
-import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
/**
* Enter a description of class XMLLoggerTest.java.
* @author Rick Giles
*/
// -@cs[AbbreviationAsWordInName] Test should be named as its main class.
-public class XMLLoggerTest {
+public class XMLLoggerTest extends AbstractXmlTestSupport {
private final CloseAndFlushTestByteArrayOutputStream outStream =
new CloseAndFlushTestByteArrayOutputStream();
+ @Override
+ protected String getPackageLocation() {
+ return "com/puppycrawl/tools/checkstyle/xmllogger";
+ }
+
@Test
public void testEncode()
throws IOException {
@@ -116,7 +114,7 @@ public class XMLLoggerTest {
@Test
public void testCloseStream()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream,
AutomaticBean.OutputStreamOptions.CLOSE);
logger.auditStarted(null);
@@ -124,13 +122,12 @@ public class XMLLoggerTest {
assertEquals("Invalid close count", 1, outStream.getCloseCount());
- final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY;
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream);
}
@Test
public void testNoCloseStream()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream,
AutomaticBean.OutputStreamOptions.NONE);
logger.auditStarted(null);
@@ -139,42 +136,34 @@ public class XMLLoggerTest {
assertEquals("Invalid close count", 0, outStream.getCloseCount());
outStream.close();
- final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY;
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream);
}
@Test
public void testFileStarted()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final AuditEvent ev = new AuditEvent(this, "Test.java");
logger.fileStarted(ev);
+ logger.fileFinished(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLogger.xml"), outStream);
}
@Test
public void testFileFinished()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final AuditEvent ev = new AuditEvent(this, "Test.java");
logger.fileFinished(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLogger.xml"), outStream);
}
@Test
- public void testAddError() throws IOException {
+ public void testAddError() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -182,19 +171,15 @@ public class XMLLoggerTest {
"messages.properties", "key", null, SeverityLevel.ERROR, null,
getClass(), null);
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
+ logger.fileStarted(ev);
logger.addError(ev);
+ logger.fileFinished(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\""
- + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerError.xml"), outStream, message.getMessage());
}
@Test
- public void testAddErrorWithNullFileName() throws IOException {
+ public void testAddErrorWithNullFileName() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -204,15 +189,12 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, null, message);
logger.addError(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\""
- + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerErrorNullFileName.xml"), outStream,
+ message.getMessage());
}
@Test
- public void testAddErrorModuleId() throws IOException {
+ public void testAddErrorModuleId() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -222,17 +204,11 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
logger.addError(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\""
- + " source=\"module\"/>",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerErrorModuleId.xml"), outStream, message.getMessage());
}
@Test
- public void testAddErrorOnZeroColumns() throws IOException {
+ public void testAddErrorOnZeroColumns() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -240,19 +216,16 @@ public class XMLLoggerTest {
"messages.properties", "key", null, SeverityLevel.ERROR, null,
getClass(), null);
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
+ logger.fileStarted(ev);
logger.addError(ev);
+ logger.fileFinished(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "<error line=\"1\" severity=\"error\" message=\"key\""
- + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerErrorZeroColumn.xml"), outStream,
+ message.getMessage());
}
@Test
- public void testAddIgnored() throws IOException {
+ public void testAddIgnored() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -262,13 +235,12 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
logger.addError(ev);
logger.auditFinished(null);
- final String[] expectedLines = CommonUtils.EMPTY_STRING_ARRAY;
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerEmpty.xml"), outStream);
}
@Test
public void testAddException()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -277,20 +249,13 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;"
- + "&#10;&lt;/exception&gt;&#10;",
- "</file>",
- };
-
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerException.xml"), outStream);
assertEquals("Invalid close count", 1, outStream.getCloseCount());
}
@Test
public void testAddExceptionWithNullFileName()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -299,18 +264,13 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, null, message);
logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
logger.auditFinished(null);
- final String[] expectedLines = {
- "&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;"
- + "&#10;&lt;/exception&gt;&#10;",
- };
-
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerExceptionNullFileName.xml"), outStream);
assertEquals("Invalid close count", 1, outStream.getCloseCount());
}
@Test
public void testAddExceptionAfterFileStarted()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
@@ -323,21 +283,15 @@ public class XMLLoggerTest {
final AuditEvent ev = new AuditEvent(this, "Test.java", message);
logger.addException(ev, new TestException("msg", new RuntimeException("msg")));
+ logger.fileFinished(ev);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;"
- + "&#10;&lt;/exception&gt;&#10;",
- "</file>",
- };
-
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream);
assertEquals("Invalid close count", 1, outStream.getCloseCount());
}
@Test
public void testAddExceptionBeforeFileFinished()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -348,20 +302,13 @@ public class XMLLoggerTest {
final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java");
logger.fileFinished(fileFinishedEvent);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;"
- + "&#10;&lt;/exception&gt;&#10;",
- "</file>",
- };
-
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerException3.xml"), outStream);
assertEquals("Invalid close count", 1, outStream.getCloseCount());
}
@Test
public void testAddExceptionBetweenFileStartedAndFinished()
- throws IOException {
+ throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final LocalizedMessage message =
@@ -374,19 +321,12 @@ public class XMLLoggerTest {
final AuditEvent fileFinishedEvent = new AuditEvent(this, "Test.java");
logger.fileFinished(fileFinishedEvent);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;"
- + "&#10;&lt;/exception&gt;&#10;",
- "</file>",
- };
-
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerException2.xml"), outStream);
assertEquals("Invalid close count", 1, outStream.getCloseCount());
}
@Test
- public void testAuditFinishedWithoutFileFinished() throws IOException {
+ public void testAuditFinishedWithoutFileFinished() throws Exception {
final XMLLogger logger = new XMLLogger(outStream, true);
logger.auditStarted(null);
final AuditEvent fileStartedEvent = new AuditEvent(this, "Test.java");
@@ -399,53 +339,18 @@ public class XMLLoggerTest {
final AuditEvent errorEvent = new AuditEvent(this, "Test.java", message);
logger.addError(errorEvent);
+ logger.fileFinished(errorEvent);
logger.auditFinished(null);
- final String[] expectedLines = {
- "<file name=\"Test.java\">",
- "<error line=\"1\" column=\"1\" severity=\"error\" message=\"key\""
- + " source=\"com.puppycrawl.tools.checkstyle.XMLLoggerTest\"/>",
- "</file>",
- };
- verifyLines(expectedLines);
+ verifyXml(getPath("ExpectedXMLLoggerError.xml"), outStream, message.getMessage());
}
- private String[] getOutStreamLines()
- throws IOException {
- final byte[] bytes = outStream.toByteArray();
- final ByteArrayInputStream inStream =
- new ByteArrayInputStream(bytes);
- final List<String> lineList = new ArrayList<>();
- try (BufferedReader reader = new BufferedReader(
- new InputStreamReader(inStream, StandardCharsets.UTF_8))) {
- while (true) {
- final String line = reader.readLine();
- if (line == null) {
- break;
- }
- lineList.add(line);
- }
- }
- return lineList.toArray(new String[lineList.size()]);
- }
-
- /**
- * Verify output lines from auditStart to auditEnd.
- * Take into consideration checkstyle element (first and last lines).
- * @param expectedLines expected error report lines
- */
- private void verifyLines(String... expectedLines)
- throws IOException {
- final String[] lines = getOutStreamLines();
- assertEquals("length.", expectedLines.length + 3, lines.length);
- assertEquals("first line.",
- "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
- lines[0]);
- final Pattern checkstyleOpenTag = Pattern.compile("^<checkstyle version=\".*\">$");
- assertTrue("second line.", checkstyleOpenTag.matcher(lines[1]).matches());
- for (int i = 0; i < expectedLines.length; i++) {
- assertEquals("line " + i + ".", expectedLines[i], lines[i + 2]);
- }
- assertEquals("last line.", "</checkstyle>", lines[lines.length - 1]);
+ @Test
+ public void testFinishLocalSetup() throws CheckstyleException {
+ final XMLLogger logger = new XMLLogger(outStream, true);
+ logger.finishLocalSetup();
+ logger.auditStarted(null);
+ logger.auditFinished(null);
+ assertNotNull("instance should not be null", logger);
}
private static class TestException extends RuntimeException {
@@ -461,5 +366,4 @@ public class XMLLoggerTest {
printWriter.print("stackTrace\r\nexample");
}
}
-
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/XmlLoaderTest.java
index 80dd679d4..0c805e302 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/XmlLoaderTest.java
@@ -17,7 +17,7 @@
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
-package com.puppycrawl.tools.checkstyle.api;
+package com.puppycrawl.tools.checkstyle;
import static com.puppycrawl.tools.checkstyle.internal.utils.TestUtil.isUtilsClassHasPrivateConstructor;
import static org.junit.Assert.assertEquals;
@@ -35,26 +35,26 @@ import org.xml.sax.XMLReader;
import com.sun.org.apache.xerces.internal.impl.Constants;
-public class AbstractLoaderTest {
+public class XmlLoaderTest {
private static final String NAMESPACES_FEATURE =
Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE;
@Test
- public void testParserConfiguratedSuccefully() throws Exception {
+ public void testParserConfiguredSuccessfully() throws Exception {
final DummyLoader dummyLoader = new DummyLoader(new HashMap<>(1));
final XMLReader parser = Whitebox.getInternalState(dummyLoader, "parser");
assertTrue("Invalid feature state", parser.getFeature(NAMESPACES_FEATURE));
- assertEquals("Invalid entity resoler", dummyLoader, parser.getEntityResolver());
+ assertEquals("Invalid entity resolver", dummyLoader, parser.getEntityResolver());
}
@Test
public void testIsProperUtilsClass() throws ReflectiveOperationException {
assertTrue("Constructor is not private", isUtilsClassHasPrivateConstructor(
- AbstractLoader.FeaturesForVerySecureJavaInstallations.class, true));
+ XmlLoader.FeaturesForVerySecureJavaInstallations.class, true));
}
- private static final class DummyLoader extends AbstractLoader {
+ private static final class DummyLoader extends XmlLoader {
DummyLoader(Map<String, String> publicIdToResourceNameMap)
throws SAXException, ParserConfigurationException {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java
index 52788eba4..dee95b17f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/ant/CheckstyleAntTaskTest.java
@@ -200,7 +200,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport {
filesToCheck.size(), is(9));
assertThat("The path of file differs from expected",
filesToCheck.get(5).getAbsolutePath(), is(getPath(FLAWLESS_INPUT)));
- assertEquals("Amount of logged messages in unxexpected",
+ assertEquals("Amount of logged messages in unexpected",
9, antTask.getLoggedMessages().size());
}
@@ -250,7 +250,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport {
}
@Test
- public final void testNonExistingConfig() throws IOException {
+ public final void testNonExistentConfig() throws IOException {
final CheckstyleAntTask antTask = new CheckstyleAntTask();
antTask.setConfig(getPath(NOT_EXISTING_FILE));
antTask.setProject(new Project());
@@ -491,7 +491,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport {
}
@Test
- public final void testSetPropertiesNonExistingFile() throws IOException {
+ public final void testSetPropertiesNonExistentFile() throws IOException {
final CheckstyleAntTask antTask = getCheckstyleAntTask();
antTask.setFile(new File(getPath(FLAWLESS_INPUT)));
antTask.setProperties(new File(getPath(NOT_EXISTING_FILE)));
@@ -666,7 +666,7 @@ public class CheckstyleAntTaskTest extends AbstractPathTestSupport {
Whitebox.getInternalState(antTask, "classpath"));
}
- /** This test is created to satisfy pitest, it is hard to emulate Referece by Id */
+ /** This test is created to satisfy pitest, it is hard to emulate Reference by Id. */
@Test
public void testSetClasspathRef1() {
final CheckstyleAntTask antTask = new CheckstyleAntTask();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java
index 37b07b850..2e2d7a774 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/AbstractFileSetCheckTest.java
@@ -104,20 +104,20 @@ public class AbstractFileSetCheckTest {
}
@Test
- public void testGetFileExtention() {
+ public void testGetFileExtension() {
final DummyFileSetCheck check = new DummyFileSetCheck();
check.setFileExtensions("tmp", ".java");
- final String[] expectedExtentions = {".tmp", ".java"};
+ final String[] expectedExtensions = {".tmp", ".java"};
Assert.assertArrayEquals("Invalid extensions",
- expectedExtentions, check.getFileExtensions());
+ expectedExtensions, check.getFileExtensions());
}
/**
- * This javadoc exists only to suppress Intellij Idea inspection
+ * This javadoc exists only to suppress Intellij Idea inspection.
*/
@Test
- public void testSetExtentionThrowsExceptionWhenTheyAreNull() {
+ public void testSetExtensionThrowsExceptionWhenTheyAreNull() {
final DummyFileSetCheck check = new DummyFileSetCheck();
try {
check.setFileExtensions((String[]) null);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java
index 7ad0be759..15e6b308c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/AutomaticBeanTest.java
@@ -42,13 +42,13 @@ public class AutomaticBeanTest {
public void testConfigureNoSuchAttribute() {
final TestBean testBean = new TestBean();
final DefaultConfiguration conf = new DefaultConfiguration("testConf");
- conf.addAttribute("NonExisting", "doesn't matter");
+ conf.addAttribute("NonExistent", "doesn't matter");
try {
testBean.configure(conf);
fail("Exception is expected");
}
catch (CheckstyleException ex) {
- final String expected = "Property 'NonExisting' in module ";
+ final String expected = "Property 'NonExistent' in module ";
assertNull("Exceptions cause should be null", ex.getCause());
assertTrue("Invalid exception message, should start with: " + expected,
ex.getMessage().startsWith(expected));
@@ -209,5 +209,10 @@ public class AutomaticBeanTest {
throw new IllegalStateException(privateField + "," + wrong + "," + val + "," + value);
}
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ // No code by default
+ }
+
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java
index bf07a5be1..d3261a0a5 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/DetailASTTest.java
@@ -258,7 +258,7 @@ public class DetailASTTest extends AbstractModuleTestSupport {
}
/**
- * There are asserts in checkNode, but idea does not see them
+ * There are asserts in checkNode, but idea does not see them.
* @noinspection JUnitTestMethodWithNoAssertions
*/
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java
index 5bd90a89b..13a874328 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileContentsTest.java
@@ -34,8 +34,6 @@ import java.util.Map;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
-import com.google.common.collect.ImmutableMap;
-
public class FileContentsTest {
@Test
@@ -101,7 +99,7 @@ public class FileContentsTest {
final FileContents fileContents = new FileContents(
new FileText(new File("filename"), Collections.singletonList(" // ")));
fileContents.reportCComment(1, 2, 1, 2);
- final ImmutableMap<Integer, List<TextBlock>> comments = fileContents.getCComments();
+ final Map<Integer, List<TextBlock>> comments = fileContents.getCComments();
assertEquals("Invalid comment",
new Comment(new String[] {"/"}, 2, 1, 2).toString(),
@@ -158,7 +156,7 @@ public class FileContentsTest {
new FileText(new File("filename"), Arrays.asList(" ", " ", " /* test ",
" */ ", " ")));
fileContents.reportCComment(3, 2, 4, 2);
- final ImmutableMap<Integer, List<TextBlock>> blockComments =
+ final Map<Integer, List<TextBlock>> blockComments =
fileContents.getBlockComments();
final String[] text = blockComments.get(3).get(0).getText();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java
index af5d93cf8..7918d9683 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FileTextTest.java
@@ -38,11 +38,11 @@ import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import com.google.common.io.Closeables;
import com.puppycrawl.tools.checkstyle.AbstractPathTestSupport;
+import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@RunWith(PowerMockRunner.class)
-@PrepareForTest(Closeables.class)
+@PrepareForTest(CommonUtils.class)
public class FileTextTest extends AbstractPathTestSupport {
@Override
protected String getPackageLocation() {
@@ -67,9 +67,9 @@ public class FileTextTest extends AbstractPathTestSupport {
@Test
public void testSupportedCharset() throws IOException {
//check if reader finally closed
- mockStatic(Closeables.class);
- doNothing().when(Closeables.class);
- Closeables.closeQuietly(any(Reader.class));
+ mockStatic(CommonUtils.class);
+ doNothing().when(CommonUtils.class);
+ CommonUtils.close(any(Reader.class));
final String charsetName = StandardCharsets.ISO_8859_1.name();
final FileText fileText = new FileText(new File(getPath("InputFileTextImportControl.xml")),
@@ -77,7 +77,7 @@ public class FileTextTest extends AbstractPathTestSupport {
assertEquals("Invalid charset name", charsetName, fileText.getCharset().name());
verifyStatic(times(2));
- Closeables.closeQuietly(any(Reader.class));
+ CommonUtils.close(any(Reader.class));
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java
index d66e43619..73dc5decb 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/api/FilterSetTest.java
@@ -27,7 +27,6 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.filters.SeverityMatchFilter;
import nl.jqno.equalsverifier.EqualsVerifier;
-/** Tests SuppressElementFilter. */
public class FilterSetTest {
@Test
public void testEqualsAndHashCode() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
index d930caa79..f77c8cbae 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java
@@ -80,7 +80,7 @@ public class NewlineAtEndOfFileCheckTest
/**
* Pitest requires all closes of streams and readers to be verified. Using PowerMock
- * is almost only posibility to check it without rewriting production code.
+ * is almost only possibility to check it without rewriting production code.
*
* @throws Exception when code tested throws some exception
*/
@@ -230,7 +230,7 @@ public class NewlineAtEndOfFileCheckTest
final File impossibleFile = new File("");
final FileText fileText = new FileText(impossibleFile, lines);
final Set<LocalizedMessage> messages = check.process(impossibleFile, fileText);
- assertEquals("Ammount of messages is unexpected",
+ assertEquals("Amount of messages is unexpected",
1, messages.size());
final Iterator<LocalizedMessage> iterator = messages.iterator();
assertEquals("Violation message differs from expected",
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
index 25640caa5..a594c3db5 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/SuppressWarningsHolderTest.java
@@ -85,9 +85,9 @@ public class SuppressWarningsHolderTest extends AbstractModuleTestSupport {
@Test
public void testGetDefaultAlias() {
- assertEquals("Diffault alias differs from expected",
+ assertEquals("Default alias differs from expected",
"somename", SuppressWarningsHolder.getDefaultAlias("SomeName"));
- assertEquals("Diffault alias differs from expected",
+ assertEquals("Default alias differs from expected",
"somename", SuppressWarningsHolder.getDefaultAlias("SomeNameCheck"));
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java
index 2aafd1e76..c1b6aecdc 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TrailingCommentCheckTest.java
@@ -80,6 +80,27 @@ public class TrailingCommentCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testFormat() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(TrailingCommentCheck.class);
+ checkConfig.addAttribute("format", "NOT MATCH");
+ final String[] expected = {
+ "4: " + getCheckMessage(MSG_KEY),
+ "5: " + getCheckMessage(MSG_KEY),
+ "6: " + getCheckMessage(MSG_KEY),
+ "7: " + getCheckMessage(MSG_KEY),
+ "8: " + getCheckMessage(MSG_KEY),
+ "13: " + getCheckMessage(MSG_KEY),
+ "14: " + getCheckMessage(MSG_KEY),
+ "15: " + getCheckMessage(MSG_KEY),
+ "18: " + getCheckMessage(MSG_KEY),
+ "19: " + getCheckMessage(MSG_KEY),
+ "26: " + getCheckMessage(MSG_KEY),
+ "29: " + getCheckMessage(MSG_KEY),
+ };
+ verify(checkConfig, getPath("InputTrailingComment.java"), expected);
+ }
+
+ @Test
public void testCallVisitToken() {
final TrailingCommentCheck check = new TrailingCommentCheck();
try {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java
index 408ec6fbb..9395843bd 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/TranslationCheckTest.java
@@ -57,7 +57,7 @@ import org.powermock.modules.junit4.PowerMockRunner;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Closeables;
-import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
+import com.puppycrawl.tools.checkstyle.AbstractXmlTestSupport;
import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.XMLLogger;
@@ -68,11 +68,12 @@ import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.MessageDispatcher;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
import com.puppycrawl.tools.checkstyle.api.SeverityLevelCounter;
+import com.puppycrawl.tools.checkstyle.internal.utils.XmlUtil;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Closeables.class)
-public class TranslationCheckTest extends AbstractModuleTestSupport {
+public class TranslationCheckTest extends AbstractXmlTestSupport {
@Captor
private ArgumentCaptor<SortedSet<LocalizedMessage>> captor;
@@ -144,6 +145,7 @@ public class TranslationCheckTest extends AbstractModuleTestSupport {
checkConfig.addAttribute("requiredTranslations", "ja,de");
checkConfig.addAttribute("baseName", "^InputTranslation.*$");
final Checker checker = createChecker(checkConfig);
+ checker.setBasedir(getPath(""));
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final XMLLogger logger = new XMLLogger(out, AutomaticBean.OutputStreamOptions.NONE);
checker.addListener(logger);
@@ -162,8 +164,21 @@ public class TranslationCheckTest extends AbstractModuleTestSupport {
final String secondErrorMessage = getCheckMessage(MSG_KEY, "anotherKey");
verify(checker, propertyFiles, ImmutableMap.of(
- getPath(""), Collections.singletonList(line + firstErrorMessage),
- translationProps, Collections.singletonList(line + secondErrorMessage)));
+ ":0", Collections.singletonList(" " + firstErrorMessage),
+ "InputTranslationCheckFireErrors_de.properties",
+ Collections.singletonList(line + secondErrorMessage)));
+
+ verifyXml(getPath("ExpectedTranslationLog.xml"), out, (expected, actual) -> {
+ // order is not always maintained here for an unknown reason.
+ // File names can appear in different orders depending on the OS and VM.
+ // This ensures we pick up the correct file based on its name and the
+ // number of children it has.
+ return !"file".equals(expected.getNodeName())
+ || expected.getAttributes().getNamedItem("name").getNodeValue()
+ .equals(actual.getAttributes().getNamedItem("name").getNodeValue())
+ && XmlUtil.getChildrenElements(expected).size() == XmlUtil
+ .getChildrenElements(actual).size();
+ }, firstErrorMessage, secondErrorMessage);
}
@Test
@@ -369,7 +384,7 @@ public class TranslationCheckTest extends AbstractModuleTestSupport {
/**
* Pitest requires all closes of streams and readers to be verified. Using PowerMock
- * is almost only posibility to check it without rewriting production code.
+ * is almost only possibility to check it without rewriting production code.
*
* @throws Exception when code tested throws some exception
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java
index 4af491695..65bf7e6be 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/UniquePropertiesCheckTest.java
@@ -54,9 +54,6 @@ import com.puppycrawl.tools.checkstyle.api.FileText;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
-/**
- * JUnit tests for Unique Properties check.
- */
@RunWith(PowerMockRunner.class)
@PrepareForTest(Closeables.class)
public class UniquePropertiesCheckTest extends AbstractModuleTestSupport {
@@ -95,7 +92,7 @@ public class UniquePropertiesCheckTest extends AbstractModuleTestSupport {
/**
* Pitest requires all closes of streams and readers to be verified. Using PowerMock
- * is almost only posibility to check it without rewriting production code.
+ * is almost only possibility to check it without rewriting production code.
*
* @throws Exception when code tested throws some exception
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java
index de62224a9..9934f904e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/blocks/EmptyCatchBlockCheckTest.java
@@ -28,11 +28,6 @@ import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
-/**
- *
- * @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
- *
- */
public class EmptyCatchBlockCheckTest extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java
index 2a087202e..c19a4de62 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ExplicitInitializationCheckTest.java
@@ -72,7 +72,7 @@ public class ExplicitInitializationCheckTest extends AbstractModuleTestSupport {
}
@Test
- public void testonlyObjectReferences() throws Exception {
+ public void testOnlyObjectReferences() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ExplicitInitializationCheck.class);
checkConfig.addAttribute("onlyObjectReferences", "true");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java
index 78113a128..d35d92871 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/FallThroughCheckTest.java
@@ -53,7 +53,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport {
"424:9: " + getCheckMessage(MSG_FALL_THROUGH),
"436:9: " + getCheckMessage(MSG_FALL_THROUGH),
"446:9: " + getCheckMessage(MSG_FALL_THROUGH),
-
+ "555:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "556:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "557:9: " + getCheckMessage(MSG_FALL_THROUGH),
};
verify(checkConfig,
getPath("InputFallThrough.java"),
@@ -82,6 +84,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport {
"424:9: " + getCheckMessage(MSG_FALL_THROUGH),
"436:9: " + getCheckMessage(MSG_FALL_THROUGH),
"446:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "555:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "556:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "557:9: " + getCheckMessage(MSG_FALL_THROUGH),
};
verify(checkConfig,
getPath("InputFallThrough.java"),
@@ -133,6 +138,9 @@ public class FallThroughCheckTest extends AbstractModuleTestSupport {
"507:9: " + getCheckMessage(MSG_FALL_THROUGH),
"514:9: " + getCheckMessage(MSG_FALL_THROUGH),
"546:12: " + getCheckMessage(MSG_FALL_THROUGH),
+ "555:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "556:9: " + getCheckMessage(MSG_FALL_THROUGH),
+ "557:9: " + getCheckMessage(MSG_FALL_THROUGH),
};
verify(checkConfig,
getPath("InputFallThrough.java"),
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java
index a18cfb6f9..6898432dd 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheckTest.java
@@ -23,6 +23,7 @@ import static com.puppycrawl.tools.checkstyle.checks.coding.IllegalTokenTextChec
import java.util.Arrays;
import java.util.List;
+import java.util.regex.Pattern;
import org.junit.Assert;
import org.junit.Test;
@@ -30,6 +31,7 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
import com.puppycrawl.tools.checkstyle.utils.TokenUtils;
public class IllegalTokenTextCheckTest
@@ -123,6 +125,19 @@ public class IllegalTokenTextCheckTest
}
@Test
+ public void testOrderOfProperties() throws Exception {
+ // pure class must be used as configuration doesn't guarantee order of
+ // attributes
+ final IllegalTokenTextCheck check = new IllegalTokenTextCheck();
+ check.setFormat("test");
+ check.setIgnoreCase(true);
+ final Pattern actual = (Pattern) TestUtil.getClassDeclaredField(
+ IllegalTokenTextCheck.class, "regexp").get(check);
+ Assert.assertEquals("should match", Pattern.CASE_INSENSITIVE, actual.flags());
+ Assert.assertEquals("should match", "test", actual.pattern());
+ }
+
+ @Test
public void testAcceptableTokensMakeSense() {
final int expectedTokenTypesTotalNumber = 169;
Assert.assertEquals("Total number of TokenTypes has changed, acceptable tokens in"
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java
index ee10c281b..59fa28159 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTypeCheckTest.java
@@ -82,6 +82,7 @@ public class IllegalTypeCheckTest extends AbstractModuleTestSupport {
"com.puppycrawl.tools.checkstyle.checks.coding.illegaltype."
+ "InputIllegalType.AbstractClass"),
"16:13: " + getCheckMessage(MSG_KEY, "java.util.TreeSet"),
+ "25:36: " + getCheckMessage(MSG_KEY, "java.util.TreeSet"),
};
verify(checkConfig, getPath("InputIllegalType.java"), expected);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java
index 2d891ff93..b5b851fd6 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ModifiedControlVariableCheckTest.java
@@ -57,6 +57,7 @@ public class ModifiedControlVariableCheckTest
"56:14: " + getCheckMessage(MSG_KEY, "m"),
"67:15: " + getCheckMessage(MSG_KEY, "i"),
"68:15: " + getCheckMessage(MSG_KEY, "k"),
+ "78:15: " + getCheckMessage(MSG_KEY, "v"),
};
verify(checkConfig, getPath("InputModifiedControlVariableBothForLoops.java"), expected);
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java
index 41caf8415..fc537abef 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MultipleVariableDeclarationsCheckTest.java
@@ -46,6 +46,9 @@ public class MultipleVariableDeclarationsCheckTest extends AbstractModuleTestSup
"9:9: " + getCheckMessage(MSG_MULTIPLE),
"13:5: " + getCheckMessage(MSG_MULTIPLE),
"16:5: " + getCheckMessage(MSG_MULTIPLE),
+ "35:9: " + getCheckMessage(MSG_MULTIPLE),
+ "35:31: " + getCheckMessage(MSG_MULTIPLE),
+ "35:44: " + getCheckMessage(MSG_MULTIPLE),
};
verify(checkConfig,
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java
index 5ca5221a1..04cd3e5e5 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NestedForDepthCheckTest.java
@@ -28,10 +28,6 @@ import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
-/**
- * The unit-test for the {@code NestedForDepthCheck}-checkstyle enhancement.
- * @see NestedForDepthCheck
- */
public class NestedForDepthCheckTest extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
@@ -56,6 +52,7 @@ public class NestedForDepthCheckTest extends AbstractModuleTestSupport {
final String[] expected = {
"43:11: " + getCheckMessage(MSG_KEY, 3, 2),
"44:13: " + getCheckMessage(MSG_KEY, 4, 2),
+ "47:13: " + getCheckMessage(MSG_KEY, 4, 2),
};
verify(checkConfig, getPath("InputNestedForDepth.java"),
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java
index 89df6c04e..5aae2c10d 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/NoCloneCheckTest.java
@@ -27,9 +27,6 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
-/**
- * NoCloneCheck test.
- */
public class NoCloneCheckTest
extends AbstractModuleTestSupport {
@Override
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java
index 48fe46337..83b7dac17 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/RequireThisCheckTest.java
@@ -22,6 +22,7 @@ package com.puppycrawl.tools.checkstyle.checks.coding;
import static com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.MSG_METHOD;
import static com.puppycrawl.tools.checkstyle.checks.coding.RequireThisCheck.MSG_VARIABLE;
+import java.lang.reflect.Constructor;
import java.util.SortedSet;
import org.junit.Assert;
@@ -33,6 +34,7 @@ import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
public class RequireThisCheckTest extends AbstractModuleTestSupport {
@@ -58,6 +60,11 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport {
"121:13: " + getCheckMessage(MSG_METHOD, "instanceMethod", "Issue2240."),
"122:13: " + getCheckMessage(MSG_VARIABLE, "i", "Issue2240."),
"134:9: " + getCheckMessage(MSG_METHOD, "foo", ""),
+ "142:9: " + getCheckMessage(MSG_VARIABLE, "s", ""),
+ "168:16: " + getCheckMessage(MSG_VARIABLE, "a", ""),
+ "168:20: " + getCheckMessage(MSG_VARIABLE, "a", ""),
+ "174:16: " + getCheckMessage(MSG_VARIABLE, "b", ""),
+ "174:20: " + getCheckMessage(MSG_VARIABLE, "b", ""),
};
verify(checkConfig,
getPath("InputRequireThisEnumInnerClassesAndBugs.java"),
@@ -95,6 +102,11 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport {
"113:9: " + getCheckMessage(MSG_VARIABLE, "i", ""),
"114:9: " + getCheckMessage(MSG_VARIABLE, "i", ""),
"122:13: " + getCheckMessage(MSG_VARIABLE, "i", "Issue2240."),
+ "142:9: " + getCheckMessage(MSG_VARIABLE, "s", ""),
+ "168:16: " + getCheckMessage(MSG_VARIABLE, "a", ""),
+ "168:20: " + getCheckMessage(MSG_VARIABLE, "a", ""),
+ "174:16: " + getCheckMessage(MSG_VARIABLE, "b", ""),
+ "174:20: " + getCheckMessage(MSG_VARIABLE, "b", ""),
};
verify(checkConfig,
getPath("InputRequireThisEnumInnerClassesAndBugs.java"),
@@ -260,7 +272,7 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport {
final String[] expected = {
"15:9: " + getCheckMessage(MSG_VARIABLE, "tags", ""),
};
- verify(checkConfig, getPath("InputRequireThisMetodReferences.java"), expected);
+ verify(checkConfig, getPath("InputRequireThisMethodReferences.java"), expected);
}
@Test
@@ -294,6 +306,43 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testCatchVariables() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class);
+ checkConfig.addAttribute("validateOnlyOverlapping", "false");
+ final String[] expected = {
+ "29:21: " + getCheckMessage(MSG_VARIABLE, "ex", ""),
+ };
+ verify(checkConfig, getPath("InputRequireThisCatchVariables.java"), expected);
+ }
+
+ @Test
+ public void testEnumConstant() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class);
+ checkConfig.addAttribute("validateOnlyOverlapping", "false");
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+ verify(checkConfig, getPath("InputRequireThisEnumConstant.java"), expected);
+ }
+
+ @Test
+ public void testAnnotationInterface() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class);
+ checkConfig.addAttribute("validateOnlyOverlapping", "false");
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+ verify(checkConfig, getPath("InputRequireThisAnnotationInterface.java"), expected);
+ }
+
+ @Test
+ public void testFor() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class);
+ checkConfig.addAttribute("validateOnlyOverlapping", "false");
+ final String[] expected = {
+ "13:13: " + getCheckMessage(MSG_VARIABLE, "bottom", ""),
+ "21:34: " + getCheckMessage(MSG_VARIABLE, "name", ""),
+ };
+ verify(checkConfig, getPath("InputRequireThisFor.java"), expected);
+ }
+
+ @Test
public void test() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(RequireThisCheck.class);
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
@@ -307,4 +356,18 @@ public class RequireThisCheckTest extends AbstractModuleTestSupport {
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputRequireThisExtendedMethod.java"), expected);
}
+
+ @Test
+ public void testUnusedMethod() throws Exception {
+ final DetailAST ident = new DetailAST();
+ ident.setText("testName");
+
+ final Class<?> cls = Class.forName(RequireThisCheck.class.getName() + "$CatchFrame");
+ final Constructor<?> constructor = cls.getDeclaredConstructors()[0];
+ constructor.setAccessible(true);
+ final Object o = constructor.newInstance(null, ident);
+
+ Assert.assertEquals("expected ident token", ident,
+ TestUtil.getClassDeclaredMethod(cls, "getFrameNameIdent").invoke(o));
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java
index eccf7ec67..6e407a47f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/ReturnCountCheckTest.java
@@ -20,6 +20,7 @@
package com.puppycrawl.tools.checkstyle.checks.coding;
import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY;
+import static com.puppycrawl.tools.checkstyle.checks.coding.ReturnCountCheck.MSG_KEY_VOID;
import static org.junit.Assert.assertTrue;
import java.io.File;
@@ -48,9 +49,9 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport {
final DefaultConfiguration checkConfig =
createModuleConfig(ReturnCountCheck.class);
final String[] expected = {
- "18:5: " + getCheckMessage(MSG_KEY, 7, 1),
- "30:5: " + getCheckMessage(MSG_KEY, 2, 1),
- "35:17: " + getCheckMessage(MSG_KEY, 6, 1),
+ "18:5: " + getCheckMessage(MSG_KEY_VOID, 7, 1),
+ "30:5: " + getCheckMessage(MSG_KEY_VOID, 2, 1),
+ "35:17: " + getCheckMessage(MSG_KEY_VOID, 6, 1),
"49:5: " + getCheckMessage(MSG_KEY, 7, 2),
};
verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected);
@@ -63,9 +64,9 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport {
checkConfig.addAttribute("format", "^$");
final String[] expected = {
"5:5: " + getCheckMessage(MSG_KEY, 7, 2),
- "18:5: " + getCheckMessage(MSG_KEY, 7, 1),
- "30:5: " + getCheckMessage(MSG_KEY, 2, 1),
- "35:17: " + getCheckMessage(MSG_KEY, 6, 1),
+ "18:5: " + getCheckMessage(MSG_KEY_VOID, 7, 1),
+ "30:5: " + getCheckMessage(MSG_KEY_VOID, 2, 1),
+ "35:17: " + getCheckMessage(MSG_KEY_VOID, 6, 1),
"49:5: " + getCheckMessage(MSG_KEY, 7, 2),
};
verify(checkConfig, getPath("InputReturnCountSwitches.java"), expected);
@@ -146,10 +147,11 @@ public class ReturnCountCheckTest extends AbstractModuleTestSupport {
checkConfig.addAttribute("max", "2");
checkConfig.addAttribute("maxForVoid", "0");
final String[] expected = {
- "4:5: " + getCheckMessage(MSG_KEY, 1, 0),
- "8:5: " + getCheckMessage(MSG_KEY, 1, 0),
- "14:5: " + getCheckMessage(MSG_KEY, 2, 0),
+ "4:5: " + getCheckMessage(MSG_KEY_VOID, 1, 0),
+ "8:5: " + getCheckMessage(MSG_KEY_VOID, 1, 0),
+ "14:5: " + getCheckMessage(MSG_KEY_VOID, 2, 0),
"30:5: " + getCheckMessage(MSG_KEY, 3, 2),
+ "41:5: " + getCheckMessage(MSG_KEY_VOID, 2, 0),
};
verify(checkConfig, getPath("InputReturnCountVoid.java"), expected);
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java
index 07de21709..038eaf22c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/UnnecessaryParenthesesCheckTest.java
@@ -95,6 +95,8 @@ public class UnnecessaryParenthesesCheckTest extends AbstractModuleTestSupport {
"81:11: " + getCheckMessage(MSG_ASSIGN),
"81:16: " + getCheckMessage(MSG_LITERAL, "3"),
"82:39: " + getCheckMessage(MSG_ASSIGN),
+ "93:11: " + getCheckMessage(MSG_ASSIGN),
+ "93:14: " + getCheckMessage(MSG_STRING, "\"12345678901234567890123\""),
};
verify(checkConfig, getPath("InputUnnecessaryParenthesesOperatorsAndCasts.java"), expected);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java
index 7e17610eb..5e54ba784 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/VariableDeclarationUsageDistanceCheckTest.java
@@ -27,6 +27,7 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
+import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
public class VariableDeclarationUsageDistanceCheckTest extends
AbstractModuleTestSupport {
@@ -76,6 +77,7 @@ public class VariableDeclarationUsageDistanceCheckTest extends
"891: " + getCheckMessage(MSG_KEY, "a", 4, 1),
"901: " + getCheckMessage(MSG_KEY, "a", 4, 1),
"967: " + getCheckMessage(MSG_KEY, "a", 4, 1),
+ "978: " + getCheckMessage(MSG_KEY, "a", 2, 1),
};
verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected);
}
@@ -170,6 +172,7 @@ public class VariableDeclarationUsageDistanceCheckTest extends
"505: " + getCheckMessage(MSG_KEY, "files", 2, 1),
"540: " + getCheckMessage(MSG_KEY, "id", 2, 1),
"542: " + getCheckMessage(MSG_KEY, "parentId", 4, 1),
+ "978: " + getCheckMessage(MSG_KEY, "a", 2, 1),
};
verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected);
}
@@ -239,7 +242,27 @@ public class VariableDeclarationUsageDistanceCheckTest extends
"542: " + getCheckMessage(MSG_KEY_EXT, "parentId", 4, 3),
};
- createChecker(checkConfig);
verify(checkConfig, getPath("InputVariableDeclarationUsageDistance.java"), expected);
}
+
+ @Test
+ public void testAnonymousClass() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(VariableDeclarationUsageDistanceCheck.class);
+ final String[] expected = {
+ "9: " + getCheckMessage(MSG_KEY_EXT, "prefs", 4, 3),
+ };
+
+ verify(checkConfig, getPath("InputVariableDeclarationUsageDistanceAnonymous.java"),
+ expected);
+ }
+
+ @Test
+ public void testLabels() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(VariableDeclarationUsageDistanceCheck.class);
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+
+ verify(checkConfig, getPath("InputVariableDeclarationUsageDistanceLabels.java"), expected);
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java
index 435c53088..29798691f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/ThrowsCountCheckTest.java
@@ -114,6 +114,6 @@ public class ThrowsCountCheckTest extends AbstractModuleTestSupport {
final String[] expected = {
"18:26: " + getCheckMessage(MSG_KEY, 5, 4),
};
- verify(checkConfig, getPath("InputThrowsCountMwthodWithAnnotation.java"), expected);
+ verify(checkConfig, getPath("InputThrowsCountMethodWithAnnotation.java"), expected);
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java
index 571f9fac6..eab6ec9cc 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/VisibilityModifierCheckTest.java
@@ -450,7 +450,7 @@ public class VisibilityModifierCheckTest
* class with name "", but in this case internal collection will have short names
* as "" that will not make problems, but will be weird in debug.
*
- * @throws Exception when exception occured during execution.
+ * @throws Exception when exception occurred during execution.
*/
@Test
public void testIsStarImportNullAst() throws Exception {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java
index 8db53f01d..f82d75a2b 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/header/HeaderCheckTest.java
@@ -88,9 +88,9 @@ public class HeaderCheckTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingHeaderFile() throws Exception {
+ public void testNonExistentHeaderFile() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(HeaderCheck.class);
- checkConfig.addAttribute("headerFile", getPath("nonExisting.file"));
+ checkConfig.addAttribute("headerFile", getPath("nonExistent.file"));
try {
createChecker(checkConfig);
fail("CheckstyleException is expected");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java
index 7ef2abd28..aae83138b 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/AccessResultTest.java
@@ -48,6 +48,6 @@ public class AccessResultTest {
AccessResult.DISALLOWED,
AccessResult.UNKNOWN,
};
- assertArrayEquals("Invalid aaccess result values", expected, actual);
+ assertArrayEquals("Invalid access result values", expected, actual);
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java
index 29759138f..1aa1e08d6 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/CustomImportOrderCheckTest.java
@@ -29,11 +29,13 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import java.io.File;
import java.lang.reflect.Method;
import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
+import com.puppycrawl.tools.checkstyle.Checker;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
@@ -336,6 +338,59 @@ public class CustomImportOrderCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testCompareImports() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(CustomImportOrderCheck.class);
+ checkConfig.addAttribute("specialImportsRegExp", "com");
+ checkConfig.addAttribute("sortImportsInGroupAlphabetically", "true");
+ checkConfig.addAttribute("customImportOrderRules",
+ "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS");
+ final String[] expected = {
+ "4: " + getCheckMessage(MSG_LEX, "java.util.Map",
+ "java.util.Map.Entry"),
+ };
+
+ verify(checkConfig, getPath("InputCustomImportOrderCompareImports.java"), expected);
+ }
+
+ @Test
+ public void testFindBetterPatternMatch() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(CustomImportOrderCheck.class);
+ checkConfig.addAttribute("standardPackageRegExp", "java|javax|event.*");
+ checkConfig.addAttribute("specialImportsRegExp", "An|lang|java|collect|event");
+ checkConfig.addAttribute("thirdPartyPackageRegExp", "com");
+ checkConfig.addAttribute("separateLineBetweenGroups", "true");
+ checkConfig.addAttribute("customImportOrderRules",
+ "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS###THIRD_PARTY_PACKAGE");
+ final String[] expected = {
+ "8: " + getCheckMessage(MSG_ORDER, THIRD, SPECIAL,
+ "com.google.common.annotations.Beta"),
+ };
+
+ verify(checkConfig, getPath("InputCustomImportOrderFindBetterPatternMatch.java"), expected);
+ }
+
+ @Test
+ public void testBeginTreeClear() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(CustomImportOrderCheck.class);
+ checkConfig.addAttribute("specialImportsRegExp", "com");
+ checkConfig.addAttribute("separateLineBetweenGroups", "false");
+ checkConfig.addAttribute("customImportOrderRules",
+ "STANDARD_JAVA_PACKAGE###SPECIAL_IMPORTS");
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+ final Checker checker = createChecker(checkConfig);
+ final String fileName1 = getPath("InputCustomImportOrderImportsContainingJava.java");
+ final String fileName2 = getPath("InputCustomImportOrderNoValid.java");
+ final File[] files = {
+ new File(fileName1),
+ new File(fileName2),
+ };
+ verify(checker, files, fileName1, expected);
+ }
+
+ @Test
public void testImportsContainingJava() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(CustomImportOrderCheck.class);
checkConfig.addAttribute("customImportOrderRules",
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java
index 902dcbf87..dd4491656 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/IllegalImportCheckTest.java
@@ -112,7 +112,7 @@ public class IllegalImportCheckTest extends AbstractModuleTestSupport {
}
@Test
- public void testIllegalClassessRegularExpression()
+ public void testIllegalClassesRegularExpression()
throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(IllegalImportCheck.class);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java
index 5fab0d1a8..6cd86d2a7 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlCheckTest.java
@@ -349,7 +349,7 @@ public class ImportControlCheckTest extends AbstractModuleTestSupport {
// One more time to use cache.
verify(checkerConfig, filePath, expected);
- assertTrue("External resourse is not present in cache",
+ assertTrue("External resource is not present in cache",
new String(Files.readAllBytes(cacheFile.toPath()),
StandardCharsets.UTF_8).contains("InputImportControlOneRegExp.xml"));
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java
index ded4f34ae..7a92cc5e5 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportControlTest.java
@@ -68,92 +68,92 @@ public class ImportControlTest {
@Test
public void testLocateFinest() {
- assertEquals("Unxpected response", icRoot, icRoot
+ assertEquals("Unexpected response", icRoot, icRoot
.locateFinest("com.kazgroup.courtlink.domain"));
- assertEquals("Unxpected response", icCommon, icRoot
+ assertEquals("Unexpected response", icCommon, icRoot
.locateFinest("com.kazgroup.courtlink.common.api"));
- assertNull("Unxpected response", icRoot.locateFinest("com"));
+ assertNull("Unexpected response", icRoot.locateFinest("com"));
}
@Test
public void testEnsureTrailingDot() {
- assertNull("Unxpected response", icRoot.locateFinest("com.kazgroup.courtlinkkk"));
- assertNull("Unxpected response",
+ assertNull("Unexpected response", icRoot.locateFinest("com.kazgroup.courtlinkkk"));
+ assertNull("Unexpected response",
icRoot.locateFinest("com.kazgroup.courtlink/common.api"));
}
@Test
public void testCheckAccess() {
- assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
"com.kazgroup.courtlink.common",
"org.springframework.something"));
- assertEquals("Unxpected access result", AccessResult.ALLOWED, icCommon
+ assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommon
.checkAccess("com.kazgroup.courtlink.common",
"org.apache.commons.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
"com.kazgroup.courtlink.common", "org.apache.commons"));
- assertEquals("Unxpected access result", AccessResult.ALLOWED, icCommon.checkAccess(
+ assertEquals("Unexpected access result", AccessResult.ALLOWED, icCommon.checkAccess(
"com.kazgroup.courtlink.common", "org.hibernate.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED, icCommon.checkAccess(
"com.kazgroup.courtlink.common", "com.badpackage.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED, icRoot.checkAccess(
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED, icRoot.checkAccess(
"com.kazgroup.courtlink", "org.hibernate.something"));
}
@Test
public void testUnknownPkg() {
- assertNull("Unxpected response", icRoot.locateFinest("net.another"));
+ assertNull("Unexpected response", icRoot.locateFinest("net.another"));
}
@Test
public void testRegExpChildLocateFinest() {
- assertEquals("Unxpected response", icRootRegexpChild, icRootRegexpChild
+ assertEquals("Unexpected response", icRootRegexpChild, icRootRegexpChild
.locateFinest("com.kazgroup.courtlink.domain"));
- assertEquals("Unxpected response", icCommonRegexpChild, icRootRegexpChild
+ assertEquals("Unexpected response", icCommonRegexpChild, icRootRegexpChild
.locateFinest("com.kazgroup.courtlink.common.api"));
- assertNull("Unxpected response", icRootRegexpChild.locateFinest("com"));
+ assertNull("Unexpected response", icRootRegexpChild.locateFinest("com"));
}
@Test
public void testRegExpChildCheckAccess() {
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.springframework.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.luiframework.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"de.springframework.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"de.luiframework.something"));
- assertEquals("Unxpected access result", AccessResult.ALLOWED,
+ assertEquals("Unexpected access result", AccessResult.ALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.apache.commons.something"));
- assertEquals("Unxpected access result", AccessResult.ALLOWED,
+ assertEquals("Unexpected access result", AccessResult.ALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.lui.commons.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.apache.commons"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.lui.commons"));
- assertEquals("Unxpected access result", AccessResult.ALLOWED,
+ assertEquals("Unexpected access result", AccessResult.ALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"org.hibernate.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icCommonRegexpChild.checkAccess("com.kazgroup.courtlink.common",
"com.badpackage.something"));
- assertEquals("Unxpected access result", AccessResult.DISALLOWED,
+ assertEquals("Unexpected access result", AccessResult.DISALLOWED,
icRootRegexpChild.checkAccess("com.kazgroup.courtlink",
"org.hibernate.something"));
}
@Test
public void testRegExpChildUnknownPkg() {
- assertNull("Unxpected response", icRootRegexpChild.locateFinest("net.another"));
+ assertNull("Unexpected response", icRootRegexpChild.locateFinest("net.another"));
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java
index df5ab75f6..7d3322275 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/imports/ImportOrderCheckTest.java
@@ -133,7 +133,7 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport {
"7: " + getCheckMessage(MSG_SEPARATED_IN_GROUP, "org.junit.Assert.assertEquals"),
};
- verify(checkConfig, getPath("InputImportOrderStaticGroupSeperated.java"), expected);
+ verify(checkConfig, getPath("InputImportOrderStaticGroupSeparated.java"), expected);
}
@Test
@@ -409,6 +409,57 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testStaticGroupsAlphabeticalOrderBottomNegative() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(ImportOrderCheck.class);
+ checkConfig.addAttribute("option", "bottom");
+ checkConfig.addAttribute("groups", "org, java");
+ checkConfig.addAttribute("separated", "true");
+ checkConfig.addAttribute("sortStaticImportsAlphabetically", "true");
+ final String[] expected = {
+ "8: " + getCheckMessage(MSG_ORDERING, "java.util.Set"),
+ };
+ verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative.java"),
+ expected);
+ }
+
+ /** Tests that a non-static import after a static import correctly gives an
+ * error if order=bottom. */
+
+ @Test
+ public void testStaticGroupsAlphabeticalOrderTopNegative() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(ImportOrderCheck.class);
+ checkConfig.addAttribute("option", "top");
+ checkConfig.addAttribute("groups", "org, java");
+ checkConfig.addAttribute("separated", "true");
+ checkConfig.addAttribute("sortStaticImportsAlphabetically", "true");
+ final String[] expected = {
+ "5: " + getCheckMessage(MSG_ORDERING, "java.lang.Math.PI"),
+ };
+ verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative.java"),
+ expected);
+ }
+
+ /** Tests that a non-static import before a static import correctly gives an
+ * error if order=top. */
+
+ @Test
+ public void testStaticGroupsAlphabeticalOrderBottomNegative2() throws Exception {
+ final DefaultConfiguration checkConfig =
+ createModuleConfig(ImportOrderCheck.class);
+ checkConfig.addAttribute("option", "bottom");
+ checkConfig.addAttribute("groups", "org, java");
+ checkConfig.addAttribute("separated", "true");
+ checkConfig.addAttribute("sortStaticImportsAlphabetically", "true");
+ final String[] expected = {
+ "8: " + getCheckMessage(MSG_ORDERING, "java.util.Set"),
+ };
+ verify(checkConfig, getPath("InputImportOrderStaticGroupOrderBottom_Negative2.java"),
+ expected);
+ }
+
+ @Test
public void testStaticGroupsOrderBottom() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ImportOrderCheck.class);
@@ -430,7 +481,7 @@ public class ImportOrderCheckTest extends AbstractModuleTestSupport {
final String[] expected = {
"6: " + getCheckMessage(MSG_ORDERING, "java.awt.event.ActionEvent"),
};
- verify(checkConfig, getPath("InputImportOrderRepetiton.java"), expected);
+ verify(checkConfig, getPath("InputImportOrderRepetition.java"), expected);
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java
index 11e294814..4102b4512 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/CommentsIndentationCheckTest.java
@@ -31,12 +31,6 @@ import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
-/**
-*
-* @author <a href="mailto:nesterenko-aleksey@list.ru">Aleksey Nesterenko</a>
-* @author <a href="mailto:andreyselkin@gmail.com">Andrei Selkin</a>
-*
-*/
public class CommentsIndentationCheckTest extends AbstractModuleTestSupport {
@Override
@@ -221,7 +215,7 @@ public class CommentsIndentationCheckTest extends AbstractModuleTestSupport {
}
catch (IllegalArgumentException ex) {
final String msg = ex.getMessage();
- Assert.assertEquals("Invalid excpeton message",
+ Assert.assertEquals("Invalid exception message",
"Unexpected token type: methodStub", msg);
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java
index 464a8a714..91606fe7e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java
@@ -1746,6 +1746,39 @@ public class IndentationCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testMethodPrecedeByAnnotationsWithParameterOnSeparateLine() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class);
+ checkConfig.addAttribute("tabWidth", "4");
+ checkConfig.addAttribute("basicOffset", "2");
+ checkConfig.addAttribute("braceAdjustment", "0");
+ checkConfig.addAttribute("caseIndent", "2");
+ checkConfig.addAttribute("throwsIndent", "4");
+ checkConfig.addAttribute("lineWrappingIndentation", "4");
+ checkConfig.addAttribute("arrayInitIndent", "2");
+ final String fileName =
+ getPath("InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java");
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+ verify(checkConfig, fileName, expected);
+ }
+
+ @Test
+ public void testAnnotationIncorrect() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class);
+ checkConfig.addAttribute("tabWidth", "4");
+ checkConfig.addAttribute("basicOffset", "4");
+ checkConfig.addAttribute("braceAdjustment", "0");
+ checkConfig.addAttribute("lineWrappingIndentation", "4");
+ final String fileName =
+ getPath("InputIndentationAnnotationIncorrect.java");
+ final String[] expected = {
+ "11: " + getCheckMessage(MSG_ERROR, "(", 4, 8),
+ "14: " + getCheckMessage(MSG_ERROR, "(", 8, 12),
+ "19: " + getCheckMessage(MSG_ERROR, "(", 4, 8),
+ };
+ verify(checkConfig, fileName, expected);
+ }
+
+ @Test
public void testInputAnnotationScopeIndentationCheck() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(IndentationCheck.class);
checkConfig.addAttribute("tabWidth", "4");
@@ -1869,10 +1902,10 @@ public class IndentationCheckTest extends AbstractModuleTestSupport {
* {@link IndentationCheck#MSG_CHILD_ERROR}, {@link IndentationCheck#MSG_CHILD_ERROR_MULTI},
* {@link IndentationCheck#MSG_CHILD_ERROR_MULTI} are in appropriate order.
*
- * In other tests, the argument 0 and text before it are chopped off and only the rest of
+ * <p>In other tests, the argument 0 and text before it are chopped off and only the rest of
* messages are verified. Therefore, the argument 0 is required to be the first argument in
* the messages above. If we update the messages in the future, it is required to keep the
- * arguments in appropriate order to ensure other tests will work.
+ * arguments in appropriate order to ensure other tests will work.</p>
*
* @see IndentComment#getExpectedMessagePostfix(String)
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java
index 2873e03be..40e933ce1 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/AbstractJavadocCheckTest.java
@@ -44,9 +44,8 @@ import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.TreeWalker;
import com.puppycrawl.tools.checkstyle.api.DetailNode;
import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
-import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
-import com.puppycrawl.tools.checkstyle.utils.BlockCommentPosition;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
+import com.puppycrawl.tools.checkstyle.utils.JavadocUtils;
public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
@@ -180,7 +179,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
verify(checkConfig, getPath("InputAbstractJavadocPosition.java"), expected);
assertEquals("Invalid number of javadocs",
- 58, JavadocCatchCheck.javadocsNumber);
+ 65, JavadocCatchCheck.javadocsNumber);
}
@Test
@@ -192,7 +191,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
verify(checkConfig,
getPath("InputAbstractJavadocPositionWithSinglelineComments.java"), expected);
assertEquals("Invalid number of javadocs",
- 58, JavadocCatchCheck.javadocsNumber);
+ 65, JavadocCatchCheck.javadocsNumber);
}
@Test
@@ -207,12 +206,6 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
}
@Test
- public void testBlockCommentPositionHasPrivateConstr() throws Exception {
- Assert.assertTrue("Constructor is not private",
- TestUtil.isUtilsClassHasPrivateConstructor(BlockCommentPosition.class, true));
- }
-
- @Test
public void testTokens() {
final int[] defaultJavadocTokens = {JavadocTokenTypes.JAVADOC};
final AbstractJavadocCheck check = new AbstractJavadocCheck() {
@@ -231,7 +224,7 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
Assert.assertNotNull("Default tokens should not be null", check.getDefaultTokens());
Assert.assertArrayEquals("Acceptable tokens should be equal to default",
check.getDefaultTokens(), check.getAcceptableTokens());
- Assert.assertArrayEquals("REquired tokens should be equal to default",
+ Assert.assertArrayEquals("Required tokens should be equal to default",
check.getDefaultTokens(), check.getRequiredTokens());
Assert.assertArrayEquals("Invalid default javadoc tokens",
defaultJavadocTokens, check.getDefaultJavadocTokens());
@@ -485,6 +478,9 @@ public class AbstractJavadocCheckTest extends AbstractModuleTestSupport {
@Override
public void visitJavadocToken(DetailNode ast) {
assertEquals(ast.toString(), "JAVADOC", ast.getText());
+ final DetailNode text = JavadocUtils.findFirstToken(ast, JavadocTokenTypes.TEXT);
+ Assert.assertNotNull("Empty javadoc text at " + ast, text);
+ assertEquals(ast.toString(), "Javadoc", text.getText());
javadocsNumber++;
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java
index c4b20ee5b..15b36acac 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/ClassResolverTest.java
@@ -150,7 +150,7 @@ public class ClassResolverTest {
final String expected = "expected exception";
assertTrue("Invalid exception cause, should be: ClassNotFoundException",
ex.getCause() instanceof ClassNotFoundException);
- assertTrue("Invalid excpetion message, should end with: " + expected,
+ assertTrue("Invalid exception message, should end with: " + expected,
ex.getMessage().endsWith(expected));
}
}
@@ -158,7 +158,7 @@ public class ClassResolverTest {
/**
* This test exists to prevent any possible regression and let of
* https://github.com/checkstyle/checkstyle/issues/1192 to be persistent
- * event is not very obvious
+ * event is not very obvious.
*
* @throws Exception when smth is not expected
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java
index 1e3c28b37..8cf4210c0 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheckTest.java
@@ -135,8 +135,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport {
"254:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "java.io.FileNotFoundException"),
"256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"),
"262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"),
- "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
- "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "305: " + getCheckMessage(MSG_RETURN_EXPECTED),
+ "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"),
+ "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
};
verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected);
@@ -171,8 +173,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport {
"254:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "java.io.FileNotFoundException"),
"256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"),
"262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"),
- "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
- "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "305: " + getCheckMessage(MSG_RETURN_EXPECTED),
+ "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"),
+ "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
};
verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected);
}
@@ -287,8 +291,10 @@ public class JavadocMethodCheckTest extends AbstractModuleTestSupport {
"179:8: " + getCheckMessage(MSG_UNUSED_TAG, "@throws", "ArrayStoreException"),
"256:28: " + getCheckMessage(MSG_EXPECTED_TAG, "@throws", "IOException"),
"262:8: " + getCheckMessage(MSG_UNUSED_TAG, "@param", "aParam"),
- "320:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
- "329:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "305: " + getCheckMessage(MSG_RETURN_EXPECTED),
+ "305:22: " + getCheckMessage(MSG_EXPECTED_TAG, "@param", "aParam"),
+ "328:9: " + getCheckMessage(MSG_JAVADOC_MISSING),
+ "337:5: " + getCheckMessage(MSG_JAVADOC_MISSING),
};
verify(checkConfig, getPath("InputJavadocMethodTags.java"), expected);
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java
index b197145fa..b47008fdd 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTagInfoTest.java
@@ -86,7 +86,7 @@ public class JavadocTagInfoTest {
}
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.AUTHOR.isValidOn(ast));
}
@@ -129,11 +129,11 @@ public class JavadocTagInfoTest {
astParent.setType(TokenTypes.SLIST);
ast.setType(TokenTypes.VARIABLE_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
tagInfo.isValidOn(ast));
ast.setType(TokenTypes.PARAMETER_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
tagInfo.isValidOn(ast));
}
}
@@ -166,11 +166,11 @@ public class JavadocTagInfoTest {
astParent.setType(TokenTypes.SLIST);
ast.setType(TokenTypes.VARIABLE_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.DEPRECATED.isValidOn(ast));
ast.setType(TokenTypes.PARAMETER_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.DEPRECATED.isValidOn(ast));
}
@@ -194,11 +194,11 @@ public class JavadocTagInfoTest {
astParent.setType(TokenTypes.SLIST);
ast.setType(TokenTypes.VARIABLE_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL.isValidOn(ast));
ast.setType(TokenTypes.PARAMETER_DEF);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL.isValidOn(ast));
}
@@ -217,7 +217,7 @@ public class JavadocTagInfoTest {
}
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.EXCEPTION.isValidOn(ast));
}
@@ -236,7 +236,7 @@ public class JavadocTagInfoTest {
}
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.THROWS.isValidOn(ast));
}
@@ -258,7 +258,7 @@ public class JavadocTagInfoTest {
}
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.VERSION.isValidOn(ast));
}
@@ -279,7 +279,7 @@ public class JavadocTagInfoTest {
}
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.PARAM.isValidOn(ast));
}
@@ -303,11 +303,11 @@ public class JavadocTagInfoTest {
}
astChild2.setType(TokenTypes.LITERAL_VOID);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.RETURN.isValidOn(ast));
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.RETURN.isValidOn(ast));
}
@@ -332,15 +332,15 @@ public class JavadocTagInfoTest {
}
astChild2.setText("1111");
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL_FIELD.isValidOn(ast));
astChild2.setType(TokenTypes.LITERAL_VOID);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL_FIELD.isValidOn(ast));
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL_FIELD.isValidOn(ast));
}
@@ -368,11 +368,11 @@ public class JavadocTagInfoTest {
}
astChild.setText("1111");
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL_DATA.isValidOn(ast));
ast.setType(TokenTypes.LAMBDA);
- assertFalse("Should return false when ast type is invalid for currrent tag",
+ assertFalse("Should return false when ast type is invalid for current tag",
JavadocTagInfo.SERIAL_DATA.isValidOn(ast));
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java
index 76d9142a3..73815fdb2 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocTypeCheckTest.java
@@ -34,9 +34,6 @@ import com.puppycrawl.tools.checkstyle.api.Scope;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
-/**
- * @author Oliver.Burn
- */
public class JavadocTypeCheckTest extends AbstractModuleTestSupport {
@Override
protected String getPackageLocation() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java
index 3bf65b75c..df90f72ca 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/NonEmptyAtclauseDescriptionCheckTest.java
@@ -82,6 +82,7 @@ public class NonEmptyAtclauseDescriptionCheckTest
"91: " + getCheckMessage(MSG_KEY),
"92: " + getCheckMessage(MSG_KEY),
"93: " + getCheckMessage(MSG_KEY),
+ "120: " + getCheckMessage(MSG_KEY),
};
verify(checkConfig, getPath("InputNonEmptyAtclauseDescription.java"), expected);
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java
index e24943492..0e8801e1d 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/BlockTagUtilsTest.java
@@ -28,9 +28,6 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
-/**
- * Tests BlockTagUtils.
- */
public class BlockTagUtilsTest {
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java
index 3f29816fb..73cfff09c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/utils/InlineTagUtilsTest.java
@@ -29,9 +29,6 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
-/**
- * Tests InlineTagUtils
- */
public class InlineTagUtilsTest {
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java
index a749d18b8..bd5832945 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/BooleanExpressionComplexityCheckTest.java
@@ -45,9 +45,10 @@ public class BooleanExpressionComplexityCheckTest extends AbstractModuleTestSupp
final String[] expected = {
"13:9: " + getCheckMessage(MSG_KEY, 4, 3),
- "32:9: " + getCheckMessage(MSG_KEY, 6, 3),
- "38:34: " + getCheckMessage(MSG_KEY, 4, 3),
- "40:34: " + getCheckMessage(MSG_KEY, 4, 3),
+ "29:99: " + getCheckMessage(MSG_KEY, 4, 3),
+ "39:9: " + getCheckMessage(MSG_KEY, 6, 3),
+ "45:34: " + getCheckMessage(MSG_KEY, 4, 3),
+ "47:34: " + getCheckMessage(MSG_KEY, 4, 3),
};
verify(checkConfig, getPath("InputBooleanExpressionComplexity.java"), expected);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java
index e141d0987..05b80d379 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassDataAbstractionCouplingCheckTest.java
@@ -20,7 +20,9 @@
package com.puppycrawl.tools.checkstyle.checks.metrics;
import static com.puppycrawl.tools.checkstyle.checks.metrics.ClassDataAbstractionCouplingCheck.MSG_KEY;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -41,6 +43,17 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup
}
@Test
+ public void testTokens() {
+ final ClassDataAbstractionCouplingCheck check = new ClassDataAbstractionCouplingCheck();
+ assertNotNull("Required tokens should not be null", check.getRequiredTokens());
+ assertNotNull("Acceptable tokens should not be null", check.getAcceptableTokens());
+ assertArrayEquals("Invalid default tokens", check.getDefaultTokens(),
+ check.getAcceptableTokens());
+ assertArrayEquals("Invalid acceptable tokens", check.getDefaultTokens(),
+ check.getRequiredTokens());
+ }
+
+ @Test
public void test() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ClassDataAbstractionCouplingCheck.class);
@@ -58,7 +71,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup
}
@Test
- public void testExludedPackageDirectPackages() throws Exception {
+ public void testExcludedPackageDirectPackages() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ClassDataAbstractionCouplingCheck.class);
@@ -78,7 +91,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup
}
@Test
- public void testExludedPackageCommonPackages() throws Exception {
+ public void testExcludedPackageCommonPackages() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ClassDataAbstractionCouplingCheck.class);
@@ -97,7 +110,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup
}
@Test
- public void testExludedPackageWithEndingDot() throws Exception {
+ public void testExcludedPackageWithEndingDot() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ClassDataAbstractionCouplingCheck.class);
@@ -123,7 +136,7 @@ public class ClassDataAbstractionCouplingCheckTest extends AbstractModuleTestSup
}
@Test
- public void testExludedPackageCommonPackagesAllIgnored() throws Exception {
+ public void testExcludedPackageCommonPackagesAllIgnored() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(ClassDataAbstractionCouplingCheck.class);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java
index 9508e1f03..32cebea33 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/ClassFanOutComplexityCheckTest.java
@@ -217,4 +217,15 @@ public class ClassFanOutComplexityCheckTest extends AbstractModuleTestSupport {
verify(moduleConfig,
getPath("InputClassFanOutComplexityMultiDimensionalArray.java"), expected);
}
+
+ @Test
+ public void testPackageName() throws Exception {
+ final DefaultConfiguration moduleConfig =
+ createModuleConfig(ClassFanOutComplexityCheck.class);
+ moduleConfig.addAttribute("max", "0");
+
+ final String[] expected = CommonUtils.EMPTY_STRING_ARRAY;
+ verify(moduleConfig,
+ getPath("InputClassFanOutComplexityPackageName.java"), expected);
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java
index b72b3f6b7..ed1373b97 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/metrics/NPathComplexityCheckTest.java
@@ -21,7 +21,9 @@ package com.puppycrawl.tools.checkstyle.checks.metrics;
import static com.puppycrawl.tools.checkstyle.checks.metrics.NPathComplexityCheck.MSG_KEY;
+import java.io.File;
import java.util.Collection;
+import java.util.Optional;
import java.util.SortedSet;
import org.junit.Assert;
@@ -60,6 +62,9 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport {
"76:5: " + getCheckMessage(MSG_KEY, 3, 0),
"88:5: " + getCheckMessage(MSG_KEY, 3, 0),
"104:13: " + getCheckMessage(MSG_KEY, 2, 0),
+ "113:5: " + getCheckMessage(MSG_KEY, 48, 0),
+ "123:5: " + getCheckMessage(MSG_KEY, 1, 0),
+ "124:5: " + getCheckMessage(MSG_KEY, 1, 0),
};
verify(checkConfig, getPath("InputNPathComplexityDefault.java"), expected);
@@ -139,6 +144,35 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport {
}
@Test
+ public void testStatefulFieldsClearedOnBeginTree3() throws Exception {
+ final NPathComplexityCheck check = new NPathComplexityCheck();
+ final Optional<DetailAST> question = TestUtil.findTokenInAstByPredicate(
+ TestUtil.parseFile(new File(getPath("InputNPathComplexity.java"))),
+ ast -> ast.getType() == TokenTypes.QUESTION);
+
+ Assert.assertTrue("Ast should contain QUESTION", question.isPresent());
+
+ Assert.assertTrue("State is not cleared on beginTree",
+ TestUtil.isStatefulFieldClearedDuringBeginTree(
+ check,
+ question.get(),
+ "processingTokenEnd",
+ processingTokenEnd -> {
+ try {
+ return (Integer) TestUtil.getClassDeclaredField(
+ processingTokenEnd.getClass(), "endLineNo").get(
+ processingTokenEnd) == 0
+ && (Integer) TestUtil.getClassDeclaredField(
+ processingTokenEnd.getClass(), "endColumnNo").get(
+ processingTokenEnd) == 0;
+ }
+ catch (IllegalAccessException | NoSuchFieldException ex) {
+ throw new IllegalStateException(ex);
+ }
+ }));
+ }
+
+ @Test
public void testDefaultConfiguration() throws Exception {
final DefaultConfiguration checkConfig =
createModuleConfig(NPathComplexityCheck.class);
@@ -217,6 +251,31 @@ public class NPathComplexityCheckTest extends AbstractModuleTestSupport {
Assert.assertEquals("No exception messages expected", 0, messages2.size());
}
+ /**
+ * This must be a reflection test as it is too difficult to hit normally and
+ * the responsible code can't be removed without failing tests.
+ * TokenEnd is only used for processingTokenEnd and it is only set during visitConditional
+ * and visitUnitaryOperator. For it to be the same line/column, it must be the exact same
+ * token or a token who has the same line/column as it's child and we visit. We never
+ * visit the same token twice and we are only visiting on very specific tokens.
+ * The line can't be removed or reworked as other tests fail, and regression shows us no
+ * use cases to create a UT for.
+ * @throws Exception if there is an error.
+ */
+ @Test
+ public void testTokenEndIsAfterSameLineColumn() throws Exception {
+ final NPathComplexityCheck check = new NPathComplexityCheck();
+ final Object tokenEnd = TestUtil.getClassDeclaredField(NPathComplexityCheck.class,
+ "processingTokenEnd").get(check);
+ final DetailAST token = new DetailAST();
+ token.setLineNo(0);
+ token.setColumnNo(0);
+
+ Assert.assertTrue("isAfter must be true for same line/column",
+ (Boolean) TestUtil.getClassDeclaredMethod(tokenEnd.getClass(), "isAfter")
+ .invoke(tokenEnd, token));
+ }
+
@Test
public void testVisitTokenBeforeExpressionRange() {
// Create first ast
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java
index 4d90731cd..53405d583 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/RedundantModifierCheckTest.java
@@ -232,6 +232,16 @@ public class RedundantModifierCheckTest
}
@Test
+ public void testEnumStaticMethodsInPublicClass() throws Exception {
+ final DefaultConfiguration checkConfig = createModuleConfig(RedundantModifierCheck.class);
+ final String[] expected = {
+ "12:23: " + getCheckMessage(MSG_KEY, "final"),
+ };
+ verify(checkConfig,
+ getPath("InputRedundantModifierFinalInEnumStaticMethods.java"), expected);
+ }
+
+ @Test
public void testAnnotationOnEnumConstructor() throws Exception {
final DefaultConfiguration checkConfig = createModuleConfig(RedundantModifierCheck.class);
final String[] expected = {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java
index ac890d336..e23bd7129 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/AbstractClassNameCheckTest.java
@@ -130,7 +130,7 @@ public class AbstractClassNameCheckTest extends AbstractModuleTestSupport {
final int[] expected = {
TokenTypes.CLASS_DEF,
};
- Assert.assertArrayEquals("Invalid accaptable tokens", expected, actual);
+ Assert.assertArrayEquals("Invalid acceptable tokens", expected, actual);
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java
index d0b9617a2..851c15c38 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/MethodNameCheckTest.java
@@ -81,8 +81,8 @@ public class MethodNameCheckTest
"InputMethodNameEqualClassName", pattern),
"47:9: " + getCheckMessage(MSG_KEY, "SweetInterface"),
"47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern),
- "53:17: " + getCheckMessage(MSG_KEY, "Outter"),
- "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern),
+ "53:17: " + getCheckMessage(MSG_KEY, "Outer"),
+ "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern),
};
verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected);
@@ -109,7 +109,7 @@ public class MethodNameCheckTest
"37:24: " + getCheckMessage(MSG_INVALID_PATTERN,
"InputMethodNameEqualClassName", pattern),
"47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern),
- "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern),
+ "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern),
};
verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected);
@@ -137,7 +137,7 @@ public class MethodNameCheckTest
"37:24: " + getCheckMessage(MSG_INVALID_PATTERN,
"InputMethodNameEqualClassName", pattern),
"47:9: " + getCheckMessage(MSG_INVALID_PATTERN, "SweetInterface", pattern),
- "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outter", pattern),
+ "53:17: " + getCheckMessage(MSG_INVALID_PATTERN, "Outer", pattern),
};
verify(checkConfig, getPath("InputMethodNameEqualClassName.java"), expected);
@@ -165,7 +165,7 @@ public class MethodNameCheckTest
"20:20: " + getCheckMessage(MSG_INVALID_PATTERN, "PROTECTEDfoo", pattern),
};
- verify(checkConfig, getPath("InputMethodNameOverridenMethods.java"), expected);
+ verify(checkConfig, getPath("InputMethodNameOverriddenMethods.java"), expected);
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java
index 96875fba4..8b77df609 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/NoWhitespaceAfterCheckTest.java
@@ -58,6 +58,7 @@ public class NoWhitespaceAfterCheckTest
"289:6: " + getCheckMessage(MSG_KEY, "@"),
"290:6: " + getCheckMessage(MSG_KEY, "@"),
"291:6: " + getCheckMessage(MSG_KEY, "@"),
+ "296:27: " + getCheckMessage(MSG_KEY, "int"),
};
verify(checkConfig, getPath("InputNoWhitespaceAfter.java"), expected);
}
@@ -107,7 +108,7 @@ public class NoWhitespaceAfterCheckTest
"39:11: " + getCheckMessage(MSG_KEY, "ar"),
"39:24: " + getCheckMessage(MSG_KEY, "int"),
"40:16: " + getCheckMessage(MSG_KEY, "int"),
- "43:63: " + getCheckMessage(MSG_KEY, "getLongMultArray"),
+ "43:64: " + getCheckMessage(MSG_KEY, "getLongMultiArray"),
"47:26: " + getCheckMessage(MSG_KEY, "}"),
"49:22: " + getCheckMessage(MSG_KEY, "int"),
"50:24: " + getCheckMessage(MSG_KEY, "]"),
@@ -164,6 +165,7 @@ public class NoWhitespaceAfterCheckTest
"94:45: " + getCheckMessage(MSG_KEY, ")"),
"97:41: " + getCheckMessage(MSG_KEY, "Object"),
"100:43: " + getCheckMessage(MSG_KEY, "]"),
+ "108:31: " + getCheckMessage(MSG_KEY, "Object"),
};
verify(checkConfig, getPath("InputNoWhitespaceAfterArrayDeclarations2.java"), expected);
}
@@ -234,7 +236,7 @@ public class NoWhitespaceAfterCheckTest
}
/**
- * Creates MOCK lexical token and returns AST node for this token
+ * Creates MOCK lexical token and returns AST node for this token.
* @param tokenType type of token
* @param tokenText text of token
* @param tokenFileName file name of token
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java
index 76628ee11..6edb35afb 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/ParenPadCheckTest.java
@@ -476,7 +476,7 @@ public class ParenPadCheckTest
final Method method = Whitebox.getMethod(ParenPadCheck.class,
"isAcceptableToken", DetailAST.class);
final DetailAST ast = new DetailAST();
- final String message = "Expected that all accaptable tokens will pass isAccaptableToken "
+ final String message = "Expected that all acceptable tokens will pass isAcceptableToken "
+ "method, but some token don't: ";
for (int token : check.getAcceptableTokens()) {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java
index 769751b75..5af38b101 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/CsvFilterTest.java
@@ -27,7 +27,6 @@ import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
-/** Tests CsvFilter. */
public class CsvFilterTest {
@Test
public void testDecideSingle() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java
index c3678d4e1..2228acadb 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntMatchFilterTest.java
@@ -27,7 +27,6 @@ import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
-/** Tests IntMatchFilter. */
public class IntMatchFilterTest {
@Test
public void testDecide() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java
index 9ae249b67..5fa9fbff1 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/IntRangeFilterTest.java
@@ -26,7 +26,6 @@ import org.junit.Test;
import nl.jqno.equalsverifier.EqualsVerifier;
-/** Tests IntRangeFilter. */
public class IntRangeFilterTest {
@Test
public void testDecide() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java
index 6357f822c..e1ea27ed5 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SeverityMatchFilterTest.java
@@ -20,15 +20,17 @@
package com.puppycrawl.tools.checkstyle.filters;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
+import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
+import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
-/** Tests SeverityMatchFilter. */
public class SeverityMatchFilterTest {
private final SeverityMatchFilter filter = new SeverityMatchFilter();
@@ -87,4 +89,10 @@ public class SeverityMatchFilterTest {
final AuditEvent ev3 = new AuditEvent(this, "ATest.java", infoMessage);
assertFalse("level:" + infoLevel, filter.accept(ev3));
}
+
+ @Test
+ public void testConfigure() throws CheckstyleException {
+ filter.configure(new DefaultConfiguration("test"));
+ assertNotNull("object exists", filter);
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java
index 922338560..c5e78df7a 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressElementTest.java
@@ -33,13 +33,12 @@ import com.puppycrawl.tools.checkstyle.api.LocalizedMessage;
import nl.jqno.equalsverifier.EqualsVerifier;
import nl.jqno.equalsverifier.Warning;
-/** Tests SuppressElementFilter. */
public class SuppressElementTest {
private SuppressElement filter;
@Before
public void setUp() {
- filter = new SuppressElement("Test", "Test", null, null, null);
+ filter = new SuppressElement("Test", "Test", null, null, null, null);
}
@Test
@@ -58,16 +57,29 @@ public class SuppressElementTest {
}
@Test
+ public void testDecideByMessage() {
+ final LocalizedMessage message =
+ new LocalizedMessage(0, 0, "", "", null, null, getClass(), "Test");
+ final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
+ final SuppressElement filter1 =
+ new SuppressElement(null, null, "Test", null, null, null);
+ final SuppressElement filter2 =
+ new SuppressElement(null, null, "Bad", null, null, null);
+ assertFalse("Message match", filter1.accept(ev));
+ assertTrue("Message not match", filter2.accept(ev));
+ }
+
+ @Test
public void testDecideByLine() {
final LocalizedMessage message =
new LocalizedMessage(10, 10, "", "", null, null, getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement filter1 =
- new SuppressElement("Test", "Test", null, "1-10", null);
+ new SuppressElement("Test", "Test", null, null, "1-10", null);
final SuppressElement filter2 =
- new SuppressElement("Test", "Test", null, "1-9, 11", null);
+ new SuppressElement("Test", "Test", null, null, "1-9, 11", null);
final SuppressElement filter3 =
- new SuppressElement("Test", "Test", null, null, null);
+ new SuppressElement("Test", "Test", null, null, null, null);
//deny because there are matches on file name, check name, and line
assertFalse("In range 1-10", filter1.accept(ev));
assertTrue("Not in 1-9, 11", filter2.accept(ev));
@@ -80,9 +92,9 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, null, getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement filter1 =
- new SuppressElement("Test", "Test", null, null, "1-10");
+ new SuppressElement("Test", "Test", null, null, null, "1-10");
final SuppressElement filter2 =
- new SuppressElement("Test", "Test", null, null, "1-9, 11");
+ new SuppressElement("Test", "Test", null, null, null, "1-9, 11");
//deny because there are matches on file name, check name, and column
assertFalse("In range 1-10", filter1.accept(ev));
@@ -117,7 +129,7 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, "MyModule", getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement myFilter =
- new SuppressElement("Test", "Test", "MyModule", null, null);
+ new SuppressElement("Test", "Test", null, "MyModule", null, null);
assertFalse("Filter should not accept invalid event", myFilter.accept(ev));
}
@@ -128,7 +140,7 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, "TheirModule", getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement myFilter =
- new SuppressElement("Test", "Test", "MyModule", null, null);
+ new SuppressElement("Test", "Test", null, "MyModule", null, null);
assertTrue("Filter should accept valid event", myFilter.accept(ev));
}
@@ -147,7 +159,7 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, null, getClass(), null);
final AuditEvent ev = new AuditEvent(this, "TestSUFFIX", message);
final SuppressElement myFilter =
- new SuppressElement("Test", null, null, null, null);
+ new SuppressElement("Test", null, null, null, null, null);
assertFalse("Filter should not accept invalid event", myFilter.accept(ev));
}
@@ -157,7 +169,7 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, null, getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement myFilter =
- new SuppressElement("Test", "NON_EXISTING_CHECK", "MyModule", null, null);
+ new SuppressElement("Test", "NON_EXISTENT_CHECK", null, "MyModule", null, null);
assertTrue("Filter should accept valid event", myFilter.accept(ev));
}
@@ -167,7 +179,7 @@ public class SuppressElementTest {
new LocalizedMessage(10, 10, "", "", null, null, getClass(), null);
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement myFilter =
- new SuppressElement("Test", getClass().getCanonicalName(), null, null, null);
+ new SuppressElement("Test", getClass().getCanonicalName(), null, null, null, null);
assertFalse("Filter should not accept invalid event", myFilter.accept(ev));
}
@@ -179,7 +191,7 @@ public class SuppressElementTest {
final AuditEvent ev = new AuditEvent(this, "ATest.java", message);
final SuppressElement myFilter =
new SuppressElement("Test", TreeWalkerTest.class.getCanonicalName(),
- null, null, null);
+ null, null, null, null);
assertTrue("Filter should not accept invalid event", myFilter.accept(ev));
}
@@ -189,27 +201,27 @@ public class SuppressElementTest {
// filterBased is used instead of filter field only to satisfy IntelliJ Idea Inspection
// Inspection "Arguments to assertEquals() in wrong order "
final SuppressElement filterBased =
- new SuppressElement("Test", "Test", null, null, null);
+ new SuppressElement("Test", "Test", null, null, null, null);
final SuppressElement filter2 =
- new SuppressElement("Test", "Test", null, null, null);
+ new SuppressElement("Test", "Test", null, null, null, null);
assertEquals("filter, filter2", filterBased, filter2);
final SuppressElement filter3 =
- new SuppressElement("Test", "Test3", null, null, null);
+ new SuppressElement("Test", "Test3", null, null, null, null);
assertNotEquals("filter, filter3", filterBased, filter3);
final SuppressElement filterBased1 =
- new SuppressElement("Test", "Test", null, null, "1-10");
+ new SuppressElement("Test", "Test", null, null, null, "1-10");
assertNotEquals("filter, filter2", filterBased1, filter2);
final SuppressElement filter22 =
- new SuppressElement("Test", "Test", null, null, "1-10");
+ new SuppressElement("Test", "Test", null, null, null, "1-10");
assertEquals("filter, filter2", filterBased1, filter22);
assertNotEquals("filter, filter2", filterBased1, filter2);
final SuppressElement filterBased2 =
- new SuppressElement("Test", "Test", null, "3,4", null);
+ new SuppressElement("Test", "Test", null, null, "3,4", null);
assertNotEquals("filter, filter2", filterBased2, filter2);
final SuppressElement filter23 =
- new SuppressElement("Test", "Test", null, "3,4", null);
+ new SuppressElement("Test", "Test", null, null, "3,4", null);
assertEquals("filter, filter2", filterBased2, filter23);
assertNotEquals("filter, filter2", filterBased2, filter2);
assertEquals("filter, filter2", filterBased2, filter23);
@@ -219,7 +231,8 @@ public class SuppressElementTest {
public void testEqualsAndHashCode() {
EqualsVerifier.forClass(SuppressElement.class)
.usingGetClass()
- .withIgnoredFields("fileRegexp", "checkRegexp", "columnFilter", "lineFilter")
+ .withIgnoredFields("fileRegexp", "checkRegexp", "messageRegexp", "columnFilter",
+ "lineFilter")
.suppress(Warning.NONFINAL_FIELDS)
.verify();
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java
new file mode 100644
index 000000000..9f717333f
--- /dev/null
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressWithPlainTextCommentFilterTest.java
@@ -0,0 +1,487 @@
+////////////////////////////////////////////////////////////////////////////////
+// checkstyle: Checks Java source code for adherence to a set of rules.
+// Copyright (C) 2001-2017 the original author or authors.
+//
+// This library is free software; you can redistribute it and/or
+// modify it under the terms of the GNU Lesser General Public
+// License as published by the Free Software Foundation; either
+// version 2.1 of the License, or (at your option) any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+// Lesser General Public License for more details.
+//
+// You should have received a copy of the GNU Lesser General Public
+// License along with this library; if not, write to the Free Software
+// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+////////////////////////////////////////////////////////////////////////////////
+
+package com.puppycrawl.tools.checkstyle.filters;
+
+import static com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck.MSG_CONTAINS_TAB;
+import static com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck.MSG_FILE_CONTAINS_TAB;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.stream.Collectors;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
+import com.puppycrawl.tools.checkstyle.DefaultConfiguration;
+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.LocalizedMessage;
+import com.puppycrawl.tools.checkstyle.api.SeverityLevel;
+import com.puppycrawl.tools.checkstyle.api.TokenTypes;
+import com.puppycrawl.tools.checkstyle.checks.regexp.RegexpSinglelineCheck;
+import com.puppycrawl.tools.checkstyle.checks.whitespace.FileTabCharacterCheck;
+import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
+import nl.jqno.equalsverifier.EqualsVerifier;
+
+public class SuppressWithPlainTextCommentFilterTest extends AbstractModuleTestSupport {
+
+ private static final String MSG_REGEXP_EXCEEDED = "regexp.exceeded";
+
+ @Override
+ protected String getPackageLocation() {
+ return "com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter";
+ }
+
+ @Test
+ public void testFilterWithDefaultConfig() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ final String[] violationMessages = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testChangeOffAndOnFormat() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("onCommentFormat", "cs-on");
+ filterCfg.addAttribute("offCommentFormat", "cs-off");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "11:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "13:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ final String[] violationMessage = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "11:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java",
+ removeSuppressed(violationMessage, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testSuppressionCommentsInXmlFile() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "CS-OFF");
+ filterCfg.addAttribute("onCommentFormat", "CS-ON");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = {
+ "7:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ final String[] violationMessages = {
+ "7:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilter.xml",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testSuppressionCommentsInPropertiesFile() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "# CHECKSTYLE:OFF");
+ filterCfg.addAttribute("onCommentFormat", "# CHECKSTYLE:ON");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(RegexpSinglelineCheck.class);
+ checkCfg.addAttribute("format", "^key[0-9]=$");
+
+ final String[] suppressed = {
+ "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ "^key[0-9]=$"),
+ };
+
+ final String[] violationMessages = {
+ "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ "^key[0-9]=$"),
+ "4: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ "^key[0-9]=$"),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilter.properties",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testSuppressionCommentsInSqlFile() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "-- CHECKSTYLE OFF");
+ filterCfg.addAttribute("onCommentFormat", "-- CHECKSTYLE ON");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = {
+ "2:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ final String[] violationMessages = {
+ "2:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "5:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilter.sql",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testSuppressionCommentsInJavaScriptFile() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "// CS-OFF");
+ filterCfg.addAttribute("onCommentFormat", "// CS-ON");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(RegexpSinglelineCheck.class);
+ checkCfg.addAttribute("format", ".*===.*");
+
+ final String[] suppressed = {
+ "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"),
+ };
+
+ final String[] violationMessages = {
+ "2: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"),
+ "5: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED, ".*===.*"),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilter.js",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ }
+
+ @Test
+ public void testInvalidCheckFormat() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("checkFormat", "e[l");
+ filterCfg.addAttribute("onCommentFormat", "// cs-on");
+ filterCfg.addAttribute("offCommentFormat", "// cs-off");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = CommonUtils.EMPTY_STRING_ARRAY;
+
+ final String[] violationMessages = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ try {
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause();
+ assertEquals("Invalid exception message",
+ "unable to parse expanded comment e[l", cause.getMessage());
+ }
+ }
+
+ @Test
+ public void testInvalidMessageFormat() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("messageFormat", "e[l");
+ filterCfg.addAttribute("onCommentFormat", "// cs-on");
+ filterCfg.addAttribute("offCommentFormat", "// cs-off");
+
+ final DefaultConfiguration checkCfg = createModuleConfig(FileTabCharacterCheck.class);
+ checkCfg.addAttribute("eachLine", "true");
+
+ final String[] suppressed = CommonUtils.EMPTY_STRING_ARRAY;
+
+ final String[] violationMessages = {
+ "5:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_FILE_CONTAINS_TAB),
+ "8:7: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "10:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ try {
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, checkCfg
+ );
+ fail("CheckstyleException is expected");
+ }
+ catch (CheckstyleException ex) {
+ final IllegalArgumentException cause = (IllegalArgumentException) ex.getCause();
+ assertEquals("Invalid exception message",
+ "unable to parse expanded comment e[l", cause.getMessage());
+ }
+ }
+
+ @Test
+ public void testAcceptNullLocalizedMessage() {
+ final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter();
+ final AuditEvent auditEvent = new AuditEvent(this);
+ assertTrue("Filter should accept audit event", filter.accept(auditEvent));
+ Assert.assertNull("File name should not be null", auditEvent.getFileName());
+ }
+
+ @Test
+ public void testEqualsAndHashCodeOfTagClass() {
+ EqualsVerifier.forClass(SuppressWithPlainTextCommentFilter.Suppression.class)
+ .usingGetClass().verify();
+ }
+
+ @Test
+ public void testSuppressByModuleId() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "CSOFF (\\w+) \\(\\w+\\)");
+ filterCfg.addAttribute("onCommentFormat", "CSON (\\w+)");
+ filterCfg.addAttribute("checkFormat", "$1");
+
+ final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class);
+ regexpCheckCfg.addAttribute("id", "ignore");
+ regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*");
+
+ final DefaultConfiguration fileTabCheckCfg =
+ createModuleConfig(FileTabCharacterCheck.class);
+ fileTabCheckCfg.addAttribute("eachLine", "true");
+ fileTabCheckCfg.addAttribute("id", "foo");
+
+ final String[] suppressedViolationMessages = {
+ "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ };
+
+ final String[] expectedViolationMessages = {
+ "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "9:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "14: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterSuppressById.java",
+ removeSuppressed(expectedViolationMessages, suppressedViolationMessages),
+ filterCfg, regexpCheckCfg, fileTabCheckCfg
+ );
+ }
+
+ @Test
+ public void testSuppressByModuleIdWithNullModuleId() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ filterCfg.addAttribute("offCommentFormat", "CSOFF (\\w+) \\(\\w+\\)");
+ filterCfg.addAttribute("onCommentFormat", "CSON (\\w+)");
+ filterCfg.addAttribute("checkFormat", "$1");
+
+ final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class);
+ regexpCheckCfg.addAttribute("id", "ignore");
+ regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*");
+
+ final DefaultConfiguration fileTabCheckCfg =
+ createModuleConfig(FileTabCharacterCheck.class);
+ fileTabCheckCfg.addAttribute("eachLine", "true");
+ fileTabCheckCfg.addAttribute("id", null);
+
+ final String[] suppressedViolationMessages = {
+ "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ };
+
+ final String[] expectedViolationMessages = {
+ "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "9:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "9: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "11: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "14: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterSuppressById.java",
+ removeSuppressed(expectedViolationMessages, suppressedViolationMessages),
+ filterCfg, regexpCheckCfg, fileTabCheckCfg
+ );
+ }
+
+ @Test
+ public void testAcceptThrowsIllegalStateExceptionAsFileNotFound() {
+ final LocalizedMessage message = new LocalizedMessage(1, 1, 1, TokenTypes.CLASS_DEF,
+ "messages.properties", "key", null, SeverityLevel.ERROR, null, getClass(), null);
+ final String fileName = "nonexisting_file";
+ final AuditEvent auditEvent = new AuditEvent(this, fileName, message);
+
+ final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter();
+
+ try {
+ filter.accept(auditEvent);
+ fail(IllegalStateException.class.getSimpleName() + " is expected");
+ }
+ catch (IllegalStateException ex) {
+ assertEquals("Invalid exception message",
+ "Cannot read source file: " + fileName, ex.getMessage());
+
+ final Throwable cause = ex.getCause();
+ assertTrue("Exception cause has invalid type",
+ cause instanceof FileNotFoundException);
+ assertEquals("Invalid exception message",
+ fileName + " (No such file or directory)", cause.getMessage());
+ }
+ }
+
+ @Test
+ public void testFilterWithCustomMessageFormat() throws Exception {
+ final DefaultConfiguration filterCfg =
+ createModuleConfig(SuppressWithPlainTextCommentFilter.class);
+ final String messageFormat =
+ ".*" + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB) + ".*";
+ // -@cs[CheckstyleTestMakeup] need to test dynamic property
+ filterCfg.addAttribute("messageFormat", messageFormat);
+
+ final DefaultConfiguration fileTabCheckCfg =
+ createModuleConfig(FileTabCharacterCheck.class);
+ fileTabCheckCfg.addAttribute("eachLine", "true");
+
+ final DefaultConfiguration regexpCheckCfg = createModuleConfig(RegexpSinglelineCheck.class);
+ regexpCheckCfg.addAttribute("id", "ignore");
+ regexpCheckCfg.addAttribute("format", ".*[a-zA-Z][0-9].*");
+
+ final String[] suppressed = {
+ "8:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ };
+
+ final String[] violationMessages = {
+ "6: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "8:1: " + getCheckMessage(FileTabCharacterCheck.class, MSG_CONTAINS_TAB),
+ "8: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "10: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ "13: " + getCheckMessage(RegexpSinglelineCheck.class, MSG_REGEXP_EXCEEDED,
+ ".*[a-zA-Z][0-9].*"),
+ };
+
+ verifySuppressed(
+ "InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java",
+ removeSuppressed(violationMessages, suppressed),
+ filterCfg, fileTabCheckCfg, regexpCheckCfg
+ );
+ }
+
+ @Test
+ public void testFilterWithDirectory() throws IOException {
+ final SuppressWithPlainTextCommentFilter filter = new SuppressWithPlainTextCommentFilter();
+ final AuditEvent event = new AuditEvent(this, getPath(""), new LocalizedMessage(1, 1,
+ "bundle", "key", null, SeverityLevel.ERROR, "moduleId", getClass(),
+ "customMessage"));
+
+ assertTrue("filter should accept directory", filter.accept(event));
+ }
+
+ private void verifySuppressed(String fileNameWithExtension, String[] violationMessages,
+ Configuration... childConfigs) throws Exception {
+ final DefaultConfiguration checkerConfig = createRootConfig(null);
+
+ Arrays.stream(childConfigs).forEach(checkerConfig::addChild);
+
+ final String fileExtension = CommonUtils.getFileExtension(fileNameWithExtension);
+ checkerConfig.addAttribute("fileExtensions", fileExtension);
+
+ verify(checkerConfig, getPath(fileNameWithExtension), violationMessages);
+ }
+
+ private static String[] removeSuppressed(String[] from, String... remove) {
+ final Collection<String> coll = Arrays.stream(from).collect(Collectors.toList());
+ coll.removeAll(Arrays.asList(remove));
+ return coll.toArray(new String[coll.size()]);
+ }
+}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java
index 229a9b9af..36835cab2 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionCommentFilterTest.java
@@ -401,7 +401,7 @@ public class SuppressionCommentFilterTest
final TreeWalkerAuditEvent dummyEvent = new TreeWalkerAuditEvent(contents, "filename",
new LocalizedMessage(1, null, null, null, null, Object.class, null), null);
final boolean result = suppressionCommentFilter.accept(dummyEvent);
- assertFalse("Fileter should not accept event", result);
+ assertFalse("Filter should not accept event", result);
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java
index f0e9e8182..340485868 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionFilterTest.java
@@ -85,8 +85,8 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingSuppressionFileWithFalseOptional() {
- final String fileName = "non_existing_suppression_file.xml";
+ public void testNonExistentSuppressionFileWithFalseOptional() {
+ final String fileName = "non_existent_suppression_file.xml";
try {
final boolean optional = false;
createSuppressionFilter(fileName, optional);
@@ -108,7 +108,7 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport {
}
catch (CheckstyleException ex) {
assertEquals("Invalid error message",
- "Unable to parse " + fileName + " - invalid files or checks format",
+ "Unable to parse " + fileName + " - invalid files or checks or message format",
ex.getMessage());
}
}
@@ -126,8 +126,8 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingSuppressionFileWithTrueOptional() throws Exception {
- final String fileName = "non_existing_suppression_file.xml";
+ public void testNonExistentSuppressionFileWithTrueOptional() throws Exception {
+ final String fileName = "non_existent_suppression_file.xml";
final boolean optional = true;
final SuppressionFilter filter = createSuppressionFilter(fileName, optional);
@@ -138,9 +138,9 @@ public class SuppressionFilterTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingSuppressionUrlWithTrueOptional() throws Exception {
+ public void testNonExistentSuppressionUrlWithTrueOptional() throws Exception {
final String fileName =
- "http://checkstyle.sourceforge.net/non_existing_suppression.xml";
+ "http://checkstyle.sourceforge.net/non_existent_suppression.xml";
final boolean optional = true;
final SuppressionFilter filter = createSuppressionFilter(fileName, optional);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java
index 97b9c1eff..a7fe7ce4c 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionXpathFilterTest.java
@@ -86,8 +86,8 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingSuppressionFileWithFalseOptional() throws Exception {
- final String fileName = getPath("non_existing_suppression_file.xml");
+ public void testNonExistentSuppressionFileWithFalseOptional() throws Exception {
+ final String fileName = getPath("non_existent_suppression_file.xml");
try {
final boolean optional = false;
createSuppressionXpathFilter(fileName, optional);
@@ -108,9 +108,8 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport {
fail("Exception is expected");
}
catch (CheckstyleException ex) {
- assertEquals("Invalid error message",
- "Unable to parse " + fileName + " - invalid files or checks format for "
- + "suppress-xpath",
+ assertEquals("Invalid error message", "Unable to parse " + fileName
+ + " - invalid files or checks or message format for suppress-xpath",
ex.getMessage());
}
}
@@ -129,9 +128,9 @@ public class SuppressionXpathFilterTest extends AbstractModuleTestSupport {
}
@Test
- public void testNonExistingSuppressionFileWithTrueOptional() throws Exception {
+ public void testNonExistentSuppressionFileWithTrueOptional() throws Exception {
final String fileName = "src/test/resources/com/puppycrawl/tools/checkstyle/filters/"
- + "non_existing_suppression_file.xml";
+ + "non_existent_suppression_file.xml";
final boolean optional = true;
final SuppressionXpathFilter filter = createSuppressionXpathFilter(fileName, optional);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
index 0a7be080b..294599ecd 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
@@ -27,6 +27,7 @@ import java.io.IOException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
+import java.util.HashSet;
import java.util.Set;
import org.junit.Rule;
@@ -104,7 +105,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
}
@Test
- public void testLoadFromNonExistingUrl() {
+ public void testLoadFromNonExistentUrl() {
try {
SuppressionsLoader.loadSuppressions("http://^%$^* %&% %^&");
fail("exception expected");
@@ -122,17 +123,20 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
final FilterSet fc2 = new FilterSet();
final SuppressElement se0 =
- new SuppressElement("file0", "check0", null, null, null);
+ new SuppressElement("file0", "check0", null, null, null, null);
fc2.addFilter(se0);
final SuppressElement se1 =
- new SuppressElement("file1", "check1", null, "1,2-3", null);
+ new SuppressElement("file1", "check1", null, null, "1,2-3", null);
fc2.addFilter(se1);
final SuppressElement se2 =
- new SuppressElement("file2", "check2", null, null, "1,2-3");
+ new SuppressElement("file2", "check2", null, null, null, "1,2-3");
fc2.addFilter(se2);
final SuppressElement se3 =
- new SuppressElement("file3", "check3", null, "1,2-3", "1,2-3");
+ new SuppressElement("file3", "check3", null, null, "1,2-3", "1,2-3");
fc2.addFilter(se3);
+ final SuppressElement se4 =
+ new SuppressElement(null, null, "message0", null, null, null);
+ fc2.addFilter(se4);
assertEquals("Multiple suppressions were loaded incorrectly", fc2, fc);
}
@@ -268,7 +272,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
}
catch (CheckstyleException ex) {
assertEquals("Invalid error message",
- "Unable to parse " + fn + " - missing checks and id attribute",
+ "Unable to parse " + fn + " - missing checks or id or message attribute",
ex.getMessage());
}
}
@@ -290,7 +294,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
}
catch (CheckstyleException ex) {
assertEquals("Invalid error message",
- "Unable to parse " + fn + " - invalid files or checks format",
+ "Unable to parse " + fn + " - invalid files or checks or message format",
ex.getMessage());
}
}
@@ -318,7 +322,15 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
final String fn = getPath("InputSuppressionsLoaderXpathCorrect.xml");
final Set<TreeWalkerFilter> filterSet = SuppressionsLoader.loadXpathSuppressions(fn);
- assertEquals("Invalid number of filters", 1, filterSet.size());
+ final Set<TreeWalkerFilter> expectedFilterSet = new HashSet<>();
+ final XpathFilter xf0 =
+ new XpathFilter("file1", "test", null, "id1", "/CLASS_DEF");
+ expectedFilterSet.add(xf0);
+ final XpathFilter xf1 =
+ new XpathFilter(null, null, "message1", null, "/CLASS_DEF");
+ expectedFilterSet.add(xf1);
+ assertEquals("Multiple xpath suppressions were loaded incorrectly", expectedFilterSet,
+ filterSet);
}
@Test
@@ -330,7 +342,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
}
catch (CheckstyleException ex) {
assertEquals("Invalid error message",
- "Unable to parse " + fn + " - invalid files or checks format for "
+ "Unable to parse " + fn + " - invalid files or checks or message format for "
+ "suppress-xpath",
ex.getMessage());
}
@@ -346,7 +358,7 @@ public class SuppressionsLoaderTest extends AbstractPathTestSupport {
}
catch (CheckstyleException ex) {
assertEquals("Invalid error message",
- "Unable to parse " + fn + " - missing checks and id attribute for "
+ "Unable to parse " + fn + " - missing checks or id or message attribute for "
+ "suppress-xpath",
ex.getMessage());
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java
index f74af313e..4580cd3e4 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/XpathFilterTest.java
@@ -61,7 +61,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testMatching() throws Exception {
final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 0,
TokenTypes.CLASS_DEF);
assertFalse("Event should be rejected", filter.accept(ev));
@@ -71,7 +71,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingTokenType() throws Exception {
final String xpath = "//METHOD_DEF[@text='countTokens']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 0,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -81,7 +81,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingLineNumber() throws Exception {
final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(100, 0,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -91,7 +91,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingColumnNumber() throws Exception {
final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 100,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -103,7 +103,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
+ "../..[@text='countTokens']] "
+ "| //VARIABLE_DEF[@text='someVariable' and ../..[@text='sum']]";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent eventOne = getEvent(5, 8,
TokenTypes.VARIABLE_DEF);
final TreeWalkerAuditEvent eventTwo = getEvent(10, 4,
@@ -120,7 +120,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
final String xpath = "1@#";
try {
final Object test = new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null,
- xpath);
+ null, xpath);
fail("Exception was expected but got " + test);
}
catch (IllegalStateException ex) {
@@ -134,15 +134,15 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
final TreeWalkerAuditEvent event = getEvent(15, 8,
TokenTypes.VARIABLE_DEF);
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null);
- assertTrue("Event should be accepted", filter.accept(event));
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, null);
+ assertFalse("Event should be accepted", filter.accept(event));
}
@Test
public void testNullFileName() {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(null,
null, null, null);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -152,7 +152,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingFileRegexp() throws Exception {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter =
- new XpathFilter("NonMatchingRegexp", "Test", null, xpath);
+ new XpathFilter("NonMatchingRegexp", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 0,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -162,7 +162,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNullLocalizedMessage() {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(null,
file.getName(), null, null);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -172,7 +172,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingModuleId() throws Exception {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", "id19", xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, "id19", xpath);
final LocalizedMessage message =
new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id20",
getClass(), null);
@@ -185,7 +185,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testMatchingModuleId() throws Exception {
final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", "id19", xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, "id19", xpath);
final LocalizedMessage message =
new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19",
getClass(), null);
@@ -198,7 +198,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingChecks() throws Exception {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter = new XpathFilter("InputXpathFilterSuppressByXpath",
- "NonMatchingRegexp", "id19", xpath);
+ "NonMatchingRegexp", null, "id19", xpath);
final LocalizedMessage message =
new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19",
getClass(), null);
@@ -211,7 +211,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNonMatchingFileNameModuleIdAndCheck() throws Exception {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", null, null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", null, null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 0,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
@@ -221,17 +221,29 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
public void testNullModuleIdAndNonMatchingChecks() throws Exception {
final String xpath = "NON_MATCHING_QUERY";
final XpathFilter filter = new XpathFilter("InputXpathFilterSuppressByXpath",
- "NonMatchingRegexp", null, xpath);
+ "NonMatchingRegexp", null, null, xpath);
final TreeWalkerAuditEvent ev = getEvent(3, 0,
TokenTypes.CLASS_DEF);
assertTrue("Event should be accepted", filter.accept(ev));
}
@Test
+ public void testDecideByMessage() throws Exception {
+ final LocalizedMessage message = new LocalizedMessage(0, 0, TokenTypes.CLASS_DEF, "", "",
+ null, null, null, getClass(), "Test");
+ final TreeWalkerAuditEvent ev = new TreeWalkerAuditEvent(fileContents, file.getName(),
+ message, TestUtil.parseFile(file));
+ final XpathFilter filter1 = new XpathFilter(null, null, "Test", null, null);
+ final XpathFilter filter2 = new XpathFilter(null, null, "Bad", null, null);
+ assertFalse("Message match", filter1.accept(ev));
+ assertTrue("Message not match", filter2.accept(ev));
+ }
+
+ @Test
public void testThrowException() {
final String xpath = "/CLASS_DEF[@text='InputXpathFilterSuppressByXpath']";
final XpathFilter filter =
- new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, xpath);
+ new XpathFilter("InputXpathFilterSuppressByXpath", "Test", null, null, xpath);
final LocalizedMessage message =
new LocalizedMessage(3, 0, TokenTypes.CLASS_DEF, "", "", null, null, "id19",
getClass(), null);
@@ -254,7 +266,7 @@ public class XpathFilterTest extends AbstractModuleTestSupport {
xpathEvaluator.createExpression("//METHOD_DEF"),
xpathEvaluator.createExpression("//VARIABLE_DEF"))
.usingGetClass()
- .withIgnoredFields("fileRegexp", "checkRegexp", "xpathExpression")
+ .withIgnoredFields("fileRegexp", "checkRegexp", "messageRegexp", "xpathExpression")
.verify();
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java
index 54b3f866a..ea49bf979 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/GeneratedJavaTokenTypesTest.java
@@ -22,7 +22,10 @@ package com.puppycrawl.tools.checkstyle.grammars;
import org.junit.Assert;
import org.junit.Test;
-/** @noinspection ClassIndependentOfModule */
+/**
+ * GeneratedJavaTokenTypesTest.
+ * @noinspection ClassIndependentOfModule
+ */
public class GeneratedJavaTokenTypesTest {
/**
* <p>
@@ -30,6 +33,7 @@ public class GeneratedJavaTokenTypesTest {
* old tokens must remain and keep their current numbering. Old token
* numberings are not allowed to change.
* </p>
+ *
* <p>
* The reason behind this is Java inlines static final field values directly
* into the compiled Java code. This loses all connections with the original
@@ -37,7 +41,9 @@ public class GeneratedJavaTokenTypesTest {
* up in user-created checks and causes conflicts.
* </p>
*
+ * <p>
* Issue: https://github.com/checkstyle/checkstyle/issues/505
+ * </p>
*/
@Test
public void testTokenNumbering() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java
index c90a188ed..fe4d2ed6e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/GeneratedJavadocTokenTypesTest.java
@@ -23,7 +23,10 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
-/** @noinspection ClassIndependentOfModule */
+/**
+ * GeneratedJavadocTokenTypesTest.
+ * @noinspection ClassIndependentOfModule
+ */
public class GeneratedJavadocTokenTypesTest {
private static final String MSG = "Ensure that token numbers generated for the elements"
@@ -33,7 +36,7 @@ public class GeneratedJavadocTokenTypesTest {
* This method checks that the numbers generated for tokens in <tt>JavadocLexer.g4</tt> don't
* change with the lexer grammar itself.
* <br>ANTLR maps all the lexer elements to compile time constants used internally by ANTLR.
- * Compatability damange is incurred <i>(with respect to the previous checkstyle versions)
+ * Compatibility damage is incurred <i>(with respect to the previous checkstyle versions)
* </i> if these compile time constants keep changing with the grammar.
*
* @see "https://github.com/checkstyle/checkstyle/issues/5139"
@@ -143,7 +146,7 @@ public class GeneratedJavadocTokenTypesTest {
* This method checks that the numbers generated for rules in <tt>JavadocParser.g4</tt> don't
* change with the Parser grammar itself.
* <br>ANTLR maps all the parser rules to compile time constants used internally by ANTLR.
- * Compatability damange is incurred <i>(with respect to the previous checkstyle versions)
+ * Compatibility damage is incurred <i>(with respect to the previous checkstyle versions)
* </i> if these compile time constants keep changing with the grammar.
*
* @see "https://github.com/checkstyle/checkstyle/issues/5139"
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java
index ebfb522d6..ff70d9290 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammars/javadoc/JavadocParseTreeTest.java
@@ -26,7 +26,10 @@ import org.junit.Test;
import com.puppycrawl.tools.checkstyle.AbstractTreeTestSupport;
-/** @noinspection ClassOnlyUsedInOnePackage */
+/**
+ * JavadocParseTreeTest.
+ * @noinspection ClassOnlyUsedInOnePackage
+ */
public class JavadocParseTreeTest extends AbstractTreeTestSupport {
@Override
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java
index 8adea5082..dc9e16aa4 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/gui/CodeSelectorPresentationTest.java
@@ -56,7 +56,7 @@ public class CodeSelectorPresentationTest extends AbstractPathTestSupport {
}
/** Converts lineToPosition from multicharacter to one character line separator
- * needs to support crossplatform line separators
+ * needs to support crossplatform line separators.
* @param systemLinesToPosition lines to position mapping for current system
* @return lines to position mapping with one character line separator
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java
index afd5a7f85..03e720960 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/gui/ParseTreeTablePresentationTest.java
@@ -191,18 +191,19 @@ public class ParseTreeTablePresentationTest extends AbstractPathTestSupport {
final ParseTreeTablePresentation parseTree = new ParseTreeTablePresentation(null);
int index = 0;
while (ithChild != null) {
- Assert.assertEquals("Invalud child index",
+ Assert.assertEquals("Invalid child index",
index, parseTree.getIndexOfChild(tree, ithChild));
ithChild = ithChild.getNextSibling();
index++;
}
- Assert.assertEquals("Invalud child index",
+ Assert.assertEquals("Invalid child index",
-1, parseTree.getIndexOfChild(tree, new DetailAST()));
}
/**
- * The path to class name in InputJavadocAttributesAndMethods.java
+ * The path to class name in InputJavadocAttributesAndMethods.java.
+ * <pre>
* CLASS_DEF
* - MODIFIERS
* - Comment node
@@ -210,6 +211,7 @@ public class ParseTreeTablePresentationTest extends AbstractPathTestSupport {
* - IDENT -> this is the node that holds the class name
* Line number 4 - first three lines are taken by javadoc
* Column 6 - first five columns taken by 'class '
+ * </pre>
*/
@Test
public void testGetValueAt() {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java
index 38c24c739..f82155485 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java
@@ -330,8 +330,6 @@ public class AllChecksTest extends AbstractModuleTestSupport {
public void testAllModulesAreReferencedInConfigFile() throws Exception {
final Set<String> modulesReferencedInConfig = CheckUtil.getConfigCheckStyleModules();
final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules());
- //Issue: https://github.com/checkstyle/checkstyle/issues/4421
- moduleNames.remove("SuppressionXpathFilter");
moduleNames.stream().filter(check -> !modulesReferencedInConfig.contains(check))
.forEach(check -> {
@@ -428,8 +426,6 @@ public class AllChecksTest extends AbstractModuleTestSupport {
// these are documented on non-'config_' pages
checkstyleModulesNames.remove("TreeWalker");
checkstyleModulesNames.remove("Checker");
- //Issue: https://github.com/checkstyle/checkstyle/issues/4421
- checkstyleModulesNames.remove("SuppressionXpathFilter");
checkstyleModulesNames.stream()
.filter(moduleName -> !modulesNamesWhichHaveXdocs.contains(moduleName))
@@ -445,8 +441,6 @@ public class AllChecksTest extends AbstractModuleTestSupport {
public void testAllCheckstyleModulesInCheckstyleConfig() throws Exception {
final Set<String> configChecks = CheckUtil.getConfigCheckStyleModules();
final Set<String> moduleNames = CheckUtil.getSimpleNames(CheckUtil.getCheckstyleModules());
- //Issue: https://github.com/checkstyle/checkstyle/issues/4421
- moduleNames.remove("SuppressionXpathFilter");
for (String moduleName : moduleNames) {
Assert.assertTrue("checkstyle_checks.xml is missing module: " + moduleName,
@@ -548,6 +542,7 @@ public class AllChecksTest extends AbstractModuleTestSupport {
* Checks that an array is a subset of other array.
* @param array to check whether it is a subset.
* @param arrayToCheckIn array to check in.
+ * @return {@code true} if all elements in {@code array} are in {@code arrayToCheckIn}.
*/
private static boolean isSubset(int[] array, int... arrayToCheckIn) {
Arrays.sort(arrayToCheckIn);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java
index b7269b536..d9c4c5e3f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllTestsTest.java
@@ -32,7 +32,10 @@ import java.util.Map;
import org.junit.Assert;
import org.junit.Test;
-/** @noinspection ClassIndependentOfModule */
+/**
+ * AllTestsTest.
+ * @noinspection ClassIndependentOfModule
+ */
public class AllTestsTest {
@Test
public void testAllInputsHaveTest() throws Exception {
@@ -143,7 +146,6 @@ public class AllTestsTest {
// until https://github.com/checkstyle/checkstyle/issues/5105
if (!path.contains(File.separatorChar + "grammars" + File.separatorChar)
- // until https://github.com/checkstyle/checkstyle/issues/5104
&& !path.contains(File.separatorChar + "foo" + File.separatorChar)
&& !path.contains(File.separatorChar + "bar" + File.separatorChar)) {
String fileName = file.getName();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java
index ede921efe..f6323466e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CommitValidationTest.java
@@ -49,24 +49,24 @@ import org.junit.Test;
/**
* Validate commit message has proper structure.
*
- * Commits to check are resolved from different places according
+ * <p>Commits to check are resolved from different places according
* to type of commit in current HEAD. If current HEAD commit is
* non-merge commit , previous commits are resolved due to current
* HEAD commit. Otherwise if it is a merge commit, it will invoke
- * resolving previous commits due to commits which was merged.
+ * resolving previous commits due to commits which was merged.</p>
*
- * After calculating commits to start with ts resolves previous
+ * <p>After calculating commits to start with ts resolves previous
* commits according to COMMITS_RESOLUTION_MODE variable.
* At default(BY_LAST_COMMIT_AUTHOR) it checks first commit author
* and return all consecutive commits with same author. Second
* mode(BY_COUNTER) makes returning first PREVIOUS_COMMITS_TO_CHECK_COUNT
- * commits after starter commit.
+ * commits after starter commit.</p>
*
- * Resolved commits are filtered according to author. If commit author
+ * <p>Resolved commits are filtered according to author. If commit author
* belong to list USERS_EXCLUDED_FROM_VALIDATION then this commit will
- * not be validated.
+ * not be validated.</p>
*
- * Filtered commit list is checked if their messages has proper structure.
+ * <p>Filtered commit list is checked if their messages has proper structure.</p>
*
* @author <a href="mailto:piotr.listkiewicz@gmail.com">liscju</a>
*/
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java
index 129d67c08..5f88ab111 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java
@@ -84,6 +84,7 @@ public class XdocsPagesTest {
"name=\"Header\"",
"name=\"Translation\"",
"name=\"SeverityMatchFilter\"",
+ "name=\"SuppressWithPlainTextCommentFilter\"",
"name=\"SuppressionFilter\"",
"name=\"SuppressWarningsFilter\"",
"name=\"BeforeExecutionExclusionFileFilter\"",
@@ -215,6 +216,7 @@ public class XdocsPagesTest {
// can't process non-existent examples, or out of context snippets
if (!code.contains("com.mycompany") && !code.contains("checkstyle-packages")
&& !code.contains("MethodLimit") && !code.contains("<suppress ")
+ && !code.contains("<suppress-xpath ")
&& !code.contains("<import-control ")
&& !unserializedSource.startsWith("<property ")
&& !unserializedSource.startsWith("<taskdef ")) {
@@ -292,7 +294,7 @@ public class XdocsPagesTest {
}
/**
- * Test contains asserts in callstack, but idea does not see them
+ * Test contains asserts in callstack, but idea does not see them.
* @noinspection JUnitTestMethodWithNoAssertions
*/
@Test
@@ -450,6 +452,9 @@ public class XdocsPagesTest {
if (hasParentModule(sectionName)) {
if (AbstractJavadocCheck.class.isAssignableFrom(clss)) {
properties.removeAll(JAVADOC_CHECK_PROPERTIES);
+
+ // override
+ properties.add("violateExecutionOnNonTightHtml");
}
else if (AbstractCheck.class.isAssignableFrom(clss)) {
properties.removeAll(CHECK_PROPERTIES);
@@ -643,7 +648,14 @@ public class XdocsPagesTest {
.replaceAll("\\s+", " ").trim());
}
- /** @noinspection IfStatementWithTooManyBranches */
+ /**
+ * Get's the name of the bean property's type for the class.
+ * @param clss The bean property's defined type.
+ * @param instance The class instance to work with.
+ * @param propertyName The property name to work with.
+ * @return String form of property's type.
+ * @noinspection IfStatementWithTooManyBranches
+ */
private static String getModulePropertyExpectedTypeName(Class<?> clss, Object instance,
String propertyName) {
final String instanceName = instance.getClass().getSimpleName();
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java
index f5ea98b15..c6b6cb0f1 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestFileSetCheck.java
@@ -26,6 +26,7 @@ import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
import com.puppycrawl.tools.checkstyle.api.FileText;
/**
+ * TestFileSetCheck.
* @noinspection ClassOnlyUsedInOnePackage
*/
public class TestFileSetCheck extends AbstractFileSetCheck {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java
index 2bf6b9f8a..005a58f1d 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/testmodules/TestLoggingReporter.java
@@ -22,6 +22,7 @@ package com.puppycrawl.tools.checkstyle.internal.testmodules;
import com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter;
/**
+ * TestLoggingReporter.
* @noinspection ClassOnlyUsedInOnePackage
*/
public final class TestLoggingReporter extends AbstractViolationReporter {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java
index be0898136..8a25a6cce 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CheckUtil.java
@@ -139,7 +139,7 @@ public final class CheckUtil {
.getContextClassLoader();
final String packageName = "com.puppycrawl.tools.checkstyle";
return getCheckstyleModulesRecursive(packageName, loader).stream()
- .filter(ModuleReflectionUtils::isCheckstyleCheck)
+ .filter(ModuleReflectionUtils::isCheckstyleTreeWalkerCheck)
.collect(Collectors.toSet());
}
@@ -219,6 +219,7 @@ public final class CheckUtil {
* Gets the check message 'as is' from appropriate 'messages.properties'
* file.
*
+ * @param module The package the message is located in.
* @param locale the locale to get the message for.
* @param messageKey the key of message in 'messages*.properties' file.
* @param arguments the arguments of message in 'messages*.properties' file.
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java
index 6eb65dd1f..cf62e8b6f 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/CloseAndFlushTestByteArrayOutputStream.java
@@ -22,7 +22,10 @@ package com.puppycrawl.tools.checkstyle.internal.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
-/** @noinspection ClassOnlyUsedInOnePackage */
+/**
+ * CloseAndFlushTestByteArrayOutputStream.
+ * @noinspection ClassOnlyUsedInOnePackage
+ */
public final class CloseAndFlushTestByteArrayOutputStream extends ByteArrayOutputStream {
private int closeCount;
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java
index 948a55197..a88fb960a 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/ConfigurationUtil.java
@@ -38,6 +38,7 @@ public final class ConfigurationUtil {
props.setProperty("checkstyle.basedir", "basedir");
props.setProperty("checkstyle.cache.file", "file");
props.setProperty("checkstyle.suppressions.file", "file");
+ props.setProperty("checkstyle.suppressions-xpath.file", "file");
props.setProperty("checkstyle.header.file", "file");
props.setProperty("checkstyle.regexp.header.file", "file");
props.setProperty("checkstyle.importcontrol.file", "file");
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java
index 1c5d8cc70..df85e9aad 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/TestUtil.java
@@ -25,6 +25,7 @@ import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
+import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@@ -72,6 +73,52 @@ public final class TestUtil {
}
/**
+ * Retrieves the specified field by it's name in the class or it's direct super.
+ *
+ * @param clss The class to retrieve the field for.
+ * @param fieldName The name of the field to retrieve.
+ * @return The class' field.
+ * @throws NoSuchFieldException if the requested field cannot be found in the class.
+ */
+ public static Field getClassDeclaredField(Class<?> clss, String fieldName)
+ throws NoSuchFieldException {
+ final Optional<Field> classField = Arrays.stream(clss.getDeclaredFields())
+ .filter(field -> fieldName.equals(field.getName())).findFirst();
+ final Field resultField;
+ if (classField.isPresent()) {
+ resultField = classField.get();
+ }
+ else {
+ resultField = clss.getSuperclass().getDeclaredField(fieldName);
+ }
+ resultField.setAccessible(true);
+ return resultField;
+ }
+
+ /**
+ * Retrieves the specified method by it's name in the class or it's direct super.
+ *
+ * @param clss The class to retrieve the field for.
+ * @param methodName The name of the method to retrieve.
+ * @return The class' field.
+ * @throws NoSuchMethodException if the requested method cannot be found in the class.
+ */
+ public static Method getClassDeclaredMethod(Class<?> clss, String methodName)
+ throws NoSuchMethodException {
+ final Optional<Method> classMethod = Arrays.stream(clss.getDeclaredMethods())
+ .filter(method -> methodName.equals(method.getName())).findFirst();
+ final Method resultMethod;
+ if (classMethod.isPresent()) {
+ resultMethod = classMethod.get();
+ }
+ else {
+ resultMethod = clss.getSuperclass().getDeclaredMethod(methodName);
+ }
+ resultMethod.setAccessible(true);
+ return resultMethod;
+ }
+
+ /**
* Checks if stateful field is cleared during {@link AbstractCheck#beginTree} in check.
*
* @param check check object which field is to be verified
@@ -91,16 +138,7 @@ public final class TestUtil {
check.beginTree(astToVisit);
check.visitToken(astToVisit);
check.beginTree(null);
- final Optional<Field> classField = Arrays.stream(check.getClass().getDeclaredFields())
- .filter(field -> fieldName.equals(field.getName())).findFirst();
- final Field resultField;
- if (classField.isPresent()) {
- resultField = classField.get();
- }
- else {
- resultField = check.getClass().getSuperclass().getDeclaredField(fieldName);
- }
- resultField.setAccessible(true);
+ final Field resultField = getClassDeclaredField(check.getClass(), fieldName);
return isClear.test(resultField.get(check));
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java
index ba72c98c5..1840a8370 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XdocUtil.java
@@ -37,7 +37,10 @@ import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
-/** @noinspection ClassOnlyUsedInOnePackage */
+/**
+ * XdocUtil.
+ * @noinspection ClassOnlyUsedInOnePackage
+ */
public final class XdocUtil {
public static final String DIRECTORY_PATH = "src/xdocs";
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java
index 9b36a443e..3a4897805 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XmlUtil.java
@@ -34,7 +34,10 @@ import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
-/** @noinspection ClassOnlyUsedInOnePackage */
+/**
+ * XmlUtil.
+ * @noinspection ClassOnlyUsedInOnePackage
+ */
public final class XmlUtil {
private XmlUtil() {
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java
index bedab2ef3..c2e78ebb7 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/utils/XpathUtil.java
@@ -29,6 +29,7 @@ import net.sf.saxon.sxpath.XPathExpression;
import net.sf.saxon.trans.XPathException;
/**
+ * XpathUtil.
* @noinspection ClassOnlyUsedInOnePackage
*/
public final class XpathUtil {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java
index 090b2d3b8..a000ea583 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/AnnotationUtilityTest.java
@@ -173,6 +173,7 @@ public class AnnotationUtilityTest {
final DetailAST annotationName = new DetailAST();
annotations.setType(TokenTypes.ANNOTATIONS);
annotation.setType(TokenTypes.ANNOTATION);
+ annotationNameHolder.setType(TokenTypes.AT);
annotationName.setText("Annotation");
annotationNameHolder.setNextSibling(annotationName);
@@ -184,4 +185,31 @@ public class AnnotationUtilityTest {
assertTrue("Annotation should contain " + astForTest,
AnnotationUtility.containsAnnotation(astForTest, "Annotation"));
}
+
+ @Test
+ public void testContainsAnnotationWithComment() {
+ final DetailAST astForTest = new DetailAST();
+ astForTest.setType(TokenTypes.PACKAGE_DEF);
+ final DetailAST child = new DetailAST();
+ final DetailAST annotations = new DetailAST();
+ final DetailAST annotation = new DetailAST();
+ final DetailAST annotationNameHolder = new DetailAST();
+ final DetailAST annotationName = new DetailAST();
+ final DetailAST comment = new DetailAST();
+ annotations.setType(TokenTypes.ANNOTATIONS);
+ annotation.setType(TokenTypes.ANNOTATION);
+ annotationNameHolder.setType(TokenTypes.AT);
+ comment.setType(TokenTypes.BLOCK_COMMENT_BEGIN);
+ annotationName.setText("Annotation");
+
+ annotationNameHolder.setNextSibling(annotationName);
+ annotation.setFirstChild(comment);
+ comment.setNextSibling(annotationNameHolder);
+ annotations.setFirstChild(annotation);
+ child.setNextSibling(annotations);
+ astForTest.setFirstChild(child);
+
+ assertTrue("Annotation should contain " + astForTest,
+ AnnotationUtility.containsAnnotation(astForTest, "Annotation"));
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java
index 0c8df797a..d82a70c6b 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/BlockCommentPositionTest.java
@@ -20,6 +20,7 @@
package com.puppycrawl.tools.checkstyle.utils;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.Arrays;
@@ -36,12 +37,18 @@ import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
public class BlockCommentPositionTest extends AbstractPathTestSupport {
@Test
+ public void testPrivateConstr() throws Exception {
+ assertTrue("Constructor is not private",
+ TestUtil.isUtilsClassHasPrivateConstructor(BlockCommentPosition.class, true));
+ }
+
+ @Test
public void testJavaDocsRecognition() throws Exception {
final List<BlockCommentPositionTestMetadata> metadataList = Arrays.asList(
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnClass.java",
BlockCommentPosition::isOnClass, 3),
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnMethod.java",
- BlockCommentPosition::isOnMethod, 3),
+ BlockCommentPosition::isOnMethod, 4),
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnField.java",
BlockCommentPosition::isOnField, 3),
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnEnum.java",
@@ -53,7 +60,10 @@ public class BlockCommentPositionTest extends AbstractPathTestSupport {
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnAnnotation.java",
BlockCommentPosition::isOnAnnotationDef, 3),
new BlockCommentPositionTestMetadata("InputBlockCommentPositionOnEnumMember.java",
- BlockCommentPosition::isOnEnumConstant, 2)
+ BlockCommentPosition::isOnEnumConstant, 2),
+ new BlockCommentPositionTestMetadata(
+ "InputBlockCommentPositionOnAnnotationField.java",
+ BlockCommentPosition::isOnAnnotationField, 4)
);
for (BlockCommentPositionTestMetadata metadata : metadataList) {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java
index abdde4a4c..59f2fe019 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CheckUtilsTest.java
@@ -186,23 +186,23 @@ public class CheckUtilsTest extends AbstractPathTestSupport {
@Test
public void testGetTypeParameterNames() throws Exception {
- final DetailAST parameterisedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF);
+ final DetailAST parameterizedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF);
final List<String> expected = Arrays.asList("V", "C");
assertEquals("Invalid type parameters",
- expected, CheckUtils.getTypeParameterNames(parameterisedClassNode));
+ expected, CheckUtils.getTypeParameterNames(parameterizedClassNode));
}
@Test
public void testGetTypeParameters() throws Exception {
- final DetailAST parameterisedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF);
+ final DetailAST parameterizedClassNode = getNodeFromFile(TokenTypes.CLASS_DEF);
final DetailAST firstTypeParameter =
- getNode(parameterisedClassNode, TokenTypes.TYPE_PARAMETER);
+ getNode(parameterizedClassNode, TokenTypes.TYPE_PARAMETER);
final List<DetailAST> expected = Arrays.asList(firstTypeParameter,
firstTypeParameter.getNextSibling().getNextSibling());
assertEquals("Invalid type parameters", expected,
- CheckUtils.getTypeParameters(parameterisedClassNode));
+ CheckUtils.getTypeParameters(parameterizedClassNode));
}
@Test
@@ -235,7 +235,7 @@ public class CheckUtilsTest extends AbstractPathTestSupport {
}
@Test
- public void testIsNonViodMethod() throws Exception {
+ public void testIsNonVoidMethod() throws Exception {
final DetailAST nonVoidMethod = getNodeFromFile(TokenTypes.METHOD_DEF);
final DetailAST voidMethod = nonVoidMethod.getNextSibling();
@@ -276,13 +276,13 @@ public class CheckUtilsTest extends AbstractPathTestSupport {
final DetailAST publicVariable = protectedVariable.getNextSibling();
final DetailAST packageVariable = publicVariable.getNextSibling();
- assertEquals("Invalid access modofier", AccessModifier.PRIVATE,
+ assertEquals("Invalid access modifier", AccessModifier.PRIVATE,
CheckUtils.getAccessModifierFromModifiersToken(privateVariable.getFirstChild()));
- assertEquals("Invalid access modofier", AccessModifier.PROTECTED,
+ assertEquals("Invalid access modifier", AccessModifier.PROTECTED,
CheckUtils.getAccessModifierFromModifiersToken(protectedVariable.getFirstChild()));
- assertEquals("Invalid access modofier", AccessModifier.PUBLIC,
+ assertEquals("Invalid access modifier", AccessModifier.PUBLIC,
CheckUtils.getAccessModifierFromModifiersToken(publicVariable.getFirstChild()));
- assertEquals("Invalid access modofier", AccessModifier.PACKAGE,
+ assertEquals("Invalid access modifier", AccessModifier.PACKAGE,
CheckUtils.getAccessModifierFromModifiersToken(packageVariable.getFirstChild()));
}
@@ -310,6 +310,21 @@ public class CheckUtilsTest extends AbstractPathTestSupport {
}
@Test
+ public void testGetFirstNode2() {
+ final DetailAST child = new DetailAST();
+ child.setLineNo(6);
+ child.setColumnNo(5);
+
+ final DetailAST root = new DetailAST();
+ root.setLineNo(5);
+ root.setColumnNo(6);
+
+ root.addChild(child);
+
+ assertEquals("Unexpected node", root, CheckUtils.getFirstNode(root));
+ }
+
+ @Test
public void testIsReceiverParameter() throws Exception {
final DetailAST objBlock = getNodeFromFile(TokenTypes.OBJBLOCK);
final DetailAST methodWithReceiverParameter = objBlock.getLastChild().getPreviousSibling();
@@ -344,11 +359,14 @@ public class CheckUtilsTest extends AbstractPathTestSupport {
@Test
public void testParseClassNames() {
- final String className = "I.am.class.name.with.dot.in.the.end.";
- final Set<String> result = CheckUtils.parseClassNames(className);
+ final Set<String> actual = CheckUtils.parseClassNames(
+ "I.am.class.name.with.dot.in.the.end.", "ClassOnly", "my.Class");
final Set<String> expected = new HashSet<>();
- expected.add(className);
- assertEquals("Result is not expected", expected, result);
+ expected.add("I.am.class.name.with.dot.in.the.end.");
+ expected.add("ClassOnly");
+ expected.add("my.Class");
+ expected.add("Class");
+ assertEquals("Result is not expected", expected, actual);
}
private DetailAST getNodeFromFile(int type) throws Exception {
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java
index 1a7cfae54..52997d5df 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/CommonUtilsTest.java
@@ -92,6 +92,13 @@ public class CommonUtilsTest {
}
@Test
+ public void testCreatePattern() {
+ assertEquals("invalid pattern", "Test", CommonUtils.createPattern("Test").pattern());
+ assertEquals("invalid pattern", ".*Pattern.*", CommonUtils.createPattern(".*Pattern.*")
+ .pattern());
+ }
+
+ @Test
public void testBadRegex() {
try {
CommonUtils.createPattern("[");
@@ -125,14 +132,14 @@ public class CommonUtilsTest {
assertEquals("Invalid line number", 0, testCommentBlock.getLineNo());
final DetailAST contentCommentBlock = testCommentBlock.getFirstChild();
- assertEquals("Invalid tiken type",
+ assertEquals("Invalid token type",
TokenTypes.COMMENT_CONTENT, contentCommentBlock.getType());
assertEquals("Invalid text", "*test_comment", contentCommentBlock.getText());
assertEquals("Invalid line number", 0, contentCommentBlock.getLineNo());
assertEquals("Invalid column number", -1, contentCommentBlock.getColumnNo());
final DetailAST endCommentBlock = contentCommentBlock.getNextSibling();
- assertEquals("Invalid tiken type", TokenTypes.BLOCK_COMMENT_END, endCommentBlock.getType());
+ assertEquals("Invalid token type", TokenTypes.BLOCK_COMMENT_END, endCommentBlock.getType());
assertEquals("Invalid text", "*/", endCommentBlock.getText());
}
@@ -143,6 +150,8 @@ public class CommonUtilsTest {
assertFalse("Invalid file extension",
CommonUtils.matchesFileExtension(pdfFile, fileExtensions));
assertTrue("Invalid file extension",
+ CommonUtils.matchesFileExtension(pdfFile));
+ assertTrue("Invalid file extension",
CommonUtils.matchesFileExtension(pdfFile, (String[]) null));
final File javaFile = new File("file.java");
assertTrue("Invalid file extension",
@@ -150,6 +159,20 @@ public class CommonUtilsTest {
final File emptyExtensionFile = new File("file.");
assertTrue("Invalid file extension",
CommonUtils.matchesFileExtension(emptyExtensionFile, ""));
+ assertFalse("Invalid file extension",
+ CommonUtils.matchesFileExtension(pdfFile, ".noMatch"));
+ assertTrue("Invalid file extension",
+ CommonUtils.matchesFileExtension(pdfFile, ".pdf"));
+ }
+
+ @Test
+ public void testHasWhitespaceBefore() {
+ assertTrue("Invalid result",
+ CommonUtils.hasWhitespaceBefore(0, "a"));
+ assertTrue("Invalid result",
+ CommonUtils.hasWhitespaceBefore(4, " a"));
+ assertFalse("Invalid result",
+ CommonUtils.hasWhitespaceBefore(5, " a"));
}
@Test
@@ -206,7 +229,7 @@ public class CommonUtilsTest {
}
@Test
- public void testGetNonExistingConstructor() {
+ public void testGetNonExistentConstructor() {
try {
CommonUtils.getConstructor(Math.class);
fail("IllegalStateException is expected");
@@ -266,10 +289,36 @@ public class CommonUtilsTest {
}
@Test
- public void testGetFileExtensionForFileNameWithoutExtension() {
- final String fileNameWithoutExtension = "file";
- final String extension = CommonUtils.getFileExtension(fileNameWithoutExtension);
- assertEquals("Invalid extension", "", extension);
+ public void testFillTemplateWithStringsByRegexp() {
+ assertEquals("invalid result", "template", CommonUtils.fillTemplateWithStringsByRegexp(
+ "template", "lineToPlaceInTemplate", Pattern.compile("NO MATCH")));
+ assertEquals(
+ "invalid result",
+ "before word after",
+ CommonUtils.fillTemplateWithStringsByRegexp("before $0 after", "word",
+ Pattern.compile("\\w+")));
+ assertEquals("invalid result", "before word 123 after1 word after2 123 after3",
+ CommonUtils.fillTemplateWithStringsByRegexp("before $0 after1 $1 after2 $2 after3",
+ "word 123", Pattern.compile("(\\w+) (\\d+)")));
+ }
+
+ @Test
+ public void testGetFileNameWithoutExtension() {
+ assertEquals("invalid result", "filename",
+ CommonUtils.getFileNameWithoutExtension("filename"));
+ assertEquals("invalid result", "filename",
+ CommonUtils.getFileNameWithoutExtension("filename.extension"));
+ assertEquals("invalid result", "filename.subext",
+ CommonUtils.getFileNameWithoutExtension("filename.subext.extension"));
+ }
+
+ @Test
+ public void testGetFileExtension() {
+ assertEquals("Invalid extension", "", CommonUtils.getFileExtension("filename"));
+ assertEquals("Invalid extension", "extension",
+ CommonUtils.getFileExtension("filename.extension"));
+ assertEquals("Invalid extension", "extension",
+ CommonUtils.getFileExtension("filename.subext.extension"));
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java
index 4f29b3946..8b5b77365 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/FilterUtilsTest.java
@@ -58,9 +58,9 @@ public class FilterUtilsTest {
}
@Test
- public void testNonExistingFile() {
+ public void testNonExistentFile() {
assertFalse("Suppression file does not exist",
- FilterUtils.isFileExists("non-existing.xml"));
+ FilterUtils.isFileExists("non-existent.xml"));
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java
index e03e7d2a1..4114b14e4 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/JavadocUtilsTest.java
@@ -187,7 +187,7 @@ public class JavadocUtilsTest {
@Test
public void testEmptyJavadocComment() {
final String emptyJavadocComment = "*";
- assertTrue("Should return true when empty jabadoc comment is passed",
+ assertTrue("Should return true when empty javadoc comment is passed",
JavadocUtils.isJavadocComment(emptyJavadocComment));
}
@@ -361,4 +361,11 @@ public class JavadocUtilsTest {
assertEquals("Unexpected token name",
"WBR_TAG", JavadocUtils.getTokenName(10079));
}
+
+ @Test
+ public void testEscapeAllControlChars() {
+ assertEquals("invalid result", "abc", JavadocUtils.escapeAllControlChars("abc"));
+ assertEquals("invalid result", "1\\r2\\n3\\t",
+ JavadocUtils.escapeAllControlChars("1\\r2\\n3\\t"));
+ }
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java
index ed20df745..bfabf9372 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ModuleReflectionUtilsTest.java
@@ -87,9 +87,9 @@ public class ModuleReflectionUtilsTest {
@Test
public void testIsCheckstyleCheck() {
assertTrue("Should return true when valid checkstyle check is passed",
- ModuleReflectionUtils.isCheckstyleCheck(CheckClass.class));
+ ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(CheckClass.class));
assertFalse("Should return false when invalid class is passed",
- ModuleReflectionUtils.isCheckstyleCheck(NotCheckstyleCheck.class));
+ ModuleReflectionUtils.isCheckstyleTreeWalkerCheck(NotCheckstyleCheck.class));
}
@Test
@@ -147,16 +147,23 @@ public class ModuleReflectionUtilsTest {
assertEquals("should use field", 1, test.getField());
}
- /** @noinspection SuperClassHasFrequentlyUsedInheritors */
private static class ValidCheckstyleClass extends AutomaticBean {
// empty, use default constructor
+
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
}
private static class InvalidNonAutomaticBeanClass {
// empty, use default constructor
}
- /** @noinspection AbstractClassNeverImplemented */
+ /**
+ * AbstractInvalidClass.
+ * @noinspection AbstractClassNeverImplemented
+ */
private abstract static class AbstractInvalidClass extends AutomaticBean {
public abstract void method();
}
@@ -187,6 +194,11 @@ public class ModuleReflectionUtilsTest {
private static class FilterClass extends AutomaticBean implements Filter {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
+
+ @Override
public boolean accept(AuditEvent event) {
return false;
}
@@ -195,6 +207,11 @@ public class ModuleReflectionUtilsTest {
private static class FileFilterModuleClass extends AutomaticBean
implements BeforeExecutionFileFilter {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
+
+ @Override
public boolean accept(String uri) {
return false;
}
@@ -202,6 +219,11 @@ public class ModuleReflectionUtilsTest {
private static class RootModuleClass extends AutomaticBean implements RootModule {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
+
+ @Override
public void addListener(AuditListener listener) {
//dummy method
}
@@ -224,6 +246,11 @@ public class ModuleReflectionUtilsTest {
private static class TreeWalkerFilterClass extends AutomaticBean implements TreeWalkerFilter {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
+
+ @Override
public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) {
return false;
}
@@ -232,6 +259,11 @@ public class ModuleReflectionUtilsTest {
private static class AuditListenerClass extends AutomaticBean implements AuditListener {
@Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
+
+ @Override
public void auditStarted(AuditEvent event) {
//dummy method
}
@@ -285,5 +317,10 @@ public class ModuleReflectionUtilsTest {
public int getField() {
return field;
}
+
+ @Override
+ protected void finishLocalSetup() throws CheckstyleException {
+ //dummy method
+ }
}
}
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java
index d18b5884e..e7b46c3b9 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/ScopeUtilsTest.java
@@ -39,51 +39,46 @@ public class ScopeUtilsTest {
}
@Test
- public void testInEnumOnRoot() {
+ public void testInEnumBlock() {
assertFalse("Should return false when passed is not enum",
ScopeUtils.isInEnumBlock(new DetailAST()));
- }
-
- @Test
- public void testInEnumBlockInNew() {
assertFalse("Should return false when passed is not enum",
ScopeUtils.isInEnumBlock(getNode(TokenTypes.LITERAL_NEW,
TokenTypes.MODIFIERS)));
- }
-
- @Test
- public void testInEnumBlockWithEnum() {
assertTrue("Should return true when passed is enum",
ScopeUtils.isInEnumBlock(getNode(TokenTypes.OBJBLOCK, TokenTypes.ENUM_DEF,
TokenTypes.MODIFIERS)));
- }
-
- @Test
- public void testInEnumBlockInInterface() {
assertFalse("Should return false when passed is not enum",
- ScopeUtils.isInEnumBlock(getNode(TokenTypes.INTERFACE_DEF,
+ ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.INTERFACE_DEF,
TokenTypes.MODIFIERS)));
- }
-
- @Test
- public void testInEnumBlockInAnnotation() {
assertFalse("Should return false when passed is not enum",
- ScopeUtils.isInEnumBlock(getNode(TokenTypes.ANNOTATION_DEF,
+ ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.ANNOTATION_DEF,
TokenTypes.MODIFIERS)));
- }
-
- @Test
- public void testInEnumBlockInClass() {
assertFalse("Should return false when passed is not enum",
- ScopeUtils.isInEnumBlock(getNode(TokenTypes.CLASS_DEF,
+ ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.CLASS_DEF,
TokenTypes.MODIFIERS)));
+ assertFalse("Should return false when passed is not enum",
+ ScopeUtils.isInEnumBlock(getNode(TokenTypes.ENUM_DEF, TokenTypes.LITERAL_NEW,
+ TokenTypes.IDENT)));
+ assertFalse("Should return false when passed is not expected",
+ ScopeUtils.isInEnumBlock(getNode(TokenTypes.PACKAGE_DEF, TokenTypes.DOT)));
}
@Test
- public void testInEnumBlockInLiteralNew() {
- assertFalse("Should return false when passed is not enum",
- ScopeUtils.isInEnumBlock(getNode(TokenTypes.LITERAL_NEW,
- TokenTypes.IDENT)));
+ public void testIsInCodeBlock() {
+ assertFalse("invalid result", ScopeUtils.isInCodeBlock(getNode(TokenTypes.CLASS_DEF)));
+ assertFalse("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.ASSIGN, TokenTypes.VARIABLE_DEF)));
+ assertTrue("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.METHOD_DEF, TokenTypes.OBJBLOCK)));
+ assertTrue("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.CTOR_DEF, TokenTypes.OBJBLOCK)));
+ assertTrue("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.INSTANCE_INIT, TokenTypes.OBJBLOCK)));
+ assertTrue("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.STATIC_INIT, TokenTypes.OBJBLOCK)));
+ assertTrue("invalid result",
+ ScopeUtils.isInCodeBlock(getNode(TokenTypes.LAMBDA, TokenTypes.ASSIGN)));
}
@Test
@@ -113,6 +108,12 @@ public class ScopeUtilsTest {
}
@Test
+ public void testIsOuterMostTypePackageDef() {
+ assertTrue("Should return false when passed is not outer most type",
+ ScopeUtils.isOuterMostType(getNode(TokenTypes.PACKAGE_DEF, TokenTypes.DOT)));
+ }
+
+ @Test
public void testIsLocalVariableDefCatch() {
assertTrue("Should return true when passed is variable def",
ScopeUtils.isLocalVariableDef(getNode(TokenTypes.LITERAL_CATCH,
@@ -123,6 +124,26 @@ public class ScopeUtilsTest {
public void testIsLocalVariableDefUnexpected() {
assertFalse("Should return false when passed is not variable def",
ScopeUtils.isLocalVariableDef(getNode(TokenTypes.LITERAL_CATCH)));
+ assertFalse("Should return false when passed is not variable def",
+ ScopeUtils.isLocalVariableDef(getNode(TokenTypes.COMMA, TokenTypes.PARAMETER_DEF)));
+ }
+
+ @Test
+ public void testIsLocalVariableDefResource() {
+ assertTrue("invalid result",
+ ScopeUtils.isLocalVariableDef(getNode(TokenTypes.RESOURCE)));
+ }
+
+ @Test
+ public void testIsLocalVariableDefVariable() {
+ assertTrue("invalid result",
+ ScopeUtils.isLocalVariableDef(getNode(TokenTypes.SLIST, TokenTypes.VARIABLE_DEF)));
+ assertTrue("invalid result", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.FOR_INIT,
+ TokenTypes.VARIABLE_DEF)));
+ assertTrue("invalid result", ScopeUtils.isLocalVariableDef(getNode(
+ TokenTypes.FOR_EACH_CLAUSE, TokenTypes.VARIABLE_DEF)));
+ assertFalse("invalid result", ScopeUtils.isLocalVariableDef(getNode(TokenTypes.CLASS_DEF,
+ TokenTypes.VARIABLE_DEF)));
}
@Test
@@ -130,6 +151,11 @@ public class ScopeUtilsTest {
assertTrue("Should return true when passed is class field def",
ScopeUtils.isClassFieldDef(getNode(TokenTypes.CLASS_DEF,
TokenTypes.OBJBLOCK, TokenTypes.VARIABLE_DEF)));
+ assertFalse("Should return false when passed is unexpected",
+ ScopeUtils.isClassFieldDef(getNode(TokenTypes.CLASS_DEF)));
+ assertFalse("Should return false when passed is method variable def",
+ ScopeUtils.isClassFieldDef(getNode(TokenTypes.METHOD_DEF,
+ TokenTypes.SLIST, TokenTypes.VARIABLE_DEF)));
}
@Test
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java
index c1a0d97c8..474479f87 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/utils/TokenUtilsTest.java
@@ -145,7 +145,7 @@ public class TokenUtilsTest {
@Test
public void testTokenIdIncorrect() {
- final String id = "NON_EXISTING_VALUE";
+ final String id = "NON_EXISTENT_VALUE";
try {
TokenUtils.getTokenId(id);
fail("IllegalArgumentException is expected");
@@ -158,7 +158,7 @@ public class TokenUtilsTest {
@Test
public void testShortDescriptionIncorrect() {
- final String id = "NON_EXISTING_VALUE";
+ final String id = "NON_EXISTENT_VALUE";
try {
TokenUtils.getShortDescription(id);
fail("IllegalArgumentException is expected");
@@ -184,7 +184,7 @@ public class TokenUtilsTest {
}
@Test
- public void tetsGetTokenTypesTotalNumber() {
+ public void testGetTokenTypesTotalNumber() {
final int tokenTypesTotalNumber = TokenUtils.getTokenTypesTotalNumber();
assertEquals("Invalid token total number", 169, tokenTypesTotalNumber);
diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java
index 2cc154b74..4a3abf01e 100644
--- a/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java
+++ b/src/test/java/com/puppycrawl/tools/checkstyle/xpath/XpathMapperTest.java
@@ -111,7 +111,7 @@ public class XpathMapperTest extends AbstractPathTestSupport {
@Test
public void testAttributeOr() throws Exception {
- final String xpath = "//METHOD_DEF[@text='getSomeMethod' or @text='nonExistingMethod']";
+ final String xpath = "//METHOD_DEF[@text='getSomeMethod' or @text='nonExistentMethod']";
final RootNode rootNode = getRootNode("InputXpathMapperAst.java");
final DetailAST[] actual = convertToArray(getXpathItems(xpath, rootNode));
final DetailAST expectedClassDefNode = getSiblingByType(rootNode.getUnderlyingNode(),
@@ -413,7 +413,7 @@ public class XpathMapperTest extends AbstractPathTestSupport {
}
@Test
- public void testQueryNonExistingAttribute() throws Exception {
+ public void testQueryNonExistentAttribute() throws Exception {
final String xpath = "/CLASS_DEF[@text='InputXpathMapperAst']";
final RootNode rootNode = getRootNode("InputXpathMapperAst.java");
final List<Item> nodes = getXpathItems(xpath, rootNode);
@@ -450,7 +450,7 @@ public class XpathMapperTest extends AbstractPathTestSupport {
}
@Test
- public void testQueryNonExistingAnnotation() throws Exception {
+ public void testQueryNonExistentAnnotation() throws Exception {
final String xpath = "//ANNOTATION[@text='SpringBootApplication']";
final RootNode rootNode = getRootNode("InputXpathMapperAnnotation.java");
final List<Item> nodes = getXpathItems(xpath, rootNode);
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/fallthrough/InputFallThrough.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/fallthrough/InputFallThrough.java
index a3c745e55..384499fb3 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/fallthrough/InputFallThrough.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/fallthrough/InputFallThrough.java
@@ -547,4 +547,17 @@ public class InputFallThrough
break;
}
}
+
+ void multipleCasesOnOneLine() {
+ int i = 0;
+ switch (i) {
+ case 0: case 1: i *= i; // fall through
+ case 2: case 3: i *= i; // fall through
+ case 4: case 5: i *= i; // fall through
+ case 6: case 7: i *= i;
+ break;
+ default:
+ throw new RuntimeException();
+ }
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalType.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalType.java
index dfce5fddc..2efc892ca 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalType.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/illegaltype/InputIllegalType.java
@@ -21,4 +21,6 @@ public class InputIllegalType {
InputIllegalType(Integer i) {}
private void table2(Integer i) {}
+
+ private void getInitialContext(java.util.TreeSet v) {} // ignore method by default
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/modifiedcontrolvariable/InputModifiedControlVariableBothForLoops.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/modifiedcontrolvariable/InputModifiedControlVariableBothForLoops.java
index d3f57c7be..01c24149c 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/modifiedcontrolvariable/InputModifiedControlVariableBothForLoops.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/modifiedcontrolvariable/InputModifiedControlVariableBothForLoops.java
@@ -70,6 +70,13 @@ class InputModifiedControlVariableBothForLoops
for (int i = 0,j = 0 ; i <10; i++) {
j++;
}
+
+ for (String v : sa) {
+ new NestedClass() {
+ public void method() {}
+ };
+ v = "bad";
+ }
}
private int i;
}
@@ -83,3 +90,6 @@ class VariableDeclaredBeforeTheFirstBlockBegins {
}
}
}
+abstract class NestedClass {
+ public abstract void method();
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/multiplevariabledeclarations/InputMultipleVariableDeclarations.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/multiplevariabledeclarations/InputMultipleVariableDeclarations.java
index 16487fb9c..d178fbfa0 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/multiplevariabledeclarations/InputMultipleVariableDeclarations.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/multiplevariabledeclarations/InputMultipleVariableDeclarations.java
@@ -30,4 +30,8 @@ public class InputMultipleVariableDeclarations
int k = 7;
}
}
+
+ void method3() {
+ java.lang.Object obj; Object obj1; Object obj2; Object obj3;
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/nestedfordepth/InputNestedForDepth.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/nestedfordepth/InputNestedForDepth.java
index dfa0eb6c2..cfa8356e7 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/nestedfordepth/InputNestedForDepth.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/nestedfordepth/InputNestedForDepth.java
@@ -44,6 +44,9 @@ public class InputNestedForDepth {
for (i5 = 0; i5 < 10; i5++) {
i += 1;
}
+ for (int i5a = 0; i5a < 10; i5a++) {
+ i += 1;
+ }
}
}
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineSingleLine.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineSingleLine.java
index 185b7b74f..4a20cb731 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineSingleLine.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineSingleLine.java
@@ -238,4 +238,11 @@ public class InputOneStatementPerLineSingleLine {
*/
for (;;) { one = 5; }
}
+
+ public void foo6() {
+ bar(() -> {
+ return;}, () -> {return;});
+ }
+
+ void bar(Runnable r1, Runnable r2) { }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/parameterassignment/InputParameterAssignmentWithUnchecked.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/parameterassignment/InputParameterAssignmentWithUnchecked.java
index 60f8eed0b..fbfc6e786 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/parameterassignment/InputParameterAssignmentWithUnchecked.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/parameterassignment/InputParameterAssignmentWithUnchecked.java
@@ -19,4 +19,17 @@ public class InputParameterAssignmentWithUnchecked {
void foo3(String field, int field1) {
this.field = (field1 += field.length());
}
+
+ void foo4() {
+ String hidden = "";
+ new NestedClass() {
+ public void test(String hidden) {
+ }
+ };
+ hidden += "test";
+ }
+
+ public static abstract class NestedClass {
+ public abstract void test(String hidden);
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisAnnotationInterface.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisAnnotationInterface.java
new file mode 100644
index 000000000..b7b35495c
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisAnnotationInterface.java
@@ -0,0 +1,9 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.requirethis;
+
+public @interface InputRequireThisAnnotationInterface {
+ String DEFAULT_VALUE = "DEFAULT_VALUE";
+
+ String value() default DEFAULT_VALUE;
+
+ String[] results() default {};
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisCatchVariables.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisCatchVariables.java
new file mode 100644
index 000000000..920dd6369
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisCatchVariables.java
@@ -0,0 +1,40 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.requirethis;
+
+public class InputRequireThisCatchVariables extends Thread {
+ private Throwable ex;
+
+ public InputRequireThisCatchVariables(Throwable ex) {
+ this.ex = ex;
+ }
+
+ @Override
+ public void run() {
+ if (this.ex != null) {
+ try {
+ exceptional(this.ex);
+ }
+ catch (RuntimeException ex) {
+ if (ex == this.ex) {
+ debug("Expected exception thrown", ex);
+ }
+ else {
+ ex.printStackTrace();
+ }
+ }
+ catch (Error err) {
+ if (err == this.ex) {
+ debug("Expected exception thrown", err);
+ }
+ else {
+ ex.printStackTrace();
+ }
+ }
+ catch (Throwable ex) {
+ ex.printStackTrace();
+ }
+ }
+ }
+
+ private static void exceptional(Throwable ex) {}
+ private static void debug(String message, Throwable err) {}
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumConstant.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumConstant.java
new file mode 100644
index 000000000..4cfc3b3de
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumConstant.java
@@ -0,0 +1,13 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.requirethis;
+
+public class InputRequireThisEnumConstant {
+ private final String TEST = "";
+
+ public enum TestEnum {
+ TEST;
+
+ public TestEnum method() {
+ return TEST;
+ }
+ }
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumInnerClassesAndBugs.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumInnerClassesAndBugs.java
index a0bd74681..77beca3a7 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumInnerClassesAndBugs.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisEnumInnerClassesAndBugs.java
@@ -134,3 +134,43 @@ class Issue2539{
foo();
}
}
+class NestedRechange {
+ final String s = "";
+
+ NestedRechange() {
+ String s = "t";
+ s = s.substring(0);
+ }
+
+ private static class NestedStatic {
+ static final String s = "";
+
+ public void method() {
+ s.substring(0);
+ }
+ }
+}
+class NestedFrames {
+ int a = 0;
+ int b = 0;
+
+ public int oneReturnInMethod2() {
+ for (int i = 0; i < 10; i++) {
+ int a = 1;
+ if (a != 2 && true) {
+ if (true | false) {
+ if (a - a != 0) {
+ a += 1;
+ }
+ }
+ }
+ }
+ return a + a * a;
+ }
+
+ public int oneReturnInMethod3() {
+ for (int b = 0; b < 10; b++) {
+ }
+ return b + b * b;
+ }
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisFor.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisFor.java
new file mode 100644
index 000000000..9ad0e9f5c
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisFor.java
@@ -0,0 +1,23 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.requirethis;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+public class InputRequireThisFor {
+ private String name;
+ int bottom;
+
+ public void method1() {
+ for (int i = 0; i < 10; i++) {
+ int bottom = i - 4;
+ bottom = bottom > 0 ? bottom - 1 : bottom;
+ }
+ }
+
+ public void method2() {
+ for (String name : new String[]{}) {
+ }
+
+ Path jarfile = Paths.get(name + ".jar");
+ }
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMetodReferences.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMethodReferences.java
index 516b85aed..b0b528e81 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMetodReferences.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/requirethis/InputRequireThisMethodReferences.java
@@ -6,16 +6,16 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
-public class InputRequireThisMetodReferences {
+public class InputRequireThisMethodReferences {
private Set<String> tags = Collections.unmodifiableSortedSet(
Arrays.stream(new String[] {"br", "li", "dt", "dd", "hr", "img", "p", "td", "tr", "th",})
.collect(Collectors.toCollection(TreeSet::new)));
- public InputRequireThisMetodReferences(Set<String> tags) {
+ public InputRequireThisMethodReferences(Set<String> tags) {
tags = tags; // violation
}
- public InputRequireThisMetodReferences() {
+ public InputRequireThisMethodReferences() {
this.tags = Arrays.stream(
new String[] {"br", "li", "dt", "dd", "hr", "img", "p", "td", "tr", "th",})
.collect(Collectors.toCollection(TreeSet::new));
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/returncount/InputReturnCountVoid.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/returncount/InputReturnCountVoid.java
index 9a2d48faa..a1beceeae 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/returncount/InputReturnCountVoid.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/returncount/InputReturnCountVoid.java
@@ -37,4 +37,12 @@ class InputReturnCountVoid {
return 0;
}
+
+ void method5() {
+ if (true) {
+ return;
+ }
+
+ return;
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/unnecessaryparentheses/InputUnnecessaryParenthesesOperatorsAndCasts.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/unnecessaryparentheses/InputUnnecessaryParenthesesOperatorsAndCasts.java
index 777f4b15e..33246c199 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/unnecessaryparentheses/InputUnnecessaryParenthesesOperatorsAndCasts.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/unnecessaryparentheses/InputUnnecessaryParenthesesOperatorsAndCasts.java
@@ -87,6 +87,14 @@ public class InputUnnecessaryParenthesesOperatorsAndCasts {
System.identityHashCode("arg = " + arg);
}
+ private int f7() {
+ String f;
+
+ f = ("12345678901234567890123");
+
+ return 0;
+ }
+
static class TypeParameterized<T> {}
static class TypeA extends TypeParameterized<String> {}
static class TypeB extends TypeA {}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistance.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistance.java
index 57ca5e725..330abb819 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistance.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistance.java
@@ -973,5 +973,16 @@ class New {
}
catch(Exception e){}
}
+
+ void m() {
+ final int a = 1;
+ int b = 0;
+
+ if (b == 1) {
+ System.lineSeparator();
+ }
+
+ final int c = a + 1;
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceAnonymous.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceAnonymous.java
new file mode 100644
index 000000000..969aa801f
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceAnonymous.java
@@ -0,0 +1,22 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.variabledeclarationusagedistance;
+
+import java.awt.event.ActionListener;
+import java.awt.event.ActionEvent;
+import javax.swing.JMenuItem;
+
+public class InputVariableDeclarationUsageDistanceAnonymous {
+ public void method() {
+ JMenuItem prefs = new JMenuItem("Preferences...");
+
+ nothing();
+ nothing();
+ nothing();
+ prefs.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ }
+ });
+ }
+
+ public void nothing() {
+ }
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceLabels.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceLabels.java
new file mode 100644
index 000000000..e9e0e3ff4
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/variabledeclarationusagedistance/InputVariableDeclarationUsageDistanceLabels.java
@@ -0,0 +1,22 @@
+package com.puppycrawl.tools.checkstyle.checks.coding.variabledeclarationusagedistance;
+
+public class InputVariableDeclarationUsageDistanceLabels {
+ public void method() {
+ boolean eol = false;
+
+ nothing();
+ nothing();
+ nothing();
+ nothing();
+ myLoop:
+ for (int i = 0; i < 5; i++) {
+ if (i == 5) {
+ eol = true;
+ break myLoop;
+ }
+ }
+ }
+
+ public void nothing() {
+ }
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMwthodWithAnnotation.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMethodWithAnnotation.java
index 879343553..20a61431f 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMwthodWithAnnotation.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/throwscount/InputThrowsCountMethodWithAnnotation.java
@@ -6,7 +6,7 @@ import java.io.FileNotFoundException;
import java.nio.file.FileAlreadyExistsException;
import java.sql.SQLException;
-public class InputThrowsCountMwthodWithAnnotation extends ParentClass {
+public class InputThrowsCountMethodWithAnnotation extends ParentClass {
@Override
public void method() throws AWTException, SQLException, FileNotFoundException,
EOFException, FileAlreadyExistsException {
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderCompareImports.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderCompareImports.java
new file mode 100644
index 000000000..a32b01951
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderCompareImports.java
@@ -0,0 +1,10 @@
+package com.puppycrawl.tools.checkstyle.checks.imports.customimportorder;
+
+import java.util.Map.Entry;
+import java.util.Map;
+
+import com.google.common.*;
+import com.google.common.annotations.*;
+
+public class InputCustomImportOrderCompareImports {
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderFindBetterPatternMatch.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderFindBetterPatternMatch.java
new file mode 100644
index 000000000..0e316b9bc
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/customimportorder/InputCustomImportOrderFindBetterPatternMatch.java
@@ -0,0 +1,13 @@
+package com.puppycrawl.tools.checkstyle.checks.imports.customimportorder;
+
+import javax.lang.model.element.AnnotationValue;
+import java.awt.event.ActionEvent;
+import java.lang.*;
+import java.awt.color.ColorSpace;
+
+import com.google.common.annotations.Beta;
+
+import com.google.common.collect.HashMultimap;
+
+public class InputCustomImportOrderFindBetterPatternMatch {
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetiton.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetition.java
index 78456928e..9597953b2 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetiton.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderRepetition.java
@@ -8,5 +8,5 @@ import java.awt.event.ActionEvent; //Repetitive import
import javax.swing.JComponent;
import javax.swing.JTable;
-public class InputImportOrderRepetiton {
+public class InputImportOrderRepetition {
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative.java
new file mode 100644
index 000000000..e093b04da
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative.java
@@ -0,0 +1,13 @@
+package com.puppycrawl.tools.checkstyle.checks.imports.importorder;
+
+import org.*;
+
+import static java.lang.Math.PI;
+import static org.antlr.v4.runtime.Recognizer.EOF;
+
+import java.util.Set;
+
+public class InputImportOrderStaticGroupOrderBottom_Negative
+{
+
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative2.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative2.java
new file mode 100644
index 000000000..61277ad75
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupOrderBottom_Negative2.java
@@ -0,0 +1,15 @@
+package com.puppycrawl.tools.checkstyle.checks.imports.importorder;
+
+import org.*;
+
+import static java.lang.Math.PI;
+import static org.antlr.v4.runtime.Recognizer.EOF;
+
+import java.util.Set;
+
+import static java.util.Set.*;
+
+public class InputImportOrderStaticGroupOrderBottom_Negative2
+{
+
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeperated.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeparated.java
index dd06f8df5..2528dc279 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeperated.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/imports/importorder/InputImportOrderStaticGroupSeparated.java
@@ -7,7 +7,7 @@ import static java.lang.Math.cos;;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
-public class InputImportOrderStaticGroupSeperated {
+public class InputImportOrderStaticGroupSeparated {
void method() {
}
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationAnnotationIncorrect.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationAnnotationIncorrect.java
new file mode 100644
index 000000000..20d878423
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationAnnotationIncorrect.java
@@ -0,0 +1,24 @@
+package com.puppycrawl.tools.checkstyle.checks.indentation.indentation; //indent:0 exp:0
+
+class InpuIndentationAnnotationIncorrect { //indent:0 exp:0
+
+ public @interface MyAnnotation1 { //indent:4 exp:4
+ String value(); //indent:8 exp:8
+ } //indent:4 exp:4
+
+ @MyAnnotation2 //indent:4 exp:4
+ @MyAnnotation1 //indent:4 exp:4
+ (value = "") //indent:4 exp:8
+ class innerClass { //indent:4 exp:4
+ @MyAnnotation2 @MyAnnotation1 //indent:8 exp:8
+ (value = "") //indent:8 exp:12
+ public int a; //indent:8 exp:8
+ } //indent:4 exp:4
+
+ @MyAnnotation2 @MyAnnotation1 //indent:4 exp:4
+ (value = "") //indent:4 exp:8
+ class InputIndentationAnnotationInnerClass { //indent:4 exp:4
+
+ } //indent:4 exp:4
+} //indent:0 exp:0
+
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java
new file mode 100644
index 000000000..b0ea5d2de
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/indentation/indentation/InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine.java
@@ -0,0 +1,20 @@
+package com.puppycrawl.tools.checkstyle.checks.indentation.indentation; //indent:0 exp:0
+
+public class InputIndentationMethodPrecededByAnnotationWithParameterOnSeparateLine { //indent:0 exp:0
+
+ @interface Annotation1 { //indent:2 exp:2
+ String field1(); //indent:4 exp:4
+ String field2(); //indent:4 exp:4
+ } //indent:2 exp:2
+
+ @interface Annotation2 {}; //indent:2 exp:2
+
+ @Annotation1(field1 = "foo", field2 = "bar") //indent:2 exp:2
+ public @Annotation2 String method( //indent:2 exp:2
+ String param //indent:6 exp:6
+ ) { //indent:2 exp:2
+ return null; //indent:4 exp:4
+ } //indent:2 exp:2
+
+} //indent:0 exp:0
+
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPosition.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPosition.java
index c83a6078e..258c51185 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPosition.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPosition.java
@@ -95,6 +95,11 @@ class GGG {
void/**nope*/ a/**nope*/(@Component/**nope*/int/**nope*/ a/**nope*/)/**nope*/{/**nope*/}/**nope*/
}
+class HHH {
+ /**Javadoc*/
+ java.lang.String/**nope*/ a/**nope*/()/**nope*/{/**nope*/return null;/**nope*/}/**nope*/
+}
+
////////////////
// INTERFACES //
////////////////
@@ -229,7 +234,14 @@ enum CCCCCCC {
}
/**Javadoc*/
-@interface/**nope*/ MyAnnotation/**nope*/ {/**nope*/
+@interface/**nope*/ MyAnnotation/**nope*/ {
+ /**Javadoc*/
+ @Component/**nope*/abstract/**nope*/String/**nope*/val1()/**nope*/default/**nope*/"";
+ /**Javadoc*/
+ abstract/**nope*/String/**nope*/val2()/**nope*/;
+ /**Javadoc*/
+ java.lang.String/**nope*/val3()/**nope*/;
+ /**nope*/
}
class MyTemp1 {
@@ -239,3 +251,28 @@ class MyTemp1 {
}
/**nope*/
+/*noise*/
+/**nope*/
+/**Javadoc*/
+//noise
+@Component
+/*noise*/
+interface MultipleJavadoc {
+ /**nope*/
+ /*noise*/
+ /**nope*/
+ /**Javadoc*/
+ /* noise */
+ public /**nope*/ int method();
+ /**nope*/
+ /*noise*/
+ /**nope*/
+ /**Javadoc*/
+ // noise
+ @Deprecated
+ // noise
+ /**nope*/
+ public /**nope*/ void method2();
+}
+
+/**nope*/
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPositionWithSinglelineComments.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPositionWithSinglelineComments.java
index c95e4708b..3f320c17e 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPositionWithSinglelineComments.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/abstractjavadoc/InputAbstractJavadocPositionWithSinglelineComments.java
@@ -95,6 +95,11 @@ class LKJ {
void/**nope*/ a/**nope*/(@Component2/**nope*/int/**nope*/ a/**nope*/)/**nope*/{/**nope*/}/**nope*/
}
+class LKM {
+ /**Javadoc*/ //noise
+ java.lang.String/**nope*/ a/**nope*/(/**nope*/)/**nope*/{/**nope*/return null;/**nope*/}/**nope*/
+}
+
////////////////
// INTERFACES //
////////////////
@@ -230,7 +235,14 @@ enum XXXXXXX {
}
/**Javadoc*/ //noise
-@interface/**nope*/ MyAnnotation2/**nope*/ {/**nope*/
+@interface/**nope*/ MyAnnotation2/**nope*/ {
+ /**Javadoc*/ //noise
+ @Component2/**nope*/abstract/**nope*/String/**nope*/val1()/**nope*/default/**nope*/"";
+ /**Javadoc*/ //noise
+ abstract/**nope*/String/**nope*/val2()/**nope*/;
+ /**Javadoc*/ //noise
+ java.lang.String/**nope*/val3()/**nope*/;
+ /**nope*/
}
class MyTemp2 {
@@ -239,4 +251,16 @@ class MyTemp2 {
}
}
+/**nope*/ /*noise*/ /**nope*/ /**Javadoc*/ //noise
+interface MultipleJavadocs2 {
+ /**nope*/ /*noise*/ /**nope*/ /**Javadoc*/ //noise
+ int method();
+ /**nope*/ /*noise*/ /**nope*/ /**Javadoc*/ //noise
+ @Deprecated
+ /**nope*/ /*noise*/ /**nope*/ //noise
+ public
+ /**nope*/ /*noise*/ /**nope*/ //noise
+ void method2();
+}
+
/**nope*/
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodTags.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodTags.java
index 1926f2de4..0766afea3 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodTags.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/javadocmethod/InputJavadocMethodTags.java
@@ -297,6 +297,14 @@ class InputJavadocMethodTags1
return 1;
}
+
+ /**
+ * misplaced @param aParam
+ * misplaced @return something very important.
+ */
+ int method29(int aParam)
+ { return 0;
+ }
}
enum InputJavadocMethodTagsEnum
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/nonemptyatclausedescription/InputNonEmptyAtclauseDescription.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/nonemptyatclausedescription/InputNonEmptyAtclauseDescription.java
index bf3346d00..1251e9955 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/nonemptyatclausedescription/InputNonEmptyAtclauseDescription.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/nonemptyatclausedescription/InputNonEmptyAtclauseDescription.java
@@ -96,4 +96,31 @@ class InputNonEmptyAtclauseDescription
{
return 1;
}
+
+ /**
+ * Some javadoc
+ * @param a Some javadoc
+ * @param b Some javadoc
+ * @param c Some javadoc
+ * @return Some javadoc
+ * @exception Exception Some javadoc
+ * @deprecated Some javadoc
+ */
+ public int foo5(String a, int b, double c) throws Exception
+ {
+ return 1;
+ }
+
+ /**
+ *
+ * @param a Some javadoc
+ * @param b Some javadoc
+ * @param c Some javadoc
+ * @return Some javadoc
+ * @exception Exception
+ */
+ public int foo6(String a, int b, double c) throws Exception
+ {
+ return 1;
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/booleanexpressioncomplexity/InputBooleanExpressionComplexity.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/booleanexpressioncomplexity/InputBooleanExpressionComplexity.java
index 8d5bd7a13..1c8b48131 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/booleanexpressioncomplexity/InputBooleanExpressionComplexity.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/booleanexpressioncomplexity/InputBooleanExpressionComplexity.java
@@ -24,6 +24,13 @@ public class InputBooleanExpressionComplexity {
}
public boolean equals(Object object) {
+ new NestedClass() {
+ public void method() {
+ new Settings(Settings.FALSE || Settings.FALSE || Settings.FALSE || Settings.FALSE || Settings.FALSE);
+ }
+ public void method2() {
+ }
+ };
return (((_a && (_b & _c)) || (_c ^ _d) || (_a && _d)));
}
@@ -68,4 +75,9 @@ public class InputBooleanExpressionComplexity {
{
}
}
+
+ abstract class NestedClass {
+ public abstract void method();
+ public abstract void method2();
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityPackageName.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityPackageName.java
new file mode 100644
index 000000000..c0386f196
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityPackageName.java
@@ -0,0 +1,7 @@
+package com.puppycrawl.tools.checkstyle.checks.metrics.classfanoutcomplexity;
+
+public interface InputClassFanOutComplexityPackageName {
+ public com.puppycrawl.tools.checkstyle.checks.metrics.classfanoutcomplexity.InputClassFanOutComplexityPackageName method1();
+
+ public com.puppycrawl.tools.checkstyle.checks.metrics.classfanoutcomplexity.InputClassFanOutComplexityPackageName method2();
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/npathcomplexity/InputNPathComplexityDefault.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/npathcomplexity/InputNPathComplexityDefault.java
index 390d4dd44..fe4a52a08 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/npathcomplexity/InputNPathComplexityDefault.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/npathcomplexity/InputNPathComplexityDefault.java
@@ -109,4 +109,17 @@ public class InputNPathComplexityDefault {
};
new Thread(runnable).start();
}
+
+ public void InputNestedTernaryCheck() {
+ double x = (getSmth() || Math.random() == 5) ? null : (int) Math
+ .cos(400 * (10 + 40)); // good
+ double y = (0.2 == Math.random()) ? (0.3 == Math.random()) ? null : (int) Math
+ .cos(400 * (10 + 40)) : 6; // bad (nested in first position)
+ double z = (Integer) ((0.2 == Math.random()) ? (Integer) null + apply(null)
+ : (0.3 == Math.random()) ? (Integer) null : (int) Math
+ .sin(300 * (12 + 30))); // bad (nested in second
+ // position)
+ }
+ public boolean getSmth() { return true; };
+ public int apply(Object o) { return 0; }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierFinalInEnumStaticMethods.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierFinalInEnumStaticMethods.java
new file mode 100644
index 000000000..0668729c0
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierFinalInEnumStaticMethods.java
@@ -0,0 +1,16 @@
+package com.puppycrawl.tools.checkstyle.checks.modifier.redundantmodifier;
+
+public class InputRedundantModifierFinalInEnumStaticMethods {
+ public enum TestEnum {
+ VALUE {
+ @Override public void someMethodToOverride() {
+ // do it differently
+ }
+ };
+
+ public void someMethodToOverride() { }
+ public static final void someStaticMethod() { } //violation
+ public static void someMethod() { }
+ }
+}
+
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameEqualClassName.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameEqualClassName.java
index 277ab486f..5a9ed016e 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameEqualClassName.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameEqualClassName.java
@@ -47,10 +47,10 @@ interface SweetInterface {
int SweetInterface();
}
-class Outter {
+class Outer {
//illegal name
- public void Outter() {
+ public void Outer() {
}
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverridenMethods.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverriddenMethods.java
index c253ffaf9..102be8bbe 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverridenMethods.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNameOverriddenMethods.java
@@ -1,6 +1,6 @@
package com.puppycrawl.tools.checkstyle.checks.naming.methodname;
-public class InputMethodNameOverridenMethods extends SomeClass
+public class InputMethodNameOverriddenMethods extends SomeClass
{
@Override
public void PUBLICfoo() { //Ignored due to impossibility of change by developer
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/ExpectedTranslationLog.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/ExpectedTranslationLog.xml
new file mode 100644
index 000000000..7f7a77215
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/ExpectedTranslationLog.xml
@@ -0,0 +1,15 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="8.3-SNAPSHOT">
+<file name="InputTranslationCheckFireErrors.properties">
+</file>
+<file name="InputTranslationCheckFireErrors_de.properties">
+</file>
+<file name="">
+<error line="0" severity="error" message="$0" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
+</file>
+<file name="InputTranslationCheckFireErrors.properties">
+</file>
+<file name="InputTranslationCheckFireErrors_de.properties">
+<error line="0" severity="error" message="$1" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckLinux.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckLinux.xml
deleted file mode 100644
index 34a16cbbe..000000000
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckLinux.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<checkstyle version="8.3-SNAPSHOT">
-<file name="path_to_file/InputTranslationCheckFireErrors.properties">
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors_de.properties">
-</file>
-<file name="path_to_file">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors.properties">
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors_de.properties">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckMacOS.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckMacOS.xml
deleted file mode 100644
index 865791fde..000000000
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckMacOS.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<checkstyle version="8.3-SNAPSHOT">
-<file name="path_to_file/InputTranslationCheckFireErrors.properties">
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors_de.properties">
-</file>
-<file name="path_to_file">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors_de.properties">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-<file name="path_to_file/InputTranslationCheckFireErrors.properties">
-</file>
-</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckWindows.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckWindows.xml
deleted file mode 100644
index 443bba39b..000000000
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/translation/OutputTranslationCheckWindows.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<checkstyle version="8.3-SNAPSHOT">
-<file name="path_to_file\InputTranslationCheckFireErrors.properties">
-</file>
-<file name="path_to_file\InputTranslationCheckFireErrors_de.properties">
-</file>
-<file name="path_to_file">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-<file name="path_to_file\InputTranslationCheckFireErrors.properties">
-</file>
-<file name="path_to_file\InputTranslationCheckFireErrors_de.properties">
-<error line="0" severity="error" message="%s" source="com.puppycrawl.tools.checkstyle.checks.TranslationCheck"/>
-</file>
-</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfter.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfter.java
index 4cdd50621..34f62a329 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfter.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfter.java
@@ -291,4 +291,8 @@ class SpecialCasesInForLoop
@
interface BAD3{}
@interface Ok{}
+
+ static {
+ int[]err = new int [50];
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations.java
index 9ba53befb..001bd78e3 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations.java
@@ -37,10 +37,10 @@ public class InputNoWhitespaceAfterArrayDeclarations
};
}
int ar [] = new int [] {1, 2}; //Incorrect (2 warnings)
- private int [][][] getMultArray() { //Incorrect
+ private int [][][] getMultiArray() { //Incorrect
return null;
}
- private long getLongMultArray(int someParam, String value) [][][] { //Incorrect
+ private long getLongMultiArray(int someParam, String value) [][][] { //Incorrect
return null;
}
int aa = new int[]{1}[0];//Correct
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations2.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations2.java
index f632316f8..7a33245b2 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations2.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/nowhitespaceafter/InputNoWhitespaceAfterArrayDeclarations2.java
@@ -103,6 +103,14 @@ public class InputNoWhitespaceAfterArrayDeclarations2
if(someStuff15 instanceof Object[][]) {
}
+ Object[] a = null;
+
+ if(a instanceof Object []) {//incorrect
+
+ }
+ if(a instanceof Object[][]) {
+
+ }
}
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistingProperty.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistentProperty.xml
index 95bb8a3f1..58441ac91 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistingProperty.xml
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/configurationloader/InputConfigurationLoaderNonexistentProperty.xml
@@ -5,5 +5,5 @@
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<module name="Checker">
- <property name="tabWidth" value="${nonexisting}" />
+ <property name="tabWidth" value="${nonexistent}" />
</module>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderMultiple.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderMultiple.xml
index 283d5505a..3754f2d27 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderMultiple.xml
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderMultiple.xml
@@ -1,10 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC
- "-//Puppy Crawl//DTD Suppressions 1.0//EN"
- "http://checkstyle.sourceforge.net/dtds/suppressions_1_0.dtd">
+ "-//Puppy Crawl//DTD Suppressions 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2.dtd">
<suppressions>
<suppress files="file0" checks="check0"/>
<suppress files="file1" checks="check1" lines="1,2-3"/>
<suppress files="file2" checks="check2" columns="1,2-3"/>
<suppress files="file3" checks="check3" lines="1,2-3" columns="1,2-3"/>
+ <suppress message="message0"/>
</suppressions>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderXpathCorrect.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderXpathCorrect.xml
index d1e284a4e..05aa13585 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderXpathCorrect.xml
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppressionsloader/InputSuppressionsLoaderXpathCorrect.xml
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC
- "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.1//EN"
- "http://checkstyle.sourceforge.net/dtds/suppressions_1_1_xpath_experimental.dtd">
+ "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN"
+ "http://checkstyle.sourceforge.net/dtds/suppressions_1_2_xpath_experimental.dtd">
<suppressions>
<suppress-xpath files="file1" id="id1" checks="test" query="/CLASS_DEF"/>
+ <suppress-xpath message="message1" query="/CLASS_DEF"/>
</suppressions>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.js b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.js
new file mode 100644
index 000000000..9e0fbce6c
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.js
@@ -0,0 +1,7 @@
+// CS-OFF
+alert( 2 === 1 );
+
+// CS-ON
+alert( 2 === 1 );
+
+alert( 2 != 1 );
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.properties b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.properties
new file mode 100644
index 000000000..549756f6a
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.properties
@@ -0,0 +1,4 @@
+# CHECKSTYLE:OFF
+key1=
+# CHECKSTYLE:ON
+key2=
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.sql b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.sql
new file mode 100644
index 000000000..662164f04
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.sql
@@ -0,0 +1,5 @@
+-- CHECKSTYLE OFF
+ SELECT COUNT(1) FROM filters;
+
+-- CHECKSTYLE ON
+ SELECT COUNT(1) FROM checks;
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.xml
new file mode 100644
index 000000000..685ec350d
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilter.xml
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--CS-OFF-->
+
+<root>
+ <child>
+ </child>
+ <!--CS-ON-->
+ <child>
+ </child>
+</root>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java
new file mode 100644
index 000000000..d66fce649
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterCustomMessageFormat.java
@@ -0,0 +1,15 @@
+package com.puppycrawl.tools.checkstyle.filters.suppresswithplaintextcommentfilter;
+
+public class InputSuppressWithPlainTextCommentFilterCustomMessageFormat {
+
+ // CHECKSTYLE:OFF
+ private int A1;
+
+ private static final int a1 = 5; // contains tab character
+
+ int a2 = 100;
+
+ // CHECKSTYLE:ON
+ private long a3 = 1;
+
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterSuppressById.java b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterSuppressById.java
new file mode 100644
index 000000000..f18d95ee8
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterSuppressById.java
@@ -0,0 +1,16 @@
+package com.puppycrawl.tools.checkstyle.filters.suppresswithplaintextcommentfilter;
+
+public class InputSuppressWithPlainTextCommentFilterSuppressById {
+
+ //CSOFF ignore (reason)
+ private int A1;
+
+ // @cs-: ignore (reason)
+ private static final int a1 = 5; // contains tab character
+
+ int a2 = 100;
+ //CSON ignore
+
+ private long a3 = 1;
+
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java
new file mode 100644
index 000000000..9f7067de3
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments.java
@@ -0,0 +1,14 @@
+package com.puppycrawl.tools.checkstyle.filters.suppresswithplaintextcommentfilter;
+
+public class InputSuppressWithPlainTextCommentFilterWithCustomOnAndOffComments {
+ // cs-off
+ // has tab here
+
+ // cs-on
+ // has tab here
+
+
+ /* cs-off **/ private int b; /* cs-on **/
+
+ private int c;
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java
new file mode 100644
index 000000000..3a1a64d20
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/filters/suppresswithplaintextcommentfilter/InputSuppressWithPlainTextCommentFilterWithDefaultCfg.java
@@ -0,0 +1,12 @@
+package com.puppycrawl.tools.checkstyle.filters.suppresswithplaintextcommentfilter;
+
+public class InputSuppressWithPlainTextCommentFilterWithDefaultCfg {
+ // CHECKSTYLE:OFF
+ // has tab here
+
+ // CHECKSTYLE:ON
+ // has tab here
+
+ private int a; // CHECKSTYLE:OFF
+ // CHECKSTYLE:ON
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname-ignore.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname-ignore.xml
index efee92a8d..cb1e347eb 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname-ignore.xml
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname-ignore.xml
@@ -6,7 +6,7 @@
<module name="Checker">
<module name="TreeWalker">
- <module name="NonExistingClass">
+ <module name="NonExistentClass">
<property name="severity" value="ignore"/>
</module>
</module>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname.xml
index 59454580b..01316ff20 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existing-classname.xml
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/main/InputMainConfig-non-existent-classname.xml
@@ -6,7 +6,7 @@
<module name="Checker">
<module name="TreeWalker">
- <module name="NonExistingClass">
+ <module name="NonExistentClass">
<property name="severity" value="warning"/>
</module>
</module>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnAnnotationField.java b/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnAnnotationField.java
new file mode 100644
index 000000000..80577e124
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnAnnotationField.java
@@ -0,0 +1,25 @@
+package com.puppycrawl.tools.checkstyle.utils.blockcommentposition;
+
+public @interface InputBlockCommentPositionOnAnnotationField {
+ /**
+ * I'm a javadoc
+ */
+ String value() default "";
+
+ /**
+ * I'm a javadoc
+ */
+ abstract String value1() default "";
+
+ /**
+ * I'm a javadoc
+ */
+ @Deprecated
+ String value2() default "";
+
+ /**
+ * I'm a javadoc
+ */
+ @Deprecated
+ abstract String value3() default "";
+}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnMethod.java b/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnMethod.java
index e2b5a0b8e..06e4f4d49 100644
--- a/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnMethod.java
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/utils/blockcommentposition/InputBlockCommentPositionOnMethod.java
@@ -22,4 +22,11 @@ public class InputBlockCommentPositionOnMethod {
int method2(){
return 0;
}
+
+ /**
+ * I'm a javadoc
+ */
+ java.lang.String method3(){
+ return null;
+ }
}
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLogger.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLogger.xml
new file mode 100644
index 000000000..9d02b7689
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLogger.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<file name="Test.java">
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerEmpty.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerEmpty.xml
new file mode 100644
index 000000000..91fd28495
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerEmpty.xml
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerError.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerError.xml
new file mode 100644
index 000000000..b3998bf18
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerError.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<file name="Test.java">
+<error line="1" column="1" severity="error" message="$0" source="com.puppycrawl.tools.checkstyle.XMLLoggerTest"/>
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorModuleId.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorModuleId.xml
new file mode 100644
index 000000000..cd3bec8ed
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorModuleId.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<error line="1" column="1" severity="error" message="$0" source="module"/>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorNullFileName.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorNullFileName.xml
new file mode 100644
index 000000000..dae3ac4ec
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorNullFileName.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<error line="1" column="1" severity="error" message="$0" source="com.puppycrawl.tools.checkstyle.XMLLoggerTest"/>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorZeroColumn.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorZeroColumn.xml
new file mode 100644
index 000000000..b0959a9c0
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerErrorZeroColumn.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<file name="Test.java">
+<error line="1" severity="error" message="$0" source="com.puppycrawl.tools.checkstyle.XMLLoggerTest"/>
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException.xml
new file mode 100644
index 000000000..0a5b431d7
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;&#10;&lt;/exception&gt;&#10;
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException2.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException2.xml
new file mode 100644
index 000000000..9f125a0da
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException2.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+<file name="Test.java">
+&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;&#10;&lt;/exception&gt;&#10;
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException3.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException3.xml
new file mode 100644
index 000000000..a28d5156f
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerException3.xml
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;&#10;&lt;/exception&gt;&#10;
+<file name="Test.java">
+</file>
+</checkstyle>
diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerExceptionNullFileName.xml b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerExceptionNullFileName.xml
new file mode 100644
index 000000000..0a5b431d7
--- /dev/null
+++ b/src/test/resources/com/puppycrawl/tools/checkstyle/xmllogger/ExpectedXMLLoggerExceptionNullFileName.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<checkstyle version="">
+&lt;exception&gt;&#10;&lt;![CDATA[&#10;stackTrace&#10;example]]&gt;&#10;&lt;/exception&gt;&#10;
+</checkstyle>
diff --git a/src/xdocs/config.xml b/src/xdocs/config.xml
index 2e8103b16..1b7143160 100644
--- a/src/xdocs/config.xml
+++ b/src/xdocs/config.xml
@@ -14,13 +14,12 @@
</head>
<body>
-<!-- till https://issues.apache.org/jira/browse/MSITE-748
<section name="Content">
<macro name="toc">
<param name="fromDepth" value="1"/>
<param name="toDepth" value="1"/>
</macro>
- </section> -->
+ </section>
<section name="Overview">
<p>
@@ -823,7 +822,7 @@
</source>
<div class="tip">
- <h4>Note</h4>
+ <b>Note</b>
<p>
As of Checkstyle 5.0 it is unnecessary to repeat the
<code>package</code> elements for Checkstyle's packages in
@@ -835,7 +834,7 @@
<section name="XML Structure">
- <h4>Configuration XML Document</h4>
+ <b>Configuration XML Document</b>
<p>
The following DTD for a configuration XML document specifies the
hierarchy of modules and their properties:
@@ -880,7 +879,7 @@
conventions.
</p>
- <h4>Package Names XML Document</h4>
+ <b>Package Names XML Document</b>
<p>
This is a DTD for a package names XML document:
</p>
@@ -907,7 +906,7 @@
&quot;http://checkstyle.sourceforge.net/dtds/packages_1_1.dtd&quot;&gt;
</source>
- <h4>Suppressions XML Document</h4>
+ <b>Suppressions XML Document</b>
<p>
This is a DTD for a suppressions XML document:
</p>
@@ -918,8 +917,9 @@
&lt;!ELEMENT suppressions (suppress*)&gt;
&lt;!ELEMENT suppress EMPTY&gt;
-&lt;!ATTLIST suppress files CDATA #REQUIRED
+&lt;!ATTLIST suppress files CDATA #IMPLIED
checks CDATA #IMPLIED
+ message CDATA #IMPLIED
id CDATA #IMPLIED
lines CDATA #IMPLIED
columns CDATA #IMPLIED&gt;
diff --git a/src/xdocs/config_coding.xml b/src/xdocs/config_coding.xml
index d05b6c229..c44d889f6 100644
--- a/src/xdocs/config_coding.xml
+++ b/src/xdocs/config_coding.xml
@@ -3984,6 +3984,10 @@ class C {
<a href="https://github.com/search?q=path%3Asrc%2Fmain%2Fresources%2Fcom%2Fpuppycrawl%2Ftools%2Fcheckstyle%2Fchecks%2Fcoding+filename%3Amessages*.properties+repo%3Acheckstyle%2Fcheckstyle+%22return.count%22">
return.count</a>
</li>
+ <li>
+ <a href="https://github.com/search?q=path%3Asrc%2Fmain%2Fresources%2Fcom%2Fpuppycrawl%2Ftools%2Fcheckstyle%2Fchecks%2Fcoding+filename%3Amessages*.properties+repo%3Acheckstyle%2Fcheckstyle+%22return.countVoid%22">
+ return.countVoid</a>
+ </li>
</ul>
<p>
All messages can be customized if the default message doesn't suit you.
diff --git a/src/xdocs/config_filters.xml b/src/xdocs/config_filters.xml
index e5ae5cd77..f78de0410 100644
--- a/src/xdocs/config_filters.xml
+++ b/src/xdocs/config_filters.xml
@@ -483,19 +483,25 @@ public class UserService {
<code>files</code> -
a <a href="property_types.html#regexp">Regular Expression</a>
matched against the file name associated with an audit
- event. It is mandatory.
+ event. It is optional.
</li>
<li>
<code>checks</code> -
a <a href="property_types.html#regexp">Regular Expression</a>
matched against the name of the check associated with an audit
- event. Optional if <code>id</code> is specified.
+ event. Optional as long as <code>id</code> or <code>message</code> is specified.
+ </li>
+ <li>
+ <code>message</code> -
+ a <a href="property_types.html#regexp">Regular Expression</a>
+ matched against the message of the check associated with an audit
+ event. Optional as long as <code>checks</code> or <code>id</code> is specified.
</li>
<li>
<code>id</code> -
a <a href="property_types.html#string">string</a>
matched against the ID of the check associated with an audit
- event. Optional if <code>checks</code> is specified.
+ event. Optional as long as <code>checks</code> or <code>message</code> is specified.
</li>
<li>
<code>lines</code> - a comma-separated list of
@@ -527,7 +533,9 @@ public class UserService {
lines 82 and 108 to 122 of
file <code>AbstractComplexityCheck.java</code>,
and <code>MagicNumberCheck</code> errors for line
- 221 of file <code>JavadocStyleCheck.java</code>:
+ 221 of file <code>JavadocStyleCheck.java</code>,
+ and '<code>Missing a Javadoc comment</code>' errors
+ for all lines and files:
</p>
<source>
&lt;?xml version=&quot;1.0&quot;?&gt;
@@ -544,6 +552,7 @@ public class UserService {
files=&quot;JavadocStyleCheck.java&quot;
lines=&quot;221&quot;/&gt;
&lt;/suppressions&gt;
+&lt;suppress message=&quot;Missing a Javadoc comment&quot;/&gt;&lt;/suppressions&gt;
</source>
<p>
As another example to suppress Check by module id:
@@ -615,6 +624,12 @@ public class UserService {
<source>
&lt;suppress checks=&quot;FileLength&quot; files=&quot;com[\\/]mycompany[\\/]app[\\/].*IT.java&quot;/&gt;
</source>
+ <p>
+ Suppress naming errors on variable named 'log' in all files:
+ </p>
+ <source>
+&lt;suppress message=&quot;Name 'log' must match pattern&quot;/&gt;
+ </source>
</subsection>
<subsection name="Example of Usage">
<ul>
@@ -633,6 +648,229 @@ public class UserService {
</subsection>
</section>
+ <section name="SuppressionXpathFilter">
+ <subsection name="Description">
+ <p>Since Checkstyle 8.6</p>
+ <p>
+ Filter <code>SuppressionXpathFilter</code> works as
+ <a href="config_filters.html#SuppressionFilter">SuppressionFilter</a>.
+ Additionally, filter processes <code>suppress-xpath</code> elements,
+ which contains xpath-expressions. Xpath-expressions
+ are queries for suppressed nodes inside the AST tree.
+ </p>
+ <p>
+ Note, after resolving
+ <a href="https://github.com/checkstyle/checkstyle/issues/4530">issue 4530</a>
+ CLI will have option to generate the basic suppression xpath to elements.
+ </p>
+ <p>
+ Currently, filter supports the following
+ checks:
+ </p>
+ <ul>
+ <li>CyclomaticComplexityCheck</li>
+ <li>DeclarationOrderCheck</li>
+ <li>DefaultComesLastCheck</li>
+ <li>ExplicitInitializationCheck</li>
+ <li>FallThroughCheck</li>
+ <li>HiddenFieldCheck</li>
+ <li>IllegalCatchCheck</li>
+ <li>IllegalThrowsCheck</li>
+ <li>JavadocMethodCheck</li>
+ <li>JavadocVariableCheck</li>
+ <li>ImportControlCheck</li>
+ <li>LeftCurlyCheck</li>
+ <li>MethodParamPadCheck</li>
+ <li>MultipleVariableDeclarationCheck</li>
+ <li>NestedForDepthCheck</li>
+ <li>NestedIfDepthCheck</li>
+ <li>NestedTryDepthCheck</li>
+ <li>NPathComplexityCheck</li>
+ <li>OneStatementPerLineCheck</li>
+ <li>OuterTypeNumberCheck</li>
+ <li>RequireThisCheck</li>
+ <li>RightCurlyCheck</li>
+ </ul>
+ <p>
+ Note, that support for other Checks will be available after resolving
+ <a href="https://github.com/checkstyle/checkstyle/issues/4830">issue 4830</a>.
+ </p>
+ </subsection>
+ <subsection name="Properties">
+ <table>
+ <tr>
+ <th>name</th>
+ <th>description</th>
+ <th>type</th>
+ <th>default value</th>
+ <th>since</th>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>
+ the location of the <em>suppressions XML document</em> file.
+ The order the location is checked is:
+ <ol>
+ <li>as a filesystem location</li>
+ <li>
+ if no file found, and the location starts with either
+ <code>http://</code> or <code>https://</code>, then it
+ is interpreted as a URL
+ </li>
+ <li>
+ if no file found, then passed to the
+ <code>ClassLoader.getResource()</code> method.
+ </li>
+ </ol>
+ </td>
+ <td><a href="property_types.html#string">string</a></td>
+ <td><code>none</code></td>
+ <td>8.6</td>
+ </tr>
+ <tr>
+ <td>optional</td>
+ <td>
+ Tells what to do when the file is not existing. If
+ optional is set to false the file must exist, or else
+ it ends with error. On the other hand if optional is
+ true and file is not found, the filter accept all
+ audit events.
+ </td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.6</td>
+ </tr>
+ </table>
+ </subsection>
+ <subsection name="Examples">
+ <p>
+ For example, the following configuration fragment directs the
+ Checker to use a <code>SuppressionXpathFilter</code>
+ with suppressions
+ file <code>config/suppressions.xml</code>:
+ </p>
+ <source>
+&lt;module name=&quot;SuppressionXpathFilter&quot;&gt;
+ &lt;property name=&quot;file&quot; value=&quot;config/suppressions.xml&quot;/&gt;
+ &lt;property name=&quot;optional&quot; value=&quot;false&quot;/&gt;
+&lt;/module&gt;
+ </source>
+ <p>
+ A <a href="config.html#XML_Structure"><em>suppressions XML
+ document</em></a> contains a set
+ of <code>suppress</code> and <code>suppress-xpath</code> elements, where
+ each <code>suppress-xpath</code> element can have the
+ following attributes:
+ </p>
+ <ul>
+ <li>
+ <code>files</code> -
+ a <a href="property_types.html#regexp">Regular Expression</a>
+ matched against the file name associated with an audit
+ event. It is optional.
+ </li>
+ <li>
+ <code>checks</code> -
+ a <a href="property_types.html#regexp">Regular Expression</a>
+ matched against the name of the check associated with an audit
+ event. Optional as long as <code>id</code> or <code>message</code> is specified.
+ </li>
+ <li>
+ <code>message</code> -
+ a <a href="property_types.html#regexp">Regular Expression</a>
+ matched against the message of the check associated with an audit
+ event. Optional as long as <code>checks</code> or <code>id</code> is specified.
+ </li>
+ <li>
+ <code>id</code> -
+ a <a href="property_types.html#string">string</a>
+ matched against the ID of the check associated with an audit
+ event. Optional as long as <code>checks</code> or <code>message</code> is specified.
+ </li>
+ <li>
+ <code>query</code> -
+ a <a href="property_types.html#string">string</a>
+ xpath query. It is optional.
+ </li>
+ </ul>
+ <p>
+ Each audit event is checked against
+ each <code>suppress</code> and <code>suppress-xpath</code> element. It is
+ suppressed if all specified attributes match against the audit
+ event.
+ </p>
+ <p>
+ The following suppressions XML document directs
+ a <code>SuppressionXpathFilter</code> to
+ reject <code>CyclomaticComplexity</code> errors for
+ all methods with name <i>sayHelloWorld</i> inside <i>FileOne</i>
+ and <i>FileTwo</i> classes:
+ </p>
+ <source>
+&lt;?xml version=&quot;1.0&quot;?&gt;
+
+&lt;!DOCTYPE suppressions PUBLIC
+&quot;-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN&quot;
+&quot;http://checkstyle.sourceforge.net/dtds/suppressions_1_2_xpath_experimental.dtd&quot;&gt;
+
+&lt;suppressions&gt;
+ &lt;suppress-xpath checks=&quot;CyclomaticComplexity&quot;
+ files=&quot;FileOne.java,FileTwo.java&quot;
+ query=&quot;//METHOD_DEF[@text='sayHelloWorld']&quot;/&gt;
+&lt;/suppressions&gt;
+ </source>
+ <p>
+ Suppress checks for package definitions:
+ </p>
+ <source>
+&lt;suppress-xpath checks=&quot;.*&quot; query=&quot;/PACKAGE_DEF&quot;/&gt;
+ </source>
+ <p>
+ Suppress checks for parent element of the first variable definition:
+ </p>
+ <source>
+&lt;suppress-xpath checks=&quot;.*&quot; query=&quot;(//VARIABLE_DEF)[1]/..&quot;/&gt;
+ </source>
+ <p>
+ Suppress checks for elements which are either class definitions,
+ either method definitions.
+ </p>
+ <source>
+&lt;suppress-xpath checks=&quot;.*&quot; query=&quot;//CLASS_DEF | //METHOD_DEF&quot;/&gt;
+ </source>
+ <p>
+ Suppress checks for certain methods:
+ </p>
+ <source>
+&lt;suppress-xpath checks=&quot;.*&quot; query=&quot;//METHOD_DEF[@text='getSomeVar'
+ or @text='setSomeVar']&quot;/&gt;
+ </source>
+ <p>
+ Suppress checks for variable <i>testVariable</i> inside <i>testMethod</i> method
+ inside <i>TestClass</i> class.
+ </p>
+ <source>
+&lt;suppress-xpath checks=&quot;.*&quot; query=&quot;/CLASS_DEF[@text='TestClass']
+ //METHOD_DEF[@text='testMethod']//VARIABLE_DEF[@text='testVariable']&quot;/&gt;
+ </source>
+ </subsection>
+ <subsection name="Example of Usage">
+ <ul>
+ <li>
+ <a href="https://github.com/search?q=path%3Aconfig+filename%3Acheckstyle_checks.xml+repo%3Acheckstyle%2Fcheckstyle+SuppressionXpathFilter">
+ Checkstyle Style</a>
+ </li>
+ </ul>
+ </subsection>
+ <subsection name="Package">
+ <p> com.puppycrawl.tools.checkstyle.filters </p>
+ </subsection>
+
+ <subsection name="Parent Module">
+ <p> <a href="config.html#TreeWalker">TreeWalker</a> </p>
+ </subsection>
+ </section>
+
<section name="SuppressWarningsFilter">
<subsection name="Description">
<p>Since Checkstyle 5.7</p>
@@ -986,5 +1224,301 @@ public class UserService {
<p> <a href="config.html#TreeWalker">TreeWalker</a> </p>
</subsection>
</section>
+
+ <section name="SuppressWithPlainTextCommentFilter">
+ <subsection name="Description">
+ <p>Since Checkstyle 8.6</p>
+ <p>
+ Filter <code>SuppressWithPlainTextCommentFilter</code> uses plain text to suppress
+ audit events. The filter can be used only to suppress audit events received from
+ the checks which implement FileSetCheck interface. In other words, the checks
+ which have Checker as a parent module. The filter knows nothing about AST,
+ it treats only plain text comments and extracts the information required
+ for suppression from the plain text comments. Currently the filter supports
+ only single line comments.
+ </p>
+ <p>
+ Please, be aware of the fact that, it is not recommended to use the filter
+ for Java code anymore, however you still are able to use it to suppress audit
+ events received from the checks which implement FileSetCheck interface.
+ </p>
+ <p>
+ Rationale: Sometimes there are legitimate reasons for violating
+ a check. When this is a matter of the code in question and not
+ personal preference, the best place to override the policy is in
+ the code itself. Semi-structured comments can be associated
+ with the check. This is sometimes superior to a separate
+ suppressions file, which must be kept up-to-date as the source
+ file is edited.
+ </p>
+ <p>
+ Note that the suppression comment should be put before the violation. You can use more
+ than one suppression comment each on separate line.
+ </p>
+ </subsection>
+ <subsection name="Properties">
+ <table>
+ <tr>
+ <th>name</th>
+ <th>description</th>
+ <th>type</th>
+ <th>default value</th>
+ <th>since</th>
+ </tr>
+ <tr>
+ <td>offCommentFormat</td>
+ <td>comment pattern to trigger filter to begin suppression</td>
+ <td><a href="property_types.html#regexp">Regular Expression</a></td>
+ <td><code>"// CHECKSTYLE:OFF"</code></td>
+ <td>8.6</td>
+ </tr>
+ <tr>
+ <td>onCommentFormat</td>
+ <td>comment pattern to trigger filter to end suppression</td>
+ <td><a href="property_types.html#regexp">Regular Expression</a></td>
+ <td><code>"// CHECKSTYLE:ON"</code></td>
+ <td>8.6</td>
+ </tr>
+ <tr>
+ <td>checkFormat</td>
+ <td>check pattern to suppress</td>
+ <td><a href="property_types.html#regexp">Regular Expression</a></td>
+ <td><code>".*"</code></td>
+ <td>8.6</td>
+ </tr>
+ <tr>
+ <td>messageFormat</td>
+ <td>message pattern to suppress</td>
+ <td><a href="property_types.html#regexp">Regular Expression</a></td>
+ <td><code>null</code></td>
+ <td>8.6</td>
+ </tr>
+ </table>
+ <p>
+ offCommentFormat and onCommentFormat must have equal <a
+ href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#groupCount()">paren counts</a>.
+ </p>
+ </subsection>
+ <subsection name="Examples">
+ <p>
+ To configure a filter to suppress audit events between a comment
+ containing <code>CHECKSTYLE:OFF</code> and a comment containing
+ <code>CHECKSTYLE:ON</code>:
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ ...
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;/&gt;
+ ...
+&lt;/module&gt;
+ </source>
+ <p>
+ To configure a filter to suppress audit events between a comment
+ containing line <code>BEGIN GENERATED CONTENT</code> and a comment
+ containing line <code>END GENERATED CONTENT</code>
+ (Checker is configured to check only properties files):
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;properties&quot;/&gt;
+
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name=&quot;offCommentFormat&quot; value=&quot;BEGIN GENERATED CONTENT&quot;/&gt;
+ &lt;property name=&quot;onCommentFormat&quot; value=&quot;END GENERATED CONTENT&quot;/&gt;
+ &lt;/module>
+
+&lt;/module&gt;
+ </source>
+ <source>
+//BEGIN GENERATED CONTENT
+my.property=value1 // No violation events will be reported
+my.property=value2 // No violation events will be reported
+//END GENERATED CONTENT
+. . .
+ </source>
+ <p>
+ To configure a filter so that <code>-- stop tab
+ check</code> and <code>-- resume tab check</code> marks allowed tab positions
+ (Checker is configured to check only sql files):
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;sql&quot;/&gt;
+
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name=&quot;offCommentFormat&quot; value=&quot;stop tab check&quot;/&gt;
+ &lt;property name=&quot;onCommentFormat&quot; value=&quot;resume tab check&quot;/&gt;
+ &lt;property name=&quot;checkFormat&quot; value=&quot;FileTabCharacterCheck&quot;/&gt;
+ &lt;/module>
+
+&lt;/module>
+ </source>
+ <source>
+-- stop tab check
+ SELECT * FROM users // won't warn here if there is a tab character on line
+-- resume tab check
+ SELECT 1 // will warn here if there is a tab character on line
+ </source>
+ <p>
+ To configure a filter so that name of suppressed check mentioned
+ in comment <code>CSOFF: <i>regexp</i></code>
+ and <code>CSON: <i>regexp</i></code> mark a matching check
+ (Checker is configured to check only xml files):
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;xml&quot;/&gt;
+
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name=&quot;offCommentFormat&quot; value=&quot;CSOFF\: ([\w\|]+)&quot;/&gt;
+ &lt;property name=&quot;onCommentFormat&quot; value=&quot;CSON\: ([\w\|]+)&quot;/&gt;
+ &lt;property name=&quot;checkFormat&quot; value=&quot;$1&quot;/&gt;
+ &lt;/module&gt;
+
+&lt;/module>
+ </source>
+ <source>
+// CSOFF: RegexpSinglelineCheck
+&lt;condition property=&quot;checkstyle.ant.skip&quot;&gt; // RegexpSingleline check won't warn here if the line matches regexp
+ &lt;isset property=&quot;checkstyle.ant.skip&quot;/&gt; // RegexpSingleline check won't warn here if the line matches regexp
+&lt;/condition&gt; // RegexpSingleline check won't warn here if the line matches regexp
+// CSON: RegexpSinglelineCheck
+&lt;property name=&quot;checkstyle.pattern.todo&quot; value=&quot;NOTHingWillMatCH_-&quot;/&gt; // RegexpSingleline check will warn here if the line matches regexp
+ </source>
+ <p>
+ To configure a filter to suppress all audit events between a comment
+ containing <code>CHECKSTYLE_OFF: ALMOST_ALL</code> and a comment containing
+ <code>CHECKSTYLE_OFF: ALMOST_ALL</code> except for the <em>EqualsHashCode</em> check
+ (Checker is configured to check only java files):
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;java&quot;/&gt;
+
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name=&quot;offCommentFormat&quot; value=&quot;CHECKSTYLE_OFF: ALMOST_ALL&quot;/&gt;
+ &lt;property name=&quot;onCommentFormat&quot; value=&quot;CHECKSTYLE_ON: ALMOST_ALL&quot;/&gt;
+ &lt;property name=&quot;checkFormat&quot; value=&quot;^((?!(FileTabCharacterCheck)).)*$&quot;/&gt;
+ &lt;/module&gt;
+
+&lt;/module>
+ </source>
+ <source>
+// CHECKSTYLE_OFF: ALMOST_ALL
+public static final int array [];
+private String [] strArray;
+// CHECKSTYLE_ON: ALMOST_ALL
+private int array1 [];
+ </source>
+ <p>
+ To configure a filter to suppress Check's violation message <b>which matches
+ specified message in messageFormat</b> (so suppression will not be only by
+ Check's name, but also by message text, as the same Check can report
+ violations with different message format) between a comment
+ containing <code>stop</code> and comment containing <code>resume</code>:
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;module name=&quot;SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name=&quot;offCommentFormat&quot; value=&quot;stop&quot;/&gt;
+ &lt;property name=&quot;onCommentFormat&quot; value=&quot;resume&quot;/&gt;
+ &lt;property name=&quot;checkFormat&quot; value=&quot;FileTabCharacterCheck&quot;/&gt;
+ &lt;property name=&quot;messageFormat&quot; value=&quot;^File contains tab characters (this is the first instance)\.$&quot;/&gt;
+ &lt;/module&gt;
+&lt;/module>
+ </source>
+ <p>
+ It is possible to specify an ID of checks, so that it can be leveraged by the
+ SuppressWithPlainTextCommentFilter to skip validations.
+ The following examples show how to skip validations near code that is surrounded
+ with <code>-- CSOFF &lt;ID> (reason)</code> and <code>-- CSON &lt;ID></code>,
+ where ID is the ID of checks you want to suppress.
+ </p>
+ <p>
+ Examples of Checkstyle checks configuration:
+ </p>
+ <source>
+&lt;module name=&quot;RegexpSinglelineJava&quot;&gt;
+ &lt;property name=&quot;id&quot; value=&quot;count&quot;/&gt;
+ &lt;property name="format" value="^.*COUNT(*).*$"/&gt;
+ &lt;property name="message" value="Don't use COUNT(*), use COUNT(1) instead."/&gt;
+&lt;/module&gt;
+
+&lt;module name=&quot;RegexpSinglelineJava&quot;&gt;
+ &lt;property name=&quot;id&quot; value=&quot;join&quot;/&gt;
+ &lt;property name="format" value="^.*JOIN\s.+\s(ON|USING)$"/&gt;
+ &lt;property name="message" value="Don't use JOIN, use sub-select instead."/&gt;
+&lt;/module&gt;
+ </source>
+ <p>
+ Example of SuppressWithPlainTextCommentFilter configuration (checkFormat which is set to '$1'
+ points that ID of the checks is in the first group of offCommentFormat and
+ onCommentFormat regular expressions):
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;sql&quot;/&gt;
+
+ &lt;module name="SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name="offCommentFormat" value="CSOFF (\w+) \(\w+\)"/&gt;
+ &lt;property name="onCommentFormat" value="CSON (\w+)"/&gt;
+ &lt;property name="checkFormat" value="$1"/&gt;
+ &lt;/module&gt;
+
+&lt;/module&gt;
+ </source>
+ <source>
+-- CSOFF join (it is ok to use join here for performance reasons)
+SELECT name, job_name
+FROM users AS u
+JOIN jobs AS j ON u.job_id = j.id
+-- CSON join
+
+-- CSOFF count (test query execution plan)
+EXPLAIN SELECT COUNT(*) FROM restaurants
+-- CSON count
+ </source>
+ <p>
+ Example of how to configure the check to suppress more than one check
+ (Checker is configured to check only sql files).
+ </p>
+ <source>
+&lt;module name=&quot;Checker&quot;&gt;
+ &lt;property name=&quot;fileExtensions&quot; value=&quot;sql&quot;/&gt;
+
+ &lt;module name="SuppressWithPlainTextCommentFilter&quot;&gt;
+ &lt;property name="offCommentFormat" value="@cs-\: ([\w\|]+)"/&gt;
+ &lt;property name="checkFormat" value="$1"/&gt;
+ &lt;/module&gt;
+
+&lt;/module&gt;
+ </source>
+ <source>
+-- @cs-: RegexpSinglelineCheck
+-- @cs-: FileTabCharacterCheck
+CREATE TABLE STATION (
+ ID INTEGER PRIMARY KEY,
+ CITY CHAR(20),
+ STATE CHAR(2),
+ LAT_N REAL,
+ LONG_W REAL);
+ </source>
+ </subsection>
+ <subsection name="Example of Usage">
+ <ul>
+ <li>
+ <a href="https://github.com/search?q=path%3Aconfig+filename%3Acheckstyle_checks.xml+repo%3Acheckstyle%2Fcheckstyle+SuppressWithPlainTextCommentFilter">
+ Checkstyle Style</a>
+ </li>
+ </ul>
+ </subsection>
+ <subsection name="Package">
+ <p> com.puppycrawl.tools.checkstyle.filters </p>
+ </subsection>
+
+ <subsection name="Parent Module">
+ <p> <a href="config.html#Checker">Checker</a> </p>
+ </subsection>
+ </section>
</body>
</document>
diff --git a/src/xdocs/config_javadoc.xml b/src/xdocs/config_javadoc.xml
index c1ade7ffd..49da8de24 100644
--- a/src/xdocs/config_javadoc.xml
+++ b/src/xdocs/config_javadoc.xml
@@ -41,6 +41,16 @@
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>target</td>
<td>allows to specify targets to check at-clauses.</td>
<td>subset of tokens
@@ -619,6 +629,16 @@ public boolean isSomething()
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>allowNewlineParagraph</td>
<td>whether the &lt;p&gt; tag should be placed immediately before the first word</td>
<td><a href="property_types.html#boolean">Boolean</a></td>
@@ -991,6 +1011,16 @@ public boolean isSomething()
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>offset</td>
<td>How many spaces to use for new indentation level.</td>
<td><a href="property_types.html#integer">Integer</a></td>
@@ -1417,18 +1447,30 @@ public boolean isSomething()
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>javadocTokens</td>
<td>javadoc tokens to check</td>
<td>subset of javadoc tokens
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#PARAM_LITERAL">PARAM_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#RETURN_LITERAL">RETURN_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#THROWS_LITERAL">THROWS_LITERAL</a>,
+ <a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#TEXCEPTION_LITERAL">EXCEPTION_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#DEPRECATED_LITERAL">DEPRECATED_LITERAL</a>.
</td>
<td>
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#PARAM_LITERAL">PARAM_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#RETURN_LITERAL">RETURN_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#THROWS_LITERAL">THROWS_LITERAL</a>,
+ <a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#TEXCEPTION_LITERAL">EXCEPTION_LITERAL</a>,
<a href="apidocs/com/puppycrawl/tools/checkstyle/api/JavadocTokenTypes.html#DEPRECATED_LITERAL">DEPRECATED_LITERAL</a>.
</td>
<td>7.3</td>
@@ -1517,6 +1559,16 @@ public boolean isSomething()
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>ignoredTags</td>
<td>allows to specify at-clauses which are ignored by the check.</td>
<td><a href="property_types.html#stringSet">String Set</a></td>
@@ -1622,6 +1674,16 @@ public boolean isSomething()
<th>since</th>
</tr>
<tr>
+ <td>violateExecutionOnNonTightHtml</td>
+ <td>
+ If turned on, will print violations if the Javadoc being examined by this check
+ violates the tight html rules defined at
+ <a href="writingjavadocchecks.html#Tight-HTML_rules">Tight-HTML Rules</a>.</td>
+ <td><a href="property_types.html#boolean">Boolean</a></td>
+ <td><code>false</code></td>
+ <td>8.3</td>
+ </tr>
+ <tr>
<td>forbiddenSummaryFragments</td>
<td>forbidden summary fragments</td>
<td><a href="property_types.html#regexp">Regular Expression</a></td>
diff --git a/src/xdocs/index.xml.vm b/src/xdocs/index.xml.vm
index 1b281fe52..56ad4ecad 100644
--- a/src/xdocs/index.xml.vm
+++ b/src/xdocs/index.xml.vm
@@ -312,6 +312,12 @@
<td>Part of the standard JDEE distribution - <a href="https://github.com/jdee-emacs/jdee"/></td>
<td><a href="https://github.com/jdee-emacs/jdee/blob/master/jdee-checkstyle.el">configuration could be seen at jdee-checkstyle.el</a></td>
</tr>
+ <tr>
+ <td><a href="https://code.visualstudio.com/">Visual Studio Code</a></td>
+ <td>Sheng Chen</td>
+ <td><a href="https://marketplace.visualstudio.com/items?itemName=shengchen.vscode-checkstyle">vscode-checkstyle</a></td>
+ <td>Checkstyle for Microsoft Visual Studio Code</td>
+ </tr>
</table>
</subsection>
diff --git a/src/xdocs/releasenotes.xml b/src/xdocs/releasenotes.xml
index b4580cc8a..9a511e499 100644
--- a/src/xdocs/releasenotes.xml
+++ b/src/xdocs/releasenotes.xml
@@ -16,6 +16,129 @@
<body>
<!-- placeholder for a new section -->
+ <section name="Release 8.6">
+ <p>Breaking backward compatibility:</p>
+ <ul>
+ <li>
+ AbstractLoader: move out of api, rename, and remove abstract modifier . Author: Roman_Zhigunov <a href="https://github.com/checkstyle/checkstyle/issues/5338">#5338</a>
+ </li>
+ </ul>
+ <p>New:</p>
+ <ul>
+ <li>
+ new Checker filter SuppressWithPlainTextCommentFilter as akin to Treewalker's SuppressionCommentFilter. Author: Andrei Selkin <a href="https://github.com/checkstyle/checkstyle/issues/4841">#4841</a>
+ </li>
+ <li>
+ Add @exception JavaDoc block tag to NonEmptyAtclauseDescriptionCheck. Author: Lev_Sikhovets <a href="https://github.com/checkstyle/checkstyle/issues/5388">#5388</a>
+ </li>
+ <li>
+ Support suppression-xpath element in SuppressionLoader. Author: Timur Tibeyev <a href="https://github.com/checkstyle/checkstyle/issues/4421">#4421</a>
+ </li>
+ <li>
+ add ANNOTATION_DEF to RequireThisCheck. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5363">#5363</a>
+ </li>
+ <li>
+ SuppressionFilter: add suppression by message. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/2804">#2804</a>
+ </li>
+ </ul>
+ <p>Bug fixes:</p>
+ <ul>
+ <li>
+ TranslationCheck: should fire file started/finished when invoking errors. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5057">#5057</a>
+ </li>
+ <li>
+ fixed RequireThisCheck and for loop variable handling. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5392">#5392</a>
+ </li>
+ <li>
+ changed RequireThis kept track of the frame being examined. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5364">#5364</a>
+ </li>
+ <li>
+ ImportOrder with option=bottom should not allow non-static import after static import. Author: Julian Hyde <a href="https://github.com/checkstyle/checkstyle/issues/4981">#4981</a>
+ </li>
+ <li>
+ ReturnCount: unclear message when only max property is specified. Author: vaano94 <a href="https://github.com/checkstyle/checkstyle/issues/5306">#5306</a>
+ </li>
+ <li>
+ Incorrect indentation check for method preceded by annotation, with method parameter on separate line. Author: BBG <a href="https://github.com/checkstyle/checkstyle/issues/5154">#5154</a>
+ </li>
+ <li>
+ fixed RequireThisCheck and enum constants handling. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5361">#5361</a>
+ </li>
+ <li>
+ fixed RequireThisCheck and catch variable handling. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5351">#5351</a>
+ </li>
+ <li>
+ AnnotationUtility.getAnnotation fails when there is an comment in the annotation. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5327">#5327</a>
+ </li>
+ <li>
+ False RedundantModifier violation for final method of enum inside final class. Author: BBG <a href="https://github.com/checkstyle/checkstyle/issues/5268">#5268</a>
+ </li>
+ <li>
+ fixed bug on matching xpath when no xpath given. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5321">#5321</a>
+ </li>
+ <li>
+ Checkstyle ignores javadoc that placed over Annotation type elements . Author: Pavel Bludov <a href="https://github.com/checkstyle/checkstyle/issues/4169">#4169</a>
+ </li>
+ <li>
+ JavadocMethod: No error for a misplaced javadoc tag. Author: Pavel Bludov <a href="https://github.com/checkstyle/checkstyle/issues/4701">#4701</a>
+ </li>
+ </ul>
+ <p>Notes:</p>
+ <ul>
+ <li>
+ pitest: increase mutation coverage for pitest-checks-misc profile to 100%. Author: rnveach, vasilyeva <a href="https://github.com/checkstyle/checkstyle/issues/4675">#4675</a>
+ </li>
+ <li>
+ Some contents in messages_zh.properties for imports check are not well translated. Author: zhangduo <a href="https://github.com/checkstyle/checkstyle/issues/5393">#5393</a>
+ </li>
+ <li>
+ TranslationCheckTest.testLogOutput is failed . Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5141">#5141</a>
+ </li>
+ <li>
+ pitest: increase mutation coverage for pitest-checks-imports profile to 100%. Author: BBG <a href="https://github.com/checkstyle/checkstyle/issues/5004">#5004</a>
+ </li>
+ <li>
+ Indentaion problem in pjdbc project. Author: Roman Ivanov <a href="https://github.com/checkstyle/checkstyle/issues/5286">#5286</a>
+ </li>
+ <li>
+ Use versions-maven-plugin to report versions to update. Author: Roman Ivanov <a href="https://github.com/checkstyle/checkstyle/issues/5208">#5208</a>
+ </li>
+ <li>
+ minimize pitest-checkstyle-utils profile execution. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/4605">#4605</a>
+ </li>
+ <li>
+ api: abstract classes that extending concrete class. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/4716">#4716</a>
+ </li>
+ <li>
+ pitest: increase mutation coverage for pitest-checks-whitespace profile to 100%. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5003">#5003</a>
+ </li>
+ <li>
+ pitest: increase mutation coverage for pitest-checks-metrics profile to 100%. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5005">#5005</a>
+ </li>
+ <li>
+ pitest: increase mutation coverage for pitest-checks-coding profile to 100%. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5008">#5008</a>
+ </li>
+ <li>
+ internal code: terminolozy problems in ModuleReflectionUtils. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/4876">#4876</a>
+ </li>
+ <li>
+ Add violateExecutionOnNonTightHtml property of AbstractJavadocCheck to xdoc. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5002">#5002</a>
+ </li>
+ <li>
+ change all sonarqube.com to sonarcloud.io. Author: Roman Ivanov <a href="https://github.com/checkstyle/checkstyle/issues/5290">#5290</a>
+ </li>
+ <li>
+ doc: add 'Checkstyle for Microsoft Visual Studio Code' in known tools. Author: Roman Ivanov
+ </li>
+ <li>
+ Revert "infra: fix for travis:osx problem with 'shell_session_update: command not found'". Author: Roman Ivanov
+ </li>
+ <li>
+ Remove usage of DetailAST.branchContains. Author: rnveach <a href="https://github.com/checkstyle/checkstyle/issues/5124">#5124</a>
+ </li>
+ </ul>
+ </section>
+
<section name="Release 8.5">
<p>New:</p>
<ul>
@@ -3818,7 +3941,7 @@
Remove usage of deprecated methods from MainTest. Author: Michal Kordas <a href="https://github.com/checkstyle/checkstyle/issues/1325">#1325</a>
</li>
<li>
- Restore checkstyle validation on https://sonarqube.com. Author: Roman Ivanov <a href="https://github.com/checkstyle/checkstyle/issues/1319">#1319</a>
+ Restore checkstyle validation on https://sonarcloud.io. Author: Roman Ivanov <a href="https://github.com/checkstyle/checkstyle/issues/1319">#1319</a>
</li>
<li>
Update Maven Shade Plugin, EqualsVerifier, antlr, system-rules and Maven PMD Plugin to latest versions. Author: Michal Kordas
diff --git a/src/xdocs/writingjavadocchecks.xml.vm b/src/xdocs/writingjavadocchecks.xml.vm
index b07b52d14..209cbe666 100644
--- a/src/xdocs/writingjavadocchecks.xml.vm
+++ b/src/xdocs/writingjavadocchecks.xml.vm
@@ -23,25 +23,74 @@
<section name="What is Javadoc comment">
<p>
- Javadoc comment is multiline comment <code>/* */</code> that starts with <b>*</b> character and placed above class definition, interface definition, enum definition, method definition or field definition.
+ Javadoc comment is a multiline comment <code>/* */</code> that starts with the <b>*</b>
+ character and placed above the class definition, interface definition, enum definition,
+ method definition or field definition.
+ If an annotation precedes any of the definitions listed above, then the javadoc comment
+ should be placed before the annotation.
+ If several multiline comments with javadoc identifiers are placed sequentially, only
+ the one closest to the definition, right above it, with the javadoc identifier will be used.
+ </p>
+ <p>
+ Javadoc comments should contain: a short summary (the first sentence), an optional
+ documentation section, an optional tag section.
+ The first sentence has a special meaning and should be clear, punchy, short, and is ended by
+ a period symbol.
+ Immediately after the first sentence, the main description could begin, which may be followed
+ by the tag section.
+ The tag section starts with the first block tag, which is defined by the first <code>@</code>
+ character that begins a line (ignoring leading asterisks, white space, and leading separator
+ <code>/**</code>).
+ </p>
<p>For example, here is java file:</p>
<source><![CDATA[
/**
* My <b>class</b>.
- * @see AbstractClass
+ *
+ * @see Annotation
*/
public class MyClass {
+ /** Not a javadoc (ignored). */
+
+ /**
+ * Doubles the value.
+ * The long and detailed explanation what the method does.
+ *
+ * @param value for doubling.
+ * @return double value.
+ */
+
+ /*
+ Multiline comment (ignored).
+ */
+ @Annotation
+ /** Extra javadoc (ignored). */
+ // Single line comment (ignored).
+ public int method(int value) {
+ /** Inner javadoc (ignored). */
+ return value * 2;
+ }
}
]]></source>
- Javadoc content is:
+ <p>Javadoc content for the MyClass will be:</p>
<source><![CDATA[
- * My <b>class</b>.
- * @see AbstractClass
+ My <b>class</b>.
+
+ @see Annotation
]]></source>
- </p>
+ <p>Javadoc content for the MyClass.method will be:</p>
+ <source><![CDATA[
+ Doubles the value.
+ The long and detailed explanation what the method does.
+
+ @param value for doubling.
+ @return double value.
+ ]]></source>
+ <p>
Attention that java comment starts with <code>/*</code>, following with Identificator of comment type. Javadoc Identificator is <code>*</code>. All symbols after Javadoc Identificator till <code>*/</code> are part of javadoc comment.
- <p>Please note that javadoc-like(miltiline comment with javdoc identificator) comment inside a method is not a javadoc comment and skipped by
+ </p>
+ <p>Please note that javadoc-like (miltiline comment with javdoc identificator) comment inside a method is not a javadoc comment and skipped by
Sun/Oracle javadoc tool and by our javadoc comment matcher, but such comment will be in AST.
</p>
<p>In internet you can find different types of documentation
diff --git a/wercker.yml b/wercker.yml
index d6e78dccf..464f2f458 100644
--- a/wercker.yml
+++ b/wercker.yml
@@ -3,7 +3,7 @@ box: maven:3.3.9-jdk-8
build:
steps:
- script:
- name: setup mvn local repo
+ name: setup maven local repo
code: |
export MAVEN_OPTS="-Dmaven.repo.local=${WERCKER_CACHE_DIR}"
mvn -version
@@ -24,7 +24,6 @@ build:
PATH=$GROOVY_HOME/bin:$PATH
groovy -v
- # Build Checkstyle
- script:
name: Build Checkstyle
code: |
@@ -32,322 +31,165 @@ build:
export SKIP_CI=$(if [[ $(git diff --name-only HEAD HEAD~1 | grep -vE "$SKIP_FILES" | cat | wc -c) > 0 ]]; then echo false; else echo true; fi;)
echo "SKIP_CI="$SKIP_CI
if [[ $SKIP_CI == 'false' ]]; then
- mvn clean install -Pno-validations
+ mvn -e clean install -Pno-validations
else
echo "build is skipped ..."
fi
- # NoErrorTest - Postgresql JDBC Driver (oraclejdk8)
- script:
name: NoErrorTest - Postgresql JDBC Driver
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/pgjdbc/pgjdbc.git && break || sleep 15; done
- cd pgjdbc/pgjdbc
- # special checkout till https://github.com/checkstyle/checkstyle/issues/5286
- git checkout 279fb435b392114c45266ecef901bfd59470842a
- wget https://gist.githubusercontent.com/timurt/a981d094cbbbe746ecd400424f5f3af8/raw/6e5d28a83b0d63a880f897d839f7f536b64f0979/pgjdbc.patch
- git apply pgjdbc.patch
- mvn compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
- cd ../../
- rm -rf pgjdbc
+ ./.ci/wercker.sh no-error-pgjdbc
else
echo "build is skipped ..."
fi
- # NoErrorTest - Orekit (oraclejdk8)
- script:
name: NoErrorTest - Orekit
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/Hipparchus-Math/hipparchus.git && break || sleep 15; done
- cd hipparchus
- git checkout 905006092493e350dcd68dd7b2ec1dedaf4983b7
- mvn clean install -DskipTests
- cd ../
- for i in 1 2 3 4 5; do git clone https://github.com/CS-SI/Orekit.git && break || sleep 15; done
- cd Orekit
- git checkout f7abe7ea0c7fbf6d138ed7eaf9487510dfbbcaac
- wget https://gist.githubusercontent.com/timurt/7c45454a233ce775a7e5acaa1231d845/raw/225ef24f84e671b501caeef8279dc1363869d5ae/orekit.patch
- git apply orekit.patch
- mvn compile checkstyle:check -Dorekit.checkstyle.version=${CS_POM_VERSION}
- cd ../
- rm -rf hipparchus Orekit
+ ./.ci/wercker.sh no-error-orekit
else
echo "build is skipped ..."
fi
- # NoErrorTest - XWiki (oraclejdk8)
- script:
name: NoErrorTest - XWiki
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/xwiki/xwiki-commons/ && break || sleep 15; done
- cd xwiki-commons
- git checkout 44b0c0048c516dae20cf5f8a71181af836549484
- mvn install -DskipTests -Dxwiki.clirr.skip=true checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
- cd ../../
- rm -rf xwiki-commons
+ ./.ci/wercker.sh no-error-xwiki
else
echo "build is skipped ..."
fi
- # NoErrorTest - Apache Apex (oraclejdk8)
- script:
name: NoErrorTest - Apache Apex
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/apache/incubator-apex-core/ && break || sleep 15; done
- cd incubator-apex-core
- mvn compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
- cd ../
- rm -rf incubator-apex-core
+ ./.ci/wercker.sh no-error-apex-core
else
echo "build is skipped ..."
fi
- # NoErrorTest - Hibernate Search (oraclejdk8)
- script:
name: NoErrorTest - Hibernate Search
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/hibernate/hibernate-search.git && break || sleep 15; done
- cd hibernate-search
- mvn -s settings-example.xml clean install -DskipTests=true -Dtest.elasticsearch.host.provided=true -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION}
- mvn -s settings-example.xml checkstyle:check -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION}
- cd ../
- rm -rf hibernate-search
+ ./.ci/wercker.sh no-error-hibernate-search
else
echo "build is skipped ..."
fi
- # NoErrorTest - HtmlUnit (oraclejdk8)
- script:
name: NoErrorTest - HtmlUnit
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- echo "checkouting project sources ..."
- svn -q export https://svn.code.sf.net/p/htmlunit/code/trunk/htmlunit@r14923 htmlunit
- cd htmlunit
- sed -i "s/ <version>2.28-SNAPSHOT/ <version>2.28-20171106.080245-12/" pom.xml
- echo "Running checkstyle validation ..."
- mvn compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION}
- cd ../
- rm -rf htmlunit
+ ./.ci/wercker.sh no-error-htmlunit
else
echo "build is skipped ..."
fi
- # NoErrorTest - checkstyle's sevntu
- script:
name: NoErrorTest - checkstyle's sevntu
code: |
- if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- mvn compile verify -Dmaven.sevntu-checkstyle-check.checkstyle.version=${CS_POM_VERSION} -Dmaven.test.skip=true -Dcheckstyle.ant.skip=true -Dpmd.skip=true -Dfindbugs.skip=true -Dcobertura.skip=true -Dforbiddenapis.skip=true -Dxml.skip=true
+ if [[ 'true' == 'false' ]]; then
+ ./.ci/wercker.sh no-error-checkstyles-sevntu
else
echo "build is skipped ..."
fi
- # NoErrorTest - sevntu-checks
- - script:
- name: NoErrorTest - sevntu-checks
- code: |
- if [[ $SKIP_CI == 'false' ]]; then
- set -e
- CS_POM_VERSION=$(mvn -q -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive org.codehaus.mojo:exec-maven-plugin:1.3.1:exec)
- echo CS_version: ${CS_POM_VERSION}
- for i in 1 2 3 4 5; do git clone https://github.com/sevntu-checkstyle/sevntu.checkstyle && break || sleep 15; done
- cd sevntu.checkstyle/sevntu-checks
- mvn -Pno-validations verify -Dcheckstyle.skip=false -Dcheckstyle.version=${CS_POM_VERSION} -Dcheckstyle.configLocation=../../config/checkstyle_checks.xml
- else
- echo "build is skipped ..."
- fi
+# - script:
+# name: NoErrorTest - sevntu-checks
+# code: |
+# if [[ $SKIP_CI == 'false' ]]; then
+# ./.ci/wercker.sh no-error-sevntu-checks
+# else
+# echo "build is skipped ..."
+# fi
- # NoExceptiontest - Apache Struts (oraclejdk8)
- script:
name: NoExceptiontest - Apache Struts
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#apache-struts/apache-struts/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-struts
else
echo "build is skipped ..."
fi
- # NoExceptiontest - Checkstyle ,sevntu-checkstyle (oraclejdk8)
- script:
name: NoExceptiontest - Checkstyle ,sevntu-checkstyle
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#checkstyle/checkstyle/' projects-for-wercker.properties
- sed -i'' 's/#sevntu-checkstyle/sevntu-checkstyle/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-checkstyle-sevntu
else
echo "build is skipped ..."
fi
- # NoExceptiontest - Guava (oraclejdk8)
- script:
name: NoExceptiontest - Guava
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#guava/guava/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-guava
else
echo "build is skipped ..."
fi
- # NoExceptiontest - Hibernate (oraclejdk8)
- script:
name: NoExceptiontest - Hibernate
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#hibernate-orm/hibernate-orm/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-hibernate-orm
else
echo "build is skipped ..."
fi
- # NoExceptiontest - Findbugs (oraclejdk8)
- script:
name: NoExceptiontest - findbugs
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#findbugs/findbugs/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-findbugs
else
echo "build is skipped ..."
fi
- # NoExceptiontest - spring-framework (oraclejdk8)
- script:
name: NoExceptiontest - spring-framework
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#spring-framework/spring-framework/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-spring-framework
else
echo "build is skipped ..."
fi
- # NoExceptiontest - Hbase (oraclejdk8)
- script:
name: NoExceptiontest - Hbase
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#Hbase/Hbase/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-hbase
else
echo "build is skipped ..."
fi
- # NoExceptiontest - pmd elasticsearch lombok-ast (oraclejdk8)
- script:
name: NoExceptiontest - pmd elasticsearch lombok-ast
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#pmd/pmd/' projects-for-wercker.properties
- sed -i'' 's/#elasticsearch/elasticsearch/' projects-for-wercker.properties
- sed -i'' 's/#lombok-ast/lombok-ast/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-Pmd-elasticsearch-lombok-ast
else
echo "build is skipped ..."
fi
- # NoExceptiontest - RxJava java-design-patterns MaterialDesignLibrary apache-ant apache-jsecurity android-launcher (oraclejdk8)
- script:
name: NoExceptiontest - RxJava java-design-patterns MaterialDesignLibrary apache-ant apache-jsecurity android-launcher
code: |
if [[ $SKIP_CI == 'false' ]]; then
- set -e
- for i in 1 2 3 4 5; do git clone https://github.com/checkstyle/contribution && break || sleep 15; done
- cd contribution/checkstyle-tester
- sed -i'' 's/^guava/#guava/' projects-for-wercker.properties
- sed -i'' 's/#RxJava/RxJava/' projects-for-wercker.properties
- sed -i'' 's/#Vavr/Vavr/' projects-for-wercker.properties
- sed -i'' 's/#java-design-patterns/java-design-patterns/' projects-for-wercker.properties
- sed -i'' 's/#MaterialDesignLibrary/MaterialDesignLibrary/' projects-for-wercker.properties
- sed -i'' 's/#apache-ant/apache-ant/' projects-for-wercker.properties
- sed -i'' 's/#apache-jsecurity/apache-jsecurity/' projects-for-wercker.properties
- sed -i'' 's/#android-launcher/android-launcher/' projects-for-wercker.properties
- groovy ./launch.groovy --listOfProjects projects-for-wercker.properties --config checks-nonjavadoc-error.xml
- cd ../../
- rm -rf contribution
+ ./.ci/wercker.sh no-exception-alot-of-projects
else
echo "build is skipped ..."
fi
- # Cleanup
- script:
name: Cleanup maven local repo
code: |