Merge branch 'master' into pmd/7.0.x

This commit is contained in:
Andreas Dangel 2022-12-31 16:17:32 +01:00
commit 44914419e2
No known key found for this signature in database
GPG Key ID: 93450DF2DF9A3FA3
26 changed files with 1022 additions and 225 deletions

View File

@ -7042,6 +7042,25 @@
"contributions": [
"bug"
]
},
{
"login": "Tarush-Singh35",
"name": "Tarush Singh",
"avatar_url": "https://avatars.githubusercontent.com/u/86368099?v=4",
"profile": "https://www.linkedin.com/in/tarush-singh-46763819b",
"contributions": [
"code"
]
},
{
"login": "kdebski85",
"name": "kdebski85",
"avatar_url": "https://avatars.githubusercontent.com/u/9674813?v=4",
"profile": "https://github.com/kdebski85",
"contributions": [
"bug",
"code"
]
}
],
"contributorsPerLine": 7,

View File

@ -55,7 +55,7 @@ jobs:
run: |
echo "LANG=en_US.UTF-8" >> $GITHUB_ENV
echo "MAVEN_OPTS=-Dmaven.wagon.httpconnectionManager.ttlSeconds=180 -Dmaven.wagon.http.retryHandler.count=3 -DautoReleaseAfterClose=true -DstagingProgressTimeoutMinutes=30" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/18/scripts" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/19/scripts" >> $GITHUB_ENV
- name: Check Environment
shell: bash
run: |

View File

@ -25,7 +25,7 @@ jobs:
shell: bash
run: |
echo "LANG=en_US.UTF-8" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/18/scripts" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/19/scripts" >> $GITHUB_ENV
- name: Sync
run: .ci/git-repo-sync.sh
shell: bash

View File

@ -36,7 +36,7 @@ jobs:
run: |
echo "LANG=en_US.UTF-8" >> $GITHUB_ENV
echo "MAVEN_OPTS=-Dmaven.wagon.httpconnectionManager.ttlSeconds=180 -Dmaven.wagon.http.retryHandler.count=3 -DstagingProgressTimeoutMinutes=30" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/18/scripts" >> $GITHUB_ENV
echo "PMD_CI_SCRIPTS_URL=https://raw.githubusercontent.com/pmd/build-tools/19/scripts" >> $GITHUB_ENV
- name: Check Environment
shell: bash
run: |

View File

@ -53,7 +53,7 @@ GEM
faraday-patron (1.0.0)
faraday-rack (1.0.0)
faraday-retry (1.0.3)
fugit (1.7.2)
fugit (1.8.0)
et-orbi (~> 1, >= 1.2.7)
raabro (~> 1.4)
git (1.12.0)
@ -69,7 +69,7 @@ GEM
multipart-post (2.2.3)
nap (1.1.0)
no_proxy_fix (0.1.2)
nokogiri (1.13.9)
nokogiri (1.13.10)
mini_portile2 (~> 2.8.0)
racc (~> 1.4)
octokit (5.6.1)
@ -83,9 +83,9 @@ GEM
nokogiri (~> 1.13)
rufus-scheduler (~> 3.8)
slop (~> 4.9)
public_suffix (5.0.0)
public_suffix (5.0.1)
raabro (1.4.0)
racc (1.6.0)
racc (1.6.1)
rchardet (1.8.0)
rexml (3.2.5)
rouge (4.0.0)

View File

@ -212,7 +212,7 @@ GEM
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.16.3)
nokogiri (1.13.9)
nokogiri (1.13.10)
mini_portile2 (~> 2.8.0)
racc (~> 1.4)
octokit (4.25.1)
@ -221,7 +221,7 @@ GEM
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (4.0.7)
racc (1.6.0)
racc (1.6.1)
rb-fsevent (0.11.2)
rb-inotify (0.10.1)
ffi (~> 1.0)

View File

