Skip to content

Commit

Permalink
SONARJAVA-4436 Fix FP on S2095 when using @lombok.Cleanup (#4957)
Browse files Browse the repository at this point in the history
Co-authored-by: Dorian Burihabwa <[email protected]>
  • Loading branch information
1 parent 565282b commit 2d6bb09
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
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 -> annotation.symbol().type().fullyQualifiedName().endsWith("Cleanup"));
}
}

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 fullyQualified(String fileName) throws IOException {
@lombok.Cleanup
InputStream in = new FileInputStream(fileName);
in.read();
}

public void annotated(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,24 @@ void test() {
.verifyIssues();
}

@Test
void doesNotRaiseOnLombokCleanupAnnotatedVariable() {
SECheckVerifier.newVerifier()
.onFile("src/test/files/se/UnclosedResourcesLombokCheck.java")
.withCheck(new UnclosedResourcesCheck())
.withClassPath(SETestUtils.CLASS_PATH)
.verifyNoIssues();
}

@Test
void doesNotRaiseOnLombokCleanupAnnotatedVariableNoSemantic() {
SECheckVerifier.newVerifier()
.onFile("src/test/files/se/UnclosedResourcesLombokCheck.java")
.withCheck(new UnclosedResourcesCheck())
.withoutSemantic()
.verifyNoIssues();
}

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

0 comments on commit 2d6bb09

Please sign in to comment.