-
Notifications
You must be signed in to change notification settings - Fork 720
SONARJAVA-5975 S6856: Add support for record component extraction #5520
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
asya-vorobeva
wants to merge
1
commit into
master
Choose a base branch
from
asya/S6856-improve-1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,6 @@ | ||
| { | ||
| "ruleKey": "S6856", | ||
| "hasTruePositives": false, | ||
| "falseNegatives": 59, | ||
| "falseNegatives": 61, | ||
| "falsePositives": 0 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
...-checks-test-sources/spring-3.2/src/main/java/checks/ExtractRecordPropertiesTestData.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| package checks; | ||
|
|
||
| import org.springframework.web.bind.annotation.BindParam; | ||
|
|
||
| public class ExtractRecordPropertiesTestData { | ||
| // Record with components | ||
| record RecordWithComponents(String project, int year, String month) { | ||
| } | ||
|
|
||
| // Empty record | ||
| record EmptyRecord() { | ||
| } | ||
|
|
||
| // Record with @BindParam annotation | ||
| record RecordWithBindParam(@BindParam("order-name") String orderName, String details) { | ||
| } | ||
|
|
||
| // Record with mixed @BindParam and regular components | ||
| record RecordMixedBindParam( | ||
| @BindParam("project-id") String projectId, | ||
| String name, | ||
| @BindParam("user-id") String userId | ||
| ) { | ||
| } | ||
| } |
70 changes: 70 additions & 0 deletions
70
...es/spring-3.2/src/main/java/checks/MissingPathVariableAnnotationCheck_classAndRecord.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| package checks; | ||
|
|
||
| import org.springframework.web.bind.annotation.BindParam; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
|
|
||
| public class MissingPathVariableAnnotationCheck_classAndRecord { | ||
| static class ReportPeriod { | ||
| private String project; | ||
| private int year; | ||
| private String month; | ||
|
|
||
| public String getProject() { | ||
| return project; | ||
| } | ||
|
|
||
| public int getYear() { | ||
| return year; | ||
| } | ||
|
|
||
| public String getMonth() { | ||
| return month; | ||
| } | ||
|
|
||
| public void setProject(String project) { | ||
| this.project = project; | ||
| } | ||
|
|
||
| public void setYear(int year) { | ||
| this.year = year; | ||
| } | ||
|
|
||
| public void setMonth(String month) { | ||
| this.month = month; | ||
| } | ||
| } | ||
|
|
||
| record ReportPeriodRecord(String project, int year, String month) { | ||
| } | ||
|
|
||
| static class ReportPeriodBind { | ||
| @GetMapping("/reports/{project}/{year}/{month}") | ||
| public String getReport(ReportPeriod period) { | ||
| // Spring sees {project} in the URL and calls period.setProject() | ||
| // Spring sees {year} in the URL and calls period.setYear() | ||
| return "reportDetails"; | ||
| } | ||
|
|
||
| @GetMapping("/reports/{project}/{year}/{month}") | ||
| public String getAnotherReport(ReportPeriodRecord period) { | ||
| // Spring sees {project} in the URL and calls period.project() | ||
| // Spring sees {year} in the URL and calls period.year() | ||
| return "reportDetails"; | ||
| } | ||
|
|
||
| public record Order(@BindParam("order-name") String orderName, String details){} | ||
|
|
||
| @GetMapping("/{order-name}/details") | ||
| public String getOrderDetails(Order order){ | ||
| // Spring sees {order-name} in the URL and calls order.orderName() | ||
| return order.details(); | ||
| } | ||
|
|
||
| @GetMapping("/{orderName}/details") // Noncompliant {{Bind template variable "orderName" to a method parameter.}} | ||
| public String getOrderDetailsWrongParameterName(Order order){ | ||
| // Spring sees {orderName} in the URL and can't find order's orderName because of the wrong binding | ||
| return order.details(); | ||
| } | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -21,13 +21,17 @@ | |||||||
| import java.util.HashSet; | ||||||||
| import java.util.List; | ||||||||
| import java.util.Map; | ||||||||
| import java.util.Optional; | ||||||||
| import java.util.Set; | ||||||||
| import java.util.function.Function; | ||||||||
| import java.util.stream.Collectors; | ||||||||
| import java.util.stream.Stream; | ||||||||
| import javax.annotation.Nullable; | ||||||||
| import org.sonar.check.Rule; | ||||||||
| import org.sonar.java.annotations.VisibleForTesting; | ||||||||
| import org.sonar.plugins.java.api.DependencyVersionAware; | ||||||||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||||||||
| import org.sonar.plugins.java.api.Version; | ||||||||
| import org.sonar.plugins.java.api.semantic.Symbol; | ||||||||
| import org.sonar.plugins.java.api.semantic.SymbolMetadata; | ||||||||
| import org.sonar.plugins.java.api.semantic.Type; | ||||||||
|
|
@@ -41,7 +45,7 @@ | |||||||
| import static org.sonar.java.checks.helpers.MethodTreeUtils.isSetterLike; | ||||||||
|
|
||||||||
| @Rule(key = "S6856") | ||||||||
| public class MissingPathVariableAnnotationCheck extends IssuableSubscriptionVisitor { | ||||||||
| public class MissingPathVariableAnnotationCheck extends IssuableSubscriptionVisitor implements DependencyVersionAware { | ||||||||
| private static final String PATH_VARIABLE_ANNOTATION = "org.springframework.web.bind.annotation.PathVariable"; | ||||||||
| private static final String MAP = "java.util.Map"; | ||||||||
| private static final String MODEL_ATTRIBUTE_ANNOTATION = "org.springframework.web.bind.annotation.ModelAttribute"; | ||||||||
|
|
@@ -60,6 +64,10 @@ public class MissingPathVariableAnnotationCheck extends IssuableSubscriptionVisi | |||||||
| "lombok.Data", | ||||||||
| "lombok.Setter"); | ||||||||
|
|
||||||||
| private static final String BIND_PARAM_ANNOTATION = "org.springframework.web.bind.annotation.BindParam"; | ||||||||
|
|
||||||||
| private SpringWebVersion springWebVersion; | ||||||||
|
|
||||||||
| @Override | ||||||||
| public List<Tree.Kind> nodesToVisit() { | ||||||||
| return List.of(Tree.Kind.CLASS); | ||||||||
|
|
@@ -191,14 +199,14 @@ private void checkParametersAndPathTemplate(MethodTree method, Set<String> model | |||||||
| return; | ||||||||
| } | ||||||||
|
|
||||||||
| // finally, we handle the case where a uri parameter (/{aParam}/) doesn't match to path- or ModelAttribute- inherited variables | ||||||||
| // finally, we handle the case where a uri parameter (/{aParam}/) doesn't match to path-, ModelAttribute-, or class / record inherited variables | ||||||||
| Set<String> allPathVariables = methodParameters.stream() | ||||||||
| .map(ParameterInfo::value) | ||||||||
| .collect(Collectors.toSet()); | ||||||||
| // Add properties inherited from @ModelAttribute methods | ||||||||
| allPathVariables.addAll(modelAttributeMethodParameters); | ||||||||
| // Add properties inherited from @ModelAttribute class parameters | ||||||||
| allPathVariables.addAll(extractModelAttributeClassProperties(method)); | ||||||||
| // Add properties inherited from class and record parameters | ||||||||
| allPathVariables.addAll(extractClassAndRecordProperties(method)); | ||||||||
|
|
||||||||
| templateVariables.stream() | ||||||||
| .filter(uri -> !allPathVariables.containsAll(uri.value())) | ||||||||
|
|
@@ -278,20 +286,29 @@ private static String removePropertyPlaceholder(String path){ | |||||||
| return path.replaceAll(PROPERTY_PLACEHOLDER_PATTERN, ""); | ||||||||
| } | ||||||||
|
|
||||||||
| private static Set<String> extractModelAttributeClassProperties(MethodTree method) { | ||||||||
| private boolean requiresModelAttributeAnnotation(SymbolMetadata metadata) { | ||||||||
| // for spring-web < 5.3 we need to use ModelAttribute annotation to extract properties from classes / records | ||||||||
| return springWebVersion == SpringWebVersion.LESS_THAN_5_3 && !metadata.isAnnotatedWith(MODEL_ATTRIBUTE_ANNOTATION); | ||||||||
| } | ||||||||
|
|
||||||||
| private Set<String> extractClassAndRecordProperties(MethodTree method) { | ||||||||
| Set<String> properties = new HashSet<>(); | ||||||||
|
|
||||||||
| for (var parameter : method.parameters()) { | ||||||||
| SymbolMetadata metadata = parameter.symbol().metadata(); | ||||||||
| Type parameterType = parameter.type().symbolType(); | ||||||||
|
|
||||||||
| if (!metadata.isAnnotatedWith(MODEL_ATTRIBUTE_ANNOTATION) || parameterType.isUnknown() | ||||||||
| || isStandardDataType(parameterType) || parameterType.isSubtypeOf(MAP)) { | ||||||||
| if (parameterType.isUnknown() | ||||||||
| || isStandardDataType(parameterType) || parameterType.isSubtypeOf(MAP) | ||||||||
| || requiresModelAttributeAnnotation(parameter.symbol().metadata())) { | ||||||||
| continue; | ||||||||
| } | ||||||||
|
|
||||||||
| // Extract setter properties from the class | ||||||||
| properties.addAll(extractSetterProperties(parameterType)); | ||||||||
| if (parameterType.isSubtypeOf("java.lang.Record") && springWebVersion != SpringWebVersion.LESS_THAN_5_3) { | ||||||||
| // Extract record's components | ||||||||
| properties.addAll(extractRecordProperties(parameterType)); | ||||||||
| } else if (parameterType.isClass()) { | ||||||||
| // Extract setter properties from the class | ||||||||
| properties.addAll(extractSetterProperties(parameterType)); | ||||||||
| } | ||||||||
| } | ||||||||
|
|
||||||||
| return properties; | ||||||||
|
|
@@ -345,6 +362,32 @@ private static Set<String> checkForLombokSetters(Symbol.TypeSymbol typeSymbol) { | |||||||
| return properties; | ||||||||
| } | ||||||||
|
|
||||||||
| @VisibleForTesting | ||||||||
| static Set<String> extractRecordProperties(Type type) { | ||||||||
| Set<String> properties = new HashSet<>(); | ||||||||
| // For records, extract component names from the record components | ||||||||
| // Records automatically generate accessor methods for their components | ||||||||
| type.symbol().memberSymbols().stream() | ||||||||
| .filter(Symbol::isVariableSymbol) | ||||||||
| .map(Symbol.VariableSymbol.class::cast) | ||||||||
| .filter(f -> !f.isStatic()).forEach(field -> properties.add(getComponentName(field))); | ||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nitpick: for readability
Suggested change
|
||||||||
|
|
||||||||
| return properties; | ||||||||
| } | ||||||||
|
|
||||||||
| private static String getComponentName(Symbol.VariableSymbol field) { | ||||||||
| // Check if the component has @BindParam annotation for custom binding name | ||||||||
| String componentName = field.name(); | ||||||||
| var bindParamValues = field.metadata().valuesForAnnotation(BIND_PARAM_ANNOTATION); | ||||||||
| if (bindParamValues != null) { | ||||||||
| Object value = bindParamValues.get(0).value(); | ||||||||
| if (value instanceof String bindParamName && !bindParamName.isEmpty()) { | ||||||||
| componentName = bindParamName; | ||||||||
| } | ||||||||
| } | ||||||||
| return componentName; | ||||||||
| } | ||||||||
|
|
||||||||
| static class PathPatternParser { | ||||||||
| private PathPatternParser() { | ||||||||
| } | ||||||||
|
|
@@ -474,4 +517,23 @@ private static String substringToCurrentChar(int start) { | |||||||
| } | ||||||||
|
|
||||||||
| } | ||||||||
|
|
||||||||
| @Override | ||||||||
| public boolean isCompatibleWithDependencies(Function<String, Optional<Version>> dependencyFinder) { | ||||||||
| Optional<Version> springWebCurrentVersion = dependencyFinder.apply("spring-web"); | ||||||||
| if (springWebCurrentVersion.isEmpty()) { | ||||||||
| return false; | ||||||||
| } | ||||||||
| springWebVersion = getSpringWebVersion(springWebCurrentVersion.get()); | ||||||||
| return true; | ||||||||
| } | ||||||||
|
|
||||||||
| private static SpringWebVersion getSpringWebVersion(Version springWebVersion) { | ||||||||
| return (springWebVersion.isLowerThan("5.3") ? SpringWebVersion.LESS_THAN_5_3 : SpringWebVersion.START_FROM_5_3); | ||||||||
| } | ||||||||
|
|
||||||||
| private enum SpringWebVersion { | ||||||||
| LESS_THAN_5_3, | ||||||||
| START_FROM_5_3; | ||||||||
| } | ||||||||
| } | ||||||||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should this
// Compliantcomment be removed ?