@ -1618,96 +1618,132 @@ large projects, with many duplications, it was causing `OutOfMemoryError`s (see
### List of currently deprecated rules
* The Java rules `VariableNamingConventions` (java-codestyle), `MIsLeadingVariableName` (java-codestyle),
`SuspiciousConstantFieldName` (java-codestyle), and `AvoidPrefixingMethodParameters` (java-codestyle) are
now deprecated, and will be removed with version 7.0.0. They are replaced by the more general
{% rule java/codestyle/FieldNamingConventions %}, {% rule java/codestyle/FormalParameterNamingConventions %}, and
{% rule java/codestyle/LocalVariableNamingConventions %}.
These rules will be removed with PMD 7.0.0.
* The Java rule `AbstractNaming` (java-codestyle) is deprecated
in favour of {% rule java/codestyle/ClassNamingConventions %}.
* Since 6.0.0: The Java rules `NcssConstructorCount` (design), `NcssMethodCount` (design),
and `NcssTypeCount` (design) have been deprecated. They will be replaced by the new rule
{% rule java/design/NcssCount %}.
* The Java rules `WhileLoopsMustUseBraces` (java-codestyle), `ForLoopsMustUseBraces` (java-codestyle), `IfStmtsMustUseBraces` (java-codestyle), and `IfElseStmtsMustUseBraces` (java-codestyle)
are deprecated. They will be replaced by the new rule {% rule java/codestyle/ControlStatementBraces %}.
* Since 6.0.0: The Java rule `LooseCoupling` in ruleset `java-typeresolution` is deprecated. Use the rule with the
same name from category `bestpractices` instead: {% rule java/bestpractices/LooseCoupling %}.
* The Java rules NcssConstructorCount (java-design), NcssMethodCount (java-design), and NcssTypeCount (java-design) have been
deprecated. They will be replaced by the new rule {% rule java/design/NcssCount %} in the category `design`.
* Since 6.0.0: The Java rule `CloneMethodMustImplementCloneable` in ruleset `java-typeresolution` is deprecated.
Use the rule with the same name from category `errorprone` instead:
{% rule java/errorprone/CloneMethodMustImplementCloneable %}.
* The Java rule `LooseCoupling` in ruleset `java-typeresolution` is deprecated. Use the rule with the same name from category `bestpractices` instead.
* Since 6.0.0: The Java rule `UnusedImports` in ruleset `java-typeresolution` is deprecated. Use the rule with
the same name from category `bestpractices` instead: {% rule java/bestpractices/UnusedImports %}.
* The Java rule `CloneMethodMustImplementCloneable` in ruleset `java-typeresolution` is deprecated. Use the rule with the same name from category `errorprone` instead.
* Since 6.0.0: The Java rule `SignatureDeclareThrowsException` in ruleset `java-typeresolution` is deprecated.
Use the rule with the same name from category `design` instead:
{% rule java/design/SignatureDeclareThrowsException %}.
* The Java rule `UnusedImports` in ruleset `java-typeresolution` is deprecated. Use the rule with
the same name from category `bestpractices` instead.
* Since 6.0.0: The Java rule `EmptyStaticInitializer` in ruleset `java-empty` is deprecated.
Use the rule {% rule java/errorprone/EmptyInitializer %} instead, which covers both static and non-static
empty initializers.
* The Java rule `SignatureDeclareThrowsException` in ruleset `java-typeresolution` is deprecated. Use the rule with the same name from category `design` instead.
* Since 6.0.0: The Java rules `GuardDebugLogging` (ruleset `java-logging-jakarta-commons`) and
`GuardLogStatementJavaUtil` (ruleset `java-logging-java`) have been deprecated. Use the rule
{% rule java/bestpractices/GuardLogStatement %} instead, which covers all cases regardless of the logging framework.
* The Java rule `EmptyStaticInitializer` in ruleset `java-empty` is deprecated. Use the rule {% rule java/errorprone/EmptyInitializer %}, which covers both static and non-static empty initializers.`
* Since 6.2.0: The Java rules `WhileLoopsMustUseBraces` (codestyle),
`ForLoopsMustUseBraces` (codestyle), `IfStmtsMustUseBraces` (codestyle), and
`IfElseStmtsMustUseBraces` (codestyle) are deprecated. They will be replaced by the new rule
{% rule java/codestyle/ControlStatementBraces %}.
* The Java rules `GuardDebugLogging` (ruleset `java-logging-jakarta-commons`) and `GuardLogStatementJavaUtil`
(ruleset `java-logging-java`) have been deprecated. Use the rule {% rule java/bestpractices/GuardLogStatement %}, which covers all cases regardless of the logging framework.
* Since 6.3.0: The Java rule `AbstractNaming` (codestyle) is deprecated
in favour of {% rule java/codestyle/ClassNamingConventions %}.
* The Java rule "java/multithreading/UnsynchronizedStaticDateFormatter" has been deprecated and
will be removed with PMD 7.0.0. The rule is replaced by the more general
{% rule "java/multithreading/UnsynchronizedStaticFormatter" %}.
* Since 6.7.0: The Java rules `VariableNamingConventions` (codestyle),
`MIsLeadingVariableName` (codestyle), `SuspiciousConstantFieldName` (codestyle), and
`AvoidPrefixingMethodParameters` (codestyle) are now deprecated. They are replaced by the more general
{% rule java/codestyle/FieldNamingConventions %}, {% rule java/codestyle/FormalParameterNamingConventions %}, and
{% rule java/codestyle/LocalVariableNamingConventions %}.
* The two Java rules [`PositionLiteralsFirstInComparisons`](https://pmd.github.io/pmd-6.29.0/pmd_rules_java_bestpractices.html#positionliteralsfirstincomparisons)
and [`PositionLiteralsFirstInCaseInsensitiveComparisons`](https://pmd.github.io/pmd-6.29.0/pmd_rules_java_bestpractices.html#positionliteralsfirstincaseinsensitivecomparisons) (ruleset `java-bestpractices`)
have been deprecated in favor of the new rule {% rule "java/bestpractices/LiteralsFirstInComparisons" %}.
* Since 6.11.0: The Java rule `UnsynchronizedStaticDateFormatter` (multithreading) has been deprecated.
The rule is replaced by the more general {% rule java/multithreading/UnsynchronizedStaticFormatter %}.
* The Java rule [`AvoidFinalLocalVariable`](https://pmd.github.io/pmd-6.16.0/pmd_rules_java_codestyle.html#avoidfinallocalvariable) (`java-codestyle`) has been deprecated
and will be removed with PMD 7.0.0. The rule is controversial and also contradicts other existing
rules such as [`LocalVariableCouldBeFinal`](https://pmd.github.io/pmd-6.16.0/pmd_rules_java_codestyle.html#localvariablecouldbefinal). If the goal is to avoid defining
constants in a scope smaller than the class, then the rule [`AvoidDuplicateLiterals`](https://pmd.github.io/pmd-6.16.0/pmd_rules_java_errorprone.html#avoidduplicateliterals)
should be used instead.
* Since 6.15.0: The Apex rule {% rule apex/codestyle/VariableNamingConventions %} has been deprecated. The rule is
replaced by the more general rules {% rule apex/codestyle/FieldNamingConventions %},
{% rule apex/codestyle/FormalParameterNamingConventions %}, {% rule apex/codestyle/LocalVariableNamingConventions %},
and {% rule apex/codestyle/PropertyNamingConventions %}.
* The Apex rule [`VariableNamingConventions`](https://pmd.github.io/pmd-6.15.0/pmd_rules_apex_codestyle.html#variablenamingconventions) (`apex-codestyle`) has been deprecated and
will be removed with PMD 7.0.0. The rule is replaced by the more general rules
[`FieldNamingConventions`](https://pmd.github.io/pmd-6.15.0/pmd_rules_apex_codestyle.html#fieldnamingconventions),
[`FormalParameterNamingConventions`](https://pmd.github.io/pmd-6.15.0/pmd_rules_apex_codestyle.html#formalparameternamingconventions),
[`LocalVariableNamingConventions`](https://pmd.github.io/pmd-6.15.0/pmd_rules_apex_codestyle.html#localvariablenamingconventions), and
[`PropertyNamingConventions`](https://pmd.github.io/pmd-6.15.0/pmd_rules_apex_codestyle.html#propertynamingconventions).
* Since 6.15.0: The Java rule {% rule java/errorprone/LoggerIsNotStaticFinal %} has been deprecated.
The rule is replaced by {% rule java/errorprone/ProperLogger %}.
* The Java rule [`LoggerIsNotStaticFinal`](https://pmd.github.io/pmd-6.15.0/pmd_rules_java_errorprone.html#loggerisnotstaticfinal) (`java-errorprone`) has been deprecated
and will be removed with PMD 7.0.0. The rule is replaced by [`ProperLogger`](https://pmd.github.io/pmd-6.15.0/pmd_rules_java_errorprone.html#properlogger).
* Since 6.16.0: The Java rule {% rule java/codestyle/AvoidFinalLocalVariable %} has been deprecated.
The rule is controversial and also contradicts other existing rules such as
{% rule java/codestyle/LocalVariableCouldBeFinal %}. If the goal is to avoid defining
constants in a scope smaller than the class, then the rule {% rule java/errorprone/AvoidDuplicateLiterals %}
should be used instead.
* The Java rule [`DataflowAnomalyAnalysis`](https://pmd.github.io/pmd-6.27.0/pmd_rules_java_errorprone.html#dataflowanomalyanalysis) (`java-errorprone`)
is deprecated in favour of {% rule "java/bestpractices/UnusedAssignment" %} (`java-bestpractices`),
which was introduced in PMD 6.26.0.
* Since 6.19.0: The Java rule {% rule java/errorprone/InvalidSlf4jMessageFormat %} has been renamed to
{% rule java/errorprone/InvalidLogMessageFormat %}.
* The java rule `DefaultPackage` (java-codestyle) has been deprecated in favor of
{% rule "java/codestyle/CommentDefaultAccessModifier" %}.
* Since 6.24.0: The two Java rules `PositionLiteralsFirstInComparisons` (bestpractices)
and `PositionLiteralsFirstInCaseInsensitiveComparisons` (bestpractices)
have been deprecated in favor of the new rule {% rule java/bestpractices/LiteralsFirstInComparisons %}.
* The Java rule `CloneThrowsCloneNotSupportedException` (java-errorprone) has been deprecated without
replacement.
* Since 6.27.0: The Java rule `DataflowAnomalyAnalysis` (errorprone)
is deprecated in favour of {% rule java/bestpractices/UnusedAssignment %},
which was introduced in PMD 6.26.0.
* The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule {% rule java/bestpractices/SimplifiableTestAssertion %} merges
their functionality:
* `UseAssertEqualsInsteadOfAssertTrue` (java-bestpractices)
* `UseAssertNullInsteadOfAssertTrue` (java-bestpractices)
* `UseAssertSameInsteadOfAssertTrue` (java-bestpractices)
* `UseAssertTrueInsteadOfAssertEquals` (java-bestpractices)
* `SimplifyBooleanAssertion` (java-design)
* Since 6.29.0: The Apex rules {% rule apex/performance/AvoidDmlStatementsInLoops %},
{% rule apex/performance/AvoidSoqlInLoops %}, and {% rule apex/performance/AvoidSoslInLoops %} are deprecated
in favor of the new rule {% rule apex/performance/OperationWithLimitsInLoop %}.
* The Java rule `ReturnEmptyArrayRatherThanNull` (java-errorprone) is deprecated and removed from
the quickstart ruleset, as the new rule {% rule java/errorprone/ReturnEmptyCollectionRatherThanNull %}
supersedes it.
* Since 6.29.0: The Java rule {% rule java/errorprone/DoNotCallSystemExit %} has been renamed to
{% rule/java/errorprone/DoNotTerminateVM %}.
* The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule {% rule java/bestpractices/PrimitiveWrapperInstantiation %} merges
their functionality:
* java/performance/BooleanInstantiation
* java/performance/ByteInstantiation
* java/performance/IntegerInstantiation
* java/performance/LongInstantiation
* java/performance/ShortInstantiation
* Since 6.31:0: The Java rule {% rule java/performance/AvoidUsingShortType %} is deprecated
for removal without replacement.
* The Java rule java/performance/UnnecessaryWrapperObjectCreation is deprecated
with no planned replacement before PMD 7. In it's current state, the rule is not useful
as it finds only contrived cases of creating a primitive wrapper and unboxing it explicitly
in the same expression. In PMD 7 this and more cases will be covered by a
new rule `UnnecessaryBoxing`.
* Since 6.31.0: The Java rule {% rule java/performance/SimplifyStartsWith %} is deprecated
for removal without replacement.
* Since 6.34.0: The Java rules {% rule java/bestpractices/UnusedImports %}, {% rule java/codestyle/DuplicateImports %},
{% rule java/codestyle/DontImportJavaLang %}, and {% rule java/errorprone/ImportFromSamePackage %} are
deprecated. These rules are replaced by {% rule java/codestyle/UnnecessaryImport %}.
* Since 6.35.0: The Java rule `DefaultPackage` (codestyle) has been deprecated in favor of
{% rule java/codestyle/CommentDefaultAccessModifier %}.
* Since 6.35.0: The Java rule `CloneThrowsCloneNotSupportedException` (errorprone) has been
deprecated without replacement.
* Since 6.36.0: The Java rule {% rule java/errorprone/BadComparison %} has been renamed to
{% rule java/errorprone/ComparisonWithNaN %}.
* Since 6.37.0: The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule {% rule java/bestpractices/SimplifiableTestAssertion %} merges
their functionality:
* `UseAssertEqualsInsteadOfAssertTrue` (bestpractices)
* `UseAssertNullInsteadOfAssertTrue` (bestpractices)
* `UseAssertSameInsteadOfAssertTrue` (bestpractices)
* `UseAssertTrueInsteadOfAssertEquals` (bestpractices)
* `SimplifyBooleanAssertion` (design)
* Since 6.37.0: The Java rule `ReturnEmptyArrayRatherThanNull` (errorprone) is deprecated and removed from
the quickstart ruleset, as the new rule {% rule java/errorprone/ReturnEmptyCollectionRatherThanNull %}
supersedes it.
* Since 6.37.0: The following Java rules are deprecated and removed from the quickstart ruleset,
as the new rule {% rule java/bestpractices/PrimitiveWrapperInstantiation %} merges
their functionality:
* `BooleanInstantiation` (performance)
* `ByteInstantiation` (performance)
* `IntegerInstantiation` (performance)
* `LongInstantiation` (performance)
* `ShortInstantiation` (performance)
* Since 6.37.0: The Java rule `UnnecessaryWrapperObjectCreation` (performance) is deprecated
with no planned replacement before PMD 7. In its current state, the rule is not useful
as it finds only contrived cases of creating a primitive wrapper and unboxing it explicitly
in the same expression. In PMD 7 this and more cases will be covered by a
new rule {% rule java/codestyle/UnnecessaryBoxing %}.
* Since 6.37.0: The Java rule {% rule java/errorprone/MissingBreakInSwitch %} has been renamed to
{% rule java/errorprone/ImplicitSwitchFallThrough %}.
* Since 6.46.0: The following Java rules are deprecated and removed from the quickstart ruleset, as the new rule
{% rule java/codestyle/EmptyControlStatement %} merges their functionality:
@ -1720,8 +1756,12 @@ large projects, with many duplications, it was causing `OutOfMemoryError`s (see
* {% rule java/errorprone/EmptyTryBlock %}
* {% rule java/errorprone/EmptyWhileStmt %}
* Since 6.46.0: The Java rule {% rule java/errorprone/EmptyStatementNotInLoop %} is deprecated and removed from the quickstart
ruleset. Use the new rule {% rule java/codestyle/UnnecessarySemicolon %} instead.
* Since 6.52.0: The Java rule {% rule java/errorprone/BeanMembersShouldSerialize %} has been renamed to
{% rule java/errorprone/NonSerializableClass %}.
* Since 6.53.0: The Java rules {% rule java/design/ExcessiveClassLength %} and
{% rule java/design/ExcessiveMethodLength %} have been deprecated. The rule
{% rule java/design/NcssCount %} can be used instead.
* Since 6.53.0: The Java rule {% rule java/errorprone/EmptyStatementNotInLoop %} is deprecated.
Use the rule {% rule java/codestyle/UnnecessarySemicolon %} instead.

File diff suppressed because it is too large Load Diff

View File

@ -19,13 +19,53 @@ This is a {{ site.pmd.release_type }} release.
### New and noteworthy
#### Modified rules
* The Java rule {% rule java/bestpractices/UnusedPrivateField %} has a new property `reportForAnnotations`.
This is a list of fully qualified names of the annotation types that should be reported anyway. If an unused field
has any of these annotations, then it is reported. If it has any other annotation, then it is still considered
to be used and is not reported.
#### Deprecated rules
* The Java rules {% rule java/design/ExcessiveClassLength %} and {% rule java/design/ExcessiveMethodLength %}
have been deprecated. The rule {% rule java/design/NcssCount %} can be used instead.
The deprecated rules will be removed with PMD 7.0.0.
* The Java rule {% rule java/errorprone/EmptyStatementNotInLoop %} is deprecated.
Use the rule {% rule java/codestyle/UnnecessarySemicolon %} instead.
Note: Actually it was announced to be deprecated since 6.46.0 but the rule was not marked as deprecated yet.
This has been done now.
### Fixed Issues
* core
* [#4248](https://github.com/pmd/pmd/issues/4248): \[core] Can't analyze sources in zip files
* apex-security
* [#4146](https://github.com/pmd/pmd/issues/4146): \[apex] ApexCRUDViolation: Recognize User Mode in SOQL + DML
* java
* [#4266](https://github.com/pmd/pmd/issues/4266): \[java] PMD fails to process a record with lambda in compact constructor
* java-bestpractices
* [#4166](https://github.com/pmd/pmd/issues/4166): \[java] UnusedPrivateField doesn't find annotated unused private fields anymore
* [#4250](https://github.com/pmd/pmd/issues/4250): \[java] WhileLoopWithLiteralBoolean - false negative with complex expressions still occurs in PMD 6.52.0
* java-design
* [#2127](https://github.com/pmd/pmd/issues/2127): \[java] Deprecate rules ExcessiveClassLength and ExcessiveMethodLength
* java-errorprone
* [#4164](https://github.com/pmd/pmd/issues/4164): \[java]\[doc] AvoidAssertAsIdentifier and AvoidEnumAsIdentifier - clarify use case
* java-multithreading
* [#4210](https://github.com/pmd/pmd/issues/4210): \[java] DoNotUseThreads report duplicate warnings
### API Changes
#### Deprecated APIs
##### For removal
These classes / APIs have been deprecated and will be removed with PMD 7.0.0.
* {% jdoc java::lang.java.rule.design.ExcessiveLengthRule %} (Java)
### External Contributions
* [#4244](https://github.com/pmd/pmd/pull/4244): \[apex] ApexCRUDViolation: user mode and system mode with test cases added - [Tarush Singh](https://github.com/Tarush-Singh35) (@Tarush-Singh35)
* [#4274](https://github.com/pmd/pmd/pull/4274): \[java] Fix finding lambda scope in record compact constructor - [kdebski85](https://github.com/kdebski85) (@kdebski85)
{% endtocmaker %}

View File

@ -43,6 +43,7 @@ import net.sourceforge.pmd.lang.apex.ast.ASTNewKeyValueObjectExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTNewListInitExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTNewListLiteralExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTNewObjectExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTParameter;
import net.sourceforge.pmd.lang.apex.ast.ASTProperty;
import net.sourceforge.pmd.lang.apex.ast.ASTReferenceExpression;
import net.sourceforge.pmd.lang.apex.ast.ASTReturnStatement;
@ -79,6 +80,8 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
private static final String S_OBJECT_TYPE = "sObjectType";
private static final String GET_DESCRIBE = "getDescribe";
private static final String ACCESS_LEVEL = "AccessLevel";
// ESAPI.accessController().isAuthorizedToView(Lead.sObject, fields)
private static final String[] ESAPI_ISAUTHORIZED_TO_VIEW = new String[] { "ESAPI", "accessController",
"isAuthorizedToView", };
@ -94,6 +97,11 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
private static final Pattern WITH_SECURITY_ENFORCED = Pattern.compile("(?is).*[^']\\s*WITH\\s+SECURITY_ENFORCED\\s*[^']*");
//Added For USER MODE
private static final Pattern WITH_USER_MODE = Pattern.compile("(?is).*[^']\\s*WITH\\s+USER_MODE\\s*[^']*");
//Added For SYSTEM MODE
private static final Pattern WITH_SYSTEM_MODE = Pattern.compile("(?is).*[^']\\s*WITH\\s+SYSTEM_MODE\\s*[^']*");
// <operation>AuthMethodPattern config properties; these are string properties instead of regex properties to help
// ensure that the compiled patterns are case-insensitive vs. requiring the pattern author to use "(?i)"
private static final PropertyDescriptor<String> CREATE_AUTH_METHOD_PATTERN_DESCRIPTOR = authMethodPatternProperty("create");
@ -188,14 +196,24 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
public Object visit(ASTMethodCallExpression node, Object data) {
if (Helper.isAnyDatabaseMethodCall(node)) {
if (hasAccessLevelArgument(node)) {
return data;
}
switch (node.getMethodName().toLowerCase(Locale.ROOT)) {
case "insert":
case "insertasync":
case "insertimmediate":
checkForCRUD(node, data, IS_CREATEABLE);
break;
case "update":
case "updateasync":
case "updateimmediate":
checkForCRUD(node, data, IS_UPDATEABLE);
break;
case "delete":
case "deleteasync":
case "deleteimmediate":
checkForCRUD(node, data, IS_DELETABLE);
break;
case "undelete":
@ -219,6 +237,30 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
return data;
}
/**
* Checks whether any parameter is of type "AccessLevel". It doesn't check
* whether it is "USER_MODE" or "SYSTEM_MODE", because this rule doesn't
* report a violation for neither.
*
* @param node the Database DML method call
*/
private boolean hasAccessLevelArgument(ASTMethodCallExpression node) {
for (int i = 0; i < node.getNumChildren(); i++) {
ApexNode<?> argument = node.getChild(i);
if (argument instanceof ASTVariableExpression
&& argument.getFirstChildOfType(ASTReferenceExpression.class) != null) {
ASTReferenceExpression ref = argument.getFirstChildOfType(ASTReferenceExpression.class);
List<String> names = ref.getNames();
if (names.size() == 1 && ACCESS_LEVEL.equalsIgnoreCase(names.get(0))) {
return true;
} else if (names.size() == 2 && "System".equalsIgnoreCase(names.get(0)) && ACCESS_LEVEL.equalsIgnoreCase(names.get(1))) {
return true;
}
}
}
return false;
}
@Override
public Object visit(ASTDmlInsertStatement node, Object data) {
checkForCRUD(node, data, IS_CREATEABLE);
@ -280,6 +322,13 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
}
@Override
public Object visit(ASTParameter node, Object data) {
String type = node.getType();
addVariableToMapping(Helper.getFQVariableName(node), type);
return data;
}
@Override
public Object visit(final ASTFieldDeclaration node, Object data) {
ASTFieldDeclarationStatements field = node.getFirstParentOfType(ASTFieldDeclarationStatements.class);
@ -429,6 +478,22 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
&& WITH_SECURITY_ENFORCED.matcher(((ASTSoqlExpression) node).getQuery()).matches();
}
//For USER_MODE
private boolean isWithUserMode(final ApexNode<?> node) {
if (node instanceof ASTSoqlExpression) {
return WITH_USER_MODE.matcher(((ASTSoqlExpression) node).getQuery()).matches();
}
return false;
}
//For System Mode
private boolean isWithSystemMode(final ApexNode<?> node) {
if (node instanceof ASTSoqlExpression) {
return WITH_SYSTEM_MODE.matcher(((ASTSoqlExpression) node).getQuery()).matches();
}
return false;
}
private String getType(final ASTMethodCallExpression methodNode) {
final ASTReferenceExpression reference = methodNode.getFirstChildOfType(ASTReferenceExpression.class);
if (!reference.getNames().isEmpty()) {
@ -630,11 +695,14 @@ public class ApexCRUDViolationRule extends AbstractApexRule {
boolean isImproperDMLCheck = !isProperESAPICheckForDML(typeCheck, crudMethod)
&& !isProperAuthPatternBasedCheckForDML(typeCheck, crudMethod);
boolean noSecurityEnforced = !isWithSecurityEnforced(node);
boolean noUserMode = !isWithUserMode(node);
boolean noSystemMode = !isWithSystemMode(node);
if (missingKey) {
//if condition returns true, add violation, otherwise return.
if (isImproperDMLCheck && noSecurityEnforced) {
addViolation(data, node);
return true;
if (isImproperDMLCheck) {
if (noSecurityEnforced && noUserMode && noSystemMode) {
addViolation(data, node);
return true;
}
}
} else {
boolean properChecksHappened = false;

View File

@ -64,7 +64,7 @@ public class Foo {
<description>
Avoid DML statements inside loops to avoid hitting the DML governor limit. Instead, try to batch up the data into a list and invoke your DML once on that list of data outside the loop.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
_Note:_ This rule is deprecated since PMD 6.29.0 and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule {% rule "apex/performance/OperationWithLimitsInLoop" %}.
</description>
<priority>3</priority>
@ -93,7 +93,7 @@ public class Something {
<description>
New objects created within loops should be checked to see if they can created outside them and reused.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
_Note:_ This rule is deprecated since PMD 6.29.0 and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule {% rule "apex/performance/OperationWithLimitsInLoop" %}.
</description>
<priority>3</priority>
@ -120,7 +120,7 @@ public class Something {
<description>
Sosl calls within loops can cause governor limit exceptions.
This rule is deprecated and will be removed with PMD 7.0.0. The rule is replaced
_Note:_ This rule is deprecated since PMD 6.29.0 and will be removed with PMD 7.0.0. The rule is replaced
by the more general rule {% rule "apex/performance/OperationWithLimitsInLoop" %}.
</description>
<priority>3</priority>

View File

@ -35,14 +35,18 @@ public without sharing class Foo {
<rule name="ApexCRUDViolation"
language="apex"
since="5.5.3"
message="Validate CRUD permission before SOQL/DML operation"
message="Validate CRUD permission before SOQL/DML operation or enforce user mode"
class="net.sourceforge.pmd.lang.apex.rule.security.ApexCRUDViolationRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_apex_security.html#apexcrudviolation">
<description><![CDATA[
The rule validates you are checking for access permissions before a SOQL/SOSL/DML operation.
Since Apex runs in system mode not having proper permissions checks results in escalation of
Since Apex runs by default in system mode not having proper permissions checks results in escalation of
privilege and may produce runtime errors. This check forces you to handle such scenarios.
Since Winter '23 (API Version 56) you can enforce user mode for database operations by using
`WITH USER_MODE` in SOQL. This makes Apex to respect Field-level security (FLS) and object
permissions of the running user. When using user mode, no violation is reported by this rule.
By default, the rule allows access checks can be performed using system Apex provisions such as
`DescribeSObjectResult.isAccessible/Createable/etc.`, the SOQL `WITH SECURITY_ENFORCED` clause,
or using the open source [Force.com ESAPI](https://github.com/forcedotcom/force-dot-com-esapi)

View File

@ -9,5 +9,4 @@ import net.sourceforge.pmd.testframework.PmdRuleTst;
class ApexCRUDViolationTest extends PmdRuleTst {
// no additional unit tests
}

View File

@ -4,6 +4,7 @@
package net.sourceforge.pmd.lang.java.rule.bestpractices;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.pmd.lang.java.ast.ASTAnyTypeDeclaration;
@ -25,9 +26,18 @@ public class UnusedPrivateFieldRule extends AbstractJavaRulechainRule {
.desc("Field Names that are ignored from the unused check")
.build();
private static final PropertyDescriptor<List<String>> REPORT_FOR_ANNOTATIONS_DESCRIPTOR
= PropertyFactory.stringListProperty("reportForAnnotations")
.desc("Fully qualified names of the annotation types that should be reported anyway. If an unused field "
+ "has any of these annotations, then it is reported. If it has any other annotation, then "
+ "it is still considered to used and is not reported.")
.defaultValue(new ArrayList<String>())
.build();
public UnusedPrivateFieldRule() {
super(ASTAnyTypeDeclaration.class);
definePropertyDescriptor(IGNORED_FIELD_NAMES);
definePropertyDescriptor(REPORT_FOR_ANNOTATIONS_DESCRIPTOR);
}
@Override

View File

@ -10,7 +10,10 @@ import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule;
/**
* This rule detects when a class exceeds a certain threshold. i.e. if a class
* has more than 1000 lines of code.
*
* @deprecated Use {@link NcssCountRule} instead.
*/
@Deprecated
public class ExcessiveClassLengthRule extends AbstractJavaCounterCheckRule.AbstractLineLengthCheckRule<ASTAnyTypeDeclaration> {
public ExcessiveClassLengthRule() {
super(ASTAnyTypeDeclaration.class);

View File

@ -11,7 +11,10 @@ import net.sourceforge.pmd.lang.java.rule.internal.AbstractJavaCounterCheckRule;
/**
* This rule detects when a method exceeds a certain threshold. i.e. if a method
* has more than x lines of code.
*
* @deprecated Use {@link NcssCountRule} instead.
*/
@Deprecated
public class ExcessiveMethodLengthRule extends AbstractJavaCounterCheckRule.AbstractLineLengthCheckRule<ASTMethodOrConstructorDeclaration> {
public ExcessiveMethodLengthRule() {
super(ASTMethodOrConstructorDeclaration.class);

View File

@ -632,6 +632,7 @@ public void bar() {
<rule name="ExcessiveClassLength"
language="java"
since="0.6"
deprecated="true"
message="Avoid really long classes."
class="net.sourceforge.pmd.lang.java.rule.design.ExcessiveClassLengthRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_design.html#excessiveclasslength">
@ -639,6 +640,16 @@ public void bar() {
Excessive class file lengths are usually indications that the class may be burdened with excessive
responsibilities that could be provided by external classes or functions. In breaking these methods
apart the code becomes more manageable and ripe for reuse.
_Note:_ This rule is deprecated since PMD 6.53.0 and will be removed with PMD 7.0.0.
The rule is based on the simple metric lines of code (LoC). The reasons for deprecation are:
* LoC is a noisy metric, NCSS (non-commenting source statements) is a more solid metric
(results are code-style independent, comment-insensitive)
* LoC is easily circumvented by bad code style (e.g. stuffing several assignments into one, concatenating code lines)
* Enforcing length limits with LoC is not very meaningful, could even be called a bad practice
In order to find "big" classes, the rule {% rule NcssCount %} can be used instead.
</description>
<priority>3</priority>
<example>
@ -689,6 +700,7 @@ public class Foo {
<rule name="ExcessiveMethodLength"
language="java"
since="0.6"
deprecated="true"
message="Avoid really long methods."
class="net.sourceforge.pmd.lang.java.rule.design.ExcessiveMethodLengthRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_design.html#excessivemethodlength">
@ -697,6 +709,16 @@ When methods are excessively long this usually indicates that the method is doin
name/signature might suggest. They also become challenging for others to digest since excessive
scrolling causes readers to lose focus.
Try to reduce the method length by creating helper methods and removing any copy/pasted code.
_Note:_ This rule is deprecated since PMD 6.53.0 and will be removed with PMD 7.0.0.
The rule is based on the simple metric lines of code (LoC). The reasons for deprecation are:
* LoC is a noisy metric, NCSS (non-commenting source statements) is a more solid metric
(results are code-style independent, comment-insensitive)
* LoC is easily circumvented by bad code style (e.g. stuffing several assignments into one, concatenating code lines)
* Enforcing length limits with LoC is not very meaningful, could even be called a bad practice
In order to find "big" methods, the rule {% rule NcssCount %} can be used instead.
</description>
<priority>3</priority>
<example>

View File

@ -130,12 +130,17 @@ public class Violation {
<rule name="AvoidAssertAsIdentifier"
language="java"
maximumLanguageVersion="1.3"
since="3.4"
message="Avoid using assert as an identifier; it became a reserved word in JDK 1.4"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidassertasidentifier">
<description>
Use of the term 'assert' will conflict with newer versions of Java since it is a reserved word.
Use of the term `assert` will conflict with newer versions of Java since it is a reserved word.
Since Java 1.4, the token `assert` became a reserved word and using it as an identifier will
result in a compilation failure for Java 1.4 and later. This rule is therefore only useful
for old Java code before Java 1.4. It can be used to identify problematic code prior to a Java update.
</description>
<priority>2</priority>
<properties>
@ -347,12 +352,17 @@ private void buz(String x) {}
<rule name="AvoidEnumAsIdentifier"
language="java"
maximumLanguageVersion="1.4"
since="3.4"
message="Avoid using enum as an identifier; it's a reserved word in JDK 1.5"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#avoidenumasidentifier">
<description>
Use of the term 'enum' will conflict with newer versions of Java since it is a reserved word.
Use of the term `enum` will conflict with newer versions of Java since it is a reserved word.
Since Java 1.5, the token `enum` became a reserved word and using it as an identifier will
result in a compilation failure for Java 1.5 and later. This rule is therefore only useful
for old Java code before Java 1.5. It can be used to identify problematic code prior to a Java update.
</description>
<priority>2</priority>
<properties>
@ -1074,7 +1084,7 @@ class Foo {
Finally, comparisons like `someDouble <= Double.NaN` are nonsensical
and will always evaluate to false.
This rule has been renamed from "BadComparison" with PMD 6.36.0.
This rule has been renamed from "BadComparison" in PMD 6.36.0.
]]></description>
<priority>3</priority>
<properties>
@ -1291,7 +1301,7 @@ running on the same application server.
This rule also checks for the equivalent calls `Runtime.getRuntime().exit()` and `Runtime.getRuntime().halt()`.
This rule was called *DoNotCallSystemExit* until PMD 6.29.0.
This rule has been renamed from "DoNotCallSystemExit" in PMD 6.29.0.
</description>
<priority>3</priority>
<properties>
@ -1506,8 +1516,8 @@ public class Foo {
<description>
Empty finally blocks serve no purpose and should be removed.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1544,8 +1554,8 @@ public class Foo {
<description>
Empty If Statement finds instances where a condition is checked but nothing is done about it.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1580,8 +1590,8 @@ public class Foo {
<description>
Empty initializers serve no purpose and should be removed.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1612,8 +1622,8 @@ public class Foo {
<description>
Empty block statements serve no purpose and should be removed.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1640,6 +1650,7 @@ public class Foo {
<rule name="EmptyStatementNotInLoop"
language="java"
since="1.5"
deprecated="true"
message="An empty statement (semicolon) not part of a loop"
class="net.sourceforge.pmd.lang.rule.XPathRule"
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_errorprone.html#emptystatementnotinloop">
@ -1647,6 +1658,9 @@ public class Foo {
An empty statement (or a semicolon by itself) that is not used as the sole body of a 'for'
or 'while' loop is probably a bug. It could also be a double semicolon, which has no purpose
and should be removed.
_Note:_ This rule is deprecated since PMD 6.53.0 and will be removed with PMD 7.0.0.
Use the rule {% rule java/codestyle/UnnecessarySemicolon %} instead.
</description>
<priority>3</priority>
<properties>
@ -1687,8 +1701,8 @@ public void doit() {
<description>
Empty switch statements serve no purpose and should be removed.#
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1719,8 +1733,8 @@ public void bar() {
<description>
Empty synchronized blocks serve no purpose and should be removed.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1751,8 +1765,8 @@ public class Foo {
<description>
Avoid empty try blocks - what's the point?
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -1790,8 +1804,8 @@ Empty While Statement finds all instances where a while statement does nothing.
If it is a timing loop, then you should use Thread.sleep() for it; if it is
a while loop that does a lot in the exit expression, rewrite it to make it clearer.
This rule is deprecated since PMD 6.46.0. Use the rule {% rule "java/codestyle/EmptyControlStatement" %}
from category codestyle instead.
_Note:_ This rule is deprecated since PMD 6.46.0 and will be removed with PMD 7.0.0.
Use the rule {% rule "java/codestyle/EmptyControlStatement" %} from category codestyle instead.
</description>
<priority>3</priority>
<properties>
@ -2012,7 +2026,7 @@ an intentional fall-through.
You can ignore a violation by commenting `// fallthrough` before the case label
which is reached by fallthrough, or with `@SuppressWarnings("fallthrough")`.
This rule has been renamed from "MissingBreakInSwitch" with PMD 6.37.0.
This rule has been renamed from "MissingBreakInSwitch" in PMD 6.37.0.
</description>
<priority>3</priority>
<example>
@ -2082,6 +2096,8 @@ Check for messages in slf4j and log4j2 (since 6.19.0) loggers with non matching
Since 6.32.0 in addition to parameterized message placeholders (`{}`) also format specifiers of string formatted
messages are supported (`%s`).
This rule has been renamed from "InvalidSlf4jMessageFormat" in PMD 6.19.0.
</description>
<priority>5</priority>
<example>

View File

@ -143,7 +143,7 @@ public class ThrDeux {
<description>
The J2EE specification explicitly forbids the use of threads. Threads are resources, that should be managed and monitored by the J2EE server.
If the application creates threads on its own or uses own custom thread pools, then these threads are not managed, which could lead to resource exhaustion.
Also EJB's might be moved between machines in a cluster and only managed resources can be moved along.
Also, EJBs might be moved between machines in a cluster and only managed resources can be moved along.
</description>
<priority>3</priority>
<properties>

View File

@ -131,9 +131,7 @@
<!-- <rule ref="category/java/design.xml/DataClass" /> -->
<rule ref="category/java/design.xml/DoNotExtendJavaLangError" />
<!-- <rule ref="category/java/design.xml/ExceptionAsFlowControl" /> -->
<!-- <rule ref="category/java/design.xml/ExcessiveClassLength" /> -->
<!-- <rule ref="category/java/design.xml/ExcessiveImports" /> -->
<!-- <rule ref="category/java/design.xml/ExcessiveMethodLength" /> -->
<!-- <rule ref="category/java/design.xml/ExcessiveParameterList" /> -->
<!-- <rule ref="category/java/design.xml/ExcessivePublicCount" /> -->
<rule ref="category/java/design.xml/FinalFieldCouldBeStatic"/>

View File

@ -0,0 +1,24 @@
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.lang.java.ast;
import org.junit.Assert;
import org.junit.Test;
public class ASTCompactConstructorDeclarationTest extends BaseParserTest {
@Test
public void compactConstructorWithLambda() {
ASTCompactConstructorDeclaration compactConstructor = getNodes(ASTCompactConstructorDeclaration.class,
"import java.util.Objects;"
+ "record RecordWithLambdaInCompactConstructor(String foo) {"
+ " RecordWithLambdaInCompactConstructor {"
+ " Objects.requireNonNull(foo, () -> \"foo\");"
+ " }"
+ "}")
.get(0);
Assert.assertEquals(1, compactConstructor.getBody().getNumChildren());
}
}

View File

@ -771,6 +771,50 @@ public class C {
@ToString.Include
private int a; // Should not report a warning in this line
}
]]></code>
</test-code>
<test-code>
<description>[java] UnusedPrivateField doesn't find annotated unused private fields anymore #4166 (default)</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.WebElement;
class ClassWithUnusedField {
@FindBy(id = "myId")
private WebElement myElement;
}
]]></code>
</test-code>
<test-code>
<description>[java] UnusedPrivateField doesn't find annotated unused private fields anymore #4166 (default, other annotation)</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
class ClassWithUnusedField {
@Deprecated
private String unusedField;
}
]]></code>
</test-code>
<test-code>
<description>[java] UnusedPrivateField doesn't find annotated unused private fields anymore #4166 (configuration)</description>
<rule-property name="reportForAnnotations">java.lang.Deprecated|org.openqa.selenium.support.FindBy</rule-property>
<expected-problems>2</expected-problems>
<expected-linenumbers>6,9</expected-linenumbers>
<code><![CDATA[
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
class ClassWithUnusedField {
@Deprecated
private String unusedField;
@FindBy(id = "whatEverId")
private WebElement myElement;
}
]]></code>
</test-code>
</test-data>

