package pkg;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InitInstanceFieldServlet extends HttpServlet {
// java:S2226 flags this field (false positive, it is initialized in the init() method)
private int timeoutSeconds;
// java:S2226 does not flag this field (also initialized in the init() method)
private long timeoutMilliseconds;
public @Override void init() throws ServletException {
String timeoutSecondsString =
this.getServletContext().getInitParameter("timeoutSeconds");
// java:S2226 flags this field (false positive)
this.timeoutSeconds = Integer.parseInt(timeoutSecondsString);
// java:S2226 does not flag this field
timeoutMilliseconds = this.timeoutSeconds * 1000L;
// Apparently:
// java:S2226 fails to recognize assignment with "this." before field name.
}
protected @Override void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
try {
Thread.sleep(this.timeoutMilliseconds);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
try {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"timed out after "+this.timeoutSeconds+" seconds");
} catch (IOException ignore) {
// connection lost
}
}
}
The above description contains a minimal project that demonstrates that a field intialized in a servlet init() method with “this.field = …” can trigger a false positive of java S2226.
java S2226 says Servlets should not have mutable instance fields, with exceptions for fields initialized in the init() method, or for fields annotated to be initialized by injection.
Servlets should not have mutable instance fields java:S2226
…
Exceptions
Fields annotated with @javax.inject.Inject , @javax.ejb.EJB , @org.springframework.beans.factory.annotation.Autowired , @javax.annotation.Resource
Fields initialized in init() or init(ServletConfig config) methods
Hello @nimarukan,
Thanks for reporting the issue. It looks like the rule does not identify instance fields in the init method that are referenced with this in the assignment.
A ticket has been created to solve the issue.
Thank you. Good to hear there is progress. But an initialization like what appears in the ticket, “this.first = 42”, does not make clear why it must be initialized in the init method.
In case you do not yet have a fix, here is what I found.
Below is a possible addition to the test case for S2226, to test for a field initialized within the init method by “this.field = …”.
Also, the ticket title seems to say there no problem to fix? I suggest renaming it
"S2226 improperly identifies instance variables assigned in init method with this.field = ..."