diff --git a/.ci/jsoref-spellchecker/exclude.pl b/.ci/jsoref-spellchecker/exclude.pl index 2579c0d0b7e..70f8f249181 100755 --- a/.ci/jsoref-spellchecker/exclude.pl +++ b/.ci/jsoref-spellchecker/exclude.pl @@ -4,6 +4,7 @@ # output is null delimited to match input $/="\0"; my @excludes=qw( + \.png$ (^|/)images/ ^src/it/resources/ ^src/test/resources/ diff --git a/.ci/jsoref-spellchecker/whitelist.words b/.ci/jsoref-spellchecker/whitelist.words index 016c13fb9e7..c93de6c4de3 100644 --- a/.ci/jsoref-spellchecker/whitelist.words +++ b/.ci/jsoref-spellchecker/whitelist.words @@ -352,6 +352,7 @@ Dstrict Dtest Dubinin Duser +Dversion Dxml eb ecj @@ -1060,6 +1061,7 @@ propertycachefile prot PROTECTE protonpack +Pstatic pubconstr pubifc PUBLI diff --git a/.ci/no-exception-test.sh b/.ci/no-exception-test.sh index dc7ae2a77dd..7fabf17e7c8 100755 --- a/.ci/no-exception-test.sh +++ b/.ci/no-exception-test.sh @@ -14,7 +14,6 @@ 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 -e --no-transfer-progress clean install -Pno-validations cp src/main/resources/google_checks.xml .ci-temp/google_checks.xml sed -i.'' 's/warning/ignore/' .ci-temp/google_checks.xml cd .ci-temp/contribution/checkstyle-tester @@ -37,7 +36,6 @@ guava-with-sun-checks) sed -i.'' 's/^guava/#guava/' projects-to-test-on.properties sed -i.'' 's/#guava|/guava|/' projects-to-test-on.properties cd ../../../ - mvn -e --no-transfer-progress clean install -Pno-validations cp src/main/resources/sun_checks.xml .ci-temp/sun_checks.xml sed -i.'' 's/value=\"error\"/value=\"ignore\"/' .ci-temp/sun_checks.xml cd .ci-temp/contribution/checkstyle-tester diff --git a/.ci/pitest.sh b/.ci/pitest.sh index c0178c9a7e9..544b79b16ff 100755 --- a/.ci/pitest.sh +++ b/.ci/pitest.sh @@ -38,20 +38,19 @@ pitest-annotation|pitest-design \ |pitest-packagenamesloader \ |pitest-common-2|pitest-misc|pitest-xpath \ |pitest-filters \ -|pitest-coding \ |pitest-regexp \ |pitest-meta \ |pitest-tree-walker \ |pitest-utils \ |pitest-java-ast-visitor) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=(); checkPitestReport "${ignoredItems[@]}" ;; # till #9351 pitest-main) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "Main.java.html:
        }
" ); @@ -59,7 +58,7 @@ pitest-main) ;; pitest-header) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "RegexpHeaderCheck.java.html:
                    isMatch = headerLineNo == headerSize
" "RegexpHeaderCheck.java.html:
                            || isMatch(line, headerLineNo);
