Skip to content
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

SONARJAVA-4436 Fix FP on S2095 when using @lombok.Cleanup #4957

Merged
merged 7 commits into from
Dec 11, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -474,11 +474,21 @@ private void closeResource(@Nullable final SymbolicValue target) {
@Override
public void visitIdentifier(IdentifierTree tree) {
// close resource as soon as it is encountered in the resource declaration
if (isWithinTryHeader(tree)) {
// or if it is annotated with @lombok.Cleanup
if (isWithinTryHeader(tree) || isAnnotatedLombokCleanup(tree)) {
Symbol symbol = tree.symbol();
closeResource(programState.getValue(symbol));
}
}

private static boolean isAnnotatedLombokCleanup(IdentifierTree tree) {
return tree
.symbol()
.metadata()
.annotations()
.stream()
.anyMatch(annotation -> "lombok.Cleanup".equals(annotation.symbol().type().fullyQualifiedName()));
tomasz-tylenda-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
}
}

private class PostStatementVisitor extends CheckerTreeNodeVisitor {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import lombok.Cleanup;

class UnclosedResourcesLombokCheck {
public void missingAnnotation(String fileName) throws IOException {
InputStream in = new FileInputStream(fileName); // Noncompliant
in.read();
}
tomasz-tylenda-sonarsource marked this conversation as resolved.
Show resolved Hide resolved

public void sameButAnnotated(String fileName) throws IOException {
@Cleanup
InputStream in = new FileInputStream(fileName);
in.read();
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ void test() {
.verifyIssues();
}

@Test
void test_lombok() {
tomasz-tylenda-sonarsource marked this conversation as resolved.
Show resolved Hide resolved
SECheckVerifier.newVerifier()
.onFile("src/test/files/se/UnclosedResourcesLombokCheck.java")
.withCheck(new UnclosedResourcesCheck())
.withClassPath(SETestUtils.CLASS_PATH)
.verifyIssues();
}

@Test
void jdbcTests() {
SECheckVerifier.newVerifier()
Expand Down
Loading