View File

@ -22,8 +22,8 @@ class Foo {
<test-code>
<description>do while true | true</description>
<expected-problems>4</expected-problems>
<expected-linenumbers>3,4,5,6</expected-linenumbers>
<expected-problems>8</expected-problems>
<expected-linenumbers>3,4,5,6,9,10,11,12</expected-linenumbers>
<code><![CDATA[
class Foo {
{
@ -31,6 +31,12 @@ class Foo {
do { } while (true || true);
do { } while ((true | true));
do { } while ((true || true));
boolean otherBool = false;
do { } while (true | otherBool);
do { } while (true || otherBool);
do { } while ((true | otherBool));
do { } while ((true || otherBool));
}
}
]]></code>
@ -54,8 +60,8 @@ class Foo {
<test-code>
<description>do while false | false #3455</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>3,5</expected-linenumbers>
<expected-problems>4</expected-problems>
<expected-linenumbers>3,5,8,10</expected-linenumbers>
<code><![CDATA[
class Foo {
{
@ -63,28 +69,87 @@ class Foo {
} while (false | false);
do {
} while ((false | false));
do {
} while (false || false);
do {
} while ((false || false));
}
}
]]></code>
</test-code>
<test-code>
<description>do while false || false #3455</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>3,6</expected-linenumbers>
<description>do while false &amp; false</description>
<expected-problems>8</expected-problems>
<expected-linenumbers>3,5,7,9,13,15,17,19</expected-linenumbers>
<code><![CDATA[
class Foo {
{
do {
} while (false || false);
} while (false & false);
do {
} while ((false || false));
} while ((false & false));
do {
} while (false && false);
do {
} while ((false && false));
boolean otherBool = true;
do {
} while (false & otherBool);
do {
} while ((false & otherBool));
do {
} while (false && otherBool);
do {
} while ((false && otherBool));
}
}
]]></code>
</test-code>
<test-code>
<description>do while true &amp;&amp; true</description>
<expected-problems>8</expected-problems>
<expected-linenumbers>3,5,7,9,12,14,16,18</expected-linenumbers>
<code><![CDATA[
class Foo {
{
do {
} while (true & true);
do {
} while ((true & true));
do {
} while (true && true);
do {
} while ((true && true));
do {
} while (true & true & true);
do {
} while ((true & true & true));
do {
} while (true && true && true);
do {
} while ((true && true && true));
// the following loops are not reported, because they depend on otherBool
boolean otherBool = true;
do {
} while (true & otherBool);
do {
} while ((true & otherBool));
do {
} while (true && otherBool);
do {
} while ((true && otherBool));
}
}
]]></code>
</test-code>
<test-code>
<description>do while call</description>
<expected-problems>0</expected-problems>
@ -129,8 +194,8 @@ class Foo {
<test-code>
<description>while false | false</description>
<expected-problems>4</expected-problems>
<expected-linenumbers>3,4,5,6</expected-linenumbers>
<expected-problems>8</expected-problems>
<expected-linenumbers>3,4,5,6,8,9,10,11</expected-linenumbers>
<code><![CDATA[
class Foo {
{
@ -138,6 +203,11 @@ class Foo {
while ((false | false)) { }
while (false || false) { }
while ((false || false)) { }
while (false | false | false) { }
while ((false | false | false)) { }
while (false || false || false) { }
while ((false || false || false)) { }
}
}
]]></code>
@ -231,6 +301,47 @@ class Foo {
do {} while ((true && true));
}
}
]]></code>
</test-code>
<test-code>
<description>[java] WhileLoopWithLiteralBoolean - false negative with complex expressions still occurs in PMD 6.52.0 #4250</description>
<expected-problems>4</expected-problems>
<expected-linenumbers>3,7,11,15</expected-linenumbers>
<code><![CDATA[
public class Foo {
public void func() {
do {
// Loop Body
} while (false || false || false || false); // This is a false negative
do {
// Loop Body
} while (false | false | false | false | false); // This is a similar false negative.
do { //reported: WhileLoopWithLiteralBoolean: The loop can be simplified.
// Loop Body
} while (false && false && false && false);
do { //reported: WhileLoopWithLiteralBoolean: The loop can be simplified.
// Loop Body
} while (false & false & false & false & false);
}
}
]]></code>
</test-code>
<test-code>
<description>False positives without literal booleans</description>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
public void func(int x, int y) {
do {
System.out.println("Testing");
} while (x==0 || y==2);
}
}
]]></code>
</test-code>
</test-data>