" @@ -68,7 +67,7 @@ pitest-header) ;; pitest-imports) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "ImportControlLoader.java.html:
        else if (ALLOW_ELEMENT_NAME.equals(qName) || "disallow".equals(qName)) {
" "PkgImportControl.java.html:
        if (regex || parent.regex) {
" @@ -78,7 +77,7 @@ pitest-imports) ;; pitest-common) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "Checker.java.html:
                if (cacheFile != null && cacheFile.isInCache(fileName, timestamp)
" "DefaultLogger.java.html:
        closeError = errorStreamOptions == OutputStreamOptions.CLOSE;
" @@ -95,7 +94,7 @@ pitest-common) pitest-ant) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" "CheckstyleAntTask.java.html:
            if (toFile == null || !useFile) {
" @@ -107,7 +106,7 @@ pitest-ant) ;; pitest-indentation) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "AbstractExpressionHandler.java.html:
                    && curNode.getColumnNo() < realStart.getColumnNo()) {
" "AbstractExpressionHandler.java.html:
            if (colNum == null || thisLineColumn < colNum) {
" @@ -137,7 +136,7 @@ pitest-indentation) ;; pitest-javadoc) - mvn --no-transfer-progress -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; declare -a ignoredItems=( "AbstractJavadocCheck.java.html:
        beginJavadocTree(root);
" "AbstractJavadocCheck.java.html:
        finishJavadocTree(root);
" @@ -146,8 +145,63 @@ pitest-javadoc) checkPitestReport "${ignoredItems[@]}" ;; +pitest-coding) + mvn --no-transfer-progress -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; + declare -a ignoredItems=( + "FinalLocalVariableCheck.java.html:
                            && isSameVariables(storedVariable, variable)
" + "FinalLocalVariableCheck.java.html:
                        == ast.getParent()) {
" + "FinalLocalVariableCheck.java.html:
                if (ast.getParent().getType() == TokenTypes.SWITCH_RULE
" + "FinalLocalVariableCheck.java.html:
            if (astIterator.getType() == childType
" + "FinalLocalVariableCheck.java.html:
            if (storedVariable != null && isSameVariables(storedVariable, ast)) {
" + "FinalLocalVariableCheck.java.html:
            result = findLastChildWhichContainsSpecifiedToken(
" + "FinalLocalVariableCheck.java.html:
        return ast.getType() == TokenTypes.LITERAL_IF
" + "FinalLocalVariableCheck.java.html:
        return loop1 != null && loop1 == loop2;
" + "HiddenFieldCheck.java.html:
                && ast.getType() == TokenTypes.PARAMETER_DEF) {
" + "HiddenFieldCheck.java.html:
                && firstChild.getType() == TokenTypes.IDENT) {
" + "HiddenFieldCheck.java.html:
                && methodAST.getType() == TokenTypes.METHOD_DEF
" + "HiddenFieldCheck.java.html:
            if (method.getType() == TokenTypes.METHOD_DEF) {
" + "HiddenFieldCheck.java.html:
            return instanceFields.contains(field)
" + "HiddenFieldCheck.java.html:
        if (ignoreSetter && ast.getType() == TokenTypes.PARAMETER_DEF) {
" + "HiddenFieldCheck.java.html:
        if (type == TokenTypes.CLASS_DEF
" + "IllegalInstantiationCheck.java.html:
            && illegal.startsWith(JAVA_LANG)) {
" + "OneStatementPerLineCheck.java.html:
                        && currentStatement.getPreviousSibling().getType() == TokenTypes.RESOURCES;
" + "OneStatementPerLineCheck.java.html:
                currentStatement.getPreviousSibling() != null
" + "OneStatementPerLineCheck.java.html:
                if (countOfSemiInLambda.isEmpty()) {
" + "OneStatementPerLineCheck.java.html:
            multiline = !TokenUtil.areOnSameLine(prevSibling, ast)
" + "OneStatementPerLineCheck.java.html:
        if (!hasResourcesPrevSibling && isMultilineStatement(currentStatement)) {
" + "RequireThisCheck.java.html:
                        && ast.getParent().getType() != TokenTypes.LITERAL_CATCH) {
" + "RequireThisCheck.java.html:
                if (isAnonymousClassDef(ast)) {
" + "RequireThisCheck.java.html:
                if (toVisit == null) {
" + "RequireThisCheck.java.html:
               && parent.getType() != TokenTypes.CTOR_DEF
" + "RequireThisCheck.java.html:
            && lastChild.getType() == TokenTypes.OBJBLOCK;
" + "RequireThisCheck.java.html:
            if (definitionToken.getType() == TokenTypes.STATIC_INIT) {
" + "RequireThisCheck.java.html:
            if (elistToken != null && ident.getText().equals(ast.getText())) {
" + "RequireThisCheck.java.html:
            if (lookForMethod && containsMethod(nameToFind)
" + "RequireThisCheck.java.html:
            if (variableDeclarationFrame.getType() == FrameType.CLASS_FRAME) {
" + "RequireThisCheck.java.html:
        if (fieldUsageFrame.getType() == FrameType.BLOCK_FRAME) {
" + "RequireThisCheck.java.html:
        if (sibling != null && isAssignToken(parent.getType())) {
" + "RequireThisCheck.java.html:
        return left.getType() == right.getType() && left.getText().equals(right.getText());
" + "UnnecessaryParenthesesCheck.java.html:
            || parent.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) {
" + "UnnecessaryParenthesesCheck.java.html:
        else if (type != TokenTypes.ASSIGN
" + "UnnecessaryParenthesesCheck.java.html:
        if (firstChild != null && firstChild.getType() == TokenTypes.LPAREN) {
" + "UnnecessaryParenthesesCheck.java.html:
        if (type != TokenTypes.ASSIGN
" + "UnnecessaryParenthesesCheck.java.html:
        if (type == TokenTypes.LAMBDA && isLambdaSingleParameterSurrounded(ast)) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
                && currentAst.getType() != TokenTypes.RCURLY) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
                && currentNode.getType() == TokenTypes.LITERAL_CATCH) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
                && currentStatementAst.getType() != TokenTypes.RCURLY) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
                else if (isChild(currentNode, variable)) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
                if (currentNode.getType() == TokenTypes.LITERAL_IF) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
            if (curNode.getType() == ast.getType() && curNode.getText().equals(ast.getText())) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
            if (currentNodeType == TokenTypes.SLIST) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
        if (!firstUsageFound) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
        if (!isVarInOperatorDeclaration && operator.getType() == TokenTypes.LITERAL_IF) {
" + "VariableDeclarationUsageDistanceCheck.java.html:
        while (result
" + ); + checkPitestReport "${ignoredItems[@]}" + ;; + # pitesttyle-gui) -# mvn -e -P$1 clean test org.pitest:pitest-maven:mutationCoverage; +# mvn -e -P$1 clean test-compile org.pitest:pitest-maven:mutationCoverage; # # post validation is skipped, we do not test gui throughly # ;; diff --git a/.ci/travis.sh b/.ci/travis.sh index 06258a13424..d57bad4f3d2 100755 --- a/.ci/travis.sh +++ b/.ci/travis.sh @@ -40,6 +40,13 @@ install-custom-mvn) fi ;; +remove-custom-mvn) + if [[ -n "${CUSTOM_MVN_VERSION}" ]]; then + rm apache-maven-${CUSTOM_MVN_VERSION}-bin.zip + rm -rf apache-maven-${CUSTOM_MVN_VERSION} + fi + ;; + run-command) if [[ $RUN_JOB == 1 ]]; then echo "eval of CMD is starting"; diff --git a/.ci/validation.sh b/.ci/validation.sh index 5e78a6ecaa9..3a3f26a941e 100755 --- a/.ci/validation.sh +++ b/.ci/validation.sh @@ -85,16 +85,6 @@ eclipse-static-analysis) mvn -e --no-transfer-progress clean compile exec:exec -Peclipse-compiler ;; -eclipse-static-analysis-java11) - # Ensure that project sources can be compiled by eclipse with Java11 language features. - mvn -e --no-transfer-progress clean compile exec:exec -Peclipse-compiler -D java.version=11 - ;; - -java11-verify) - # Ensure that project sources can be compiled by jdk with Java11 language features. - mvn -e --no-transfer-progress clean verify -D java.version=11 - ;; - nondex) # Below we exclude test that fails due to picocli library usage mvn -e --no-transfer-progress --fail-never clean nondex:nondex -DargLine='-Xms1024m -Xmx2048m' \ @@ -479,7 +469,7 @@ check-since-version) fi ;; -javac8) +javac11) # InputCustomImportOrderNoPackage2 - nothing is required in front of first import # InputIllegalTypePackageClassName - bad import for testing # InputVisibilityModifierPackageClassName - bad import for testing @@ -496,20 +486,6 @@ javac8) done ;; -javac9) - files=($(grep -Rl --include='*.java' ': Compilable with Java9' \ - src/test/resources-noncompilable || true)) - if [[ ${#files[@]} -eq 0 ]]; then - echo "No Java9 files to process" - else - mkdir -p target - for file in "${files[@]}" - do - javac --release 9 -d target "${file}" - done - fi - ;; - javac14) files=($(grep -Rl --include='*.java' ': Compilable with Java14' \ src/test/resources-noncompilable || true)) @@ -610,7 +586,7 @@ no-error-pgjdbc) checkout_from https://github.com/pgjdbc/pgjdbc.git cd .ci-temp/pgjdbc # pgjdbc easily damage build, we should use stable versions - git checkout "3a2bb""d77969903f8a4ce721d45905c72bd1688d6" + git checkout "417c9a2354ad""c3d2c80f84b0a5059ce""ad92e7c2b" ./gradlew --no-parallel --no-daemon checkstyleAll \ -PenableMavenLocal -Pcheckstyle.version=${CS_POM_VERSION} cd ../ @@ -632,7 +608,7 @@ no-error-orekit) # no CI is enforced in project, so to make our build stable we should # checkout to latest release/development (annotated tag or hash) or sha that have fix we need # git checkout $(git describe --abbrev=0 --tags) - git checkout "76760bf""bf""b847e227490cd5d3662f""ca087f1a324" + git checkout "851de782c6""d16d""f725fa""bb4646ff0dd086723415" mvn -e --no-transfer-progress compile checkstyle:check \ -Dorekit.checkstyle.version=${CS_POM_VERSION} cd .. @@ -645,10 +621,12 @@ no-error-hibernate-search) echo CS_version: ${CS_POM_VERSION} checkout_from https://github.com/hibernate/hibernate-search.git cd .ci-temp/hibernate-search - mvn -e --no-transfer-progress clean install -DskipTests=true -Dtest.elasticsearch.run.skip=true \ + mvn -e --no-transfer-progress clean install -pl build/config -am \ + -DskipTests=true -Dmaven.compiler.failOnWarning=false \ -Dcheckstyle.skip=true -Dforbiddenapis.skip=true \ - -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION} - mvn -e --no-transfer-progress checkstyle:check -Dpuppycrawl.checkstyle.version=${CS_POM_VERSION} + -Dversion.com.puppycrawl.tools.checkstyle=${CS_POM_VERSION} + mvn -e --no-transfer-progress checkstyle:check \ + -Dversion.com.puppycrawl.tools.checkstyle=${CS_POM_VERSION} cd ../ removeFolderWithProtectedFiles hibernate-search ;; @@ -724,7 +702,8 @@ no-error-equalsverifier) echo CS_version: ${CS_POM_VERSION} checkout_from https://github.com/jqno/equalsverifier.git cd .ci-temp/equalsverifier - mvn -e --no-transfer-progress compile checkstyle:check -Dcheckstyle.version=${CS_POM_VERSION} + mvn -e --no-transfer-progress -Pstatic-analysis-checkstyle compile \ + checkstyle:check -Dversion.checkstyle=${CS_POM_VERSION} cd ../ removeFolderWithProtectedFiles equalsverifier ;; diff --git a/.circleci/config.yml b/.circleci/config.yml index c02379d8c6b..4171c9aae29 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ jobs: no-exception-lucene-and-others-javadoc: docker: - - image: checkstyle/jdk-8-groovy-git-mvn:1.8.0_282-3.0.8-2.25.1-3.6.3 + - image: &default-image checkstyle/jdk-11-groovy-git-mvn:11.0.13__3.0.9__2.25.1__3.6.3 steps: - checkout - run: @@ -11,7 +11,7 @@ jobs: ./.ci/no-exception-test.sh no-exception-lucene-and-others-javadoc no-exception-cassandra-storm-tapestry-javadoc: docker: - - image: checkstyle/jdk-8-groovy-git-mvn:1.8.0_282-3.0.8-2.25.1-3.6.3 + - image: *default-image steps: - checkout - run: @@ -19,7 +19,7 @@ jobs: ./.ci/no-exception-test.sh no-exception-cassandra-storm-tapestry-javadoc no-exception-hadoop-apache-groovy-scouter-javadoc: docker: - - image: checkstyle/jdk-8-groovy-git-mvn:1.8.0_282-3.0.8-2.25.1-3.6.3 + - image: *default-image steps: - checkout - run: @@ -27,7 +27,7 @@ jobs: ./.ci/no-exception-test.sh no-exception-hadoop-apache-groovy-scouter-javadoc no-exception-only-javadoc: docker: - - image: checkstyle/jdk-8-groovy-git-mvn:1.8.0_282-3.0.8-2.25.1-3.6.3 + - image: *default-image steps: - checkout - run: @@ -35,7 +35,7 @@ jobs: ./.ci/no-exception-test.sh no-exception-only-javadoc no-error-xwiki: docker: - - image: checkstyle/jdk-11-groovy-git-mvn:11.0.13__3.0.9__2.25.1__3.6.3 + - image: *default-image steps: - checkout - run: diff --git a/.drone.yml b/.drone.yml index dc46d6fcd12..04a46d4770c 100644 --- a/.drone.yml +++ b/.drone.yml @@ -8,7 +8,7 @@ volumes: steps: - name: restore-cache - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 failure: ignore volumes: - name: m2-cache @@ -17,7 +17,7 @@ steps: - ./.ci/drone-io.sh restore-maven-cache - name: checkstyle-and-sevntu - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -27,7 +27,7 @@ steps: - ./.ci/validation.sh checkstyle-and-sevntu - name: spotbugs-and-pmd - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -46,7 +46,7 @@ volumes: steps: - name: restore-cache - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 failure: ignore volumes: - name: m2-cache @@ -55,7 +55,7 @@ steps: - ./.ci/drone-io.sh restore-maven-cache - name: site - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -75,7 +75,7 @@ volumes: steps: - name: restore-cache - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 failure: ignore volumes: - name: m2-cache @@ -84,7 +84,7 @@ steps: - ./.ci/drone-io.sh restore-maven-cache - name: release-dry-run - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -94,7 +94,7 @@ steps: - ./.ci/validation.sh release-dry-run - name: assembly-run-all-jar - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -113,7 +113,7 @@ volumes: steps: - name: restore-cache - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 failure: ignore volumes: - name: m2-cache @@ -122,7 +122,7 @@ steps: - ./.ci/drone-io.sh restore-maven-cache - name: releasenotes-gen - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: READ_ONLY_TOKEN: from_secret: READ_ONLY_TOKEN @@ -139,25 +139,19 @@ name: non-mvn_javac steps: - name: check-chmod - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 commands: - ./.ci/checkchmod.sh - name: check-since-version - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image commands: - ./.ci/validation.sh check-since-version -- name: javac8 - image: maven:3.6.3-adoptopenjdk-8 +- name: javac11 + image: *default-image commands: - - ./.ci/validation.sh javac8 - - -- name: javac9 - image: maven:3.6.3-jdk-11 - commands: - - ./.ci/validation.sh javac9 + - ./.ci/validation.sh javac11 - name: javac14 image: maven:3.6.3-adoptopenjdk-14 @@ -189,7 +183,7 @@ volumes: steps: - name: restore-cache - image: maven:3.6.3-adoptopenjdk-8 + image: &default-image maven:3.8.4-openjdk-11 failure: ignore volumes: - name: m2-cache @@ -208,7 +202,7 @@ steps: - ./.ci/validation.sh jdk14-assembly-site - name: assembly/site with OpenJDK11 - image: maven:3.6.3-adoptopenjdk-11 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: @@ -219,7 +213,7 @@ steps: mvn -e --no-transfer-progress site -Dlinkcheck.skip=true" - name: no-error-test-sbe - image: maven:3.6.3-adoptopenjdk-8 + image: *default-image environment: MAVEN_OPTS: "-Dmaven.repo.local=/.m2" volumes: diff --git a/.github/workflows/no-exception-workflow.yml b/.github/workflows/no-exception-workflow.yml index 754dfae9e47..7781a90a184 100644 --- a/.github/workflows/no-exception-workflow.yml +++ b/.github/workflows/no-exception-workflow.yml @@ -9,10 +9,10 @@ jobs: no-exception-openjdk17: runs-on: ubuntu-latest steps: - - name: Set up JDK 8 + - name: Set up JDK 11 uses: actions/setup-java@v1 with: - java-version: 8 + java-version: 11 - name: Install dependencies run: sudo apt install groovy diff --git a/.github/workflows/pitest.yml b/.github/workflows/pitest.yml index c0c71ecfcb9..3b0f989a66c 100644 --- a/.github/workflows/pitest.yml +++ b/.github/workflows/pitest.yml @@ -335,10 +335,10 @@ jobs: pitest-main: runs-on: ubuntu-latest steps: - - name: Set up JDK 8 + - name: Set up JDK 11 uses: actions/setup-java@v1 with: - java-version: 8 + java-version: 11 - name: Setup local maven cache uses: actions/cache@v2 with: @@ -642,10 +642,10 @@ jobs: - uses: actions/checkout@v2 with: ref: ${{ github.event.pull_request.head.sha }} - - name: Set up JDK 8 + - name: Set up JDK 11 uses: actions/setup-java@v1 with: - java-version: 8 + java-version: 11 - name: Generate pitest report run: ./.ci/pitest.sh pitest-java-ast-visitor diff --git a/.semaphore/semaphore.yml b/.semaphore/semaphore.yml index de06658d38d..f613cdb69b0 100644 --- a/.semaphore/semaphore.yml +++ b/.semaphore/semaphore.yml @@ -3,7 +3,7 @@ name: "Checkstyle CI pipeline on Semaphore" agent: machine: type: e1-standard-2 - os_image: ubuntu1804 + os_image: ubuntu2004 auto_cancel: running: when: "branch != 'master'" @@ -27,20 +27,21 @@ blocks: cache store m2 $HOME/.m2 fi jobs: - - name: NonDex (openjdk8) - priority: - - value: 90 - when: true - matrix: - - env_var: CMD - values: - - .ci/validation.sh nondex - commands: - - sem-version java 8 # NonDex only supports Java 8 - - echo "eval of CMD is starting"; - - echo "CMD=$CMD"; - - eval $CMD; - - echo "eval of CMD is completed"; + # NonDex supports only Java 8 till https://github.com/TestingResearchIllinois/NonDex/pull/155 + # - name: NonDex (openjdk11) + # priority: + # - value: 90 + # when: true + # matrix: + # - env_var: CMD + # values: + # - .ci/validation.sh nondex + # commands: + # - sem-version java 11 + # - echo "eval of CMD is starting"; + # - echo "CMD=$CMD"; + # - eval $CMD; + # - echo "eval of CMD is completed"; - name: Validation (openjdk11, fast pool) matrix: @@ -49,13 +50,9 @@ blocks: - .ci/validation.sh all-sevntu-checks - .ci/validation.sh check-missing-pitests - .ci/validation.sh eclipse-static-analysis - - .ci/validation.sh eclipse-static-analysis-java11 - - .ci/validation.sh java11-verify - .ci/validation.sh verify-regexp-id - - mvn -e --no-transfer-progress clean install -Pno-validations - && .ci/no-exception-test.sh guava-with-google-checks - - mvn -e --no-transfer-progress clean install -Pno-validations - && .ci/no-exception-test.sh guava-with-sun-checks + - .ci/no-exception-test.sh guava-with-google-checks + - .ci/no-exception-test.sh guava-with-sun-checks # until https://github.com/checkstyle/checkstyle/issues/9807 # - mvn -e --no-transfer-progress clean package -Passembly # && .ci/validation.sh no-violation-test-josm diff --git a/.travis.yml b/.travis.yml index 9f3f94fbcb1..f0c6277fc4a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -26,8 +26,8 @@ jobs: include: # this job do deploy maven repository - # unit tests (openjdk8) - - jdk: openjdk8 + # unit tests (openjdk11) + - jdk: openjdk11 env: - DESC="tests and deploy" - CMD="mvn -e --no-transfer-progress clean integration-test failsafe:verify @@ -43,7 +43,7 @@ jobs: # - CMD2="./.ci/validation.sh verify-no-exception-configs" # - CMD="$CMD1 && $CMD2" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - Postgresql JDBC Driver" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -51,7 +51,7 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - Orekit" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -62,7 +62,7 @@ jobs: - jdk: openjdk11 env: - DESC="NoErrorTest - Hibernate Search" - - CUSTOM_MVN_VERSION="3.8.1" + - CUSTOM_MVN_VERSION="3.8.4" - M2_HOME="$PWD/apache-maven-${CUSTOM_MVN_VERSION}" - PATH="$M2_HOME/bin:$PATH" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -70,7 +70,7 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - checkstyle's sevntu" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -78,7 +78,7 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - sevntu-checks" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -86,7 +86,7 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - contribution" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -94,7 +94,7 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - methods distance" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" @@ -102,28 +102,29 @@ jobs: - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - - jdk: openjdk8 + - jdk: openjdk11 env: - DESC="NoErrorTest - Spring Cloud GCP" - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" - CMD2="./.ci/validation.sh no-error-spring-cloud-gcp" - CMD="$CMD1 && $CMD2" - USE_MAVEN_REPO="true" - # until https://github.com/jqno/equalsverifier/issues/586 - # - jdk: openjdk8 - # env: - # - DESC="NoErrorTest - EqualsVerifier" - # - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" - # - CMD2="./.ci/validation.sh no-error-equalsverifier" - # - CMD="$CMD1 && $CMD2" - # - USE_MAVEN_REPO="true" + + - jdk: openjdk11 + env: + - DESC="NoErrorTest - EqualsVerifier" + - CMD1="mvn -e --no-transfer-progress clean install -Pno-validations" + - CMD2="./.ci/validation.sh no-error-equalsverifier" + - CMD="$CMD1 && $CMD2" + - USE_MAVEN_REPO="true" script: - ./.ci/travis.sh init-m2-repo - ./.ci/travis.sh run-command "$CMD" + - ./.ci/travis.sh remove-custom-mvn + - ./.ci/travis.sh git-diff + - ./.ci/travis.sh ci-temp-check after_success: - ./.ci/travis.sh run-command-after-success - ./.ci/travis.sh deploy-snapshot - - ./.ci/travis.sh git-diff - - ./.ci/travis.sh ci-temp-check diff --git a/appveyor.yml b/appveyor.yml index 524237042a6..ced9cb79325 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -11,21 +11,21 @@ branches: install: - ps: | Add-Type -AssemblyName System.IO.Compression.FileSystem - if (!(Test-Path -Path "C:\maven\apache-maven-3.8.1" )) { + if (!(Test-Path -Path "C:\maven\apache-maven-3.8.4" )) { (new-object System.Net.WebClient).DownloadFile( - 'https://downloads.apache.org/maven/maven-3/3.8.1/binaries/apache-maven-3.8.1-bin.zip', + 'https://downloads.apache.org/maven/maven-3/3.8.4/binaries/apache-maven-3.8.4-bin.zip', 'C:\maven-bin.zip' ) [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") } - - cmd: SET M2_HOME=C:\maven\apache-maven-3.8.1 + - cmd: SET M2_HOME=C:\maven\apache-maven-3.8.4 - cmd: SET PATH=%M2_HOME%\bin;%JAVA_HOME%\bin;%PATH% - cmd: git config core.autocrlf - cmd: mvn --version - cmd: java -version cache: - - C:\maven\apache-maven-3.8.1 + - C:\maven\apache-maven-3.8.4 - C:\Users\appveyor\.m2 matrix: @@ -39,26 +39,14 @@ environment: # We do matrix as AppVeyor could fail to finish simple "mvn -e verify" # if he loose maven cache (happens from time to time) matrix: - # checkstyle and sevntu.checkstyle (JDK8) - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "checkstyle and sevntu.checkstyle (JDK8)" - CMD: "./.ci/validation.cmd sevntu" # checkstyle and sevntu.checkstyle (JDK11) - JAVA_HOME: C:\Program Files\Java\jdk11 DESC: "checkstyle and sevntu.checkstyle (JDK11)" CMD: "./.ci/validation.cmd sevntu" - # verify without checkstyle (JDK8) - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "verify without checkstyle (JDK8)" - CMD: "./.ci/validation.cmd verify_without_checkstyle" # verify without checkstyle (JDK11) - JAVA_HOME: C:\Program Files\Java\jdk11 DESC: "verify without checkstyle (JDK11)" CMD: "./.ci/validation.cmd verify_without_checkstyle" - # site, without verify (JDK8) - - JAVA_HOME: C:\Program Files\Java\jdk1.8.0 - DESC: "site, without verify (JDK8)" - CMD: "./.ci/validation.cmd site_without_verify" # site, without verify (JDK11) - JAVA_HOME: C:\Program Files\Java\jdk11 DESC: "site, without verify (JDK11)" @@ -79,5 +67,5 @@ build_script: Write-Host "build is skipped ..." } - ps: echo "Size of caches (bytes):" - - ps: Get-ChildItem -Recurse 'C:\maven\apache-maven-3.8.1' | Measure-Object -Property Length -Sum + - ps: Get-ChildItem -Recurse 'C:\maven\apache-maven-3.8.4' | Measure-Object -Property Length -Sum - ps: Get-ChildItem -Recurse 'C:\Users\appveyor\.m2' | Measure-Object -Property Length -Sum diff --git a/azure-pipelines.yml b/azure-pipelines.yml index df295c49e18..d1478e46aac 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -30,47 +30,47 @@ strategy: cmd: "./.ci/test-spelling-unknown-words.sh" skipCache: true - # unit tests (openjdk8) + # unit tests (openjdk11) 'test': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test" - # unit tests in German locale (openjdk8) + # unit tests in German locale (openjdk11) 'test-de': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-de" - # unit tests in Spanish locale (openjdk8) + # unit tests in Spanish locale (openjdk11) 'test-es': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-es" - # unit tests in Finnish locale (openjdk8) + # unit tests in Finnish locale (openjdk11) 'test-fi': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-fi" - # unit tests in French locale (openjdk8) + # unit tests in French locale (openjdk11) 'test-fr': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-fr" - # unit tests in Chinese locale (openjdk8) + # unit tests in Chinese locale (openjdk11) 'test-zh': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-zh" - # unit tests in Japanese locale (openjdk8) + # unit tests in Japanese locale (openjdk11) 'test-ja': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-ja" - # unit tests in Portuguese locale (openjdk8) + # unit tests in Portuguese locale (openjdk11) 'test-pt': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-pt" - # unit tests in Turkish locale (openjdk8) + # unit tests in Turkish locale (openjdk11) 'test-tr': image: 'ubuntu-20.04' cmd: "./.ci/validation.sh test-tr" @@ -80,25 +80,15 @@ strategy: image: 'ubuntu-20.04' cmd: "mvn -e --no-transfer-progress verify" - # MacOS JDK8 verify - 'MacOS JDK8 verify': - image: 'macOS-10.15' - cmd: "export JAVA_HOME=$JAVA_HOME_8_X64 && mvn -e --no-transfer-progress verify" - # MacOS JDK11 verify 'MacOS JDK11 verify': image: 'macOS-10.15' - cmd: "export JAVA_HOME=$JAVA_HOME_11_X64 && mvn -e --no-transfer-progress verify" - - # MacOS JDK13 verify - 'MacOS JDK13 verify': - image: 'macOS-10.15' - cmd: "export JAVA_HOME=$JAVA_HOME_13_X64 && mvn -e --no-transfer-progress verify" + cmd: "JAVA_HOME=$JAVA_HOME_11_X64 mvn -e --no-transfer-progress verify" - # MacOS JDK14 verify + # MacOS JDK17 verify 'MacOS JDK14 verify': - image: 'macOS-10.15' - cmd: "export JAVA_HOME=$JAVA_HOME_14_X64 && mvn -e --no-transfer-progress verify" + image: 'macOS-11' + cmd: "JAVA_HOME=$JAVA_HOME_17_X64 mvn -e --no-transfer-progress verify" # moved back to Travis till we find a way to keep secrets in azure # ensure that all modules are used in no exception configs @@ -126,7 +116,7 @@ pool: variables: MAVEN_CACHE_FOLDER: $(Pipeline.Workspace)/.m2/repository - MAVEN_OPTS: '-Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' + MAVEN_OPTS: '--show-version -Dmaven.repo.local=$(MAVEN_CACHE_FOLDER)' SKIP_CACHE: $(skipCache) IMAGE: $(image) ON_CRON_ONLY: $(onCronOnly) @@ -147,6 +137,12 @@ steps: gem install mdl condition: eq(variables.NEED_MDL, 'true') +- task: JavaToolInstaller@0 + inputs: + versionSpec: 11 + jdkArchitectureOption: 'X64' + jdkSourceOption: 'PreInstalled' + - task: Cache@2 inputs: key: 'maven | "$(Agent.OS)" | **/pom.xml' diff --git a/config/checkstyle_checks.xml b/config/checkstyle_checks.xml index 05c56d16b2e..49039b3aaea 100644 --- a/config/checkstyle_checks.xml +++ b/config/checkstyle_checks.xml @@ -462,6 +462,14 @@ + + + + + - + diff --git a/config/version-number-rules.xml b/config/version-number-rules.xml index 507c4c39eef..1c984ebb1d1 100644 --- a/config/version-number-rules.xml +++ b/config/version-number-rules.xml @@ -26,12 +26,6 @@ .* - - - - .* - - diff --git a/pom.xml b/pom.xml index 1edd855e2e4..4711850e513 100644 --- a/pom.xml +++ b/pom.xml @@ -12,7 +12,7 @@ com.puppycrawl.tools checkstyle - 9.3 + 10.0 jar checkstyle @@ -200,10 +200,10 @@ ${project.version} 4.9.3 - 3.10.0 + 3.11.0 4.2.3 - 3.15.0 - 6.41.0 + 3.16.0 + 6.42.0 0.8.7 4.3.1 10.6 @@ -213,8 +213,8 @@ 9.1 2.9.0 - 1.8 - 1.7.3 + 11 + 1.7.4 10 50000 4 @@ -229,13 +229,13 @@ com.tngtech.archunit archunit-junit5 - 0.22.0 + 0.23.0 test info.picocli picocli - 4.6.2 + 4.6.3 org.antlr @@ -280,13 +280,13 @@ org.itsallcode junit5-system-extensions - 1.1.0 + 1.2.0 test org.junit-pioneer junit-pioneer - 1.5.0 + 1.6.1 test @@ -298,7 +298,7 @@ nl.jqno.equalsverifier equalsverifier - 3.8.3 + 3.9 test @@ -322,7 +322,7 @@ org.slf4j slf4j-simple - 1.7.35 + 1.7.36 test @@ -394,7 +394,7 @@ org.codehaus.mojo sonar-maven-plugin - 3.9.0.2155 + 3.9.1.2184 org.apache.maven.plugins @@ -416,7 +416,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.3.1 + 3.3.2 @@ -1097,7 +1097,7 @@ org.sonatype.plugins nexus-staging-maven-plugin - 1.6.8 + 1.6.12 true **/XpathFileGeneratorAuditListenerTest.class - - **/AllChecksTest.class - **/XdocsPagesTest.class **/DefaultConfigurationTest.class @@ -1629,7 +1625,7 @@ maven-project-info-reports-plugin - 3.1.2 + 3.2.2 @@ -1872,6 +1868,7 @@ http://maven.apache.org/plugins/maven-linkcheck-plugin/ https://www.ej-technologies.com/* + https://travis-ci.com/ @@ -2040,7 +2037,6 @@ pitest-misc - true true @@ -2132,7 +2128,6 @@ pitest-annotation - true true @@ -2177,7 +2172,6 @@ pitest-blocks - true true @@ -2222,7 +2216,6 @@ pitest-coding - true true @@ -2240,8 +2233,7 @@ INVERT_NEGS MATH NEGATE_CONDITIONALS - - + REMOVE_CONDITIONALS RETURN_VALS TRUE_RETURNS VOID_METHOD_CALLS @@ -2256,7 +2248,7 @@ *.Input* 100 - 100 + 99 ${pitest.plugin.timeout.factor} ${pitest.plugin.timeout.constant} ${pitest.plugin.threads} @@ -2268,7 +2260,6 @@ pitest-design - true true @@ -2313,7 +2304,6 @@ pitest-header - true true @@ -2358,7 +2348,6 @@ pitest-imports - true true @@ -2403,7 +2392,6 @@ pitest-indentation - true true @@ -2449,7 +2437,6 @@ pitest-javadoc - true true @@ -2504,7 +2491,6 @@ pitest-metrics - true true @@ -2549,7 +2535,6 @@ pitest-modifier - true true @@ -2594,7 +2579,6 @@ pitest-naming - true true @@ -2639,7 +2623,6 @@ pitest-regexp - true true @@ -2684,7 +2667,6 @@ pitest-sizes - true true @@ -2729,7 +2711,6 @@ pitest-whitespace - true true @@ -2775,7 +2756,6 @@ pitest-ant - true true @@ -2820,7 +2800,6 @@ pitest-packagenamesloader - true true @@ -2862,7 +2841,6 @@ pitest-common - true true @@ -2944,7 +2922,6 @@ pitest-common-2 - true true @@ -3007,7 +2984,6 @@ pitest-main - true true @@ -3049,7 +3025,6 @@ pitest-tree-walker - true true @@ -3143,7 +3118,6 @@ pitest-api - true true @@ -3199,7 +3173,6 @@ pitest-filters - true true @@ -3246,7 +3219,6 @@ pitest-utils - true true @@ -3336,7 +3308,6 @@ pitest-gui - true true @@ -3407,7 +3378,6 @@ pitest-xpath - true true @@ -3456,7 +3426,6 @@ pitest-java-ast-visitor - true true diff --git a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAfterTest.java b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAfterTest.java index 0bde24a5317..eb03d79e4f9 100644 --- a/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAfterTest.java +++ b/src/it/java/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/WhitespaceAfterTest.java @@ -53,6 +53,9 @@ public void testWhitespaceAfterBad() throws Exception { "14:9: " + getCheckMessage(clazz, message, "if"), "14:18: " + getCheckMessage(clazz, message, "typecast"), "17:9: " + getCheckMessage(clazz, message, "else"), + "22:28: " + getCheckMessage(clazz, message, "..."), + "23:26: " + getCheckMessage(clazz, message, "->"), + "24:9: " + getCheckMessage(clazz, message, "switch"), }; final Configuration checkConfig = getModuleConfig("WhitespaceAfter"); final String filePath = getPath("InputWhitespaceAfterBad.java"); diff --git a/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRedundantImportTest.java b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRedundantImportTest.java new file mode 100644 index 00000000000..7d64edf66c2 --- /dev/null +++ b/src/it/java/org/checkstyle/suppressionxpathfilter/XpathRegressionRedundantImportTest.java @@ -0,0 +1,92 @@ +//////////////////////////////////////////////////////////////////////////////// +// checkstyle: Checks Java source code for adherence to a set of rules. +// Copyright (C) 2001-2022 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 org.checkstyle.suppressionxpathfilter; + +import java.io.File; +import java.util.Collections; +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.puppycrawl.tools.checkstyle.DefaultConfiguration; +import com.puppycrawl.tools.checkstyle.checks.imports.RedundantImportCheck; + +public class XpathRegressionRedundantImportTest extends AbstractXpathTestSupport { + + private final String checkName = RedundantImportCheck.class.getSimpleName(); + + @Override + protected String getCheckName() { + return checkName; + } + + @Test + public void testOne() throws Exception { + final File fileToProcess = + new File(getPath("SuppressionXpathRegressionRedundantImport1.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_SAME, "org.checkstyle.suppressionxpathfilter" + + ".redundantimport.SuppressionXpathRegressionRedundantImport1"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testTwo() throws Exception { + final File fileToProcess = + new File(getPath("SuppressionXpathRegressionRedundantImport2.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "3:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_LANG, "java.lang.String"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + + @Test + public void testThree() throws Exception { + final File fileToProcess = + new File(getPath("SuppressionXpathRegressionRedundantImport3.java")); + final DefaultConfiguration moduleConfig = + createModuleConfig(RedundantImportCheck.class); + final String[] expectedViolation = { + "4:1: " + getCheckMessage(RedundantImportCheck.class, + RedundantImportCheck.MSG_DUPLICATE, 3, "java.util.Scanner"), + }; + final List expectedXpathQueries = Collections.singletonList( + "/COMPILATION_UNIT/IMPORT[./DOT/IDENT[@text='Scanner']]"); + + runVerifications(moduleConfig, fileToProcess, expectedViolation, + expectedXpathQueries); + } + +} diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java index dcd6abea3a8..cdacb817b15 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterBad.java @@ -18,4 +18,12 @@ public void check2(final int a,final int b){ // warn System.out.println("false"); } } + + public void check3 (int...a) { // warn + Runnable r2 = () ->String.valueOf("Hello world two!"); // warn + switch(a[0]) { // warn + default: + break; + } + } } diff --git a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java index a889ea97884..dd20afb6e0e 100644 --- a/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java +++ b/src/it/resources/com/google/checkstyle/test/chapter4formatting/rule462horizontalwhitespace/InputWhitespaceAfterGood.java @@ -18,4 +18,12 @@ public void check2(final int a, final int b){ System.out.println("false"); } } + + public void check3(int... a) { + Runnable r2 = () -> String.valueOf("Hello world two!"); + switch (a[0]) { + default: + break; + } + } } diff --git a/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport1.java b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport1.java new file mode 100644 index 00000000000..93be31e0b69 --- /dev/null +++ b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport1.java @@ -0,0 +1,6 @@ +package org.checkstyle.suppressionxpathfilter.redundantimport; + +import org.checkstyle.suppressionxpathfilter.redundantimport.SuppressionXpathRegressionRedundantImport1; // warn + +public class SuppressionXpathRegressionRedundantImport1 { +} diff --git a/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport2.java b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport2.java new file mode 100644 index 00000000000..9f5d2b69629 --- /dev/null +++ b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport2.java @@ -0,0 +1,6 @@ +package org.checkstyle.suppressionxpathfilter.redundantimport; + +import java.lang.String; // warn + +public class SuppressionXpathRegressionRedundantImport2 { +} diff --git a/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport3.java b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport3.java new file mode 100644 index 00000000000..6438f4286b2 --- /dev/null +++ b/src/it/resources/org/checkstyle/suppressionxpathfilter/redundantimport/SuppressionXpathRegressionRedundantImport3.java @@ -0,0 +1,7 @@ +package org.checkstyle.suppressionxpathfilter.redundantimport; + +import java.util.Scanner; +import java.util.Scanner; // warn + +public class SuppressionXpathRegressionRedundantImport3 { +} diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java b/src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java index d29df50e29b..eab0cece793 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/DefaultConfiguration.java @@ -140,7 +140,7 @@ public void removeChild(final Configuration configuration) { * @deprecated This shall be removed in future releases. Please use * {@code addProperty(String propertyName, String value)} instead. */ - @Deprecated + @Deprecated(since = "8.45") public void addAttribute(String attributeName, String value) { addProperty(attributeName, value); } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/Definitions.java b/src/main/java/com/puppycrawl/tools/checkstyle/Definitions.java index cb2e6770cdd..732deded94b 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/Definitions.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/Definitions.java @@ -19,8 +19,6 @@ package com.puppycrawl.tools.checkstyle; -import java.util.Collections; -import java.util.HashSet; import java.util.Set; /** @@ -33,10 +31,8 @@ public final class Definitions { "com.puppycrawl.tools.checkstyle.messages"; /** Name of modules which are not checks, but are internal modules. */ - public static final Set INTERNAL_MODULES = Collections.unmodifiableSet( - new HashSet<>(Collections.singletonList( - "com.puppycrawl.tools.checkstyle.meta.JavadocMetadataScraper" - ))); + public static final Set INTERNAL_MODULES = Set.of( + "com.puppycrawl.tools.checkstyle.meta.JavadocMetadataScraper"); /** * Do no allow {@code Definitions} instances to be created. diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java b/src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java index c27b067b668..1df1a4a4d5c 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/JavadocPropertiesGenerator.java @@ -100,8 +100,7 @@ public static void main(String... args) throws CheckstyleException { * @throws CheckstyleException if a javadoc comment can not be parsed */ private static void writePropertiesFile(CliOptions options) throws CheckstyleException { - try (PrintWriter writer = new PrintWriter(options.outputFile, - StandardCharsets.UTF_8.name())) { + try (PrintWriter writer = new PrintWriter(options.outputFile, StandardCharsets.UTF_8)) { final DetailAST top = JavaParser.parseFile(options.inputFile, JavaParser.Options.WITH_COMMENTS).getFirstChild(); final DetailAST objBlock = getClassBody(top); diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java b/src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java index f3a767c56d1..8521c81d981 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/SarifLogger.java @@ -137,12 +137,6 @@ public void auditStarted(AuditEvent event) { // No code by default } - /** - * {@inheritDoc} - * Following idea suppressions are false positives - * - * @noinspection DynamicRegexReplaceableByCompiledPattern - */ @Override public void auditFinished(AuditEvent event) { final String version = SarifLogger.class.getPackage().getImplementationVersion(); @@ -158,12 +152,6 @@ public void auditFinished(AuditEvent event) { } } - /** - * {@inheritDoc} - * Following idea suppressions are false positives - * - * @noinspection DynamicRegexReplaceableByCompiledPattern - */ @Override public void addError(AuditEvent event) { if (event.getColumn() > 0) { @@ -187,12 +175,6 @@ public void addError(AuditEvent event) { } } - /** - * {@inheritDoc} - * Following idea suppressions are false positives - * - * @noinspection DynamicRegexReplaceableByCompiledPattern - */ @Override public void addException(AuditEvent event, Throwable throwable) { final StringWriter stringWriter = new StringWriter(); @@ -305,14 +287,10 @@ public static String escape(String value) { * @return the escaped string. */ private static String escapeUnicode1F(char chr) { - final StringBuilder stringBuilder = new StringBuilder(UNICODE_LENGTH + 1); - stringBuilder.append("\\u"); final String hexString = Integer.toHexString(chr); - for (int i = 0; i < UNICODE_LENGTH - hexString.length(); i++) { - stringBuilder.append('0'); - } - stringBuilder.append(hexString.toUpperCase(Locale.US)); - return stringBuilder.toString(); + return "\\u" + + "0".repeat(UNICODE_LENGTH - hexString.length()) + + hexString.toUpperCase(Locale.US); } /** @@ -334,7 +312,7 @@ public static String readResource(String name) throws IOException { result.write(buffer, 0, length); length = inputStream.read(buffer); } - return result.toString(StandardCharsets.UTF_8.name()); + return result.toString(StandardCharsets.UTF_8); } } } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java index 270fe0f4fef..abf88f71dc9 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/AbstractCheck.java @@ -192,7 +192,7 @@ public final void setFileContents(FileContents contents) { * Please use AST based methods instead. * @noinspection WeakerAccess */ - @Deprecated + @Deprecated(since = "9.3") public final FileContents getFileContents() { return context.get().fileContents; } 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 95c0e875d5b..656a793ff55 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/Configuration.java @@ -36,7 +36,7 @@ public interface Configuration extends Serializable { * @deprecated This shall be removed in future releases. Please use * {@code getPropertyNames()} instead. */ - @Deprecated + @Deprecated(since = "8.45") String[] getAttributeNames(); /** @@ -48,7 +48,7 @@ public interface Configuration extends Serializable { * @deprecated This shall be removed in future releases. Please use * {@code getProperty(String name)} instead. */ - @Deprecated + @Deprecated(since = "8.45") String getAttribute(String name) throws CheckstyleException; /** diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/api/DetailAST.java b/src/main/java/com/puppycrawl/tools/checkstyle/api/DetailAST.java index 45f8f4940da..77aeb26ac02 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/api/DetailAST.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/DetailAST.java @@ -98,7 +98,7 @@ public interface DetailAST { * traversal of subtrees to be written per the needs of each check * to avoid unintended side effects. */ - @Deprecated + @Deprecated(since = "8.43") boolean branchContains(int type); /** @@ -137,7 +137,7 @@ public interface DetailAST { * @deprecated This method will be removed in a future release. * Use {@link #getChildCount()} instead. */ - @Deprecated + @Deprecated(since = "8.30") int getNumberOfChildren(); /** 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 3b24b8b4521..a9f34199038 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/api/TokenTypes.java @@ -5054,8 +5054,8 @@ public final class TokenTypes { * `--RCURLY -> } * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #GENERIC_START * @see #GENERIC_END * @see #TYPE_PARAMETER @@ -5096,8 +5096,8 @@ public final class TokenTypes { * `--RCURLY -> } * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #IDENT * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS @@ -5165,8 +5165,8 @@ public final class TokenTypes { * `--SEMI -> ; * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #WILDCARD_TYPE * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS @@ -5196,8 +5196,8 @@ public final class TokenTypes { * |--SEMI -> ; * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #TYPE_ARGUMENT * @see #TYPE_UPPER_BOUNDS * @see #TYPE_LOWER_BOUNDS @@ -5229,8 +5229,8 @@ public final class TokenTypes { * `--SEMI -> ; * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #TYPE_PARAMETER * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE @@ -5262,8 +5262,8 @@ public final class TokenTypes { * `--SEMI -> ; * * - * @see - * JSR14 + * @see + * Generic Classes and Type Parameters * @see #TYPE_ARGUMENT * @see #WILDCARD_TYPE */ diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java index 064ee25e3d9..1e7f77619c6 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/FinalParametersCheck.java @@ -68,6 +68,19 @@ * <module name="FinalParameters"/> * *

+ * Example: + *

+ *
+ * public class Point {
+ *   public Point() { } // ok
+ *   public Point(final int m) { } // ok
+ *   public Point(final int m,int n) { } // violation, n should be final
+ *   public void methodOne(final int x) { } // ok
+ *   public void methodTwo(int x) { } // violation, x should be final
+ *   public static void main(String[] args) { } // violation, args should be final
+ * }
+ * 
+ *

* To configure the check to enforce final parameters only for constructors: *

*
@@ -76,6 +89,19 @@
  * </module>
  * 
*

+ * Example: + *

+ *
+ * public class Point {
+ *   public Point() { } // ok
+ *   public Point(final int m) { } // ok
+ *   public Point(final int m,int n) { } // violation, n should be final
+ *   public void methodOne(final int x) { } // ok
+ *   public void methodTwo(int x) { } // ok
+ *   public static void main(String[] args) { } // ok
+ * }
+ * 
+ *

* To configure the check to allow ignoring * * primitive datatypes as parameters: @@ -86,6 +112,19 @@ * </module> * *

+ * Example: + *

+ *
+ * public class Point {
+ *   public Point() { } // ok
+ *   public Point(final int m) { } // ok
+ *   public Point(final int m,int n) { } // ok
+ *   public void methodOne(final int x) { } // ok
+ *   public void methodTwo(int x) { } // ok
+ *   public static void main(String[] args) { } // violation, args should be final
+ * }
+ * 
+ *

* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} *

*

diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.java index fec4c3fda75..2f0d4dfa56c 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/AvoidDoubleBraceInitializationCheck.java @@ -162,6 +162,6 @@ && hasOnlyInitialization(ast)) { private static boolean hasOnlyInitialization(DetailAST objBlock) { final boolean hasInitBlock = objBlock.findFirstToken(TokenTypes.INSTANCE_INIT) != null; return hasInitBlock - && !TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isPresent(); + && TokenUtil.findFirstTokenByPredicate(objBlock, HAS_MEMBERS).isEmpty(); } } 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 ccb1cb9c701..d24b420e0e9 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 @@ -440,7 +440,7 @@ private static boolean isInSpecificCodeBlocks(DetailAST node, int... blockTypes) private Optional getFinalCandidate(DetailAST ast) { Optional result = Optional.empty(); final Iterator iterator = scopeStack.descendingIterator(); - while (iterator.hasNext() && !result.isPresent()) { + while (iterator.hasNext() && result.isEmpty()) { final ScopeData scopeData = iterator.next(); result = scopeData.findFinalVariableCandidateForAst(ast); } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.java index 6f053150cd1..d3b225878b5 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/IllegalTokenTextCheck.java @@ -19,6 +19,7 @@ package com.puppycrawl.tools.checkstyle.checks.coding; +import java.util.Objects; import java.util.regex.Pattern; import com.puppycrawl.tools.checkstyle.StatelessCheck; @@ -220,12 +221,7 @@ public void visitToken(DetailAST ast) { * to report about violations. */ public void setMessage(String message) { - if (message == null) { - this.message = ""; - } - else { - this.message = message; - } + this.message = Objects.requireNonNullElse(message, ""); } /** 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 2905e3dd001..cc6cfbda003 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 @@ -90,6 +90,29 @@ * </module> * *

+ * Example: + *

+ *
+ * public class MyClass {
+ *   public int sign(int x) {
+ *     if (x < 0)
+ *       return -1;
+ *     if (x == 0)
+ *       return 1;
+ *     return 0;
+ *   } // OK
+ *   public int badSign(int x) {
+ *     if (x < -2)
+ *       return -2;
+ *     if (x == 0)
+ *       return 0;
+ *     if (x > 2)
+ *       return 2;
+ *     return 1;
+ *   } // violation, more than three return statements
+ * }
+ * 
+ *

* To configure the check so that it doesn't allow any return statements per void method: *

*
@@ -98,6 +121,19 @@
  * </module>
  * 
*

+ * Example: + *

+ *
+ * public class MyClass {
+ *   public void firstMethod(int x) {
+ *   } // OK
+ *
+ *   public void badMethod(int x) {
+ *     return;
+ *   } // violation, return statements per void method
+ * }
+ * 
+ *

* To configure the check so that it doesn't allow more than 2 return statements per method * (ignoring the {@code equals()} method) and more than 1 return statements per void method: *

@@ -108,6 +144,39 @@ * </module> * *

+ * Example: + *

+ *
+ * public class MyClass {
+ *   public void firstMethod() {
+ *   } // OK
+ *
+ *   public void secondMethod() {
+ *     return;
+ *   } // OK
+ *
+ *   public void badMethod(int x) {
+ *     if (x == 0)
+ *       return;
+ *     return;
+ *   } // violation, more than one return statements
+ *
+ *   public int sign(int x) {
+ *     if (x < 0)
+ *       return -1;
+ *     return 0;
+ *   } // OK
+ *
+ *   public int badSign(int x) {
+ *     if (x < 0)
+ *       return -1;
+ *     if (x == 0)
+ *       return 1;
+ *     return 0;
+ *   } // violation, more than two return statements in methods
+ * }
+ * 
+ *

* To configure the check so that it doesn't allow more than three * return statements per method for all methods: *

@@ -118,13 +187,37 @@ * </module> * *

+ * Example: + *

+ *
+ * public class MyClass {
+ *   public int sign(int x) {
+ *     if (x < 0)
+ *       return -1;
+ *     if (x == 0)
+ *       return 1;
+ *     return 0;
+ *   } // OK
+ *
+ *   public int badSign(int x) {
+ *     if (x < -2)
+ *       return -2;
+ *     if (x == 0)
+ *       return 0;
+ *     if (x > 2)
+ *       return 2;
+ *     return 1;
+ *   } // violation, more than three return statements per method
+ * }
+ * 
+ *

* To configure the check so that it doesn't allow any return statements in constructors, * more than one return statement in all lambda expressions and more than two return * statements in methods: *

*
  * <module name="ReturnCount">
- *   <property name="max" value="0"/>
+ *   <property name="maxForVoid" value="0"/>
  *   <property name="tokens" value="CTOR_DEF"/>
  * </module>
  * <module name="ReturnCount">
@@ -137,6 +230,46 @@
  * </module>
  * 
*

+ * Example: + *

+ *
+ * import java.util.function.Predicate;
+ *
+ * public class Test {
+ *   public Test() {
+ *   } // OK
+ *
+ *   public Test(int i) {
+ *     return; // violation, max allowed for constructors is 0
+ *   }
+ *
+ *   final Predicate<Integer> p = i -> {
+ *     if (i > 5) {
+ *       return true;
+ *     }
+ *     return false;
+ *   }; // violation, max allowed for lambdas is 1
+ *
+ *   final Predicate<Integer> q = i -> {
+ *     return i > 5;
+ *   }; // OK
+ *
+ *   public int sign(int x) {
+ *     if (x > 0)
+ *       return -1;
+ *     return 0;
+ *   } // OK
+ *
+ *   public int badSign(int x) {
+ *     if (x < 0)
+ *       return -1;
+ *     if (x == 0)
+ *       return 1;
+ *     return 0;
+ *   } // violation, more than two return statements in methods
+ * }
+ * 
+ *

* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} *

*

diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java index 97f493b0e57..956465e00ac 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/UnusedLocalVariableCheck.java @@ -287,9 +287,6 @@ public int[] getRequiredTokens() { @Override public void beginTree(DetailAST root) { - // No need to set blockContainingLocalAnonInnerClass to null, if - // its value gets changed during the check then it is changed back to null - // inside the check only. variables.clear(); typeDeclarations.clear(); typeDeclAstToTypeDeclDesc.clear(); @@ -832,12 +829,12 @@ public static boolean shouldCheckIdentWithMethodRefParent(DetailAST identAst) { */ public static boolean shouldCheckIdentTokenNestedUnderDot(DetailAST dotAst) { - return !TokenUtil.findFirstTokenByPredicate(dotAst, + return TokenUtil.findFirstTokenByPredicate(dotAst, childAst -> { return TokenUtil.isOfType(childAst, UNACCEPTABLE_CHILD_OF_DOT); }) - .isPresent(); + .isEmpty(); } /** 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 16245832d40..22afc18e2d5 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 @@ -23,6 +23,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map.Entry; +import java.util.Objects; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -659,12 +660,8 @@ private static Entry calculateDistanceBetweenScopes( exprWithVariableUsage = blockWithVariableUsage.getFirstChild(); } currentScopeAst = exprWithVariableUsage; - if (exprWithVariableUsage == null) { - variableUsageAst = blockWithVariableUsage; - } - else { - variableUsageAst = exprWithVariableUsage; - } + variableUsageAst = + Objects.requireNonNullElse(exprWithVariableUsage, blockWithVariableUsage); } // If there's no any variable usage, then distance = 0. diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java index b8d5ff5c323..bac412b0f9d 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheck.java @@ -21,6 +21,9 @@ import java.util.ArrayDeque; import java.util.Deque; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import com.puppycrawl.tools.checkstyle.FileStatefulCheck; import com.puppycrawl.tools.checkstyle.api.AbstractCheck; @@ -28,12 +31,12 @@ import com.puppycrawl.tools.checkstyle.api.FullIdent; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.utils.ScopeUtil; +import com.puppycrawl.tools.checkstyle.utils.TokenUtil; /** *

- * Checks that a class which has only private constructors - * is declared as final. Doesn't check for classes nested in interfaces - * or annotations, as they are always {@code final} there. + * Checks that a class that has only private constructors and has no descendant + * classes is declared as final. *

*

* To configure the check: @@ -66,21 +69,6 @@ * } * } * - * interface CheckInterface - * { - * class MyClass { // OK, nested class in interface is always final - * private MyClass() {} - * } - * } - * - * public @interface Test { - * public boolean enabled() - * default true; - * class MyClass { // OK, class nested in an annotation is always final - * private MyClass() { } - * } - * } - * * class TestAnonymousInnerClasses { // OK, class has an anonymous inner class. * public static final TestAnonymousInnerClasses ONE = new TestAnonymousInnerClasses() { * @@ -119,6 +107,9 @@ public class FinalClassCheck */ private static final String PACKAGE_SEPARATOR = "."; + /** Keeps ClassDesc objects for all inner classes. */ + private Map innerClasses; + /** Keeps ClassDesc objects for stack of declared classes. */ private Deque classes; @@ -138,7 +129,11 @@ public int[] getAcceptableTokens() { @Override public int[] getRequiredTokens() { return new int[] { + TokenTypes.ANNOTATION_DEF, TokenTypes.CLASS_DEF, + TokenTypes.ENUM_DEF, + TokenTypes.INTERFACE_DEF, + TokenTypes.RECORD_DEF, TokenTypes.CTOR_DEF, TokenTypes.PACKAGE_DEF, TokenTypes.LITERAL_NEW, @@ -148,38 +143,29 @@ public int[] getRequiredTokens() { @Override public void beginTree(DetailAST rootAST) { classes = new ArrayDeque<>(); + innerClasses = new HashMap<>(); packageName = ""; } @Override public void visitToken(DetailAST ast) { - final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); - switch (ast.getType()) { case TokenTypes.PACKAGE_DEF: packageName = extractQualifiedName(ast.getFirstChild().getNextSibling()); break; - case TokenTypes.CLASS_DEF: - registerNestedSubclassToOuterSuperClasses(ast); - - final boolean isFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null; - final boolean isAbstract = modifiers.findFirstToken(TokenTypes.ABSTRACT) != null; + case TokenTypes.ANNOTATION_DEF: + case TokenTypes.ENUM_DEF: + case TokenTypes.INTERFACE_DEF: + case TokenTypes.RECORD_DEF: + break; - final String qualifiedClassName = getQualifiedClassName(ast); - classes.push(new ClassDesc(qualifiedClassName, isFinal, isAbstract)); + case TokenTypes.CLASS_DEF: + visitClass(ast); break; case TokenTypes.CTOR_DEF: - if (!ScopeUtil.isInEnumBlock(ast) && !ScopeUtil.isInRecordBlock(ast)) { - final ClassDesc desc = classes.peek(); - if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) { - desc.registerNonPrivateCtor(); - } - else { - desc.registerPrivateCtor(); - } - } + visitCtor(ast); break; case TokenTypes.LITERAL_NEW: @@ -198,22 +184,67 @@ public void visitToken(DetailAST ast) { } } + /** + * Called to process a type definition. + * + * @param ast the token to process + */ + private void visitClass(DetailAST ast) { + final String qualifiedClassName = getQualifiedClassName(ast); + final ClassDesc currClass = new ClassDesc(qualifiedClassName, classes.size(), ast); + classes.push(currClass); + innerClasses.put(qualifiedClassName, currClass); + } + + /** + * Called to process a constructor definition. + * + * @param ast the token to process + */ + private void visitCtor(DetailAST ast) { + if (!ScopeUtil.isInEnumBlock(ast) && !ScopeUtil.isInRecordBlock(ast)) { + final DetailAST modifiers = ast.findFirstToken(TokenTypes.MODIFIERS); + final ClassDesc desc = classes.getFirst(); + if (modifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) == null) { + desc.registerNonPrivateCtor(); + } + else { + desc.registerPrivateCtor(); + } + } + } + @Override public void leaveToken(DetailAST ast) { if (ast.getType() == TokenTypes.CLASS_DEF) { - final ClassDesc desc = classes.pop(); - if (desc.isWithPrivateCtor() + classes.pop(); + } + if (TokenUtil.isRootNode(ast.getParent())) { + // First pass: mark all classes that have derived inner classes + innerClasses.forEach(this::registerNestedSubclassToOuterSuperClasses); + // Second pass: report violation for all classes that should be declared as final + innerClasses.forEach((qualifiedClassName, classDesc) -> { + if (shouldBeDeclaredAsFinal(classDesc)) { + final String className = getClassNameFromQualifiedName(qualifiedClassName); + log(classDesc.getClassAst(), MSG_KEY, className); + } + }); + } + } + + /** + * Checks whether a class should be declared as final or not. + * + * @param desc description of the class + * @return true if given class should be declared as final otherwise false + */ + private static boolean shouldBeDeclaredAsFinal(ClassDesc desc) { + return desc.isWithPrivateCtor() && !(desc.isDeclaredAsAbstract() || desc.isWithAnonymousInnerClass()) && !desc.isDeclaredAsFinal() && !desc.isWithNonPrivateCtor() - && !desc.isWithNestedSubclass() - && !ScopeUtil.isInInterfaceOrAnnotationBlock(ast)) { - final String qualifiedName = desc.getQualifiedName(); - final String className = getClassNameFromQualifiedName(qualifiedName); - log(ast, MSG_KEY, className); - } - } + && !desc.isWithNestedSubclass(); } /** @@ -227,25 +258,80 @@ private static String extractQualifiedName(DetailAST ast) { } /** - * Register to outer super classes of given classAst that + * Register to outer super class of given classAst that * given classAst is extending them. * - * @param classAst class which outer super classes will be - * informed about nesting subclass + * @param qualifiedClassName qualifies class name(with package) of the current class + * @param currentClass class which outer super class will be informed about nesting subclass */ - private void registerNestedSubclassToOuterSuperClasses(DetailAST classAst) { - final String currentAstSuperClassName = getSuperClassName(classAst); - if (currentAstSuperClassName != null) { - for (ClassDesc classDesc : classes) { - final String classDescQualifiedName = classDesc.getQualifiedName(); - if (doesNameInExtendMatchSuperClassName(classDescQualifiedName, - currentAstSuperClassName)) { - classDesc.registerNestedSubclass(); - } + private void registerNestedSubclassToOuterSuperClasses(String qualifiedClassName, + ClassDesc currentClass) { + final String superClassName = getSuperClassName(currentClass.getClassAst()); + if (superClassName != null) { + final ClassDesc nearest = + getNearestClassWithSameName(superClassName, qualifiedClassName); + if (nearest == null) { + Optional.ofNullable(innerClasses.get(superClassName)) + .ifPresent(ClassDesc::registerNestedSubclass); + } + else { + nearest.registerNestedSubclass(); } } } + /** + * Checks if there is a class with same name. + * + * @param className name of the class + * @param superClassName name of the super class + * @return true if there is another class with same name. + * @noinspection CallToStringConcatCanBeReplacedByOperator + */ + private ClassDesc getNearestClassWithSameName(String className, String superClassName) { + final String dotAndClassName = PACKAGE_SEPARATOR.concat(className); + return innerClasses.entrySet().stream() + .filter(entry -> entry.getKey().endsWith(dotAndClassName)) + .map(Map.Entry::getValue) + .min((first, second) -> { + int diff = Integer.compare( + classNameMatchingCount(superClassName, second.getQualifiedName()), + classNameMatchingCount(superClassName, first.getQualifiedName())); + if (diff == 0) { + diff = Integer.compare(first.getDepth(), second.getDepth()); + } + return diff; + }) + .orElse(null); + } + + /** + * Calculates and returns the class name matching count. + * + *

+ * Suppose our pattern class is {@code foo.a.b} and class to be matched is + * {@code foo.a.ball} then classNameMatchingCount would be calculated by comparing every + * character, and updating main counter when we hit "." + * to prevent matching "a.b" with "a.ball". In this case classNameMatchingCount would + * be equal to 6 and not 7 (b of ball is not counted). + *

+ * + * @param patternClass class against which the given class has to be matched + * @param classToBeMatched class to be matched + * @return class name matching count + */ + private static int classNameMatchingCount(String patternClass, String classToBeMatched) { + final char packageSeparator = PACKAGE_SEPARATOR.charAt(0); + final int length = Math.min(classToBeMatched.length(), patternClass.length()); + int result = 0; + for (int i = 0; i < length && patternClass.charAt(i) == classToBeMatched.charAt(i); ++i) { + if (patternClass.charAt(i) == packageSeparator) { + result = i; + } + } + return result; + } + /** * Check if class name matches with anonymous inner class name. * @@ -318,23 +404,6 @@ private static String getSuperClassName(DetailAST classAst) { return superClassName; } - /** - * Checks if given super class name in extend clause match super class qualified name. - * - * @param superClassQualifiedName super class qualified name (with package) - * @param superClassInExtendClause name in extend clause - * @return true if given super class name in extend clause match super class qualified name, - * false otherwise - */ - private static boolean doesNameInExtendMatchSuperClassName(String superClassQualifiedName, - String superClassInExtendClause) { - String superClassNormalizedName = superClassQualifiedName; - if (!superClassInExtendClause.contains(PACKAGE_SEPARATOR)) { - superClassNormalizedName = getClassNameFromQualifiedName(superClassQualifiedName); - } - return superClassNormalizedName.equals(superClassInExtendClause); - } - /** * Get class name from qualified name. * @@ -348,6 +417,9 @@ private static String getClassNameFromQualifiedName(String qualifiedName) { /** Maintains information about class' ctors. */ private static final class ClassDesc { + /** Corresponding node. */ + private final DetailAST classAst; + /** Qualified class name(with package). */ private final String qualifiedName; @@ -357,6 +429,9 @@ private static final class ClassDesc { /** Is class declared as abstract. */ private final boolean declaredAsAbstract; + /** Class nesting level. */ + private final int depth; + /** Does class have non-private ctors. */ private boolean withNonPrivateCtor; @@ -373,16 +448,16 @@ private static final class ClassDesc { * Create a new ClassDesc instance. * * @param qualifiedName qualified class name(with package) - * @param declaredAsFinal indicates if the - * class declared as final - * @param declaredAsAbstract indicates if the - * class declared as abstract + * @param depth class nesting level + * @param classAst classAst node */ - /* package */ ClassDesc(String qualifiedName, boolean declaredAsFinal, - boolean declaredAsAbstract) { + /* package */ ClassDesc(String qualifiedName, int depth, DetailAST classAst) { this.qualifiedName = qualifiedName; - this.declaredAsFinal = declaredAsFinal; - this.declaredAsAbstract = declaredAsAbstract; + this.depth = depth; + this.classAst = classAst; + final DetailAST modifiers = classAst.findFirstToken(TokenTypes.MODIFIERS); + declaredAsFinal = modifiers.findFirstToken(TokenTypes.FINAL) != null; + declaredAsAbstract = modifiers.findFirstToken(TokenTypes.ABSTRACT) != null; } /** @@ -394,6 +469,15 @@ private String getQualifiedName() { return qualifiedName; } + /** + * Get the classAst node. + * + * @return classAst node + */ + public DetailAST getClassAst() { + return classAst; + } + /** Adds private ctor. */ private void registerPrivateCtor() { withPrivateCtor = true; @@ -414,6 +498,15 @@ private void registerAnonymousInnerClass() { withAnonymousInnerClass = true; } + /** + * Returns class nesting level. + * + * @return class nesting level + */ + private int getDepth() { + return depth; + } + /** * Does class have private ctors. * @@ -469,5 +562,4 @@ private boolean isWithAnonymousInnerClass() { } } - } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java index 8bfd76883a2..c379fbc8f9c 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/javadoc/SummaryJavadocCheck.java @@ -20,8 +20,6 @@ package com.puppycrawl.tools.checkstyle.checks.javadoc; import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; @@ -264,12 +262,10 @@ public class SummaryJavadocCheck extends AbstractJavadocCheck { private static final String SUMMARY_TEXT = "@summary"; /** Set of allowed Tokens tags in summary java doc. */ - private static final Set ALLOWED_TYPES = Collections.unmodifiableSet( - new HashSet<>(Arrays.asList( + private static final Set ALLOWED_TYPES = Set.of( JavadocTokenTypes.WS, JavadocTokenTypes.DESCRIPTION, - JavadocTokenTypes.TEXT)) - ); + JavadocTokenTypes.TEXT); /** * Specify the regexp for forbidden summary fragments. 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 c5bf1579dba..db7192d5aac 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 @@ -30,6 +30,7 @@ import java.util.Optional; import java.util.Set; import java.util.TreeSet; +import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -150,7 +151,7 @@ public final void setMax(int max) { */ public final void setExcludedClasses(String... excludedClasses) { this.excludedClasses = - Collections.unmodifiableSet(Arrays.stream(excludedClasses).collect(Collectors.toSet())); + Arrays.stream(excludedClasses).collect(Collectors.toUnmodifiableSet()); } /** @@ -159,9 +160,10 @@ public final void setExcludedClasses(String... excludedClasses) { * @param from array representing regular expressions of classes to ignore. */ public void setExcludeClassesRegexps(String... from) { - excludeClassesRegexps.addAll(Arrays.stream(from.clone()) + Arrays.stream(from) .map(CommonUtil::createPattern) - .collect(Collectors.toSet())); + .distinct() + .forEach(excludeClassesRegexps::add); } /** @@ -173,16 +175,15 @@ public void setExcludeClassesRegexps(String... from) { */ public final void setExcludedPackages(String... excludedPackages) { final List invalidIdentifiers = Arrays.stream(excludedPackages) - .filter(excludedPackageName -> !CommonUtil.isName(excludedPackageName)) + .filter(Predicate.not(CommonUtil::isName)) .collect(Collectors.toList()); if (!invalidIdentifiers.isEmpty()) { throw new IllegalArgumentException( - "the following values are not valid identifiers: " - + invalidIdentifiers.stream().collect(Collectors.joining(", ", "[", "]"))); + "the following values are not valid identifiers: " + invalidIdentifiers); } - this.excludedPackages = Collections.unmodifiableSet( - Arrays.stream(excludedPackages).collect(Collectors.toSet())); + this.excludedPackages = + Arrays.stream(excludedPackages).collect(Collectors.toUnmodifiableSet()); } @Override 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 85c71f11be1..4a091322fb0 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 @@ -48,7 +48,7 @@ * Final modifier on methods of final and anonymous classes. * *
  • - * Inner {@code interface} declarations that are declared as {@code static}. + * Type declarations nested under interfaces that are declared as {@code public} or {@code static}. *
  • *
  • * Class constructors. @@ -58,13 +58,11 @@ *
  • * *

    - * Interfaces by definition are abstract so the {@code abstract} - * modifier on the interface is redundant. + * interfaces by definition are abstract so the {@code abstract} modifier is redundant on them. *

    - *

    Classes inside of interfaces by definition are public and static, - * so the {@code public} and {@code static} modifiers - * on the inner classes are redundant. On the other hand, classes - * inside of interfaces can be abstract or non abstract. + *

    Type declarations nested under interfaces by definition are public and static, + * so the {@code public} and {@code static} modifiers on nested type declarations are redundant. + * On the other hand, classes inside of interfaces can be abstract or non abstract. * So, {@code abstract} modifier is allowed. *

    *

    Fields in interfaces and annotations are automatically @@ -155,7 +153,9 @@ * * ENUM_DEF, * - * RESOURCE. + * RESOURCE, + * + * ANNOTATION_DEF. * * *

    @@ -225,36 +225,53 @@ public int[] getAcceptableTokens() { TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF, TokenTypes.RESOURCE, + TokenTypes.ANNOTATION_DEF, }; } @Override public void visitToken(DetailAST ast) { - if (ast.getType() == TokenTypes.INTERFACE_DEF) { - checkInterfaceModifiers(ast); - } - else if (ast.getType() == TokenTypes.ENUM_DEF) { - checkEnumDef(ast); - } - else { - if (ast.getType() == TokenTypes.CTOR_DEF) { - if (isEnumMember(ast)) { - checkEnumConstructorModifiers(ast); - } - else { - checkClassConstructorModifiers(ast); - } - } - else if (ast.getType() == TokenTypes.METHOD_DEF) { + switch (ast.getType()) { + case TokenTypes.INTERFACE_DEF: + case TokenTypes.ANNOTATION_DEF: + checkInterfaceModifiers(ast); + break; + case TokenTypes.ENUM_DEF: + checkForRedundantModifier(ast, TokenTypes.LITERAL_STATIC); + break; + case TokenTypes.CTOR_DEF: + checkConstructorModifiers(ast); + break; + case TokenTypes.METHOD_DEF: processMethods(ast); - } - else if (ast.getType() == TokenTypes.RESOURCE) { + break; + case TokenTypes.RESOURCE: processResources(ast); - } + break; + case TokenTypes.CLASS_DEF: + case TokenTypes.VARIABLE_DEF: + case TokenTypes.ANNOTATION_FIELD_DEF: + break; + default: + throw new IllegalStateException("Unexpected token type: " + ast.getType()); + } - if (isInterfaceOrAnnotationMember(ast)) { - processInterfaceOrAnnotation(ast); - } + if (isInterfaceOrAnnotationMember(ast)) { + processInterfaceOrAnnotation(ast); + } + } + + /** + * Check modifiers of constructor. + * + * @param ctorDefAst ast node of type {@link TokenTypes#CTOR_DEF} + */ + private void checkConstructorModifiers(DetailAST ctorDefAst) { + if (isEnumMember(ctorDefAst)) { + checkEnumConstructorModifiers(ctorDefAst); + } + else { + checkClassConstructorModifiers(ctorDefAst); } } @@ -288,20 +305,6 @@ private void checkEnumConstructorModifiers(DetailAST ast) { ).ifPresent(modifier -> log(modifier, MSG_KEY, modifier.getText())); } - /** - * Checks whether enum has proper modifiers. - * - * @param ast enum definition. - */ - private void checkEnumDef(DetailAST ast) { - if (isInterfaceOrAnnotationMember(ast)) { - processInterfaceOrAnnotation(ast); - } - else { - checkForRedundantModifier(ast, TokenTypes.LITERAL_STATIC); - } - } - /** * Do validation of interface of annotation. * diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java index 0e9d334e6bf..96198a5890d 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheck.java @@ -935,8 +935,7 @@ private static boolean isPrecededByJavadoc(DetailAST token) { * @return true variable definition is a type field. */ private static boolean isTypeField(DetailAST variableDef) { - return TokenUtil.isOfType(variableDef.getParent().getParent(), - TokenTypes.CLASS_DEF, TokenTypes.RECORD_DEF); + return TokenUtil.isTypeDeclaration(variableDef.getParent().getParent().getType()); } } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java index bac2e2dc6f2..d6a3da4f1be 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheck.java @@ -55,7 +55,13 @@ * * LITERAL_FOR, * - * DO_WHILE. + * DO_WHILE, + * + * ELLIPSIS, + * + * LITERAL_SWITCH, + * + * LAMBDA. * * *

    @@ -150,6 +156,9 @@ public int[] getAcceptableTokens() { TokenTypes.LITERAL_DO, TokenTypes.LITERAL_FOR, TokenTypes.DO_WHILE, + TokenTypes.ELLIPSIS, + TokenTypes.LITERAL_SWITCH, + TokenTypes.LAMBDA, }; } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java b/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java index c9cbf4e40f1..d2db0688f43 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrame.java @@ -22,6 +22,7 @@ import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; +import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.File; @@ -57,6 +58,9 @@ public class MainFrame extends JFrame { /** A unique serial version identifier. */ private static final long serialVersionUID = 7970053543351871890L; + /** The icon to show in the OS task panel. */ + private static final String ICON = "icon.png"; + /** Checkstyle frame model. */ private final transient MainFrameModel model = new MainFrameModel(); /** Reload action. */ @@ -76,6 +80,7 @@ public MainFrame() { /** Create content of this MainFrame. */ private void createContent() { setLayout(new BorderLayout()); + setIconImage(Toolkit.getDefaultToolkit().getImage(MainFrame.class.getResource(ICON))); textArea = new JTextArea(20, 15); textArea.setEditable(false); diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java b/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java index cabc5249cec..8a7c73e2593 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/gui/MainFrameModel.java @@ -163,7 +163,7 @@ public static boolean shouldAcceptFile(File file) { public File getLastDirectory() { File lastDirectory = null; if (currentFile != null) { - lastDirectory = new File(currentFile.getParent()); + lastDirectory = currentFile.getParentFile(); } return lastDirectory; } diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraper.java b/src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraper.java index 6e0132439fe..d9fd3d5d742 100644 --- a/src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraper.java +++ b/src/main/java/com/puppycrawl/tools/checkstyle/meta/JavadocMetadataScraper.java @@ -106,12 +106,10 @@ public class JavadocMetadataScraper extends AbstractJavadocCheck { * This set contains faulty property default value which should not be written to the XML * metadata files. */ - private static final Set PROPERTIES_TO_NOT_WRITE = Collections.unmodifiableSet( - new HashSet<>(Arrays.asList( + private static final Set PROPERTIES_TO_NOT_WRITE = Set.of( "null", "the charset property of the parent Checker module" - ))); + + "config.html#Checker>Checker module"); /** * Format for exception message for missing type for check property. diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/gui/icon.png b/src/main/resources/com/puppycrawl/tools/checkstyle/gui/icon.png new file mode 100644 index 00000000000..ca6c5906a47 Binary files /dev/null and b/src/main/resources/com/puppycrawl/tools/checkstyle/gui/icon.png differ diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/design/FinalClassCheck.xml b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/design/FinalClassCheck.xml index 4713beffba0..3b1b206f4f7 100644 --- a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/design/FinalClassCheck.xml +++ b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/design/FinalClassCheck.xml @@ -5,9 +5,8 @@ name="FinalClass" parent="com.puppycrawl.tools.checkstyle.TreeWalker"> <p> - Checks that a class which has only private constructors - is declared as final. Doesn't check for classes nested in interfaces - or annotations, as they are always {@code final} there. + Checks that a class that has only private constructors and has no descendant + classes is declared as final. </p> diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/modifier/RedundantModifierCheck.xml b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/modifier/RedundantModifierCheck.xml index a5023e5156d..2a4dcc3522c 100644 --- a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/modifier/RedundantModifierCheck.xml +++ b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/modifier/RedundantModifierCheck.xml @@ -21,7 +21,7 @@ Final modifier on methods of final and anonymous classes. </li> <li> - Inner {@code interface} declarations that are declared as {@code static}. + Type declarations nested under interfaces that are declared as {@code public} or {@code static}. </li> <li> Class constructors. @@ -31,13 +31,11 @@ </li> </ol> <p> - Interfaces by definition are abstract so the {@code abstract} - modifier on the interface is redundant. + interfaces by definition are abstract so the {@code abstract} modifier is redundant on them. </p> - <p>Classes inside of interfaces by definition are public and static, - so the {@code public} and {@code static} modifiers - on the inner classes are redundant. On the other hand, classes - inside of interfaces can be abstract or non abstract. + <p>Type declarations nested under interfaces by definition are public and static, + so the {@code public} and {@code static} modifiers on nested type declarations are redundant. + On the other hand, classes inside of interfaces can be abstract or non abstract. So, {@code abstract} modifier is allowed. </p> <p>Fields in interfaces and annotations are automatically @@ -108,7 +106,7 @@ } </pre> - diff --git a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/whitespace/WhitespaceAfterCheck.xml b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/whitespace/WhitespaceAfterCheck.xml index 1b3413a769c..605a57493b8 100644 --- a/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/whitespace/WhitespaceAfterCheck.xml +++ b/src/main/resources/com/puppycrawl/tools/checkstyle/meta/checks/whitespace/WhitespaceAfterCheck.xml @@ -11,7 +11,7 @@ EmptyForIteratorPad</a> to validate empty for iterators. </p> - diff --git a/src/main/resources/google_checks.xml b/src/main/resources/google_checks.xml index 515a844ac4d..a1db6502d1e 100644 --- a/src/main/resources/google_checks.xml +++ b/src/main/resources/google_checks.xml @@ -105,7 +105,8 @@ + LITERAL_WHILE, LITERAL_DO, LITERAL_FOR, DO_WHILE, ELLIPSIS, + LITERAL_SWITCH, LAMBDA"/> diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java index a3f4a0113b3..84ff80dd6dd 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AbstractPathTestSupport.java @@ -21,7 +21,6 @@ import java.io.File; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Collectors; @@ -79,14 +78,15 @@ protected final String getResourcePath(String filename) { /** * Reads the contents of a file. + * IDEA inspection RedundantThrows suppressed as a false positive. * * @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 + * @noinspection RedundantThrows */ protected static String readFile(String filename) throws IOException { - return toLfLineEnding(new String(Files.readAllBytes( - Paths.get(filename)), StandardCharsets.UTF_8)); + return toLfLineEnding(Files.readString(Paths.get(filename))); } /** diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/AstTreeStringPrinterTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/AstTreeStringPrinterTest.java index 62b2be410ad..fb566a9e3ae 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/AstTreeStringPrinterTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/AstTreeStringPrinterTest.java @@ -97,8 +97,8 @@ public void testPrintAst() throws Exception { System.getProperty("file.encoding", StandardCharsets.UTF_8.name())); final String actual = toLfLineEnding(AstTreeStringPrinter.printAst(text, JavaParser.Options.WITHOUT_COMMENTS)); - final String expected = toLfLineEnding(new String(Files.readAllBytes(Paths.get( - getPath("ExpectedAstTreeStringPrinter.txt"))), StandardCharsets.UTF_8)); + final String expected = toLfLineEnding(Files.readString(Paths.get( + getPath("ExpectedAstTreeStringPrinter.txt")))); assertWithMessage("Print AST output is invalid") .that(actual) diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java index 0075029bcc3..5033ad70be2 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DefaultLoggerTest.java @@ -65,7 +65,7 @@ public void testCtor() throws Exception { errorStream, OutputStreamOptions.CLOSE); dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); - final String output = errorStream.toString(StandardCharsets.UTF_8.name()); + final String output = errorStream.toString(StandardCharsets.UTF_8); final Constructor cons = getConstructor(); cons.setAccessible(true); final Object addExceptionMessage = cons.newInstance(DefaultLogger.ADD_EXCEPTION_MESSAGE, @@ -320,8 +320,8 @@ public void testNewCtor() throws Exception { dl.addException(new AuditEvent(5000, "myfile"), new IllegalStateException("upsss")); dl.auditFinished(new AuditEvent(6000, "myfile")); - infoOutput = infoStream.toString(StandardCharsets.UTF_8.name()); - errorOutput = errorStream.toString(StandardCharsets.UTF_8.name()); + infoOutput = infoStream.toString(StandardCharsets.UTF_8); + errorOutput = errorStream.toString(StandardCharsets.UTF_8); assertWithMessage("Info stream should be closed") .that(infoStream.closedCount) diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/DetailAstImplTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/DetailAstImplTest.java index 71717d3451d..4adb2f4cd6f 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/DetailAstImplTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/DetailAstImplTest.java @@ -30,8 +30,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; -import java.util.Collections; -import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; @@ -53,8 +51,7 @@ public class DetailAstImplTest extends AbstractModuleTestSupport { // Ignores file which are not meant to have root node intentionally. - public static final Set NO_ROOT_FILES = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + public static final Set NO_ROOT_FILES = Set.of( // fails with unexpected character "InputGrammar.java", // comment only files, no root @@ -64,7 +61,7 @@ public class DetailAstImplTest extends AbstractModuleTestSupport { "InputNoCodeInFile2.java", "InputNoCodeInFile3.java", "InputNoCodeInFile5.java" - ))); + ); @TempDir public File temporaryFolder; diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParserTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParserTest.java index 6dfcb74c770..8762a090955 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParserTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/JavadocDetailNodeParserTest.java @@ -22,7 +22,6 @@ import static com.google.common.truth.Truth.assertWithMessage; import java.io.File; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; @@ -47,9 +46,8 @@ public void testParseJavadocAsDetailNode() throws Exception { final JavadocDetailNodeParser.ParseStatus status = parser.parseJavadocAsDetailNode(ast); final String actual = toLfLineEnding(DetailNodeTreeStringPrinter.printTree(status.getTree(), "", "")); - final String expected = toLfLineEnding(new String(Files.readAllBytes(Paths.get( - getPath("ExpectedJavadocDetailNodeParser.txt"))), - StandardCharsets.UTF_8)); + final String expected = toLfLineEnding(Files.readString(Paths.get( + getPath("ExpectedJavadocDetailNodeParser.txt")))); assertWithMessage("Invalid parse result") .that(actual) .isEqualTo(expected); diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java index d0ff6b04498..06aaa526d88 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/MainTest.java @@ -32,7 +32,6 @@ import java.io.File; import java.io.IOException; import java.io.PrintStream; -import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import java.nio.file.Files; @@ -424,11 +423,10 @@ public void testExistingTargetFileXmlOutput(@SysErr Capturable systemErr, * * @param systemErr the system error stream * @param systemOut the system output stream - * @throws Exception if there is an error. */ @Test public void testNonClosedSystemStreams(@SysErr Capturable systemErr, - @SysOut Capturable systemOut) throws Exception { + @SysOut Capturable systemOut) { try (ShouldNotBeClosedStream stream = new ShouldNotBeClosedStream()) { System.setOut(stream); System.setErr(stream); @@ -1151,11 +1149,20 @@ public void testPrintTreeCommentsOption(@SysErr Capturable systemErr, .isEqualTo(""); } + /** + * Verifies the output of the command line parameter "-j". + * IDEA inspection RedundantThrows suppressed as a false positive. + * + * @param systemErr wrapper for {@code System.err} + * @param systemOut wrapper for {@code System.out} + * @throws IOException if I/O exception occurs while reading the test input. + * @noinspection RedundantThrows + */ @Test public void testPrintTreeJavadocOption(@SysErr Capturable systemErr, - @SysOut Capturable systemOut) throws Exception { - final String expected = new String(Files.readAllBytes(Paths.get( - getPath("InputMainExpectedInputJavadocComment.txt"))), StandardCharsets.UTF_8) + @SysOut Capturable systemOut) throws IOException { + final String expected = Files.readString(Paths.get( + getPath("InputMainExpectedInputJavadocComment.txt"))) .replaceAll("\\\\r\\\\n", "\\\\n").replaceAll("\r\n", "\n"); assertMainReturnCode(0, "-j", getPath("InputMainJavadocComment.javadoc")); @@ -1535,12 +1542,21 @@ public void testGenerateXpathSuppressionOptionCustomTabWidth(@SysErr Capturable .isEqualTo(""); } + /** + * Verifies the output of the command line parameter "-J". + * IDEA inspection RedundantThrows suppressed as a false positive. + * + * @param systemErr wrapper for {@code System.err} + * @param systemOut wrapper for {@code System.out} + * @throws IOException if I/O exception occurs while reading the test input. + * @noinspection RedundantThrows + */ @Test public void testPrintFullTreeOption(@SysErr Capturable systemErr, @SysOut Capturable systemOut) throws IOException { - final String expected = new String(Files.readAllBytes(Paths.get( - getPath("InputMainExpectedInputAstTreeStringPrinterJavadoc.txt"))), - StandardCharsets.UTF_8).replaceAll("\\\\r\\\\n", "\\\\n") + final String expected = Files.readString(Paths.get( + getPath("InputMainExpectedInputAstTreeStringPrinterJavadoc.txt"))) + .replaceAll("\\\\r\\\\n", "\\\\n") .replaceAll("\r\n", "\n"); assertMainReturnCode(0, "-J", getPath("InputMainAstTreeStringPrinterJavadoc.java")); @@ -1859,8 +1875,8 @@ private static class ShouldNotBeClosedStream extends PrintStream { private boolean isClosed; - /* package */ ShouldNotBeClosedStream() throws UnsupportedEncodingException { - super(new ByteArrayOutputStream(), false, StandardCharsets.UTF_8.name()); + /* package */ ShouldNotBeClosedStream() { + super(new ByteArrayOutputStream(), false, StandardCharsets.UTF_8); } @Override diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java index 7e6c2c6d723..b17def945a9 100644 --- a/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java +++ b/src/test/java/com/puppycrawl/tools/checkstyle/TreeWalkerTest.java @@ -107,7 +107,7 @@ public void testProperFileExtension() throws Exception { * This test is needed for 100% coverage. * The Pitest reports some conditions as redundant, for example: *

    -     *     if (!collection.isEmpty()) { // This may me omitted.
    +     *     if (!collection.isEmpty()) { // This may be omitted.
          *         Object value = doSomeHardJob();
          *         for (Item item : collection) {
          *             item.accept(value);
    @@ -603,9 +603,8 @@ public void testCacheWhenFileExternalResourceContentDoesNotChange() throws Excep
             verify(checkerConfig, filePath, expected);
     
             assertWithMessage("External resource is not present in cache")
    -                .that(new String(Files.readAllBytes(cacheFile.toPath()), StandardCharsets.UTF_8)
    -                        .contains("InputTreeWalkerSuppressionXpathFilter.xml"))
    -                .isTrue();
    +                .that(Files.readString(cacheFile.toPath()))
    +                .contains("InputTreeWalkerSuppressionXpathFilter.xml");
         }
     
         @Test
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java
    index 63c6b847734..d6765526cb7 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/MatchXpathCheckTest.java
    @@ -170,7 +170,7 @@ public void testAvoidInstanceCreationWithoutVar()
                 "13:9: " + getCheckMessage(MatchXpathCheck.MSG_KEY),
             };
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputMatchXpathAvoidInstanceCreationWithoutVar.java"),
    +                getPath("InputMatchXpathAvoidInstanceCreationWithoutVar.java"),
                     expected);
         }
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.java
    index e24f2f57ffa..2378963e718 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheckTest.java
    @@ -108,7 +108,7 @@ public void testResourceReferenceVariableIgnored() throws Exception {
             };
     
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputOneStatementPerLineTryWithResources.java"),
    +                getPath("InputOneStatementPerLineTryWithResources.java"),
                     expected);
         }
     
    @@ -116,7 +116,7 @@ public void testResourceReferenceVariableIgnored() throws Exception {
         public void testResourcesIgnored() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputOneStatementPerLineTryWithResourcesIgnore.java"),
    +                getPath("InputOneStatementPerLineTryWithResourcesIgnore.java"),
                     expected);
         }
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheckTest.java
    index 752d1a46380..929f6565bd3 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/design/FinalClassCheckTest.java
    @@ -28,7 +28,6 @@
     import com.puppycrawl.tools.checkstyle.DetailAstImpl;
     import com.puppycrawl.tools.checkstyle.api.TokenTypes;
     import com.puppycrawl.tools.checkstyle.internal.utils.TestUtil;
    -import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
     
     public class FinalClassCheckTest
         extends AbstractModuleTestSupport {
    @@ -41,12 +40,16 @@ protected String getPackageLocation() {
         @Test
         public void testGetRequiredTokens() {
             final FinalClassCheck checkObj = new FinalClassCheck();
    -        final int[] expected =
    -            {TokenTypes.CLASS_DEF,
    -             TokenTypes.CTOR_DEF,
    -             TokenTypes.PACKAGE_DEF,
    -             TokenTypes.LITERAL_NEW,
    -            };
    +        final int[] expected = {
    +            TokenTypes.ANNOTATION_DEF,
    +            TokenTypes.CLASS_DEF,
    +            TokenTypes.ENUM_DEF,
    +            TokenTypes.INTERFACE_DEF,
    +            TokenTypes.RECORD_DEF,
    +            TokenTypes.CTOR_DEF,
    +            TokenTypes.PACKAGE_DEF,
    +            TokenTypes.LITERAL_NEW,
    +        };
             assertWithMessage("Default required tokens are invalid")
                 .that(checkObj.getRequiredTokens())
                 .isEqualTo(expected);
    @@ -58,6 +61,8 @@ public void testFinalClass() throws Exception {
                 "11:1: " + getCheckMessage(MSG_KEY, "InputFinalClass"),
                 "19:4: " + getCheckMessage(MSG_KEY, "test4"),
                 "117:5: " + getCheckMessage(MSG_KEY, "someinnerClass"),
    +            "124:5: " + getCheckMessage(MSG_KEY, "SomeClass"),
    +            "130:5: " + getCheckMessage(MSG_KEY, "SomeClass"),
                 "151:1: " + getCheckMessage(MSG_KEY, "TestNewKeyword"),
                 "184:5: " + getCheckMessage(MSG_KEY, "NestedClass"),
             };
    @@ -91,7 +96,9 @@ public void testClassWithPrivateCtorAndNestedExtendingSubclassWithoutPackage()
         @Test
         public void testFinalClassConstructorInRecord() throws Exception {
     
    -        final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
    +        final String[] expected = {
    +            "27:9: " + getCheckMessage(MSG_KEY, "F"),
    +        };
     
             verifyWithInlineConfigParser(
                     getNonCompilablePath("InputFinalClassConstructorInRecord.java"),
    @@ -116,12 +123,16 @@ public void testImproperToken() {
         @Test
         public void testGetAcceptableTokens() {
             final FinalClassCheck obj = new FinalClassCheck();
    -        final int[] expected =
    -            {TokenTypes.CLASS_DEF,
    -             TokenTypes.CTOR_DEF,
    -             TokenTypes.PACKAGE_DEF,
    -             TokenTypes.LITERAL_NEW,
    -            };
    +        final int[] expected = {
    +            TokenTypes.ANNOTATION_DEF,
    +            TokenTypes.CLASS_DEF,
    +            TokenTypes.ENUM_DEF,
    +            TokenTypes.INTERFACE_DEF,
    +            TokenTypes.RECORD_DEF,
    +            TokenTypes.CTOR_DEF,
    +            TokenTypes.PACKAGE_DEF,
    +            TokenTypes.LITERAL_NEW,
    +        };
             assertWithMessage("Default acceptable tokens are invalid")
                 .that(obj.getAcceptableTokens())
                 .isEqualTo(expected);
    @@ -136,4 +147,55 @@ public void testQualifiedClassName() throws Exception {
                 .isEqualTo("ClassName");
         }
     
    +    @Test
    +    public void testFinalClassInnerAndNestedClasses() throws Exception {
    +        final String[] expected = {
    +            "19:5: " + getCheckMessage(MSG_KEY, "SameName"),
    +            "45:9: " + getCheckMessage(MSG_KEY, "SameName"),
    +            "69:13: " + getCheckMessage(MSG_KEY, "B"),
    +        };
    +        verifyWithInlineConfigParser(getPath("InputFinalClassInnerAndNestedClass.java"), expected);
    +    }
    +
    +    @Test
    +    public void testFinalClassStaticNestedClasses() throws Exception {
    +
    +        final String[] expected = {
    +            "14:17: " + getCheckMessage(MSG_KEY, "C"),
    +            "32:9: " + getCheckMessage(MSG_KEY, "B"),
    +            "43:9: " + getCheckMessage(MSG_KEY, "C"),
    +            "60:13: " + getCheckMessage(MSG_KEY, "Q"),
    +            "76:9: " + getCheckMessage(MSG_KEY, "F"),
    +            "83:9: " + getCheckMessage(MSG_KEY, "c"),
    +        };
    +
    +        verifyWithInlineConfigParser(
    +                getNonCompilablePath("InputFinalClassNestedStaticClassInsideInnerClass.java"),
    +                expected);
    +    }
    +
    +    @Test
    +    public void testFinalClassEnum() throws Exception {
    +        final String[] expected = {
    +            "35:5: " + getCheckMessage(MSG_KEY, "DerivedClass"),
    +        };
    +        verifyWithInlineConfigParser(getPath("InputFinalClassEnum.java"), expected);
    +    }
    +
    +    @Test
    +    public void testFinalClassAnnotation() throws Exception {
    +        final String[] expected = {
    +            "15:5: " + getCheckMessage(MSG_KEY, "DerivedClass"),
    +        };
    +        verifyWithInlineConfigParser(getPath("InputFinalClassAnnotation.java"), expected);
    +    }
    +
    +    @Test
    +    public void testFinalClassInterface() throws Exception {
    +        final String[] expected = {
    +            "15:5: " + getCheckMessage(MSG_KEY, "DerivedClass"),
    +        };
    +        verifyWithInlineConfigParser(getPath("InputFinalClassInterface.java"), expected);
    +    }
    +
     }
    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 24043c439ac..967145759b6 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
    @@ -25,7 +25,6 @@
     import static com.puppycrawl.tools.checkstyle.checks.imports.ImportControlCheck.MSG_UNKNOWN_PKG;
     
     import java.io.File;
    -import java.nio.charset.StandardCharsets;
     import java.nio.file.Files;
     
     import org.junit.jupiter.api.Test;
    @@ -121,9 +120,9 @@ public void testUnknown() throws Exception {
                 final String message = getCheckstyleExceptionMessage(ex);
                 final String messageStart = "Unable to find: ";
     
    -            assertWithMessage("Invalid message, should start with: " + messageStart)
    -                    .that(message.startsWith(message))
    -                    .isTrue();
    +            assertWithMessage("Invalid message, should start with: %s", messageStart)
    +                    .that(message)
    +                    .startsWith(messageStart);
             }
         }
     
    @@ -140,9 +139,9 @@ public void testBroken() throws Exception {
                 final String message = getCheckstyleExceptionMessage(ex);
                 final String messageStart = "Unable to load ";
     
    -            assertWithMessage("Invalid message, should start with: " + messageStart)
    -                    .that(message.startsWith(message))
    -                    .isTrue();
    +            assertWithMessage("Invalid message, should start with: %s", messageStart)
    +                    .that(message)
    +                    .startsWith(messageStart);
             }
         }
     
    @@ -292,9 +291,9 @@ public void testResourceUnableToLoad() throws Exception {
                 final String message = getCheckstyleExceptionMessage(ex);
                 final String messageStart = "Unable to find: ";
     
    -            assertWithMessage("Invalid message, should start with: " + messageStart)
    -                    .that(message.startsWith(message))
    -                    .isTrue();
    +            assertWithMessage("Invalid message, should start with: %s", messageStart)
    +                    .that(message)
    +                    .startsWith(messageStart);
             }
         }
     
    @@ -319,9 +318,9 @@ public void testUrlInFilePropertyUnableToLoad() throws Exception {
                 final String message = getCheckstyleExceptionMessage(ex);
                 final String messageStart = "Unable to load ";
     
    -            assertWithMessage("Invalid message, should start with: " + messageStart)
    -                    .that(message.startsWith(message))
    -                    .isTrue();
    +            assertWithMessage("Invalid message, should start with: %s", messageStart)
    +                    .that(message)
    +                    .startsWith(messageStart);
             }
         }
     
    @@ -344,8 +343,7 @@ public void testCacheWhenFileExternalResourceContentDoesNotChange() throws Excep
             // One more time to use cache.
             verify(checkerConfig, filePath, expected);
     
    -        final String contents = new String(Files.readAllBytes(cacheFile.toPath()),
    -                StandardCharsets.UTF_8);
    +        final String contents = Files.readString(cacheFile.toPath());
             assertWithMessage("External resource is not present in cache")
                     .that(contents.contains("InputImportControlOneRegExp.xml"))
                     .isTrue();
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheckTest.java
    index 1c8d9ec31a8..52ed3d6855e 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/javadoc/MissingJavadocMethodCheckTest.java
    @@ -403,8 +403,7 @@ public void testConstructor() throws Exception {
         public void testNotPublicInterfaceMethods() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath(
    -            "InputMissingJavadocMethodInterfacePrivateMethod.java"), expected);
    +                getPath("InputMissingJavadocMethodInterfacePrivateMethod.java"), expected);
         }
     
         @Test
    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 8bea161e5cb..0df0e065b24 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
    @@ -255,7 +255,7 @@ public void testClassFanOutComplexityRecords() throws Exception {
         public void testClassFanOutComplexityIgnoreVar() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputClassFanOutComplexityVar.java"), expected);
    +                getPath("InputClassFanOutComplexityVar.java"), expected);
         }
     
         @Test
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheckTest.java
    index 85d97366701..5d2dba63018 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/modifier/InterfaceMemberImpliedModifierCheckTest.java
    @@ -358,7 +358,7 @@ public void testPackageScopeInterface() throws Exception {
         public void testPrivateMethodsOnInterface() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputInterfaceMemberImpliedModifierPrivateMethods.java"),
    +                getPath("InputInterfaceMemberImpliedModifierPrivateMethods.java"),
                 expected);
         }
     
    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 c22b0057365..6190c4b20bf 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
    @@ -21,10 +21,12 @@
     
     import static com.google.common.truth.Truth.assertWithMessage;
     import static com.puppycrawl.tools.checkstyle.checks.modifier.RedundantModifierCheck.MSG_KEY;
    +import static org.junit.jupiter.api.Assertions.assertThrows;
     
     import org.junit.jupiter.api.Test;
     
     import com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport;
    +import com.puppycrawl.tools.checkstyle.DetailAstImpl;
     import com.puppycrawl.tools.checkstyle.api.TokenTypes;
     import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
     
    @@ -126,6 +128,7 @@ public void testNestedClassConsInPublicInterfaceHasValidPublicModifier() throws
     
             final String[] expected = {
                 "22:17: " + getCheckMessage(MSG_KEY, "public"),
    +            "24:13: " + getCheckMessage(MSG_KEY, "public"),
                 "26:21: " + getCheckMessage(MSG_KEY, "public"),
                 "37:12: " + getCheckMessage(MSG_KEY, "public"),
                 "45:17: " + getCheckMessage(MSG_KEY, "public"),
    @@ -149,12 +152,28 @@ public void testGetAcceptableTokens() {
                 TokenTypes.CLASS_DEF,
                 TokenTypes.ENUM_DEF,
                 TokenTypes.RESOURCE,
    +            TokenTypes.ANNOTATION_DEF,
             };
             assertWithMessage("Invalid acceptable tokens")
                 .that(actual)
                 .isEqualTo(expected);
         }
     
    +    @Test
    +    public void testWrongTokenType() {
    +        final RedundantModifierCheck obj = new RedundantModifierCheck();
    +        final DetailAstImpl ast = new DetailAstImpl();
    +        ast.initialize(TokenTypes.LITERAL_NULL, "null");
    +
    +        final IllegalStateException exception = assertThrows(IllegalStateException.class, () -> {
    +            obj.visitToken(ast);
    +        }, "IllegalStateException was expected");
    +
    +        assertWithMessage("Expected and actual violation messages do not match")
    +                .that(exception.getMessage())
    +                .isEqualTo("Unexpected token type: " + ast.getType());
    +    }
    +
         @Test
         public void testGetRequiredTokens() {
             final RedundantModifierCheck redundantModifierCheckObj = new RedundantModifierCheck();
    @@ -259,7 +278,7 @@ public void testTryWithResourcesBlock() throws Exception {
                 "18:19: " + getCheckMessage(MSG_KEY, "final"),
             };
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputRedundantModifierTryWithResources.java"),
    +                getPath("InputRedundantModifierTryWithResources.java"),
                     expected);
         }
     
    @@ -273,6 +292,22 @@ public void testNestedDef() throws Exception {
                 "13:5: " + getCheckMessage(MSG_KEY, "static"),
                 "13:12: " + getCheckMessage(MSG_KEY, "public"),
                 "16:9: " + getCheckMessage(MSG_KEY, "public"),
    +            "19:5: " + getCheckMessage(MSG_KEY, "public"),
    +            "19:12: " + getCheckMessage(MSG_KEY, "static"),
    +            "22:5: " + getCheckMessage(MSG_KEY, "public"),
    +            "22:12: " + getCheckMessage(MSG_KEY, "abstract"),
    +            "22:21: " + getCheckMessage(MSG_KEY, "static"),
    +            "26:1: " + getCheckMessage(MSG_KEY, "abstract"),
    +            "28:5: " + getCheckMessage(MSG_KEY, "public"),
    +            "28:12: " + getCheckMessage(MSG_KEY, "static"),
    +            "32:9: " + getCheckMessage(MSG_KEY, "public"),
    +            "32:16: " + getCheckMessage(MSG_KEY, "static"),
    +            "34:13: " + getCheckMessage(MSG_KEY, "public"),
    +            "34:20: " + getCheckMessage(MSG_KEY, "static"),
    +            "37:13: " + getCheckMessage(MSG_KEY, "public"),
    +            "37:20: " + getCheckMessage(MSG_KEY, "static"),
    +            "40:13: " + getCheckMessage(MSG_KEY, "public"),
    +            "40:20: " + getCheckMessage(MSG_KEY, "static"),
             };
             verifyWithInlineConfigParser(getPath(
                     "InputRedundantModifierNestedDef.java"), expected);
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTest.java
    index 053721d615c..3bf46e4103c 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/naming/LocalFinalVariableNameCheckTest.java
    @@ -116,8 +116,7 @@ public void testTryWithResourcesJava9() throws Exception {
     
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath(
    -            "InputLocalFinalVariableNameTryResourcesJava9.java"), expected);
    +                getPath("InputLocalFinalVariableNameTryResourcesJava9.java"), expected);
         }
     
     }
    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 c29129f5795..8152f10ffbf 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
    @@ -162,7 +162,7 @@ public void testInterfacesExcludePublic() throws Exception {
             };
     
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputMethodNamePublicMethodsInInterfaces.java"),
    +                getPath("InputMethodNamePublicMethodsInInterfaces.java"),
                 expected);
         }
     
    @@ -178,7 +178,7 @@ public void testInterfacesExcludePrivate() throws Exception {
             };
     
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputMethodNamePrivateMethodsInInterfaces.java"),
    +                getPath("InputMethodNamePrivateMethodsInInterfaces.java"),
                 expected);
         }
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.java
    index 63239857fa6..e00db20dd31 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/regexp/RegexpMultilineCheckTest.java
    @@ -229,12 +229,8 @@ public void testMinimumWithCustomMessage() throws Exception {
         private static CharSequence makeLargeXyString() {
             // now needs 10'000 or 100'000, as just 1000 is no longer enough today to provoke the
             // StackOverflowError
    -        final int size = 100000;
    -        final StringBuilder largeString = new StringBuilder(size);
    -        for (int i = 0; i < size / 2; i++) {
    -            largeString.append("xy");
    -        }
    -        return largeString;
    +        final int size = 100_000;
    +        return "xy".repeat(size / 2);
         }
     
         @Test
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheckTest.java
    index fc5cfa374ee..004d055af36 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/EmptyLineSeparatorCheckTest.java
    @@ -248,6 +248,35 @@ public void testSingleCommentSeparatedFromPackage() throws Exception {
                 expected);
         }
     
    +    @Test
    +    public void testEnumMembers() throws Exception {
    +        final String[] expected = {
    +            "22:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "27:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "28:5: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "VARIABLE_DEF"),
    +            "31:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "CTOR_DEF"),
    +            "36:5: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "STATIC_INIT"),
    +            "40:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "STATIC_INIT"),
    +        };
    +        verifyWithInlineConfigParser(
    +            getPath("InputEmptyLineSeparatorEnumMembers.java"), expected
    +        );
    +    }
    +
    +    @Test
    +    public void testInterfaceFields() throws Exception {
    +        final String[] expected = {
    +            "21:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "25:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "34:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "38:5: " + getCheckMessage(MSG_MULTIPLE_LINES, "VARIABLE_DEF"),
    +            "45:5: " + getCheckMessage(MSG_SHOULD_BE_SEPARATED, "VARIABLE_DEF"),
    +        };
    +        verifyWithInlineConfigParser(
    +            getPath("InputEmptyLineSeparatorInterfaceFields.java"), expected
    +        );
    +    }
    +
         @Test
         public void testGetAcceptableTokens() {
             final EmptyLineSeparatorCheck emptyLineSeparatorCheckObj = new EmptyLineSeparatorCheck();
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.java
    index 9f70a9cf1e8..bb17d3849d8 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/OperatorWrapCheckTest.java
    @@ -160,7 +160,7 @@ public void testGuardedPattern() throws Exception {
         public void testTryWithResources() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputOperatorWrapTryWithResources.java"), expected);
    +                getPath("InputOperatorWrapTryWithResources.java"), expected);
         }
     
         @Test
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.java
    index d0194a2787d..10ab8bf44b3 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/whitespace/WhitespaceAfterCheckTest.java
    @@ -186,4 +186,45 @@ public void testCountUnicodeCorrectly() throws Exception {
             verifyWithInlineConfigParser(
                     getPath("InputWhitespaceAfterCountUnicodeCorrectly.java"), expected);
         }
    +
    +    @Test
    +    public void testVarargs() throws Exception {
    +        final String[] expected = {
    +            "14:27: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "..."),
    +            "17:67: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "..."),
    +            "20:42: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "..."),
    +            "27:45: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "..."),
    +            "36:19: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "..."),
    +        };
    +        verifyWithInlineConfigParser(getPath("InputWhitespaceAfterVarargs.java"), expected);
    +    }
    +
    +    @Test
    +    public void testSwitchStatements() throws Exception {
    +        final String[] expected = {
    +            "18:9: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "switch"),
    +            "30:9: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "switch"),
    +            "32:21: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +            "39:9: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "switch"),
    +            "40:27: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +            "41:28: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +            "48:9: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "switch"),
    +        };
    +
    +        verifyWithInlineConfigParser(
    +                getNonCompilablePath("InputWhitespaceAfterSwitchStatements.java"),
    +                expected);
    +    }
    +
    +    @Test
    +    public void testLambdaExpressions() throws Exception {
    +        final String[] expected = {
    +            "17:29: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +            "19:29: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +            "27:49: " + getCheckMessage(MSG_WS_NOT_FOLLOWED, "->"),
    +        };
    +
    +        verifyWithInlineConfigParser(getPath("InputWhitespaceAfterLambdaExpressions.java"),
    +                expected);
    +    }
     }
    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 ed34838f136..f0b5896658e 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/filters/SuppressionsLoaderTest.java
    @@ -60,9 +60,9 @@ public void testNoSuppressions() throws Exception {
         @Test
         public void testLoadFromUrl() throws Exception {
             final String[] urlCandidates = {
    -            "https://checkstyle.org/files/suppressions_none.xml",
                 "https://raw.githubusercontent.com/checkstyle/checkstyle/master/src/site/resources/"
                     + "files/suppressions_none.xml",
    +            "https://checkstyle.org/files/suppressions_none.xml",
             };
             FilterSet actualFilterSet = null;
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammar/AstRegressionTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammar/AstRegressionTest.java
    index 53aa8e9c822..ff3a73f8c1d 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/grammar/AstRegressionTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammar/AstRegressionTest.java
    @@ -66,13 +66,13 @@ public void testJava8ClassAstTree2() throws Exception {
         @Test
         public void testJava9TryWithResourcesAstTree() throws Exception {
             verifyAst(getPath("ExpectedJava9TryWithResources.txt"),
    -                getNonCompilablePath("/java9/InputJava9TryWithResources.java"));
    +                getPath("/java9/InputJava9TryWithResources.java"));
         }
     
         @Test
         public void testAdvanceJava9TryWithResourcesAstTree() throws Exception {
             verifyAst(getPath("ExpectedAdvanceJava9TryWithResources.txt"),
    -                getNonCompilablePath("/java9/InputAdvanceJava9TryWithResources.java"));
    +                getPath("/java9/InputAdvanceJava9TryWithResources.java"));
         }
     
         @Test
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/grammar/Java9TryWithResourcesTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/grammar/Java9TryWithResourcesTest.java
    index 55ce07cc061..1d2a6f734e6 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/grammar/Java9TryWithResourcesTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/grammar/Java9TryWithResourcesTest.java
    @@ -38,7 +38,7 @@ protected String getPackageLocation() {
         public void testCanParse() throws Exception {
             final String[] expected = CommonUtil.EMPTY_STRING_ARRAY;
             verifyWithInlineConfigParser(
    -                getNonCompilablePath("InputJava9TryWithResources.java"), expected);
    +                getPath("InputJava9TryWithResources.java"), expected);
         }
     
     }
    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 42e4c402f8a..689bf6245c2 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/AllChecksTest.java
    @@ -552,9 +552,7 @@ public void testAllCheckstyleMessages() throws Exception {
                         .isEqualTo(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL);
     
                     // below is required for package/private classes
    -                if (!message.isAccessible()) {
    -                    message.setAccessible(true);
    -                }
    +                message.trySetAccessible();
     
                     if (!INTERNAL_MODULES.contains(module.getSimpleName())) {
                         verifyCheckstyleMessage(usedMessages, module, message);
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java
    index bd3d86c1276..d5e3fb569fc 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/CliOptionsXdocsSyncTest.java
    @@ -20,8 +20,6 @@
     package com.puppycrawl.tools.checkstyle.internal;
     
     import static com.google.common.truth.Truth.assertWithMessage;
    -import static java.nio.charset.StandardCharsets.UTF_8;
    -import static org.junit.Assert.assertTrue;
     
     import java.nio.file.Files;
     import java.nio.file.Path;
    @@ -79,8 +77,10 @@ public void validateCliDocSections() throws Exception {
                     .isEqualTo(descXdoc);
                 cmdDesc.remove(option);
             }
    -        assertTrue("CLI Options: " + cmdDesc + " present in "
    -                + "cmdline.xml.vm, not documented in Main.java", cmdDesc.isEmpty());
    +        assertWithMessage("CLI Options: %s present in cmdline.xml.vm, not documented in Main.java",
    +                    cmdDesc)
    +                .that(cmdDesc)
    +                .isEmpty();
         }
     
         @Test
    @@ -127,7 +127,7 @@ private static Set getParameters(String text, String regex) {
     
         private static NodeList getSectionsFromXdoc(String xdocPath) throws Exception {
             final Path path = Paths.get(xdocPath);
    -        final String input = new String(Files.readAllBytes(path), UTF_8);
    +        final String input = Files.readString(path);
             final Document document = XmlUtil.getRawXml(path.getFileName().toString(), input, input);
             return document.getElementsByTagName("section");
         }
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsJavaDocsTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsJavaDocsTest.java
    index ddbf2852f7d..c11c14aabfd 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsJavaDocsTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsJavaDocsTest.java
    @@ -20,7 +20,6 @@
     package com.puppycrawl.tools.checkstyle.internal;
     
     import static com.google.common.truth.Truth.assertWithMessage;
    -import static java.nio.charset.StandardCharsets.UTF_8;
     
     import java.io.File;
     import java.net.URI;
    @@ -150,7 +149,7 @@ public void testAllCheckSectionJavaDocs() throws Exception {
                     continue;
                 }
     
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
                 final NodeList sources = document.getElementsByTagName("section");
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsMobileWrapperTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsMobileWrapperTest.java
    index df1643dd222..bf88341cd6b 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsMobileWrapperTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsMobileWrapperTest.java
    @@ -20,7 +20,6 @@
     package com.puppycrawl.tools.checkstyle.internal;
     
     import static com.google.common.truth.Truth.assertWithMessage;
    -import static java.nio.charset.StandardCharsets.UTF_8;
     
     import java.io.File;
     import java.nio.file.Files;
    @@ -55,7 +54,7 @@ public void testAllCheckSectionMobileWrapper() throws Exception {
                 final File file = path.toFile();
                 final String fileName = file.getName();
     
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 assertWithMessage(fileName + ": input file cannot be empty")
                         .that(input)
                         .isNotEmpty();
    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 68cd5482f3d..4f92f595037 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XdocsPagesTest.java
    @@ -21,7 +21,6 @@
     
     import static com.google.common.truth.Truth.assertWithMessage;
     import static java.lang.Integer.parseInt;
    -import static java.nio.charset.StandardCharsets.UTF_8;
     
     import java.beans.PropertyDescriptor;
     import java.io.File;
    @@ -93,7 +92,7 @@ public class XdocsPagesTest {
         private static final Pattern DESCRIPTION_VERSION = Pattern
                 .compile("^Since Checkstyle \\d+\\.\\d+(\\.\\d+)?");
     
    -    private static final List XML_FILESET_LIST = Arrays.asList(
    +    private static final List XML_FILESET_LIST = List.of(
                 "TreeWalker",
                 "name=\"Checker\"",
                 "name=\"Header\"",
    @@ -122,7 +121,7 @@ public class XdocsPagesTest {
                 getProperties(AbstractJavadocCheck.class);
         private static final Set FILESET_PROPERTIES = getProperties(AbstractFileSetCheck.class);
     
    -    private static final List UNDOCUMENTED_PROPERTIES = Arrays.asList(
    +    private static final List UNDOCUMENTED_PROPERTIES = List.of(
                 "Checker.classLoader",
                 "Checker.classloader",
                 "Checker.moduleClassLoader",
    @@ -135,7 +134,7 @@ public class XdocsPagesTest {
                 "SuppressionCommentFilter.fileContents"
         );
     
    -    private static final List PROPERTIES_ALLOWED_GET_TYPES_FROM_METHOD = Arrays.asList(
    +    private static final List PROPERTIES_ALLOWED_GET_TYPES_FROM_METHOD = List.of(
                 // static field (all upper case)
                 "SuppressWarningsHolder.aliasList",
                 // loads string into memory similar to file
    @@ -152,11 +151,11 @@ public class XdocsPagesTest {
         );
     
         private static final Set SUN_MODULES = Collections.unmodifiableSet(
    -        new HashSet<>(CheckUtil.getConfigSunStyleModules()));
    +        CheckUtil.getConfigSunStyleModules());
         // ignore the not yet properly covered modules while testing newly added ones
         // add proper sections to the coverage report and integration tests
         // and then remove this list eventually
    -    private static final List IGNORED_SUN_MODULES = Arrays.asList(
    +    private static final List IGNORED_SUN_MODULES = List.of(
                 "ArrayTypeStyle",
                 "AvoidNestedBlocks",
                 "AvoidStarImport",
    @@ -221,11 +220,11 @@ public class XdocsPagesTest {
                 "WhitespaceAround"
         );
         private static final Set GOOGLE_MODULES = Collections.unmodifiableSet(
    -        new HashSet<>(CheckUtil.getConfigGoogleStyleModules()));
    +        CheckUtil.getConfigGoogleStyleModules());
     
         @Test
         public void testAllChecksPresentOnAvailableChecksPage() throws Exception {
    -        final String availableChecks = new String(Files.readAllBytes(AVAILABLE_CHECKS_PATH), UTF_8);
    +        final String availableChecks = Files.readString(AVAILABLE_CHECKS_PATH);
     
             CheckUtil.getSimpleNames(CheckUtil.getCheckstyleChecks())
                 .stream()
    @@ -257,7 +256,7 @@ public void testAllChecksPageInSyncWithChecksSummaries() throws Exception {
                     continue;
                 }
     
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
                 final NodeList sources = document.getElementsByTagName("subsection");
     
    @@ -288,7 +287,7 @@ public void testAllChecksPageInSyncWithChecksSummaries() throws Exception {
     
         private static Map readSummaries() throws Exception {
             final String fileName = AVAILABLE_CHECKS_PATH.getFileName().toString();
    -        final String input = new String(Files.readAllBytes(AVAILABLE_CHECKS_PATH), UTF_8);
    +        final String input = Files.readString(AVAILABLE_CHECKS_PATH);
             final Document document = XmlUtil.getRawXml(fileName, input, input);
             final NodeList rows = document.getElementsByTagName("tr");
             final Map result = new HashMap<>();
    @@ -308,7 +307,7 @@ private static Map readSummaries() throws Exception {
         @Test
         public void testAllSubSections() throws Exception {
             for (Path path : XdocUtil.getXdocsFilePaths()) {
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final String fileName = path.getFileName().toString();
     
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
    @@ -354,7 +353,7 @@ else if ("sun_style.xml".equals(fileName)) {
         @Test
         public void testAllXmlExamples() throws Exception {
             for (Path path : XdocUtil.getXdocsFilePaths()) {
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final String fileName = path.getFileName().toString();
     
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
    @@ -471,7 +470,7 @@ public void testAllCheckSections() throws Exception {
                     continue;
                 }
     
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
                 final NodeList sources = document.getElementsByTagName("section");
                 String lastSectionName = null;
    @@ -518,7 +517,7 @@ public void testAllCheckSectionsEx() throws Exception {
             final Path path = Paths.get(XdocUtil.DIRECTORY_PATH + "/config.xml");
             final String fileName = path.getFileName().toString();
     
    -        final String input = new String(Files.readAllBytes(path), UTF_8);
    +        final String input = Files.readString(path);
             final Document document = XmlUtil.getRawXml(fileName, input, input);
             final NodeList sources = document.getElementsByTagName("section");
     
    @@ -1284,7 +1283,7 @@ private static Field getField(Class fieldClass, String propertyName) {
             while (!Object.class.equals(currentClass)) {
                 try {
                     result = currentClass.getDeclaredField(propertyName);
    -                result.setAccessible(true);
    +                result.trySetAccessible();
                     break;
                 }
                 catch (NoSuchFieldException ignored) {
    @@ -1360,9 +1359,7 @@ private static void validateViolationSection(String fileName, String sectionName
     
             for (Field field : fields) {
                 // below is required for package/private classes
    -            if (!field.isAccessible()) {
    -                field.setAccessible(true);
    -            }
    +            field.trySetAccessible();
     
                 list.add(field.get(null).toString());
             }
    @@ -1539,7 +1536,7 @@ public void testAllStyleRules() throws Exception {
             for (Path path : XdocUtil.getXdocsStyleFilePaths(XdocUtil.getXdocsFilePaths())) {
                 final String fileName = path.getFileName().toString();
                 final String styleName = fileName.substring(0, fileName.lastIndexOf('_'));
    -            final String input = new String(Files.readAllBytes(path), UTF_8);
    +            final String input = Files.readString(path);
                 final Document document = XmlUtil.getRawXml(fileName, input, input);
                 final NodeList sources = document.getElementsByTagName("tr");
     
    diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XpathRegressionTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XpathRegressionTest.java
    index 702765727ca..61f7d48f294 100644
    --- a/src/test/java/com/puppycrawl/tools/checkstyle/internal/XpathRegressionTest.java
    +++ b/src/test/java/com/puppycrawl/tools/checkstyle/internal/XpathRegressionTest.java
    @@ -26,8 +26,6 @@
     import java.nio.file.Files;
     import java.nio.file.Path;
     import java.nio.file.Paths;
    -import java.util.Arrays;
    -import java.util.Collections;
     import java.util.HashSet;
     import java.util.Locale;
     import java.util.Map;
    @@ -52,19 +50,17 @@
     public class XpathRegressionTest extends AbstractModuleTestSupport {
     
         // Checks that not compatible with SuppressionXpathFilter
    -    public static final Set INCOMPATIBLE_CHECK_NAMES =
    -        Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
    +    public static final Set INCOMPATIBLE_CHECK_NAMES = Set.of(
                 "NoCodeInFile (reason is that AST is not generated for a file not containing code)",
                 "Regexp (reason is at  #7759)",
                 "RegexpSinglelineJava (reason is at  #7759)"
    -    )));
    +    );
     
         // Javadoc checks are not compatible with SuppressionXpathFilter
         // till https://github.com/checkstyle/checkstyle/issues/5770
         // then all of them should be added to the list of incompatible checks
         // and this field should be removed
    -    public static final Set INCOMPATIBLE_JAVADOC_CHECK_NAMES =
    -            Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
    +    public static final Set INCOMPATIBLE_JAVADOC_CHECK_NAMES = Set.of(
                         "AtclauseOrder",
                         "JavadocBlockTagLocation",
                         "JavadocMethod",
    @@ -80,21 +76,20 @@ public class XpathRegressionTest extends AbstractModuleTestSupport {
                         "SingleLineJavadoc",
                         "SummaryJavadoc",
                         "WriteTag"
    -    )));
    +    );
     
         // Older regex-based checks that are under INCOMPATIBLE_JAVADOC_CHECK_NAMES
         // but not subclasses of AbstractJavadocCheck.
    -    private static final Set> REGEXP_JAVADOC_CHECKS =
    -            Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
    +    private static final Set> REGEXP_JAVADOC_CHECKS = Set.of(
                         JavadocStyleCheck.class,
                         JavadocMethodCheck.class,
                         JavadocTypeCheck.class,
                         WriteTagCheck.class
    -    )));
    +    );
     
         // Checks that allowed to have no XPath IT Regression Testing
         // till https://github.com/checkstyle/checkstyle/issues/6207
    -    private static final Set MISSING_CHECK_NAMES = new HashSet<>(Arrays.asList(
    +    private static final Set MISSING_CHECK_NAMES = Set.of(
                 "BooleanExpressionComplexity",
                 "CatchParameterName",
                 "ClassDataAbstractionCoupling",
    @@ -134,7 +129,6 @@ public class XpathRegressionTest extends AbstractModuleTestSupport {
                 "ParameterAssignment",
                 "ParameterName",
                 "ParameterNumber",
    -            "RedundantImport",
                 "RedundantModifier",
                 "ReturnCount",
                 "SeparatorWrap",
    @@ -148,12 +142,12 @@ public class XpathRegressionTest extends AbstractModuleTestSupport {
                 "ThrowsCount",
                 "TypeName",
                 "VisibilityModifier"
    -    ));
    +    );
     
         // Modules that will never have xpath support ever because they not report violations
    -    private static final Set NO_VIOLATION_MODULES = new HashSet<>(Collections.singletonList(
    +    private static final Set NO_VIOLATION_MODULES = Set.of(
                 "SuppressWarningsHolder"
    -    ));
    +    );
     
         private static Set simpleCheckNames;
         private static Map allowedDirectoryAndChecks;
    @@ -256,7 +250,7 @@ public void validateIntegrationTestClassNames() throws Exception {
             final Set allChecks = new HashSet<>(simpleCheckNames);
             allChecks.removeAll(INCOMPATIBLE_JAVADOC_CHECK_NAMES);
             allChecks.removeAll(INCOMPATIBLE_CHECK_NAMES);
    -        allChecks.removeAll(Arrays.asList("Regexp", "RegexpSinglelineJava", "NoCodeInFile"));
    +        allChecks.removeAll(Set.of("Regexp", "RegexpSinglelineJava", "NoCodeInFile"));
             allChecks.removeAll(MISSING_CHECK_NAMES);
             allChecks.removeAll(NO_VIOLATION_MODULES);
             allChecks.removeAll(compatibleChecks);
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassConstructorInRecord.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassConstructorInRecord.java
    index 364ebada11d..e866794b3b0 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassConstructorInRecord.java
    +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassConstructorInRecord.java
    @@ -14,4 +14,20 @@ public record InputFinalClassConstructorInRecord(String string) { // ok
         public InputFinalClassConstructorInRecord(int x) {
             this(String.valueOf(x));
         }
    +
    +    class F {
    +        private F() {
    +        }
    +    }
    +
    +    class K extends F {
    +    }
    +
    +    class X {
    +        class F { // violation
    +            private F() {
    +            }
    +        }
    +    }
    +
     }
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassNestedStaticClassInsideInnerClass.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassNestedStaticClassInsideInnerClass.java
    new file mode 100644
    index 00000000000..057674640e2
    --- /dev/null
    +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassNestedStaticClassInsideInnerClass.java
    @@ -0,0 +1,98 @@
    +/*
    +FinalClass
    +
    +
    +*/
    +
    +//non-compiled with javac: Compilable with Java16
    +package com.puppycrawl.tools.checkstyle.checks.design.finalclass;
    +
    +public class InputFinalClassNestedStaticClassInsideInnerClass {
    +    class M {
    +        class A {
    +            static class B {
    +                static class C { // violation
    +                    private C() {
    +                    }
    +                }
    +            }
    +        }
    +    }
    +
    +    class Mw {
    +        static class B {
    +            static class C { // ok
    +                private C() {
    +                }
    +            }
    +        }
    +    }
    +
    +    class A {
    +        class B { // violation
    +            class C { // ok
    +                private C() {}
    +            }
    +            class D extends C {
    +            }
    +            private B() {}
    +        }
    +    }
    +
    +    class B {
    +        class C { // violation
    +            private C() {}
    +            class D extends Mw.B.C {
    +            }
    +        }
    +    }
    +
    +    class P extends Q {
    +    }
    +
    +    class Q { // ok
    +        private Q() {
    +        }
    +    }
    +
    +    class PR {
    +        static class P {
    +            static class Q { // violation
    +                private Q() {
    +                }
    +            }
    +        }
    +    }
    +
    +    class F {
    +        private F() {
    +        }
    +    }
    +
    +    class K extends F {
    +    }
    +
    +    class X {
    +        class F { // violation
    +            private F() {
    +            }
    +        }
    +    }
    +
    +    class a {
    +        static class c { // violation
    +            private c() {
    +            }
    +        }
    +    }
    +
    +    class d {
    +        class e extends c {
    +        }
    +    }
    +
    +    class c {
    +        private c() {
    +        }
    +    }
    +}
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterSwitchStatements.java b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterSwitchStatements.java
    new file mode 100644
    index 00000000000..440c21d3619
    --- /dev/null
    +++ b/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterSwitchStatements.java
    @@ -0,0 +1,58 @@
    +/*
    +WhitespaceAfter
    +tokens = LITERAL_SWITCH, LAMBDA
    +
    +*/
    +
    +//non-compiled with javac: Compilable with Java17
    +package com.puppycrawl.tools.checkstyle.checks.whitespace.whitespaceafter;
    +
    +public class InputWhitespaceAfterSwitchStatements {
    +    enum Day {
    +        NONE, SAT, SUN, MON,
    +        TUS, WED, THU, FRI
    +    }
    +
    +    String whatIsToday(Day day) {
    +        String today;
    +        switch(day) { // violation
    +            case SAT, SUN:
    +                today = "Weekend day";
    +                break;
    +            default:
    +                throw new IllegalArgumentException("Invalid day: " + day.name());
    +        }
    +        return today;
    +    }
    +
    +    String whatIsToday2(Day day) {
    +        var today = "";
    +        switch(day) { // violation
    +            case MON, TUS, WED, THU, FRI -> today = "Working day";
    +            default ->throw new IllegalArgumentException(); // violation
    +        }
    +        return today;
    +    }
    +
    +    void switchWithPatternMatching() {
    +        Object o = "";
    +        switch(o) { // violation
    +            case String s ->s.trim(); // violation
    +            case Integer a ->a.intValue(); // violation
    +            default -> throw new IllegalArgumentException(); // ok
    +        }
    +    }
    +
    +    void normalSwitch() {
    +        final int a = 12;
    +        switch(a) { // violation
    +            case 1:
    +                break;
    +            case 2:
    +            case 3:
    +                break;
    +            default:
    +                break;
    +        }
    +    }
    +}
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java
    similarity index 88%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java
    index d920fa09afe..a5b3422a19a 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/matchxpath/InputMatchXpathAvoidInstanceCreationWithoutVar.java
    @@ -5,7 +5,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java10
    +
     package com.puppycrawl.tools.checkstyle.checks.coding.matchxpath;
     
     public class InputMatchXpathAvoidInstanceCreationWithoutVar {
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java
    similarity index 97%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java
    index d4492710458..3477cd53ea2 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResources.java
    @@ -5,7 +5,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.checks.coding.onestatementperline;
     
     import java.io.IOException;
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java
    similarity index 97%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java
    index 1f0bb359dfc..4a8d28fd96f 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/coding/onestatementperline/InputOneStatementPerLineTryWithResourcesIgnore.java
    @@ -5,7 +5,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.checks.coding.onestatementperline;
     
     import java.io.IOException;
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClass.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClass.java
    index ab99b2da5fe..7812f133dd7 100644
    --- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClass.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClass.java
    @@ -121,13 +121,13 @@ private someinnerClass() {}
     }
     
     interface TestInterface {
    -    class SomeClass {
    +    class SomeClass { // violation
             private SomeClass() {}
         }
     }
     
     @interface SomeAnnotation {
    -    class SomeClass {
    +    class SomeClass { // violation
             private SomeClass() {}
         }
     }
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassAnnotation.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassAnnotation.java
    new file mode 100644
    index 00000000000..2af8408cc54
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassAnnotation.java
    @@ -0,0 +1,24 @@
    +/*
    +FinalClass
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.design.finalclass;
    +
    +public @interface InputFinalClassAnnotation {
    +
    +    final class FinalClass { // ok
    +        private FinalClass() {}
    +    }
    +
    +    class DerivedClass extends SuperClass { // violation
    +        private DerivedClass() {}
    +    }
    +
    +    class SuperClass { // ok
    +        private SuperClass() {}
    +    }
    +
    +}
    +
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassEnum.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassEnum.java
    new file mode 100644
    index 00000000000..2055dbc270b
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassEnum.java
    @@ -0,0 +1,44 @@
    +/*
    +FinalClass
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.design.finalclass;
    +
    +public enum InputFinalClassEnum {
    +
    +    FINAL("Final", new FinalClass()),
    +    DERIVED("Derived", new DerivedClass()),
    +    ;
    +
    +    private final String initial;
    +    private final Object object;
    +
    +    private InputFinalClassEnum(String initial, Object object) {
    +        this.initial = initial;
    +        this.object = object;
    +    }
    +
    +    public String getName() {
    +        return name();
    +    }
    +
    +    public String getInitial() {
    +        return initial;
    +    }
    +
    +    static final class FinalClass { // ok
    +        private FinalClass() {}
    +    }
    +
    +    static class DerivedClass extends SuperClass { // violation
    +        private DerivedClass() {}
    +    }
    +
    +    static class SuperClass { // ok
    +        private SuperClass() {}
    +    }
    +
    +}
    +
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInnerAndNestedClass.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInnerAndNestedClass.java
    new file mode 100644
    index 00000000000..99b04c18a09
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInnerAndNestedClass.java
    @@ -0,0 +1,76 @@
    +/*
    +FinalClass
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.design.finalclass;
    +
    +public class InputFinalClassInnerAndNestedClass {
    +
    +    private class SuperClass { // ok
    +        private SuperClass() {
    +        }
    +    }
    +
    +    private class SubClass extends SuperClass {
    +    }
    +
    +    class SameName { // violation
    +        private SameName() {
    +        }
    +    }
    +
    +    static class Test {
    +        static class SameName { // ok
    +            private SameName() {
    +            }
    +            class Test3 {
    +            }
    +        }
    +    }
    +
    +    class TestInnerClass {
    +        class SameName { // ok
    +            class Test3 {
    +                class Test4 extends SameName {
    +                }
    +            }
    +            private SameName() {
    +            }
    +        }
    +    }
    +
    +    class TestNestedClasses {
    +        class SameName { // violation
    +            private SameName() {
    +            }
    +            class Test3 {
    +                class Test4 extends Test.SameName {
    +                }
    +            }
    +        }
    +    }
    +}
    +
    +enum foo {
    +    VALUE_1, VALUE_2;
    +
    +    class A {
    +        class B { // ok
    +            private B() {
    +            }
    +        }
    +
    +        class c extends B {
    +        }
    +
    +        class D {
    +            class B { // violation
    +                private B() {
    +                }
    +            }
    +        }
    +    }
    +}
    +
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInterface.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInterface.java
    new file mode 100644
    index 00000000000..a434be80b82
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/finalclass/InputFinalClassInterface.java
    @@ -0,0 +1,24 @@
    +/*
    +FinalClass
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.design.finalclass;
    +
    +public interface InputFinalClassInterface {
    +
    +    final class FinalClass { // ok
    +        private FinalClass() {}
    +    }
    +
    +    class DerivedClass extends SuperClass { // violation
    +        private DerivedClass() {}
    +    }
    +
    +    class SuperClass { // ok
    +        private SuperClass() {}
    +    }
    +
    +}
    +
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java
    similarity index 91%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java
    index 961f908dee0..e7bb197e336 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/javadoc/missingjavadocmethod/InputMissingJavadocMethodInterfacePrivateMethod.java
    @@ -11,7 +11,6 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
     // private method in interface
     
     package com.puppycrawl.tools.checkstyle.checks.javadoc.missingjavadocmethod;
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java
    similarity index 96%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java
    index e8d20286a29..161f1e246d5 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/metrics/classfanoutcomplexity/InputClassFanOutComplexityVar.java
    @@ -18,7 +18,6 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java10
     package com.puppycrawl.tools.checkstyle.checks.metrics.classfanoutcomplexity;
     
     import javax.naming.NamingException;
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java
    similarity index 93%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java
    index 3c6032599bc..601c2c259fb 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/interfacememberimpliedmodifier/InputInterfaceMemberImpliedModifierPrivateMethods.java
    @@ -11,7 +11,6 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
     package com.puppycrawl.tools.checkstyle.checks.modifier.interfacememberimpliedmodifier;
     
     /**
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedClassInPublicInterfaceRedundantModifiers.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedClassInPublicInterfaceRedundantModifiers.java
    index a2cb3c0c0eb..03a0cb906b3 100644
    --- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedClassInPublicInterfaceRedundantModifiers.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedClassInPublicInterfaceRedundantModifiers.java
    @@ -21,7 +21,7 @@ private interface PrivateNestedInterface {
                 class ClassInPrivateNestedInterface {
                     public ClassInPrivateNestedInterface() { } // violation
                 }
    -            public interface PrivateNestedInterfaceWithPublicModifier {
    +            public interface PrivateNestedInterfaceWithPublicModifier { // violation
                     class ClassInPrivateNestedInterface {
                         public ClassInPrivateNestedInterface() { } // violation
                     }
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedDef.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedDef.java
    index 193e6451089..130f86d2bfd 100644
    --- a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedDef.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierNestedDef.java
    @@ -15,4 +15,30 @@ static public enum MyInnerEnum4 {} // 2 violations
         interface MyInnerInterface {
             public strictfp class MyInnerClass {} // violation
         }
    +
    +    public static class testClass { // 2 violations
    +    }
    +
    +    public abstract static @interface testAnnotatedInterface { // 3 violations
    +    }
    +}
    +
    +abstract @interface testAnnotatedInterface { // violation
    +
    +    public static enum testEnum { // 2 violations
    +    }
    +
    +    interface testInterface {
    +        public static interface nestedInterface { // 2 violations
    +
    +            public static class nestedClass { // 2 violations
    +            }
    +
    +            public static @interface nestedAnnInterface { // 2 violations
    +            }
    +
    +            public static enum nestedEnum { // 2 violations
    +            }
    +        }
    +    }
     }
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java
    similarity index 92%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java
    index 0e49b993da5..73717e9775e 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/modifier/redundantmodifier/InputRedundantModifierTryWithResources.java
    @@ -6,7 +6,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.checks.modifier.redundantmodifier;
     
     import java.io.IOException;
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java
    similarity index 91%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java
    index 049cbd1b21e..751a1326c4b 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/localfinalvariablename/InputLocalFinalVariableNameTryResourcesJava9.java
    @@ -6,7 +6,6 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
     package com.puppycrawl.tools.checkstyle.checks.naming.localfinalvariablename;
     
     public class InputLocalFinalVariableNameTryResourcesJava9 {
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java
    similarity index 92%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java
    index e1d3086a642..9a717fcdf30 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePrivateMethodsInInterfaces.java
    @@ -10,7 +10,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.checks.naming.methodname;
     
     public interface InputMethodNamePrivateMethodsInInterfaces {
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java
    similarity index 92%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java
    index 569eb68ca6c..21795ba3429 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/naming/methodname/InputMethodNamePublicMethodsInInterfaces.java
    @@ -10,7 +10,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.checks.naming.methodname;
     
     public interface InputMethodNamePublicMethodsInInterfaces {
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorEnumMembers.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorEnumMembers.java
    new file mode 100644
    index 00000000000..93aa0806526
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorEnumMembers.java
    @@ -0,0 +1,47 @@
    +/*
    +EmptyLineSeparator
    +allowNoEmptyLineBetweenFields = (default)false
    +allowMultipleEmptyLines = false
    +allowMultipleEmptyLinesInsideClassMembers = false
    +tokens = (default)PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, \
    +         STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF, \
    +         COMPACT_CTOR_DEF
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.whitespace.emptylineseparator;
    +
    +public class InputEmptyLineSeparatorEnumMembers {}
    +
    +enum A {
    +    ONE("one"),
    +    TWO("two");
    +
    +
    +    private final String str; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +
    +    private String otherString; // ok
    +
    +
    +    private String thirdString; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +    private String fourth; // violation ''VARIABLE_DEF' should be separated from previous line.'
    +
    +
    +    A(String s) { // violation ''CTOR_DEF' has more than 1 empty lines before.'
    +        this.str = s;
    +    }
    +
    +    private String fifth;
    +    static { // violation ''STATIC_INIT' should be separated from previous line.'
    +    }
    +
    +
    +    static { // violation ''STATIC_INIT' has more than 1 empty lines before.'
    +
    +    }
    +
    +    public String getStr() {
    +        return str;
    +    }
    +}
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorInterfaceFields.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorInterfaceFields.java
    new file mode 100644
    index 00000000000..d9c6cb29fc9
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/emptylineseparator/InputEmptyLineSeparatorInterfaceFields.java
    @@ -0,0 +1,46 @@
    +/*
    +EmptyLineSeparator
    +allowNoEmptyLineBetweenFields = (default)false
    +allowMultipleEmptyLines = false
    +allowMultipleEmptyLinesInsideClassMembers = false
    +tokens = (default)PACKAGE_DEF, IMPORT, STATIC_IMPORT, CLASS_DEF, INTERFACE_DEF, ENUM_DEF, \
    +         STATIC_INIT, INSTANCE_INIT, METHOD_DEF, CTOR_DEF, VARIABLE_DEF, RECORD_DEF, \
    +         COMPACT_CTOR_DEF
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.whitespace.emptylineseparator;
    +
    +public interface InputEmptyLineSeparatorInterfaceFields {
    +    int a = 45; // ok
    +
    +    int b = 45; // ok
    +
    +
    +    int c = 45; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +
    +
    +
    +    int d = 45; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +}
    +
    +@interface Ann {
    +    int a = 45; // ok
    +
    +    int b = 45; // ok
    +
    +
    +    int c = 45; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +
    +
    +
    +    int d = 45; // violation ''VARIABLE_DEF' has more than 1 empty lines before.'
    +}
    +
    +interface Abc {
    +    Object apply(Object array, int index);
    +
    +    Abc A = (o, i) -> new Object();
    +    Abc B = (o, i) -> o; // violation ''VARIABLE_DEF' should be separated from previous line.'
    +}
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java
    similarity index 97%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java
    index 2603ba9f993..08fd6d3680e 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/operatorwrap/InputOperatorWrapTryWithResources.java
    @@ -7,7 +7,6 @@
     
     
     */
    -//non-compiled with javac: Compilable with Java9
     package com.puppycrawl.tools.checkstyle.checks.whitespace.operatorwrap;
     
     public class InputOperatorWrapTryWithResources implements AutoCloseable
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterLambdaExpressions.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterLambdaExpressions.java
    new file mode 100644
    index 00000000000..569bc9b1d02
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterLambdaExpressions.java
    @@ -0,0 +1,29 @@
    +/*
    +WhitespaceAfter
    +tokens = LAMBDA
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.whitespace.whitespaceafter;
    +
    +import java.util.function.Function;
    +
    +public class InputWhitespaceAfterLambdaExpressions {
    +
    +    static Runnable r1 = () -> { // ok
    +        String.valueOf("Hello world one!");
    +    };
    +
    +    static Runnable r2 = () ->String.valueOf("Hello world two!"); // violation
    +
    +    static Runnable r3 = () ->{String.valueOf("Hello world two!");}; // violation
    +
    +    static Runnable r4 = () -> // ok
    +    {
    +        String.valueOf("Hello world one!");
    +    };
    +
    +    public void foo() {
    +        Function function = (o) ->o.toString(); // violation
    +    }
    +}
    diff --git a/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterVarargs.java b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterVarargs.java
    new file mode 100644
    index 00000000000..30a258b3e4c
    --- /dev/null
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/checks/whitespace/whitespaceafter/InputWhitespaceAfterVarargs.java
    @@ -0,0 +1,37 @@
    +/*
    +WhitespaceAfter
    +tokens = ELLIPSIS
    +
    +
    +*/
    +
    +package com.puppycrawl.tools.checkstyle.checks.whitespace.whitespaceafter;
    +
    +import java.util.List;
    +
    +public class InputWhitespaceAfterVarargs {
    +
    +    public void method(int...obj) { // violation
    +    }
    +
    +    public InputWhitespaceAfterVarargs(String first, List...second) { // violation
    +    }
    +
    +    public  void anotherMethod(List...args) { // violation
    +    }
    +
    +    public static String multipleArguments(int l, String format, Object ... args) { // ok
    +        return format;
    +    }
    +
    +    private void noWhitespaceBefore(boolean ...args) { // violation
    +    }
    +
    +    testInterface obj = (Integer... i) -> { // ok
    +    };
    +}
    +
    +@FunctionalInterface
    +interface testInterface {
    +    void method(T ...args); // violation
    +}
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java b/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java
    similarity index 96%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java
    index 885af6e5d08..5f63179ddb2 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputAdvanceJava9TryWithResources.java
    @@ -1,4 +1,4 @@
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.grammar.java9;
     
     /**
    diff --git a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java b/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java
    similarity index 94%
    rename from src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java
    rename to src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java
    index e9fbfb375f4..5035ae9c50c 100644
    --- a/src/test/resources-noncompilable/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java
    +++ b/src/test/resources/com/puppycrawl/tools/checkstyle/grammar/java9/InputJava9TryWithResources.java
    @@ -9,7 +9,7 @@
     
     */
     
    -//non-compiled with javac: Compilable with Java9
    +
     package com.puppycrawl.tools.checkstyle.grammar.java9;
     
     /**
    diff --git a/src/xdocs/beginning_development.xml b/src/xdocs/beginning_development.xml
    index 90411efaf16..add44e5b21f 100644
    --- a/src/xdocs/beginning_development.xml
    +++ b/src/xdocs/beginning_development.xml
    @@ -17,7 +17,7 @@
         
         

    - 1. Ensure that Git, Java JDK >= 8 until JDK 17, maven >= 3.0.1 are installed.
    + 1. Ensure that Git, Java JDK >= 11 until JDK 17, maven >= 3.0.1 are installed.
    You can find information about development environment preparation here: Prepare development environment in Ubuntu.
    diff --git a/src/xdocs/checks.xml b/src/xdocs/checks.xml index 51a1e168193..a092fc5bc60 100644 --- a/src/xdocs/checks.xml +++ b/src/xdocs/checks.xml @@ -263,8 +263,9 @@ FinalClass - Checks that a class which has only private constructors - is declared as final. + Checks that a class that has only private constructors and + has no descendant classes is declared as final. + FinalLocalVariable diff --git a/src/xdocs/config_coding.xml b/src/xdocs/config_coding.xml index 4e59149aeb7..9ff5c710e9f 100644 --- a/src/xdocs/config_coding.xml +++ b/src/xdocs/config_coding.xml @@ -6391,6 +6391,30 @@ public class D { <property name="max" value="3"/> </module> +

    + Example: +

    + +public class MyClass { + public int sign(int x) { + if (x < 0) + return -1; + if (x == 0) + return 1; + return 0; + } // OK + + public int badSign(int x) { + if (x < -2) + return -2; + if (x == 0) + return 0; + if (x > 2) + return 2; + return 1; + } // violation, more than three return statements +} +

    To configure the check so that it doesn't allow any @@ -6401,6 +6425,19 @@ public class D { <property name="maxForVoid" value="0"/> </module> +

    + Example: +

    + +public class MyClass { + public void firstMethod(int x) { + } // OK + + public void badMethod(int x) { + return; + } // violation, return statements per void method +} +

    To configure the check so that it doesn't allow more than 2 @@ -6413,6 +6450,39 @@ public class D { <property name="maxForVoid" value="1"/> </module> +

    + Example: +

    + +public class MyClass { + public void firstMethod() { + } // OK + + public void secondMethod() { + return; + } // OK + + public void badMethod(int x) { + if (x == 0) + return; + return; + } // violation, more than one return statements + + public int sign(int x) { + if (x < 0) + return -1; + return 0; + } // OK + + public int badSign(int x) { + if (x < 0) + return -1; + if (x == 0) + return 1; + return 0; + } // violation, more than two return statements in methods +} +

    To configure the check so that it doesn't allow more than three @@ -6424,6 +6494,30 @@ public class D { <property name="format" value="^$"/> </module> +

    + Example: +

    + +public class MyClass { + public int sign(int x) { + if (x < 0) + return -1; + if (x == 0) + return 1; + return 0; + } // OK + + public int badSign(int x) { + if (x < -2) + return -2; + if (x == 0) + return 0; + if (x > 2) + return 2; + return 1; + } // violation, more than three return statements per method +} +

    To configure the check so that it doesn't allow any return statements @@ -6432,7 +6526,7 @@ public class D {

    <module name="ReturnCount"> - <property name="max" value="0"/> + <property name="maxForVoid" value="0"/> <property name="tokens" value="CTOR_DEF"/> </module> <module name="ReturnCount"> @@ -6444,6 +6538,46 @@ public class D { <property name="tokens" value="METHOD_DEF"/> </module> +

    + Example: +

    + +import java.util.function.Predicate; + +public class Test { + public Test() { + } // OK + + public Test(int i) { + return; // violation, max allowed for constructors is 0 + } + + final Predicate<Integer> p = i -> { + if (i > 5) { + return true; + } + return false; + }; // violation, max allowed for lambdas is 1 + + final Predicate<Integer> q = i -> { + return i > 5; + }; // OK + + public int sign(int x) { + if (x > 0) + return -1; + return 0; + } // OK + + public int badSign(int x) { + if (x < 0) + return -1; + if (x == 0) + return 1; + return 0; + } // violation, more than two return statements in methods +} + diff --git a/src/xdocs/config_design.xml b/src/xdocs/config_design.xml index 1df3dfac41e..2003e9f9e39 100644 --- a/src/xdocs/config_design.xml +++ b/src/xdocs/config_design.xml @@ -319,9 +319,8 @@ public class A {

    Since Checkstyle 3.1

    - Checks that a class which has only private constructors is declared - as final. Doesn't check for classes nested in interfaces - or annotations, as they are always final there. + Checks that a class that has only private constructors and + has no descendant classes is declared as final.

    @@ -357,21 +356,6 @@ class MyClass { // OK, since it has a public constructor } } -interface CheckInterface -{ - class MyClass { // OK, nested class in interface is always final - private MyClass() {} - } -} - -public @interface Test { - public boolean enabled() - default true; - class MyClass { // OK, class nested in an annotation is always final - private MyClass() { } - } -} - class TestAnonymousInnerClasses { // OK, class has an anonymous inner class. public static final TestAnonymousInnerClasses ONE = new TestAnonymousInnerClasses() { diff --git a/src/xdocs/config_misc.xml b/src/xdocs/config_misc.xml index 88b3882655a..910639e1536 100644 --- a/src/xdocs/config_misc.xml +++ b/src/xdocs/config_misc.xml @@ -1032,7 +1032,19 @@ return '\ufeff' + content; // OK, non-printable escape character. <module name="FinalParameters"/> - +

    + Example: +

    + +public class Point { + public Point() { } // ok + public Point(final int m) { } // ok + public Point(final int m,int n) { } // violation, n should be final + public void methodOne(final int x) { } // ok + public void methodTwo(int x) { } // violation, x should be final + public static void main(String[] args) { } // violation, args should be final +} +

    To configure the check to enforce final parameters only for constructors: @@ -1041,6 +1053,19 @@ return '\ufeff' + content; // OK, non-printable escape character. <module name="FinalParameters"> <property name="tokens" value="CTOR_DEF"/> </module> + +

    + Example: +

    + +public class Point { + public Point() { } // ok + public Point(final int m) { } // ok + public Point(final int m,int n) { } // violation, n should be final + public void methodOne(final int x) { } // ok + public void methodTwo(int x) { } // ok + public static void main(String[] args) { } // ok +}

    To configure the check to allow ignoring @@ -1052,6 +1077,19 @@ return '\ufeff' + content; // OK, non-printable escape character. <property name="ignorePrimitiveTypes" value="true"/> </module> +

    + Example: +

    + +public class Point { + public Point() { } // ok + public Point(final int m) { } // ok + public Point(final int m,int n) { } // ok + public void methodOne(final int x) { } // ok + public void methodTwo(int x) { } // ok + public static void main(String[] args) { } // violation, args should be final +} +
    diff --git a/src/xdocs/config_modifier.xml b/src/xdocs/config_modifier.xml index d70dfe017c6..ddc9dfa4f8a 100644 --- a/src/xdocs/config_modifier.xml +++ b/src/xdocs/config_modifier.xml @@ -548,8 +548,8 @@ public interface RoadFeature {
  • Interface and annotation definitions.
  • Final modifier on methods of final and anonymous classes.
  • - Inner interface declarations that are declared - as static. + Type declarations nested under interfaces that are declared as public + or static.
  • Class constructors.
  • @@ -559,16 +559,15 @@ public interface RoadFeature {

    - Interfaces by definition are abstract so the abstract - modifier on the interface is redundant. + interfaces by definition are abstract so the abstract modifier is + redundant on them.

    - Classes inside of interfaces by definition are public and static, - so the public and static modifiers - on the inner classes are redundant. On the other hand, classes - inside of interfaces can be abstract or non abstract. - So, abstract modifier is allowed. + Type declarations nested under interfaces by definition are public and static, + so the public and static modifiers on nested type + declarations are redundant. On the other hand, classes inside of interfaces can + be abstract or non abstract. So, abstract modifier is allowed.

    @@ -689,6 +688,8 @@ public class ClassExtending extends ClassExample { ENUM_DEF , RESOURCE + , + ANNOTATION_DEF . @@ -708,6 +709,8 @@ public class ClassExtending extends ClassExample { ENUM_DEF , RESOURCE + , + ANNOTATION_DEF . 3.0 diff --git a/src/xdocs/config_whitespace.xml b/src/xdocs/config_whitespace.xml index 3a562a7d158..4592b10e4fd 100644 --- a/src/xdocs/config_whitespace.xml +++ b/src/xdocs/config_whitespace.xml @@ -2902,6 +2902,12 @@ class Bar { LITERAL_FOR , DO_WHILE + , + ELLIPSIS + , + LITERAL_SWITCH + , + LAMBDA . @@ -2924,6 +2930,12 @@ class Bar { LITERAL_FOR , DO_WHILE + , + ELLIPSIS + , + LITERAL_SWITCH + , + LAMBDA . 3.0 diff --git a/src/xdocs/index.xml.vm b/src/xdocs/index.xml.vm index 31bb3f3cb71..8f1c275d9ab 100644 --- a/src/xdocs/index.xml.vm +++ b/src/xdocs/index.xml.vm @@ -90,18 +90,47 @@

    Since Checkstyle 7, some users have been unable to continue upgrading to newer versions - of the utility because of the new JDK 1.8 compile requirement. The development team doesn't + of the utility because of the new JDK compile requirements. The development team doesn't have the resources to keep updating the utility for older JDKs for those that can't work with the latest version.

    However, some members of the community have created an unofficial backport of the latest - Checkstyle releases to be run with JDKs as old as 1.6. If you wish to continue using new - Checkstyle versions on older JDKs, we recommend you either checkout the - github site or the - documentation site on how - to use the backport version of the utility, in place of the official Checkstyle version. + Checkstyle releases to be run with older JDKs. It is not always an easy process and provided + at the same release time as Checkstyle, but it tries to maintain a functional equivalent + alternative.

    +
    + + + + + + + + + + + + + + + + +
    Backport versionMin. JRE versionLink
    + 10.0+ + + 8 + + github site +
    + 7.0 - 8.45 + + 6 + + github site +
    +
    @@ -129,6 +158,14 @@ Checkstyle version JRE version + + + 10.x + + + 11 and above + + 7.x, 8.x, 9.x diff --git a/src/xdocs/releasenotes.xml b/src/xdocs/releasenotes.xml index 018b1dbb216..3d2e6286846 100644 --- a/src/xdocs/releasenotes.xml +++ b/src/xdocs/releasenotes.xml @@ -10,6 +10,101 @@ +
    +
    27.02.2022
    +

    Breaking backward compatibility:

    +
      +
    • + upgrade minimal required jdk version to 11. + Author: rnveach, pbludov + #9146 +
    • +
    +

    New:

    +
      +
    • + WhitespaceAfter does not work on 'switch' and lambda statements. + Author: Vyom-Yadav + #11298 +
    • +
    • + WhitespaceAfter should support `ELLIPSIS` token. + Author: Vyom-Yadav + #11116 +
    • +
    +

    Bug fixes:

    +
      +
    • + FinalClass should exempt private-only constructor classes that are + extended by another class in the same compilation unit. + Author: pbludov + #10859 +
    • +
    • + False Negative: RedundantModifierCheck. + Author: Vyom-Yadav + #11268 +
    • +
    • + EmptyLineSeparator: false negative in Enum and interface fields. + Author: Andrei Paikin + #11241 +
    • +
    • + NPE in gui.MainFrameModel#getLastDirectory. + Author: pbludov + #11294 +
    • +
    +

    Notes:

    +
      +
    • + Pitest: add new mutator REMOVE_CONDITIONALS. + Author: rnveach + #6320 +
    • +
    • + Update doc for FinalParameters. + Author: Taniya + #7588 +
    • +
    • + Expand XPath IT Regression Testing. + Author: Binita Kumari + #6207 +
    • +
    • + Replace usages of deprecated method AccessibleObject.isAccessible. + Author: Nick Mancuso + #11309 +
    • +
    • + Update doc for ReturnCount. + Author: Binita Kumari + #7657 +
    • +
    • + Add icon to the GUI window. + Author: pbludov + #11292 +
    • +
    • + Add 'since' property to '@Deprecated' annotation. + Author: pbludov + #11289 +
    • +
    • + doc: update requirements to jdk 11. + Author: pbludov +
    • +
    • + remove extra checkstyle build in no-exception-test.sh. + Author: Vyom-Yadav + #11281 +
    • +
    +
    30.01.2022

    New:

    diff --git a/wercker.yml b/wercker.yml index 68ffa0a15d7..692d924c692 100644 --- a/wercker.yml +++ b/wercker.yml @@ -1,5 +1,5 @@ box: - id: maven:3.8.1-jdk-11 + id: maven:3.8.4-jdk-11 username: $DOCKERHUB_USER password: $DOCKERHUB_TOKEN