Please follow this template to help us specify this new rule:
- description of the Rule. It should answer questions “why is there an issue?”, “what could be its impact?” and “what could happen in case of a successful attack?” (for Vulnerabilities and Security Hotspots)
When using java classes that implement Closable or AutoClosable its important to close those resources after usage, this is normally done with the try-with-resources pattern. But sometimes you keep those resource as fields and only close them at the end. Currently there is no rule to detect this
- snippet of Noncompliant Code
public class A {
private B b = new B(); // implements AutoCloseable
private C c = new C();
...
}
- snippet of Compilant Code (fixing the above noncompliant code)
public class A implements AutoCloseable {
private B b = new B(); // implements AutoCloseable
private C c = new C();
@Override
public void close() {
b.close();
}
}
So there are two checks needed for compliance:
- if there is a field that implements closeable, the class containing it must also implement closeable
- this close method must call close on the field that implements closeable
- exceptions to the Noncompliant Code, i.e. conditions in which the noncompliant code should not raise an issue so that we reduce the number of False Positives.
none