View File

@ -16,6 +16,7 @@ public class UsingThread {
<test-code>
<description>extending threads is not allowed</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>2</expected-linenumbers>
<code><![CDATA[
// This is not allowed
public class UsingThread extends Thread {
@ -26,6 +27,7 @@ public class UsingThread extends Thread {
<test-code>
<description>Implementing ExecutorService is not allowed</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>3</expected-linenumbers>
<code><![CDATA[
import java.util.concurrent.ExecutorService;
@ -36,6 +38,7 @@ public class PMDTestExecutorService implements ExecutorService {}
<test-code>
<description>Extending AbstractExecutorService is not allowed</description>
<expected-problems>1</expected-problems>
<expected-linenumbers>3</expected-linenumbers>
<code><![CDATA[
import java.util.concurrent.*;
@ -46,6 +49,7 @@ public class PMDTestExecutorService extends AbstractExecutorService {}
<test-code>
<description>Using ExecutorService is not allowed</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>6,7</expected-linenumbers>
<code><![CDATA[
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
@ -65,7 +69,8 @@ public class ExecutorServiceUsage {
<test-code>
<description>Using Executors directly is not allowed</description>
<expected-problems>4</expected-problems>
<expected-problems>2</expected-problems>
<expected-linenumbers>5,10</expected-linenumbers>
<code><![CDATA[
import java.util.concurrent.Executors;
import java.util.concurrent.Callable;
@ -112,6 +117,7 @@ public class Violation {
}
]]></code>
</test-code>
<test-code>
<description>getContextClassLoader is ok</description>
<expected-problems>0</expected-problems>
@ -121,4 +127,97 @@ public class Ok {
}
]]></code>
</test-code>
<test-code>
<description>[java] DoNotUseThreads report duplicate warnings #4210</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>2,4</expected-linenumbers>
<code><![CDATA[
public final class Test {
public final Thread BAR = new Thread(); // reports two duplicate warnings in this line, but one is enough
public Thread getBAR() { // report one warning in this line
return this.BAR;
}
}
]]></code>
</test-code>
<test-code>
<description>False negatives with field declarations</description>
<expected-problems>19</expected-problems>
<expected-linenumbers>6,7,8,9,13,14,20,26,30,31,33,34,37,38,42,43,47,48,51</expected-linenumbers>
<code><![CDATA[
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
class DoNotUseThreadsTest {
private Thread background; // 6: violation expected
private ScheduledExecutorService scheduledExecutor; // 7: violation expected
private ForkJoinPool pool; // 8: violation expected
private final Thread owner = Thread.currentThread(); // 9: violation expected
static final ThreadFactory threadFactory1 = new ThreadFactory() {
@Override
public Thread newThread(final Runnable r) { // 13: violation expected
return new Thread(r); // 14: violation expected
}
};
static final ThreadFactory threadFactory2 = new ThreadFactory() {
@Override
public Thread newThread(final Runnable r) { // 20: violation expected
return null;
}
};
DoNotUseThreadsTest() {
this.background = new Thread(); // 26: violation expected
}
public void run() {
new Thread(() -> System.out.println("foo")).start(); // 30: violation expected
Thread t2 = new Thread(); // 31: one violation expected
// report two violations, if on two separate lines
Thread t3 = // 33: violation expected
new Thread(); // 34: violation expected
}
public Thread getThread() { // 37: violation expected
return new Thread(); // 38: violation expected
}
@Override
public Thread getThread1() { // 42: violation expected
return new Thread(); // 43: violation expected
}
@Override
public Thread getThread2(final Runnable r) { // 47: violation expected
return new Thread(r); // 48: violation expected
}
private static class MyThread extends Thread { } // 51: violation expected
}
]]></code>
</test-code>
<test-code>
<description>More false negatives</description>
<expected-problems>2</expected-problems>
<expected-linenumbers>5,8</expected-linenumbers>
<code><![CDATA[
import java.util.HashMap;
import java.util.Map;
class DoNotUseThreadsTest {
Map<Thread, String> m = new HashMap<>();
boolean isThread(Class<?> cl) {
return cl == Thread.class;
}
}
]]></code>
</test-code>
</test-data>

View File

@ -108,7 +108,7 @@
<argLine>-Xmx512m -Dfile.encoding=${project.build.sourceEncoding} ${extraArgLine}</argLine>
<extraArgLine /> <!-- empty by default, profiles set it as needed -->
<pmd.build-tools.version>18</pmd.build-tools.version>
<pmd.build-tools.version>19</pmd.build-tools.version>
<pmd-designer.version>7.0.0-SNAPSHOT</pmd-designer.version>
<javacc.jar>${settings.localRepository}/net/java/dev/javacc/javacc/${javacc.version}/javacc-${javacc.version}.jar</javacc.jar>