SmartReviewer
Built-in rules
Rule package builtin-java 0.20.2: 140 rules (General 98, Performance 10, Security 32).
Numbers and order are the same as in the rule lists of the IDEs (Eclipse preferences and Rules view, IntelliJ IDEA, VS Code), the rule list document and the rule sample set. A rule keeps its number, also when rules are added.
The code is sample code written for the tests. The finding message and the fix are the engine's actual output when it reviews the NG example with engine 0.1.22. No rule asserts a business error; each points at a place for a person to check.
The examples are excerpts for understanding how each rule behaves. They do not prove that a rule's detection is exhaustive, or that code without a finding has no problem.
1Check of web.xml deployment settings (development stage, directory listing, session, etc.)SR-CFG-WEBXML-001WarningSecurity
Reports 6 kinds of settings explicitly written in WEB-INF/web.xml that weaken protection or leak debugging information when deployed to production. (1) The JSF project stage is Development. (2) STATE_SAVING_METHOD is client and there is a setting that can disable view state encryption (such as com.sun.faces.disableClientStateEncryption). (3) Directory listing is allowed on the default servlet of Tomcat/Jetty (listings, dirAllowed). (4) session-timeout is 0 or less (the session never expires). (5) session-timeout is longer than 1440 minutes (can be changed with a parameter). (6) The session cookie has http-only=false. The following are not reported: a missing session-timeout, a setting of only STATE_SAVING_METHOD=client (it is encrypted by default), a stage other than Development, and placeholder values that are replaced at build time. Because it is not known whether web.xml is deployed to production, this finding is a prompt to check.
- Category
- Configuration and dependencies
- Target
- Configuration files (web.xml, pom.xml, .classpath, jar file names in WEB-INF/lib)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>demo</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
</web-app>Finding message (the engine's actual output)
Check this web.xml deployment setting: javax.faces.PROJECT_STAGE = Development in context-param.
Fix (the engine's suggestion)
First check whether this web.xml is deployed to production (development and production descriptors are often switched by the build). If it is, act on the sentence below that matches the setting name of this finding (javax.faces.PROJECT_STAGE): [JSF project stage] use the Production project stage, or remove the setting (Production is the default). [View state encryption] remove the parameter (Mojarra's com.sun.faces.disableClientStateEncryption whatever its value; MyFaces' encryption parameter: remove it or set it to true); client state is encrypted by default, and if a fixed key is needed, configure the key instead of switching the encryption off. [Directory listing] set listings (Tomcat) or dirAllowed (Jetty) to false; the default is false for Tomcat and true for Jetty, so for Jetty false must be written. [Session never expires] give session-timeout a finite, reasonable number of minutes. [Session timeout too long] shorten session-timeout to a reasonable number of minutes (the unit is minutes, not seconds). [Session cookie] remove http-only=false. If the setting is intended, suppress it in suppressions.yaml with the reason.
Note on the NG example: If the project stage is left as Development when deployed to production, debugging information (such as error messages) is shown to users. Because it is not known whether this web.xml is for production, this finding is a prompt to check.
OK example (code that is not reported)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>demo</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Production</param-value>
</context-param>
</web-app>The project stage is Production (the default), so no debugging information is shown.
Example that is not reported (boundary or exclusion)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>demo</display-name>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>${jsf.project.stage}</param-value>
</context-param>
<session-config>
<session-timeout>@session.timeout@</session-timeout>
</session-config>
</web-app>The value is a placeholder that is replaced at build time (${jsf.project.stage}, @session.timeout@), and the actual value is not known, so it is not reported.
2Getter/setter using a field other than the one its name designatesSR-JAVA-ACCESSOR-FIELD-001WarningGeneral
Reports a one-statement getter or setter that reads or writes a field other than the property that corresponds to the method name, when a field with the same name as the property actually exists (for example, getValue8() returns value7). Often the field name was not corrected after a getter or setter was copied, but it may also be an intentional alias.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public Integer getValue8() {
return value7;
}Finding message (the engine's actual output)
getValue8() uses field value7 although field value8, which its name designates, exists.
Fix (the engine's suggestion)
Check which field getValue8() should use and what its callers receive.
OK example (code that is not reported)
public Integer getValue7() {
return value7;
}The getter returns value7, as its name says.
Example that is not reported (boundary or exclusion)
public void setName(String name) {
this.name = name == null ? "" : name.trim();
}A setter that processes its argument before assigning it (turns null into an empty string and trims it) assigns to the field its name designates, so it is not reported.
3Variable referenced more than once in an array initializerSR-JAVA-ARRAY-001WarningGeneral
Reports when the same variable (the same declaration; for an instance field, one whose receiver can be proven to be the same) is read more than once among the direct elements of the same array initializer. The length of an array (names.length) is not a variable read, so it is not compared, and no limit is reported when type bindings are enabled. If another direct element of the same initializer increments or assigns the variable (n, n++, n++, n), the initializer as a whole is not compared. When a name cannot be resolved, it is not compared as text; only when the same text appears twice and no decision can be made is it reported as a "part that could not be determined", and nothing is output for names that differ from each other (Keys.NAME, Keys.AGE). Some input may have been left out after copy and paste, but the duplicate may also be intentional. It does not depend on business-related names.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static Object[] bad(Integer value1, Integer value2, Integer value3,
Integer value4, Integer value5, Integer value6,
Integer value7, Integer value8, Integer value9) {
return new Object[] {
value1, value2, value3, value4, value5, value6,
value7, value7, value9
};
}Finding message (the engine's actual output)
Array elements 7, 8 read value7 more than once; check the input mapping.
Fix (the engine's suggestion)
Check the repeated positions, the specification and regression tests; do not replace variables based on names alone.
OK example (code that is not reported)
static Object[] good(Integer value1, Integer value2, Integer value3,
Integer value4, Integer value5, Integer value6,
Integer value7, Integer value8, Integer value9) {
return new Object[] {
value1, value2, value3, value4, value5, value6,
value7, value8, value9
};
}This version correctly puts value8 in the 8th element.
Example that is not reported (boundary or exclusion)
Object[] b04(Integer a) {
return new Object[] {a, a};
}An array initializer with fewer than 3 elements (the default minElements = 3) is not evaluated.
Detection scope
Code forms detected
- Among the direct elements of an array initializer
{…}, the same variable is read twice or more:new Object[] {a, b, a}(cases P01, P02, B02). The declaration formInteger[] r = {a, b, a};counts as well (P05). The element type does not matter;int[]is examined too (P17). - Not only method bodies: array initializers in constructors (P06), instance initializer blocks (P07), static initializer blocks (P08), field initializers (P09), lambda bodies (P10) and methods of anonymous classes (P11) are examined, and so is one that is an argument of a call,
use(new Object[] {a, b, a})(P12). - Three kinds of variable are compared: local variables and method parameters (P01, P02, P13); instance fields (
value,this.value,Outer.this.valueandsuper.valuecount as one variable when they name the same field; P03, F06B, P14, P15, P15B); fields of the same local variable or parameter, such asleft.value(P04, P16). - Redundant parentheses around an element are removed first:
(a)equalsa(P02). - A repeated variable gives one finding, located at its second occurrence, with the other occurrences as related locations (B02: three occurrences, still one finding). Two different repeated variables in one array give two findings (B07), in the order of the variables' first occurrence (B09; the table of the HTML report is sorted by line instead). The name shown is the one written at the first occurrence: with
valueandthis.valuemixed it isvalue(F06B).
Conditions
- The initializer has at least 3 direct elements (parameter
minElements, default 3). A literal counts as an element ({a, a, 0}is examined; B11), a trailing comma does not ({a, a, }has 2; B12); smaller initializers are not examined (B04). - It must be the same declaration, and the declaration must be resolvable. The same name with a different declaration does not count: a local
valueand the fieldthis.value(F06), or the fieldxof an inner class andOuter.this.x(N15). A variable whose declaration cannot be resolved is not compared (see "When it cannot judge"). - A field read needs a receiver that is proven to be the same object. Proven receivers:
this, no receiver,Outer.this,super, and a local variable or parameter that is not reassigned inside that initializer (P03, F06B, P14, P15, P04, P16, N11). Other receivers: see "Not detected". - The rule applies to
**/*.java(test sources included) and not to files below any directory namedgeneratedortarget, at any depth; matching is case-sensitive, soGeneratedorgeneratedxare not excluded (scope.include,scope.exclude). - In a review of changed code only (
scope.changedCodePolicy: INTERSECT_CONTAINER): when any line of an initializer was changed, the repetitions in the whole initializer are reported, including one that existed before the change and whose two reported places are both unchanged. Repetitions in an initializer without a changed line are not reported, but what could not be judged there is still recorded. - This statement describes the package defaults. A project may change parameters in
ruleOverrides; the report's "Review conditions" then records that this rule's parameters were changed (the fact, not the values):ignoreLiterals(default true; false also compares identical literals; pm01),ignoreCompileTimeConstants(default true; pm02),referenceKinds(default local variable, parameter, instance field;STATIC_FIELDcan be added; pm03),minElements(default 3, 2 to 100000; pm04),minIdentityQuality(defaultRESOLVED, can be lowered toRECOVEREDorSYNTAX_ONLY; pm05). - Which review profiles (
--profile) enable this rule by default is generated bysmartreviewer rules docfrom the actual profile definitions: it is the row "default enablement by profile" of this rule in the rule overview (which is written in Chinese).
Not detected
- Literals and
null(N02, N03), and compile-time constants:static finalconstants (N04), andfinallocals andfinalfields initialized with a constant expression (N13). - Elements that are not a direct read of a variable: method calls (N05), casts and operator expressions (N10), increments such as
a++(F07), and array element reads (row[0]), conditional expressions,new,this, class literals, lambdas,instanceof, negation and string concatenation (B21). A variable read directly next to them is still compared:{a, c ? a : b, a}reportsa(B21). - The
lengthof an array (names.length) is not a variable read: it is not compared and causes no limitation (fx01, fx02). That holds when type bindings are on; with type bindings off see "When it cannot judge". - When another direct element of the same initializer is itself an increment, decrement or assignment of the variable (
n++,++n,n = m,n += 2), the variable is left out as a whole, reads before the change included, even when two reads still have the same value ({n, n, n++}):{n, n++, n++, n}(fx03, N14). A change hidden elsewhere is not recognised (see "Known false positives and negatives"). - Static fields are not compared, whether
finalor not, includingCls.counter, enum constants and the spelling through an instance: the default kinds of variable do not include static fields (parameterreferenceKinds; N08, N16). - Fields with different receivers, such as
left.valueandright.value(N06). When the receiver is none of the kinds that "Conditions" lists as provable, the field read is not compared either, for example an array element (hs[0].value), a field chain (p.inner.value,this.h.value), a field used as receiver, the result of a method call, a cast, or a variable that is reassigned inside the initializer (N06B, N11, N17, N17B, N17C, N17D, N17E, N18). - Nested initializers are not flattened: the outer array and each inner array are examined on their own, and the elements of an inner array are not mixed into the outer comparison (B03, B08).
- Each initializer is judged on its own: the same variable in another array (in the same method or in another method), or its value kept in another variable (
copy = a), is no repetition (N12).
When it cannot decide
- A name that cannot be resolved (undeclared, or type information missing) is not compared as text. Only when the same text stands twice in one initializer is the coverage limitation
IDENTITY_UNAVAILABLEreported, and that review result is incomplete; different unresolved names cause no limitation (B05, fx05, fx04). - When the base class cannot be resolved, two spellings of the same field are two different texts:
{inherited, o, this.inherited}is neither compared nor reported as a limitation, so the repetition is not found and the file still counts as completely checked (B13). - With type bindings off (
resolveBindings: false), local variables, parameters and instance fields declared in the file (names.lengthtoo) have only a syntax-level identity, below theRESOLVEDthe rule requires: in an array of 3 or more elements every such read, repeated or not, reportsIDENTITY_QUALITY_INSUFFICIENT, nothing is compared and the result is incomplete (B05S, B14, B25A). Not reported: static fields by simple name,finalvariables initialized with a literal, variables another element changes (B25); afinallocal initialized with2 + 3is reported (B25B). - Without type bindings these names are unknown too: one the file does not declare (an inherited field
inhread by its simple name),super.sx, a static field or constant qualified by its class (Cls.sf,Cls.SC), an enum constantColor.RED, a field chainh.value.IDENTITY_UNAVAILABLEis reported only when the same text stands twice in an initializer, and the review result is then incomplete (B25C, B25D, B25E, B25F, B25G, B25H); one read of each records nothing (B25I). - It also happens with type bindings on, when the lambda itself cannot be typed: it is passed to a method of an unknown type (
svc.each(x -> {…})) or to one whose type arguments are unknown (list.forEach(y -> {…})over aList<Unknown>); a written parameter type,(Integer x) -> {…}, does not help. The local variables and parameters read inside it (even once) have only a syntax-level identity andIDENTITY_QUALITY_INSUFFICIENTis reported; a repeated variable gives no finding (B15, B15B, B15C, B15E, B15F, B15G). - A lambda assigned to a declared type is typed even when a type argument of that type is unknown, so nothing is limited there: in
Function<Unknown, Object[]> g = u -> {…}a repeateduis reported (B15D). - A damaged array gets
CONTAINER_MALFORMEDfrom the rule only if the parser marked the initializer as recovered and at leastminElementselements are left ({a, b, a,, }); it is then not examined (B06). Other damage — a missing comma ({a b a}), a missing closing brace ({a, b, a;), fewer than 3 elements left ({a, a,, }) — can leave it unexamined and the rule reports nothing (B17, B18, B19). But a file with syntax errors is itself recorded asPARSE_RECOVERED(not judged, one per error): the result is incomplete and--strict-coverageexits with 3 for all four (B06, B17, B18, B19). - When a single element is damaged (
{a, b +, a}),ELEMENT_MALFORMEDis reported and the review result is incomplete; the other elements are still compared and a repetition is still reported, and the file is recorded asPARSE_RECOVEREDas well (B20). - With type bindings on, a field read whose receiver cannot be proven the same is recorded as
RECEIVER_UNPROVENfor every such read (even a single one) and left out of the comparison. It does not make the review result incomplete, but the report counts it among the "Parts not judged" (N06B, N11, N17, N17B, N17C, N17D, N17E, N18). - Arrays in annotation values: by default they give no finding (the elements are constants; N19). In annotations of methods, constructors, parameters, local variables, enum constants, interface methods, annotation type members and their defaults a repeated undeclared name is reported as
IDENTITY_UNAVAILABLE(B16, B16C, B16P, B16L, B16E, B16I, B16M, B16D); arrays in annotations of classes, fields and record components are not examined (B16K, B16F, B16R).
Known false positives and false negatives
- False positive: an intentional repetition, for example
xstanding for both the start and the end of a range,{x, y, x}. The tool cannot judge the business meaning, so a finding only asks for a check (confidence MEDIUM). When the repetition is confirmed as intended, an inline suppression can be used (next item); the original finding is still counted as suppressed (N07). - An inline suppression covers a finding when its target line is the line of the finding's location (the second occurrence:
disable-next-lineabove that line, su05;disable-lineat its end, su06; the other findings of the initializer stay, su07) or the line where the{of the initializer stands (then every finding of the initializer: su01, su08, su12, su13). One above the first occurrence, or above a statement whose{stands alone on the next line, does not apply and the findings still appear (su02, su11). For the general rule see "Suppression" in the README. - The reason is required: a marker without one, or with an empty one, covers nothing and the finding appears (su09, su10). The expiry
untilmay be omitted when no team policy applies, and a marker whose date has passed no longer applies (su04, su03). When the rule package'steamPolicy.maxSuppressionDaysis in force (the policy needsprotectedRulesorminimumSeverityas well), a marker withoutuntil, or with anuntilfurther away than that many days, is not permitted (suppression.statusisNOT_PERMITTEDin the JSON) and the finding appears. - False positive: the value of a variable changes between two reads and the rule does not see it. The change comes from a method call (
{count, next(), count}, wherenext()changescount; B22), or an increment or assignment is hidden inside a call, an index, a conditional expression, an operation or parentheses ({n, id(n++), n},{n, (n++), n}; B23). - False positive: a local that is never changed but is not
finalis no constant:{k, k, k}afterint k = 3;is reported (B24). - False positive relative to a baseline: the fingerprint of a finding contains the number of the array initializer among those of its method (evidence
containerId, such as…#m(Integer,Integer)/array[1]). Inserting another array initializer before it in the same method changes that number and the fingerprints of the findings after it: old findings recorded in a baseline reappear as new ones, and suppressions written by fingerprint no longer apply (B10A, B10B). - False negative: the same variable among the arguments of a method call (
Arrays.asList(a, b, a),List.of(a, b, a), varargs), or an array filled element by element (r[0] = a; r[2] = a;) is not examined, because the rule examines array initializers only (N09). - False negative: initializers with fewer than 3 elements (
{a, a}) and static fields are not examined by default. That does not mean there is no risk (B04, N08). - False negative: a repeated value that comes from a method call (
{load(), load(), x}), passes through a cast or an operator, or is kept in another variable (copy = a,{a, copy, d}) is not recognised, because the rule does not follow values (N05, N10, N12).
4Arrays compared with equalsSR-JAVA-ARRAY-EQUALS-001WarningGeneral
Arrays do not override equals(), so a.equals(b) and Objects.equals(a, b) compare whether the two arrays are the same object. Arrays with the same contents are still not equal.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean sameCodes(String[] a, String[] b) {
return a.equals(b);
}Finding message (the engine's actual output)
a.equals(b) compares the array objects (references), not their elements.
Fix (the engine's suggestion)
Compare the elements with Arrays.equals(a, b) (Arrays.deepEquals for nested arrays).
OK example (code that is not reported)
boolean sameCodesByContent(String[] a, String[] b) {
return Arrays.equals(a, b);
}The contents are compared with Arrays.equals.
Example that is not reported (boundary or exclusion)
boolean sameKbn(String kbn) {
return "1".equals(kbn);
}equals on a String, which is not an array, is outside the scope of this rule.
5Array concatenated or printed, giving [I@...SR-JAVA-ARRAY-TO-STRING-001WarningGeneral
Concatenating an array to a string ("ids=" + ids), calling toString() on it, or passing it to println/print, StringBuilder.append or String.valueOf uses Object.toString(), which gives a type name and a hash value such as "[I@1b6d3586" instead of the contents. The actual values cannot be seen in logs or on screen. Passing a char[] to println, append or valueOf is not reported because it is output as characters (concatenation is reported). Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String describe(int[] ids) {
return "ids=" + ids;
}Finding message (the engine's actual output)
The array ids (int[]) becomes a string in "ids=" + ids: that gives its type and hash code like [I@..., not its contents.
Fix (the engine's suggestion)
Convert it with Arrays.toString(ids) (Arrays.deepToString for nested arrays) or String.join before printing it.
OK example (code that is not reported)
String describeOk(int[] ids, String[] names) {
return "ids=" + Arrays.toString(ids) + " names=" + String.join(",", names);
}The contents are converted to a string with Arrays.toString or String.join.
Example that is not reported (boundary or exclusion)
void chars(char[] word) {
System.out.println(word);
StringBuilder sb = new StringBuilder();
sb.append(word);
System.out.println(String.valueOf(word));
}Passing a char[] to println, append or String.valueOf outputs it as characters, so it is not reported (concatenation such as "" + word is reported).
6Assignment in a condition (== written as =)SR-JAVA-ASSIGN-CONDITION-001WarningGeneral
Reports when the condition itself of an if, while, do, for or conditional operator is an assignment (if (flag = true)). The value of the condition is the assigned value, and the variable is also overwritten. Usually == was intended. It is reported when the assigned value is a literal or a variable. Assigning the result of a method call or the like (if (found = find(key))) may be intentional, so it is not reported by default (parameter values), and saving a variable of the same name in a field and testing it (if (this.skip = skip)) is not reported either.
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String label(boolean member) {
if (member = true) {
return "member";
}
return "guest";
}Finding message (the engine's actual output)
The if condition member = true is an assignment, not a comparison: it is always the value of true, and member is overwritten.
Fix (the engine's suggestion)
Compare with == (for a boolean, write if (member) or if (!member)); if the assignment is intended, make it before the condition.
OK example (code that is not reported)
String compare(boolean member, boolean guest) {
return member == true ? "member" : guest == false ? "guest" : "-";
}The comparison uses == (for a boolean value, if (member) can be written).
Example that is not reported (boundary or exclusion)
boolean configure(boolean skip) {
if (this.skip = skip) {
return false;
}
return true;
}Saving an argument of the same name in a field and testing that value is intentional, so it is not reported.
7Self-invocation of a Spring async methodSR-JAVA-ASYNC-SELF-001WarningGeneral
Reports a call to a method that has @Async, either on the method or on its class, when it is called directly with this (including an implicit this) from the same class or a subclass (including inherited async methods). A call that does not go through the Spring proxy does not become asynchronous and is executed synchronously in the calling thread. private, static and final methods, where the proxy cannot intervene, are not reported (the same applies when @Async is on the class). It is not reported when adviceMode is set to ASPECTJ or when the same file has @EnableAsync(mode = ASPECTJ). Calls through another object are not reported either. Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void asyncBad() { this.send(); }Finding message (the engine's actual output)
Spring async self-invocation: send.
Fix (the engine's suggestion)
Move the @Async method to another Spring bean and call it through the injected bean (e.g. asyncService.send()), or use AspectJ mode (@EnableAsync(mode = AdviceMode.ASPECTJ)), which also covers calls inside the class.
Note on the NG example: send() is a public method with @Async. Calling it directly with this bypasses the proxy, so it does not become asynchronous and runs synchronously in the calling thread.
OK example (code that is not reported)
public void asyncGood(Contracts other) { other.send(); }It is called through another object (a bean injected as a proxy), so it runs asynchronously.
Example that is not reported (boundary or exclusion)
public void close() {
flush();
}The called flush() is a final method; the Spring proxy cannot intervene and @Async has no effect, so this rule does not cover it.
8BigDecimal.divide with no rounding specifiedSR-JAVA-BIGDECIMAL-DIVIDE-001WarningGeneral
A divide() that specifies no precision, rounding mode or MathContext requires the quotient to be a finite decimal; if it is not, it throws ArithmeticException (Non-terminating decimal expansion), for example for 1 / 3. It cannot be found with round-number test data such as 10 or 100. It is not reported when the divisor is 10, 100, 4, "0.25", BigDecimal.TEN or the like (the quotient is then always a finite decimal).
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
BigDecimal average(BigDecimal total, BigDecimal count) {
return total.divide(count);
}Finding message (the engine's actual output)
total.divide(count) has no scale or rounding: it throws ArithmeticException when the quotient has no finite decimal form.
Fix (the engine's suggestion)
Give a scale and a rounding mode, e.g. a.divide(b, 2, RoundingMode.HALF_UP), or a.divide(b, MathContext.DECIMAL64).
OK example (code that is not reported)
BigDecimal roundedAverage(BigDecimal total, BigDecimal count) {
return total.divide(count, 2, RoundingMode.HALF_UP);
}The division specifies the number of decimal places and a rounding mode.
Example that is not reported (boundary or exclusion)
BigDecimal quarter(BigDecimal amount) {
return amount.divide(new BigDecimal("0.25"));
}The quotient of a division by 0.25 (= 1/4) is always a finite decimal, so it is not reported.
9BigDecimal created from a doubleSR-JAVA-BIGDECIMAL-DOUBLE-001WarningGeneral
new BigDecimal(double) takes in the binary error of the double as it is. For example, the actual value of new BigDecimal(0.1) is 0.1000000000000000055511151231257827..., so errors appear in calculations of amounts and ratios, and comparisons no longer match.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
BigDecimal taxRate() {
return new BigDecimal(0.1);
}Finding message (the engine's actual output)
new BigDecimal(0.1) carries the binary error of the double.
Fix (the engine's suggestion)
Use new BigDecimal("0.1") (a string) or BigDecimal.valueOf(double).
OK example (code that is not reported)
BigDecimal exact() {
return new BigDecimal("0.1");
}Creating it from a string gives exactly 0.1 (BigDecimal.valueOf(double) also works).
Example that is not reported (boundary or exclusion)
BigDecimal count(int n) {
return new BigDecimal(n);
}Passing an int selects the BigDecimal(int) constructor, which introduces no error, so it is not reported.
10BigDecimal compared with equals (the scale is compared too)SR-JAVA-BIGDECIMAL-EQUALS-001WarningGeneral
BigDecimal.equals() compares both the value and the scale (the number of digits after the decimal point), so 1.0 and 1.00, and 0 and 0.00, are not equal. When the scale of amounts obtained from a database or from calculations is not constant, the results of equality checks and zero checks (equals(BigDecimal.ZERO)) cannot be trusted. If the scale must also be the same, it can be left as it is. Field comparisons inside an equals(Object) method are not reported (a value class compares the scale there, consistently with hashCode(); BigDecimal.hashCode() also depends on the scale).
- Category
- Comparison and equality
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean isZero(BigDecimal amount) {
return amount.equals(BigDecimal.ZERO);
}Finding message (the engine's actual output)
amount.equals(BigDecimal.ZERO) compares BigDecimals with equals(), which is false when only the scale differs.
Fix (the engine's suggestion)
Compare values with a.compareTo(b) == 0 (signum() == 0 for zero); keep equals() where the scale must match too, with a comment saying so.
OK example (code that is not reported)
boolean isZeroByValue(BigDecimal amount) {
return amount.compareTo(BigDecimal.ZERO) == 0;
}Only the values are compared, with compareTo.
Example that is not reported (boundary or exclusion)
@Override
public boolean equals(Object o) {
return o instanceof Price && Objects.equals(amount, ((Price) o).amount);
}A field comparison inside the equals(Object) of the value class itself is not reported, because comparing the scale too is correct there, to stay consistent with hashCode().
11BigDecimal.setScale with no rounding specifiedSR-JAVA-BIGDECIMAL-SCALE-001WarningGeneral
setScale(n), which specifies only the number of digits, requires the fractional part of the value to have n digits or fewer; if it does not, it throws ArithmeticException (Rounding necessary), for example setScale(2) on 1.005. It cannot be found with test data whose fractional parts are short. It is not reported when the fractional part of the value clearly has n digits or fewer (for example, BigDecimal.valueOf(an integer), or setScale(2) on new BigDecimal("1.5")). This is the same kind of problem as SR-JAVA-BIGDECIMAL-DIVIDE-001.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
BigDecimal yen(BigDecimal amount) {
return amount.setScale(0);
}Finding message (the engine's actual output)
amount.setScale(0) has no rounding mode: it throws ArithmeticException when amount has more than 0 decimal places.
Fix (the engine's suggestion)
Give a rounding mode, e.g. amount.setScale(0, RoundingMode.HALF_UP); write RoundingMode.UNNECESSARY when no rounding may happen, to say so.
OK example (code that is not reported)
BigDecimal rounded(BigDecimal amount) {
return amount.setScale(2, RoundingMode.HALF_UP);
}A rounding mode is specified.
Example that is not reported (boundary or exclusion)
BigDecimal half() {
return new BigDecimal("0.5").setScale(2);
}Changing a value with 1 decimal place to 2 places only adds a 0 and throws no exception, so it is not reported.
12Boxed numbers compared with ==SR-JAVA-BOXED-EQ-001WarningGeneral
Comparing two wrapper objects such as Integer or Long (or BigDecimal/BigInteger) with == or != compares the object references, not the numbers. Integer and similar types reuse cached objects in the range -128 to 127, so the comparison works correctly while the values are small and goes wrong when they get larger, which makes this a defect that is hard to find in tests. When one side is a primitive type, the comparison is made after unboxing, so it is not reported.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean sameScore(Integer a, Integer b) {
return a == b;
}Finding message (the engine's actual output)
a == b compares Integer references, not values.
Fix (the engine's suggestion)
Compare values with equals() or Objects.equals() (compareTo() == 0 for BigDecimal when the scale does not matter), or unbox first.
OK example (code that is not reported)
boolean byValue(Integer a, Integer b) {
return a.equals(b);
}The values are compared with equals (Objects.equals if null is possible).
Example that is not reported (boundary or exclusion)
boolean withPrimitive(Integer a, int b) {
return a == b;
}One side is an int, so the Integer is unboxed and compared as a number, and it is not reported.
13Calendar.DAY_OF_WEEK used directly as an array index (Saturday is out of bounds)SR-JAVA-CALENDAR-FIELD-001WarningGeneral
cal.get(Calendar.DAY_OF_WEEK) is 1 for Sunday and 7 for Saturday. Using it unchanged as the index of an array of length 7 (names[cal.get(Calendar.DAY_OF_WEEK)]) puts Saturday at index 7, which is out of bounds (ArrayIndexOutOfBoundsException), and every other day gets the element of the next day. Only cases where the array length is certain to be 7 are reported (an initializer with 7 elements, new T[7], a local variable assigned only once, a final field, a private field that is not reassigned in the same file). The index may be the get call itself or a local variable assigned only once. The same applies to charAt on a string constant of exactly 7 characters. Subtracting 1, a table of length 8, DateFormatSymbols.getShortWeekdays(), % 7, other fields such as MONTH, and arrays whose length is not known are not reported. DayOfWeek.getValue() of java.time and List indexes are not checked. Requires type information.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String dayName(Calendar calendar) {
return WEEK_DAYS[calendar.get(Calendar.DAY_OF_WEEK)];
}Finding message (the engine's actual output)
WEEK_DAYS[calendar.get(Calendar.DAY_OF_WEEK)] uses Calendar.DAY_OF_WEEK (Sunday is 1, Saturday is 7) directly as an index into WEEK_DAYS, which has length 7: Saturday is out of bounds and every other day gets the entry of the next day.
Fix (the engine's suggestion)
Subtract one: cal.get(Calendar.DAY_OF_WEEK) - 1 (Sunday is 0); or make the table 8 elements long with the first one empty; or drop the table and use DateFormatSymbols.getShortWeekdays() (length 8, indexed by Calendar.SUNDAY to SATURDAY), cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, locale) or the DayOfWeek of java.time (Monday is 1).
Note on the NG example: WEEK_DAYS is a static final array with 7 elements, Sunday to Saturday, and its declaration is outside the code shown.
OK example (code that is not reported)
String dayNameMinusOne(Calendar calendar) {
return WEEK_DAYS[calendar.get(Calendar.DAY_OF_WEEK) - 1];
}1 is subtracted from the index (Sunday is 0, Saturday is 6).
Example that is not reported (boundary or exclusion)
String dayNameFromAnArrayOfUnknownLength(Calendar calendar, String[] names) {
return names[calendar.get(Calendar.DAY_OF_WEEK)];
}names is an array received as an argument, and its length is not known to be 7, so it is not reported.
14Calendar.HOUR set without AM_PM (the result changes between morning and afternoon)SR-JAVA-CALENDAR-HOUR-001WarningGeneral
cal.set(Calendar.HOUR, h) sets the hour of the 12-hour clock (0 to 11), and whether it is morning or afternoon is decided by AM_PM. If the AM_PM of that Calendar is not determined within the method, the result changes depending on whether it is run in the morning or in the afternoon (set(Calendar.HOUR, 0), meant to truncate to hour 0, gives noon for a date in the afternoon). The same Calendar variable is examined in source order, and if a section delimited by the places where the Calendar obtains a time (creation, reassignment, setTime, setTimeInMillis) contains clear() or set(Calendar.AM_PM, ...), it is not reported, whether that call comes before or after HOUR. A Calendar created with new GregorianCalendar(year, month, day) (midnight) or with a constructor whose hour is a constant is also not reported until the next setTime. Also not reported are taking the HOUR value from get(Calendar.HOUR) of the same Calendar so that morning/afternoon is kept, setting HOUR_OF_DAY, and add(Calendar.HOUR, n). Requires type information.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void setTheHourOfAParameter(Calendar calendar) {
calendar.set(Calendar.HOUR, 9);
}Finding message (the engine's actual output)
calendar.set(Calendar.HOUR, 9) sets Calendar.HOUR, the hour of the 12-hour clock, without AM_PM: the result depends on whether calendar is in the morning or in the afternoon at that moment.
Fix (the engine's suggestion)
Set the hour of the 24-hour clock with Calendar.HOUR_OF_DAY (cal.set(Calendar.HOUR_OF_DAY, 15)); truncating to midnight is set(Calendar.HOUR_OF_DAY, 0). When HOUR is really needed, set Calendar.AM_PM as well (cal.set(Calendar.AM_PM, Calendar.PM)) or call clear() first.
OK example (code that is not reported)
void hourAndPm(Calendar calendar) {
calendar.set(Calendar.HOUR, 9);
calendar.set(Calendar.AM_PM, Calendar.PM);
}AM_PM is set together with HOUR, so morning or afternoon is determined.
Example that is not reported (boundary or exclusion)
void madeAtAConstantHour() {
Calendar calendar = new GregorianCalendar(2026, Calendar.OCTOBER, 28, 15, 0);
calendar.set(Calendar.HOUR, 3);
}A Calendar created with a constructor whose hour is a constant (15:00) has morning or afternoon determined at the moment of creation, so it is not reported.
15Zero-based Calendar month used as 1 to 12SR-JAVA-CALENDAR-MONTH-001WarningGeneral
Calendar.get(Calendar.MONTH) and Date.getMonth() are zero-based (January is 0, December is 11). If they are concatenated to a string, printed or formatted (print, format, append, valueOf, toString) without adding 1, the month is displayed 1 less, and a comparison with 12 (== 12, != 12) always gives the same result. The 12 in Calendar.set(Calendar.MONTH, 12), set(y, 12, d) and new GregorianCalendar(y, 12, d) is January of the next year. It is not reported when 1 is added before use or when the value is used only in calculations. When, after concatenation or formatting, the value is compared only with the string of a date built in the same way (for example, to decide whether two dates are the same), both sides are shifted by the same amount, so it is not reported by default (usage KEY, parameter uses). Calendar.MONTH can be judged without type information, while Date.getMonth() and set(y, m, d) require type information.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String label(Calendar cal) {
return cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DAY_OF_MONTH);
}Finding message (the engine's actual output)
cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH) + "/" + cal.get(Calendar.DAY_OF_MONTH): Calendar months count from 0 (January is 0, December 11).
Fix (the engine's suggestion)
Add 1 to show it (cal.get(Calendar.MONTH) + 1), and set months with Calendar.JANUARY to Calendar.DECEMBER or subtract 1; better, use java.time (LocalDate.getMonthValue(), Month).
OK example (code that is not reported)
String labelOk(Calendar cal) {
return cal.get(Calendar.YEAR) + "/" + (cal.get(Calendar.MONTH) + 1);
}1 is added before the value is displayed.
Example that is not reported (boundary or exclusion)
boolean sameDay(Calendar a, Calendar b) {
String d1 = String.valueOf(a.get(Calendar.YEAR)) + String.valueOf(a.get(Calendar.MONTH)) + String.valueOf(a.get(Calendar.DATE));
String d2 = String.valueOf(b.get(Calendar.YEAR)) + String.valueOf(b.get(Calendar.MONTH)) + String.valueOf(b.get(Calendar.DATE));
return d1.equals(d2);
}Comparing date strings built in the same way gives a correct result, because the months on both sides are shifted by the same amount, so it is not reported by default (usage KEY).
16Shift_JIS specified as the charset name instead of Windows-31J (MS932)SR-JAVA-CHARSET-NAME-001InfoGeneral
The JDK charset name Shift_JIS (including its aliases) is the JIS standard mapping and differs from the Windows "Shift_JIS" (code page 932, JDK name Windows-31J, alias MS932). When it is used for data that Windows creates or that is passed to Windows (CSV, Excel, etc.), characters are lost or changed without any error (①, ㈱, 髙 and similar become ?, and for some, such as 〜 and ~, the same byte becomes a different character). Reports the name (a literal, a constant, a variable assigned only once, or a string concatenation) passed to new String(bytes, name), getBytes(name), InputStreamReader, Charset.forName, URLEncoder and similar. MS932, Windows-31J, UTF-8, names passed in from the caller, and calls that name no charset (covered by SR-JAVA-DEFAULT-CHARSET-001) are not reported. EUC-JP is reported only when the parameter includeEucJp is true. If the other side requires the JIS standard mapping, the code can be left as it is. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String decodeShiftJis(byte[] bytes) throws UnsupportedEncodingException {
return new String(bytes, "Shift_JIS");
}Finding message (the engine's actual output)
new String(bytes, "Shift_JIS") uses the charset Shift_JIS, the JIS standard Shift_JIS mapping of the JDK, which lacks characters that only Windows-31J has (for example U+2460 ①, U+3231 ㈱, U+2116 №, U+9AD9 髙, U+FF5E ~, U+FF0D -); they are written as ? without any error.
Fix (the engine's suggestion)
For data exchanged with a system that uses Windows-31J, use MS932, Windows-31J (for example new String(bytes, "MS932")) and keep the name in one constant. After the change the characters that only Shift_JIS can encode turn into ? instead: 4: U+2014 —, U+2016 ‖, U+2212 −, U+301C 〜. When the other side explicitly asks for the JIS standard mapping, leave it and say why in a comment.
Note on the NG example: This example reads (decodes). When reading, the byte sequence of a character that exists only in Windows-31J becomes U+FFFD (the replacement character); ? appears when writing (encoding).
OK example (code that is not reported)
byte[] ms932(String text) throws UnsupportedEncodingException {
return text.getBytes("MS932");
}MS932 (an alias of Windows-31J) is specified as the charset name.
Example that is not reported (boundary or exclusion)
String decodeEucJp(byte[] bytes) throws UnsupportedEncodingException {
return new String(bytes, "EUC-JP");
}EUC-JP is often used for exchange between Unix-like systems, where the standard mapping is what both sides agree on, so it is not reported by default (it is reported only when the parameter includeEucJp is true).
17Subtraction overflow in a comparatorSR-JAVA-COMPARATOR-SUBTRACT-001WarningGeneral
Reports an integer subtraction returned by Comparator.compare or Comparable.compareTo (this includes a comparator written as a lambda; the same applies whether it is an argument, a return value or a local variable, or the initial value of a field, an interface constant or an enum constant argument) that can actually exceed the range of int. The targets are differences truncated by a cast (such as a long difference converted to int) and differences that include a full-range operand (hashCode, System.identityHashCode, Objects.hash/hashCode, MIN_VALUE/MAX_VALUE of Integer/Long, and a parameter when the compared value itself is a number, for example Comparator<Integer>). Differences of ordinary int fields, getters and local variables are not reported, because they are domain values such as sequence numbers and IDs and do not actually overflow; differences of constants, of byte/short/char with each other, and of non-negative values (length, size, array length, ordinal, char) with each other are not reported either. Requires type information.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public Comparator<Long> compareNarrowed() { return (a,b)->(int)(a-b); }Finding message (the engine's actual output)
Comparator subtraction can overflow: a - b.
Fix (the engine's suggestion)
Use Integer.compare, Long.compare or Comparator.comparingInt/comparingLong, and add positive and negative regression cases.
Note on the NG example: Because a long difference is truncated to int, the sign is reversed for values that are 2³¹ or more apart and the sort order breaks (sorting may even throw an exception).
OK example (code that is not reported)
public Comparator<Integer> compareGood() { return Integer::compare; }The comparison uses Integer::compare (Integer.compare(a, b) and Long.compare work the same way).
Example that is not reported (boundary or exclusion)
public Comparator<Task> byPriority() {
return (a, b) -> a.getPriority() - b.getPriority();
}The difference of ordinary int getters such as a priority is between small domain values and does not overflow, so it is not reported.
18Contradictory comparisons of the same variable (condition always true or false)SR-JAVA-CONDITION-CONTRADICTION-001WarningGeneral
Reports conditions that cannot be true although they are joined with &&, or that cannot be false although they are joined with ||, when the cause is comparisons of the same operand with constants. Examples: x != 1 || x != 2, x < 5 || x >= 3 (always true for any value), month < 1 && month > 12, x == 1 && x == 2, x == 1 && x != 1, x == null && x != null, flag && !flag (always false for any value). Often || and && have been mixed up, or == and != have been mixed up, and the result is a branch that always runs or never runs. The operand is a variable without side effects (a local variable, a parameter, a field, an array length, etc.), and what it is compared with is a compile-time constant, null or an enum constant. The decision is made over all values the type can take (including NaN for double and null for reference types). It is not reported when there is a call, an assignment or ++/-- between the two comparisons, for a volatile field, for an operand that contains a method call, for a comparison between variables, or for equals. Requires type information.
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean notOneOrTwo(int type) {
return type != 1 || type != 2;
}Finding message (the engine's actual output)
The condition type != 1 || type != 2 is always true, whatever type is.
Fix (the engine's suggestion)
Fix the operator to what was meant: exclude several values with && (x != 1 && x != 2), test for out of range with || (month < 1 || month > 12), test for one of several values with || (x == 1 || x == 2), test for within a range with && (month >= 1 && month <= 12). If the condition really is meant to be constant, write true or false and say why in a comment.
OK example (code that is not reported)
boolean notBothValues(int type) {
return type != 1 && type != 2;
}The comparisons are joined with && instead of ||, so only a value that is neither 1 nor 2 gives true.
Example that is not reported (boundary or exclusion)
boolean notANumberEscapes(double ratio) {
return ratio < 0.5 || ratio >= 0.5;
}A double can be NaN (every comparison with NaN is false), so ratio < 0.5 || ratio >= 0.5 is not always true, and it is not reported.
19Mismatch between setter and getter properties in a copySR-JAVA-COPY-MISMATCH-001InfoGeneral
In a run of consecutive property copies (t.setXxx(s.getXxx()); copying between forms, DTOs and entities), reports the case where in exactly one place the getter property differs from the setter (t.setTel(s.getFax())) and s has a getter with the same name as the setter (getTel(); one whose return type the setter can accept). Because the same copy run has two or more other copies of same-named properties (parameter minMatchingCopies), a getter may have been left uncorrected after one line was copied. Requires type information. In a sampling check on the team's projects, cases where a different property is deliberately copied (storing the date and the time separately, using the official name on an official document, putting the registration date into the update date on creation, etc.) made up the majority and cannot be told apart structurally, so the severity is info and the confidence is low.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
CustomerDto toDto(CustomerForm form) {
CustomerDto dto = new CustomerDto();
dto.setName(form.getName());
dto.setKana(form.getKana());
dto.setTel(form.getFax());
dto.setFax(form.getFax());
dto.setMail(form.getMail());
return dto;
}Finding message (the engine's actual output)
dto.setTel(form.getFax()): form has getTel(), but getFax() is used here (4 copies of the same run pair same-named properties).
Fix (the engine's suggestion)
Check which value setTel() should get, usually form.getTel(); if getFax() is intended, say so in a comment.
OK example (code that is not reported)
CustomerDto plain(CustomerForm form) {
CustomerDto dto = new CustomerDto();
dto.setName(form.getName());
dto.setKana(form.getKana());
dto.setTel(form.getTel());
return dto;
}Every statement copies a property of the same name.
Example that is not reported (boundary or exclusion)
CustomerDto shortCopy(CustomerForm form) {
CustomerDto dto = new CustomerDto();
dto.setName(form.getName());
dto.setTel(form.getFax());
return dto;
}There is only one other copy of the same name, which is below minMatchingCopies (default 2), so it cannot be judged to be a copying error and is not reported.
20Date pattern hh (12-hour clock) without AM/PMSR-JAVA-DATE-12-HOUR-001WarningGeneral
In date-time patterns, h (1 to 12) and K (0 to 11) use the 12-hour clock. If the pattern has no AM/PM marker a, 13:05 and 01:05 give the same output, which causes confusion when times are recorded, compared or sorted. Use HH for the 24-hour clock.
- Category
- Date and time
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
SimpleDateFormat twelveHour() {
return new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
}Finding message (the engine's actual output)
hh in new SimpleDateFormat("yyyy/MM/dd hh:mm:ss") is a 12-hour clock without the AM/PM marker (a).
Fix (the engine's suggestion)
Use HH for a 24-hour clock; add a for a 12-hour clock, e.g. hh:mm a.
OK example (code that is not reported)
SimpleDateFormat timestamp() {
return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}HH, the 24-hour clock, is used.
Example that is not reported (boundary or exclusion)
SimpleDateFormat twelveHourWithMarker() {
return new SimpleDateFormat("hh:mm a");
}The AM/PM marker a is present, so times can be told apart even on a 12-hour clock, and it is not reported.
21DD used as the day in a date patternSR-JAVA-DATE-DAY-OF-YEAR-001WarningGeneral
In date-time patterns, D is the day of the year (5 February is 036), and the day of the month is d. A D used together with the month M is almost certainly dd mistyped as DD. A day-of-year date without a month (yyyy-DDD) is not reported.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
SimpleDateFormat dayOfYear() {
return new SimpleDateFormat("yyyy/MM/DD");
}Finding message (the engine's actual output)
DD in new SimpleDateFormat("yyyy/MM/DD") is the day of the year, not the day of the month (dd).
Fix (the engine's suggestion)
Use dd for the day of the month.
OK example (code that is not reported)
SimpleDateFormat calendarDate() {
return new SimpleDateFormat("yyyy/MM/dd");
}The day of the month is lowercase dd.
Example that is not reported (boundary or exclusion)
SimpleDateFormat ordinalDate() {
return new SimpleDateFormat("yyyy-DDD");
}In a day-of-year date without a month (the year plus the day of the year), D is the correct usage, so it is not reported.
22SS (milliseconds) used as seconds in a date patternSR-JAVA-DATE-MILLIS-SECOND-001WarningGeneral
In date-time patterns, S is milliseconds (the fraction of a second in DateTimeFormatter), and seconds are s. A pattern that has minutes but no s, such as HH:mm:SS, outputs milliseconds in the place of seconds, and the seconds are lost. SSS (explicit milliseconds) is not reported.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
SimpleDateFormat time() {
return new SimpleDateFormat("HH:mm:SS");
}Finding message (the engine's actual output)
SS in new SimpleDateFormat("HH:mm:SS") is milliseconds, and the pattern has no seconds (ss).
Fix (the engine's suggestion)
Use ss for seconds, e.g. HH:mm:ss; write HH:mm:ss.SSS when milliseconds are wanted too.
OK example (code that is not reported)
SimpleDateFormat precise() {
return new SimpleDateFormat("HH:mm:ss.SSS");
}Seconds are ss and milliseconds are SSS.
Example that is not reported (boundary or exclusion)
SimpleDateFormat millis() {
return new SimpleDateFormat("mm:SSS");
}Writing the milliseconds explicitly as 3-digit SSS is intentional, so it is not reported.
23mm used as the month in a date patternSR-JAVA-DATE-MINUTE-MONTH-001WarningGeneral
In date-time patterns, m is the minute and the month is M. When a pattern has the year, the day and m but no hour or seconds (yyyy/mm/dd), it is almost certainly MM mistyped as mm, and the "minute" of that time is output in the place of the month.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
SimpleDateFormat minuteAsMonth() {
return new SimpleDateFormat("yyyy/mm/dd");
}Finding message (the engine's actual output)
mm in new SimpleDateFormat("yyyy/mm/dd") is the minute, not the month (MM).
Fix (the engine's suggestion)
Use MM for the month.
OK example (code that is not reported)
SimpleDateFormat timestamp() {
return new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
}The month is uppercase MM and the minute is mm.
Example that is not reported (boundary or exclusion)
SimpleDateFormat minutesAndSeconds() {
return new SimpleDateFormat("mm:ss");
}In a "minutes:seconds" format that has no date, mm means minutes, so it is not reported.
24YYYY (week-based year) in a date patternSR-JAVA-DATE-WEEK-YEAR-001WarningGeneral
In patterns of SimpleDateFormat, DateTimeFormatter and the like, Y stands for the week-based year, so a few days at the end of December or the beginning of January are displayed as the next or the previous year (for example, 2025-12-29 becomes 2026-12-29). It is correct only when used together with the week number w, and characters enclosed in quotes are not covered.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
SimpleDateFormat weekYear() {
return new SimpleDateFormat("YYYY-MM-dd");
}Finding message (the engine's actual output)
YYYY in new SimpleDateFormat("YYYY-MM-dd") is the week-based year, not the calendar year (yyyy).
Fix (the engine's suggestion)
Use yyyy for the calendar year (uuuu also works in DateTimeFormatter).
OK example (code that is not reported)
SimpleDateFormat calendarDate() {
return new SimpleDateFormat("yyyy/MM/dd");
}The calendar year is lowercase yyyy.
Example that is not reported (boundary or exclusion)
SimpleDateFormat weekYearWithWeek() {
return new SimpleDateFormat("YYYY 'week' ww");
}When combined with the week number ww, the week-based year YYYY is correct, so it is not reported.
25Date.getYear() used without adding 1900SR-JAVA-DATE-YEAR-001WarningGeneral
getYear() of java.util.Date (also java.sql.Date and Timestamp) is the year minus 1900 (2024 is 124), and the year of the deprecated constructor new Date(year, month, day) is also interpreted as a value with 1900 subtracted (new Date(2024, 0, 1) is the year 3924). If, without adding 1900, it is concatenated to a string, printed or formatted, or compared with a four-digit year, a three-digit year is displayed and the result of the comparison is always the same. It is not reported when 1900 is added before use or when it is used only in calculations. When, after concatenation or formatting, it is compared only with the string of a year built in the same way, both sides are shifted by the same amount, so it is not reported by default (usage KEY, parameter uses). Requires type information.
- Category
- Date and time
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String fiscalYear(Date date) {
return "年度:" + date.getYear();
}Finding message (the engine's actual output)
"年度:" + date.getYear(): java.util.Date years are the year minus 1900 (2024 is 124).
Fix (the engine's suggestion)
Add 1900 when using it (date.getYear() + 1900) and subtract 1900 when constructing; better, use Calendar.get(Calendar.YEAR) or java.time (LocalDate.getYear()).
OK example (code that is not reported)
int year(Date date) {
return date.getYear() + 1900;
}1900 is added to give the Gregorian year.
Example that is not reported (boundary or exclusion)
boolean sameYear(Date a, Date b) {
return String.valueOf(a.getYear()).equals(String.valueOf(b.getYear()));
}When the years of two Dates are compared as strings, both sides have 1900 subtracted, so the result is correct, and it is not reported by default (usage KEY).
26Conversion between bytes and characters without a specified charsetSR-JAVA-DEFAULT-CHARSET-001InfoGeneral
String.getBytes(), new String(byte[]), new FileReader/FileWriter, new InputStreamReader(in)/new OutputStreamWriter(out) and new PrintWriter/PrintStream(file) use the platform's default charset. On Japanese Windows the default is MS932 (Windows-31J) up to Java 17; from Java 18 on, and on many servers, it is UTF-8. Even the same program changes the characters it reads and writes depending on the machine and the Java version, and Japanese text becomes garbled. An InputStreamReader/OutputStreamWriter that wraps System.in/System.out is also reported (from Java 18 the default is UTF-8, but the console of Japanese Windows remains MS932). getBytes() of a string literal consisting only of ASCII is not reported. The severity is info. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
byte[] encode(String name) {
return name.getBytes();
}Finding message (the engine's actual output)
name.getBytes() uses the platform's default charset: the result depends on the machine and the Java version.
Fix (the engine's suggestion)
Name the charset, e.g. s.getBytes(StandardCharsets.UTF_8), new String(bytes, StandardCharsets.UTF_8), Files.newBufferedReader(path, StandardCharsets.UTF_8), new InputStreamReader(in, "Windows-31J").
OK example (code that is not reported)
String convert(String text, byte[] data, InputStream in, File file) throws IOException {
byte[] utf8 = text.getBytes(StandardCharsets.UTF_8);
String sjis = new String(data, "MS932");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
FileWriter writer = new FileWriter(file, StandardCharsets.UTF_8)) {
writer.write(reader.readLine());
}
return sjis + utf8.length;
}The charset is stated explicitly (StandardCharsets.UTF_8, "MS932", etc.).
Example that is not reported (boundary or exclusion)
byte[] marker() {
return "END".getBytes();
}A literal consisting only of ASCII gives the same byte sequence in whichever charset is used, so it is not reported.
27Double-checked locking field that is not volatileSR-JAVA-DOUBLE-CHECKED-LOCKING-001WarningGeneral
Reports when the field of double-checked locking (if (f == null) { synchronized (..) { if (f == null) f = new X(); } }, or if (f != null) return f; before the synchronized block) is not declared volatile. The Java memory model allows instructions to be reordered, so another thread may see the reference first and the object's fields later, and end up using an object whose construction is not finished. This happens sporadically and is hard to reproduce. It is not reported when the declaration of the field cannot be found (when there is no type information and the field is not in the same file).
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static Settings loadSettings() {
if (settings == null) {
synchronized (DoubleCheckedLockingCases.class) {
if (settings == null) {
settings = new Settings();
}
}
}
return settings;
}Finding message (the engine's actual output)
The double-checked field settings is not volatile: other threads may see a half-built object.
Fix (the engine's suggestion)
Declare the field volatile; or use static initialization (the holder idiom), initialize it where it is declared, or synchronize the whole method.
Note on the NG example: The field is declared as private static Settings settings; (without volatile).
OK example (code that is not reported)
static Settings loadSafeSettings() {
if (safeSettings == null) {
synchronized (DoubleCheckedLockingCases.class) {
if (safeSettings == null) {
safeSettings = new Settings();
}
}
}
return safeSettings;
}Although the code is written the same way, the field safeSettings is declared volatile.
Example that is not reported (boundary or exclusion)
static Settings holderSettings() {
return Holder.INSTANCE;
}This is initialization through a static final field of a holder class (Initialization-on-demand holder). Class initialization is thread-safe and no double check is used, so it is not covered.
28Duplicate conditions in if/else-ifSR-JAVA-DUP-CONDITION-001WarningGeneral
Reports when, in an if/else if chain, a condition is exactly the same as an earlier condition and has no side effects. It is evaluated only when the earlier identical condition is false, so that branch is never executed. Often code that branches on a code value was copied and pasted and the value was not corrected.
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String subject(String kbn) {
if ("1".equals(kbn)) {
return "国語";
} else if ("2".equals(kbn)) {
return "数学";
} else if ("1".equals(kbn)) {
return "英語";
}
return "";
}Finding message (the engine's actual output)
Condition 3 repeats condition 1 ("1".equals(kbn)); its branch never runs.
Fix (the engine's suggestion)
Check which value the branch was meant to test (for example another code value), or remove the unreachable branch.
OK example (code that is not reported)
String distinct(String kbn) {
if ("1".equals(kbn)) {
return "a";
} else if ("2".equals(kbn)) {
return "b";
}
return "";
}The conditions of all the branches are different.
Example that is not reported (boundary or exclusion)
boolean read(Iterator<String> it) {
if (it.hasNext() && "x".equals(it.next())) {
return true;
} else if (it.hasNext() && "x".equals(it.next())) {
return false;
}
return false;
}The condition contains a call with side effects (it.next()), and the result may change with each evaluation, so it is not reported.
29Duplicate constant keys in consecutive settingsSR-JAVA-DUP-KEY-001WarningGeneral
When put, setAttribute, setProperty or similar are called consecutively on the same object and the same constant key appears twice, the later call overwrites the earlier value. Often the key name was not corrected after copy and paste, and another key is left unset. It is not reported when there is another statement between the two calls.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Map<String, Object> params(int kokugo, int sugaku, int eigo) {
Map<String, Object> p = new HashMap<>();
p.put("KOKUGO", kokugo);
p.put("SUGAKU", sugaku);
p.put("KOKUGO", eigo);
return p;
}Finding message (the engine's actual output)
Key "KOKUGO" is set again by p.put in a run of calls; the value set on line 18 is overwritten.
Fix (the engine's suggestion)
Check which key the second call should use and whether a key is missing.
OK example (code that is not reported)
void distinct(Request req) {
req.setAttribute("a", 1);
req.setAttribute("b", 2);
}All the keys are different.
Example that is not reported (boundary or exclusion)
Object reread(Map<String, Object> m) {
m.put("k", 1);
Object first = m.get("k");
m.put("k", 2);
return first;
}The first value is read between the two puts, so the overwrite is judged to be intentional and is not reported.
30Same setter called twice in a row, overwriting the previous valueSR-JAVA-DUP-SETTER-001WarningGeneral
Reports when, in consecutive setter statements (with no other statement between them), the same setter of the same object is called twice (dto.setName(a); dto.setName(b);). The later call overwrites the earlier value. Often a line was copied and the setter name was not corrected afterwards, and another property is left unset. It is not reported when the value reads the object itself (dto.setName(dto.getName().trim())), when both values are the same, when the first value is null, or when a boolean is set again from one literal to another (setFileFilter(null); setFileFilter(f); and setVisible(false); setVisible(true); are written this way to make the screen detect a change; parameter ignoreResets). By default only ordinary setters are reported (those for which the class has a field with the same name and type as the property, such as name, m_name or strName, or those that cannot be resolved). A setter with a different behavior such as a state transition (task.setState(SCHEDULED); task.setState(RUNNING);) and a setter declared in an interface (an API such as a serializer) may be called in a row on purpose (parameter onlyFieldSetters).
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Customer register(String name, String kana, int age) {
Customer c = new Customer();
c.setName(name);
c.setAge(age);
c.setName(kana);
return c;
}Finding message (the engine's actual output)
c.setName() is set twice in a row: name (line 68) is overwritten by kana.
Fix (the engine's suggestion)
Check which property the second call should set (setKana rather than setName, for example); delete the first call if it is redundant.
OK example (code that is not reported)
Customer distinct(String name, String kana) {
Customer c = new Customer();
c.setName(name);
c.setKana(kana);
return c;
}Each call is to a different setter.
Example that is not reported (boundary or exclusion)
Customer reset(String name) {
Customer c = new Customer();
c.setName(null);
c.setName(name);
c.setActive(false);
c.setActive(true);
return c;
}Setting null first, or setting again from false to true, is a reset made so that a change is detected, so it is not reported by default (parameter ignoreResets).
31Extra semicolon after if/for/whileSR-JAVA-EMPTY-BODY-001WarningGeneral
A semicolon right after the header, as in if (...);, for (...); or while (...);, becomes the whole body of the statement, and the code meant as the body becomes unrelated to the condition or the loop. The code after an if is executed regardless of the condition, and a loop spins with nothing to do and then executes the code just once. It is not reported when the if has an else, or when the semicolon is on the next line or after a comment. A loop is reported only when the next statement is a block or is indented deeper (an empty loop that does all its work in the header is a common way of writing, for example while ((c = read()) != '\n');).
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int discount(int amount, boolean member) {
int rate = 0;
if (member);
{
rate = 10;
}
return amount - amount * rate / 100;
}Finding message (the engine's actual output)
The semicolon after if (member) is an empty body: the code after it no longer depends on the if.
Fix (the engine's suggestion)
Remove the semicolon after if (member); if an empty body is intended, write { } with a comment.
OK example (code that is not reported)
int skipLine(Reader in) throws IOException {
int c;
while ((c = in.read()) != '\n' && c >= 0);
return c;
}This is an empty loop that does all its work in the header (the next statement is not a block and is not indented deeper).
Example that is not reported (boundary or exclusion)
void drain(Iterator<String> it) {
while (it.hasNext() && it.next() != null)
; // nothing to do per element
}Putting the semicolon on the next line and explaining it with a comment is an intentional empty body, so it is not reported.
32Empty catch block (swallowed exception)SR-JAVA-EMPTY-CATCH-001InfoGeneral
Reports when a catch block has neither a statement nor a comment. The exception is swallowed, processing continues in an uncertain state, and it cannot be told afterwards what happened. By default it does not report a case where the parameter name shows that the exception is ignored on purpose (ignore..., expected, unused, cannotHappen..., impossible...), or a try that only closes a resource (try { in.close(); } catch (IOException e) {}). Two ways of writing that are almost always intentional, "if parsing fails, keep the default value" (NumberFormatException) and no search result (NoResultException of JPA), are also not reported by default. (Parameter ignoredExceptions: comma-separated type names; a multi-catch is not reported only when all of its types are included.) The severity is info.
- Category
- Exception handling
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void pause() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}Finding message (the engine's actual output)
catch (InterruptedException e) is empty: the exception is swallowed without any record.
Fix (the engine's suggestion)
At least log it or rethrow it (wrapped if needed); if ignoring it is intended, say why in a comment or name the parameter ignored. For InterruptedException call Thread.currentThread().interrupt().
OK example (code that is not reported)
void logged(Store store, String data) {
try {
store.save(data);
} catch (IOException | SQLException e) {
System.err.println("save failed: " + e);
}
}The exception is handled by logging it.
Example that is not reported (boundary or exclusion)
int quantity(String text) {
int qty = 0;
try {
qty = Integer.parseInt(text);
} catch (NumberFormatException e) {
}
return qty;
}An empty catch of only NumberFormatException is an intentional way of writing "if parsing fails, keep the default value", so it is not reported by default (parameter ignoredExceptions).
33Empty string tested with == or !=SR-JAVA-EMPTY-STRING-EQ-001WarningGeneral
Comparing with the empty string literal "" using == or != compares object references. An empty string obtained from a request parameter, a database, substring or string concatenation is a different object from "", so s != "" is true (judged to have a value) and s == "" is false. It is not reported when both sides are compile-time constants. SR-JAVA-STRING-EQ-001 handles reference comparison of other strings.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean hasName(String name) {
return name != null && name != "";
}Finding message (the engine's actual output)
name != "" checks for an empty string by reference, not by contents.
Fix (the engine's suggestion)
Use isEmpty() after excluding null, e.g. if (name != null && !name.isEmpty()); or "".equals(name), StringUtils.isEmpty(name).
OK example (code that is not reported)
boolean hasText(String text) {
return text != null && !text.isEmpty();
}The check uses isEmpty() (or isBlank()).
Example that is not reported (boundary or exclusion)
boolean constants() {
return EMPTY == "";
}Both sides are compile-time constants (static final String EMPTY = "" and ""), so it is not reported.
34equals overridden without hashCodeSR-JAVA-EQUALS-HASHCODE-001InfoGeneral
Reports a class that directly extends Object and overrides equals(Object) but does not override hashCode(). Because equal objects have different hash values, lookups by key and duplicate removal fail when they are put into a HashMap or HashSet. When a subclass only makes equals stricter, the inherited hashCode remains valid, so it is not reported by default.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public class EqualsOnly {
private final String code;
public EqualsOnly(String code) {
this.code = code;
}
@Override
public boolean equals(Object o) {
return o instanceof EqualsOnly other && code.equals(other.code);
}
}Finding message (the engine's actual output)
example.EqualsOnly overrides equals() but not hashCode().
Fix (the engine's suggestion)
Implement hashCode() from the same fields as equals() (e.g. Objects.hash(...)).
OK example (code that is not reported)
public class EqualsAndHashCode {
protected final String code;
public EqualsAndHashCode(String code) {
this.code = code;
}
@Override
public boolean equals(Object o) {
return o instanceof EqualsAndHashCode other && Objects.equals(code, other.code);
}
@Override
public int hashCode() {
return Objects.hashCode(code);
}
}hashCode is also computed from the same fields as equals.
Example that is not reported (boundary or exclusion)
public class EqualsInSubclass extends EqualsAndHashCode {
private final int version;
public EqualsInSubclass(String code, int version) {
super(code);
this.version = version;
}
@Override
public boolean equals(Object o) {
return super.equals(o) && o instanceof EqualsInSubclass other && version == other.version;
}
}In a subclass that only makes equals stricter, the inherited hashCode remains valid, so it is not reported by default.
35equals(Object) overloaded instead of overriddenSR-JAVA-EQUALS-OVERLOAD-001WarningGeneral
Reports when boolean equals(MyType other) is declared instead of overriding equals(Object). This is an overload, and List.contains, Set, Map keys, Objects.equals and any call made through the Object type keep using the inherited equals(Object) (usually a reference comparison), so equal objects are not found in collections. It targets only an equals whose parameter is of that class (or a superclass or subclass); an equals whose parameter type is unrelated (such as equals(String) of a class that holds text), an abstract method, and a method that overrides equals(T) of a superclass (reported on the superclass side) are not reported. When the class also declares equals(Object), the overload is only a helper method, so it is not reported by default.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static final class Money {
final long amount;
final String currency;
Money(long amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public boolean equals(Money other) {
return other != null && amount == other.amount && currency.equals(other.currency);
}
@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}Finding message (the engine's actual output)
Money.equals(Money) is an overload, not an override of equals(Object): collections and Objects.equals never call it.
Fix (the engine's suggestion)
Change it to @Override public boolean equals(Object o), check the type, then compare; override hashCode() too.
OK example (code that is not reported)
static final class Code {
final String value;
Code(String value) {
this.value = value;
}
@Override
public boolean equals(Object o) {
return o instanceof Code && value.equals(((Code) o).value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}equals(Object) is overridden.
Example that is not reported (boundary or exclusion)
static final class Point {
final int x;
final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Point p) {
return p != null && x == p.x && y == p.y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point && equals((Point) o);
}
@Override
public int hashCode() {
return 31 * x + y;
}
}equals(Object) is also declared, and equals(Point) is only a helper method for it, so it is not reported by default.
36Values of different types compared with equals() (always false)SR-JAVA-EQUALS-TYPES-001WarningGeneral
The equals() of classes such as String, Integer, Long, BigDecimal, StringBuilder and java.time returns true only when the argument is an object of the same class. When the two sides are of two different classes among these (a primitive type is taken as its boxed type; for example, the number literal 1 is an Integer), the result is always false, and a branch that depends on it never runs. A call whose argument has a type that can be the same class, such as Object, is not reported.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean isOne(String kbn) {
return kbn.equals(1);
}Finding message (the engine's actual output)
kbn.equals(1) compares a String with a Integer: always false.
Fix (the engine's suggestion)
Convert to one type first, e.g. write the number as a string "1".equals(code), or compare the values id.longValue() == other.longValue().
OK example (code that is not reported)
boolean sameKbn(String kbn) {
return "1".equals(kbn);
}Compare with the string "1".
Example that is not reported (boundary or exclusion)
boolean sameNumber(Integer a, int b) {
return a.equals(b);
}An int argument is boxed to Integer and becomes the same type, so it is not reported.
37Local executor without shutdownSR-JAVA-EXECUTOR-SHUTDOWN-001WarningGeneral
The rule reports an ExecutorService that an Executors factory creates inside the body of a method, constructor, static or instance initializer block, or lambda, that is not returned, stored in a field or handed to another owner, and on which none of shutdown, shutdownNow or close is called. A local variable that holds it is tracked per variable (without distinguishing paths), and a value assigned inside a branch or a try, or chosen by a conditional expression, is also matched with the later shutdown or hand-over. A conditional expression made of two factories counts as one creation. The rule reports that no shutdown can be found; it does not prove that the code is safe on every exception path. The body of a lambda is treated as an independent unit, and only executors created inside it are tracked (what a lambda returns counts as a hand-over, and variables from outside are not inferred). An executor used to initialize a field or an enum constant is owned by that class or object, so it is not reported. Requires type information.
- Category
- Resource management
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void executorBad() { var pool=Executors.newFixedThreadPool(2); pool.execute(()->{}); }Finding message (the engine's actual output)
Locally owned executor has no shutdown: newFixedThreadPool.
Fix (the engine's suggestion)
Call shutdown() in a finally block (since Java 19 an ExecutorService can also be used in try-with-resources). Instead of creating a new pool on every call, reuse one held in a field or managed by Spring and shut it down when the application stops.
Note on the NG example: The pool is created and never shut down, so non-daemon worker threads remain and the JVM does not exit.
OK example (code that is not reported)
public void executorGood() { var pool=Executors.newFixedThreadPool(2); try { pool.execute(()->{}); } finally { pool.shutdown(); } }Shut down in the finally block of a try.
Example that is not reported (boundary or exclusion)
public ExecutorService executorReturned() { return Executors.newFixedThreadPool(2); }The pool is returned to the caller, who is responsible for shutting it down, so it is not reported (the same applies to storing it in a field or handing it to another method).
38Ignored return value of File operations (delete, renameTo, mkdir, etc.)SR-JAVA-FILE-RESULT-001InfoGeneral
The rule reports a call to a java.io.File method that signals failure through a boolean return value instead of an exception (delete, renameTo, mkdir, mkdirs, setLastModified, setReadOnly, setWritable, setReadable, setExecutable) when the call is a standalone statement and the return value is discarded. The same applies when the value is discarded in the expression body of a lambda or in a method reference (File::delete). The type must confirm that the receiver is a java.io.File (including subclasses). The rule does not report cases where the return value is assigned to a variable, returned, or used in a condition, an argument or an assert, where the next statement checks the state of the same file (f.delete(); if (f.exists()) ...), deleteOnExit(), java.nio.file.Files, a method overridden by a subclass of File, and createNewFile (which throws an exception on failure). Clean-up in finally and catch blocks is also reported by default (excluded with includeCleanupBlocks=false). Test code is out of scope. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void deleteStatement(File f) {
f.delete();
}Finding message (the engine's actual output)
The result of a File operation is ignored: f.delete().
Fix (the engine's suggestion)
Check the result and handle the failure (log it, throw, or take another way), or switch to java.nio.file.Files (Files.delete, Files.deleteIfExists, Files.createDirectories, Files.move), which throw an IOException that says why. After mkdirs you can also confirm the outcome with isDirectory(). If it really is best-effort clean-up, say so in the code, for example if (!f.delete()) log.debug("cannot delete " + f);.
OK example (code that is not reported)
void inCondition(File f) throws IOException {
if (!f.delete()) {
throw new IOException("cannot delete " + f);
}
}Check the return value in an if condition and throw an exception on failure.
Example that is not reported (boundary or exclusion)
void outcomeCheckedDelete(File f) {
f.delete();
if (f.exists()) {
System.err.println("still there: " + f);
}
}The statement right after delete() checks the state of the same file (f.exists()) in an if condition, so the result is regarded as checked and is not reported.
39Exception discarded by return or throw in finallySR-JAVA-FINALLY-JUMP-001WarningGeneral
The rule reports a return or throw in a finally block, or a break or continue that exits the finally. The exception thrown in the try or catch (or the value to be returned) is discarded, the caller does not notice the error, and nobody can tell afterwards what happened. For throw, it reports an unconditional one (which always replaces the original exception). It does not report by default a rethrow of an exception saved in a catch, as in if (error != null) throw error;, or a finally that calls addSuppressed to handle several exceptions on purpose (parameter reportConditionalThrows). A throw or return in a catch inside the finally when clean-up fails (try { in.close(); } catch (IOException e) { throw new ...; }) is a common old style that overwrites the original exception only when both the try and the clean-up fail, so it is not reported by default (parameter reportCleanupFailures). A throw that is caught by a try/catch inside the finally, and statements inside a lambda or an anonymous class, are not reported.
- Category
- Exception handling
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@SuppressWarnings("finally")
int parse(String s) {
try {
return Integer.parseInt(s);
} finally {
return 0;
}
}Finding message (the engine's actual output)
The return in finally discards the exception thrown in try or catch.
Fix (the engine's suggestion)
Move the return out of finally; keep finally to clean-up (closing resources), and log a failed clean-up or attach it to the original exception with addSuppressed. try-with-resources manages resources for you.
OK example (code that is not reported)
int readAndClose(InputStream in) throws IOException {
try {
return in.read();
} finally {
in.close();
}
}Only clean-up (close) is done in finally.
Example that is not reported (boundary or exclusion)
void copy(InputStream in) throws IOException {
IOException failure = null;
try {
in.read();
} catch (IOException e) {
failure = e;
} finally {
in.close();
if (failure != null) {
throw failure;
}
}
}Rethrowing an exception saved in a catch after the clean-up does not discard the original exception, so it is not reported by default (parameter reportConditionalThrows).
40Size change of an Arrays.asList fixed-size listSR-JAVA-FIXED-LIST-001WarningGeneral
The rule reports operations that change the length of the fixed-size list returned by Arrays.asList: add, addAll, remove, removeAll, retainAll, clear, removeIf, Collections.addAll(list, ...), the same operations on a subList view, and remove and add of iterator() and listIterator(). set, which does not change the length, is not reported. The origins of the list that the rule traces are: local variables inside the body of a method, constructor, initializer block or lambda (including aliases and reassignment; variables taken in from outside a lambda are not inferred), each branch of a conditional expression and of a switch expression (only when all branches are Arrays.asList), values assigned on each path of an if/else, and final fields initialized with Arrays.asList in the same file (such as private static final List X = Arrays.asList(..)). Each branch of a switch is traced separately, and a variable assigned inside a branch is not tracked after the switch. Non-final fields and method return values are not inferred.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void fixedAdd() { List<String> a = Arrays.asList("a"); List<String> b = a; b.add("b"); }Finding message (the engine's actual output)
A structural modification of Arrays.asList result b may fail.
Fix (the engine's suggestion)
Copy into new ArrayList<>(...) before adding or removing; set does not change the size.
Note on the NG example: b is an alias of a and is the same fixed-size list.
OK example (code that is not reported)
void copiedAdd() { List<String> a = new ArrayList<>(Arrays.asList("a")); a.add("b"); }Copy into new ArrayList<>(...) before adding.
Example that is not reported (boundary or exclusion)
void fixedSet() { List<String> a = Arrays.asList("a"); a.set(0,"b"); }set only replaces an element and does not change the size, so it works even on a fixed-size list.
41Collection modified during iteration in a for-each loopSR-JAVA-FOREACH-MODIFY-001WarningGeneral
The rule reports a for-each loop that iterates over a collection (or the keySet, values or entrySet of a Map) and changes the same collection inside the loop with remove, add, clear or similar. The loop's iterator throws ConcurrentModificationException at the next iteration (if the element removed is exactly the second to last, no exception occurs, but the last element is skipped; this goes unnoticed with little test data). The rule does not report a case where, after the change (other statements may come in between), the loop is left with break, return or throw and does not enter the next iteration (this includes a change made in an inner loop followed by leaving after the inner loop ends, except when the inner loop contains a continue of the outer loop), or collections of java.util.concurrent (including fields and variables declared as List, Set or Map to which a concurrent collection is assigned in this file). Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void dropCancelled(List<Order> orders) {
for (Order o : orders) {
if (o.cancelled) {
orders.remove(o);
}
}
}Finding message (the engine's actual output)
orders.remove(o) inside the loop over orders: the iterator throws ConcurrentModificationException at its next step.
Fix (the engine's suggestion)
Use the iterator's remove() (for (Iterator<..> it = list.iterator(); it.hasNext(); ) { if (..) it.remove(); }), list.removeIf(..), or collect the changes and apply them after the loop.
OK example (code that is not reported)
void dropCancelledSafely(List<Order> orders) {
for (Iterator<Order> it = orders.iterator(); it.hasNext();) {
if (it.next().cancelled) {
it.remove();
}
}
}Remove with the iterator's own remove() (removeIf also works).
Example that is not reported (boundary or exclusion)
void dropFirst(List<Order> orders, String code) {
for (Order o : orders) {
if (o.code.equals(code)) {
orders.remove(o);
System.out.println("removed " + code);
break;
}
}
}Right after the change (after the log output), the loop is left with break and the iterator does not advance, so it is not reported.
42Mismatch between the format string and the number of argumentsSR-JAVA-FORMAT-ARGS-001WarningGeneral
The rule reports a case where the specifiers in the format string (a literal) of String.format, printf, format or formatted do not match the number of arguments passed. If there are too few arguments, MissingFormatArgumentException occurs when that line runs, and extra arguments are ignored (usually a forgotten specifier). %% and %n use no argument, and %1$s and %<s use a numbered argument or the previous argument. The rule makes no judgment when the arguments are passed as a single array.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String missing(String name) {
return String.format("%s: %s", name);
}Finding message (the engine's actual output)
String.format("%s: %s", name): the format takes 2 arguments, 1 are given.
Fix (the engine's suggestion)
Match every specifier with an argument; use %1$s or %<s to print one value more than once.
OK example (code that is not reported)
String exact(String key, int percent) {
return String.format("%s = %d%%%n", key, percent);
}Two arguments for the specifiers %s and %d (%% and %n use no argument).
Example that is not reported (boundary or exclusion)
String array(Object[] values) {
return String.format("%s %s", values);
}When a single array is passed as the whole argument list, the count cannot be determined, so it is not reported.
43Hard-coded drive paths, Unix system paths and IP addressesSR-JAVA-HARDCODED-ENV-001InfoGeneral
The rule reports a string literal or constant that writes the runtime environment directly. (1) Windows drive paths (C:\data\x, D:/work; a bare drive root such as E:\ is excluded) and UNC paths. (2) Unix absolute paths that start with /opt, /usr, /etc, /var, /home, /data, /mnt or /srv (where the whole string is the path). (3) Private IPv4 addresses (10.x.x.x, 172.16-31.x.x, 192.168.x.x), and IPv4 addresses written in the host position (http://198.18.0.1/, @10.1.2.3 in a JDBC URL, and so on). The code stops working when the environment changes. The rule does not report strings used for comparison (equals, a switch case, etc.), Map keys, classpath or web application paths (getResource, sendRedirect, /home/index.xhtml, variables whose names contain url or action), regular expressions and format strings, values of variables whose names contain version or oid, localhost, 127.x.x.x, 0.0.0.0, documentation addresses, comments, and test code. Requires type information.
- Category
- Environment dependence
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
File windowsDrive() {
return new File("C:\\data\\import.csv");
}Finding message (the engine's actual output)
The source code hard-codes C:\data\import.csv, which stops working in another environment.
Fix (the engine's suggestion)
Move the paths and addresses into configuration (a properties file, environment variables, JNDI, system properties) and keep only the code that reads them in the source; when a default is needed, use a place that does not depend on the environment, such as System.getProperty("user.home"), java.io.tmpdir or a location relative to the application, and say how to override it.
OK example (code that is not reported)
String webInfPath() {
return "/WEB-INF/views/list.xhtml";
}/WEB-INF/... is a path inside the web application, not a path that starts with /opt, /etc or the like.
Example that is not reported (boundary or exclusion)
String versionNumber() {
String driverVersion = "10.2.0.4";
return driverVersion;
}Because the variable name contains version, 10.2.0.4 is regarded as a version number, not an IP address, and is not reported.
44if/else branches with identical codeSR-JAVA-IDENTICAL-BRANCHES-001InfoGeneral
The rule reports an if/else (or an if/else-if chain that ends with else) whose branches all contain exactly the same code (compared on the syntax tree, so comments and formatting have no effect). The condition serves no purpose, and a branch may have been copied and not corrected afterwards. Branches that consist only of return, throw, break or continue are not reported. When only some branches of a long chain are the same, this is often intentional (the same handling for two cases), so it is not reported by default (it is reported when the parameter branches is set to ANY). In a sampling check on the team's projects, most of the findings had branches that are provided separately for each condition and happen to use the same layout, color or character encoding at present; these cannot be told apart structurally from a forgotten correction, so the severity is info and the confidence is low.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int charge(boolean member, int amount) {
int rate;
if (member) {
rate = 10;
amount -= amount * rate / 100;
} else {
rate = 10;
amount -= amount * rate / 100;
}
return amount;
}Finding message (the engine's actual output)
Branch 2 has the same code as branch 1 (of 2 branches).
Fix (the engine's suggestion)
Check what branch 2 should do; if the same code is intended, merge the conditions (||) or remove the needless branch.
OK example (code that is not reported)
int differ(boolean member, int amount) {
int rate;
if (member) {
rate = 10;
} else {
rate = 0;
}
return amount - amount * rate / 100;
}Each branch does something different.
Example that is not reported (boundary or exclusion)
boolean valid(int x) {
if (x > 10) {
return false;
} else {
return false;
}
}Branches that consist only of return are out of scope, so this is not reported.
45Same expression on both sides of an operatorSR-JAVA-IDENTICAL-OPERANDS-001WarningGeneral
The rule reports a comparison, logical or bitwise operation, a subtraction, division or remainder, or equals() whose two sides are the same expression without side effects. Either the result is constant (a == a is always true, x - x is always 0, and so on) or one side was meant to be a different expression. Calls to getters and common pure functions are regarded as expressions that can be evaluated repeatedly. Floating-point comparisons and operations (idioms such as the NaN test with x != x or generating NaN with x - x) are not reported.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean sameScore(Score a, Score b) {
return a.getValue() == a.getValue();
}Finding message (the engine's actual output)
Both sides of == are a.getValue(); the result is constant.
Fix (the engine's suggestion)
Check whether one side should be another variable or field (for example the same property of another object).
OK example (code that is not reported)
boolean compare(Score a, Score b) {
return a.getValue() == b.getValue();
}Compare a with b.
Example that is not reported (boundary or exclusion)
boolean isNaN(double d) {
return d != d;
}d != d on a double is an idiom for a NaN test, so it is not reported.
46Ignored return value of an immutable object's methodSR-JAVA-IGNORED-RESULT-001WarningGeneral
The rule reports a call to a method of an immutable type such as String, BigDecimal/BigInteger or java.time that returns a new value (trim(), add(), plusDays() and so on) when the return value is discarded. The receiver itself does not change, so the statement has no effect. Usually the result was meant to be assigned again.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
BigDecimal total(BigDecimal[] amounts) {
BigDecimal total = BigDecimal.ZERO;
for (BigDecimal a : amounts) {
total.add(a);
}
return total;
}Finding message (the engine's actual output)
The result of total.add(a) is discarded; total does not change.
Fix (the engine's suggestion)
Assign the result (e.g. total = total.add(a)) or remove the statement.
OK example (code that is not reported)
BigDecimal add(BigDecimal t, BigDecimal a) {
t = t.add(a);
return t;
}Assign the return value again.
Example that is not reported (boundary or exclusion)
String build(StringBuilder sb) {
sb.append("x");
return sb.toString();
}StringBuilder is mutable, so discarding the return value of append is not a problem and is not reported.
47Integer division result used as a floating-point valueSR-JAVA-INT-DIV-001WarningGeneral
The rule reports a case where the result of dividing two integers is used as a float or double (assignment, return, argument, cast, or an operation with a floating-point value). The fractional part is truncated before the conversion, so averages, ratios, percentages and the like are truncated. It is not reported when an operand is converted to floating point before the division.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
double average(int total, int count) {
double avg = total / count;
return avg;
}Finding message (the engine's actual output)
total / count is an integer division; the fraction is dropped before the conversion to double (variable avg).
Fix (the engine's suggestion)
Convert one operand to floating point before dividing (e.g. (double) total / count), or use BigDecimal with an explicit rounding mode.
OK example (code that is not reported)
double ok(int total, int count) {
return (double) total / count;
}Cast to double before dividing.
Example that is not reported (boundary or exclusion)
double scaled(int a, int b) {
return 1.0 * a / b;
}Multiplying by 1.0 on the left makes it a floating-point division, so it is not reported.
48int multiplication that overflows before conversion to longSR-JAVA-INT-OVERFLOW-001WarningGeneral
A multiplication of ints is first computed in int, and its result is then converted to long (long ms = days * 24 * 60 * 60 * 1000;). When the product exceeds about 2.1 billion, it overflows before the conversion and becomes a negative or wrong value (in this example it goes wrong from 25 days). The conversion includes assignment, return, an argument, a cast, and an operation with a long value. The rule reports a product of constants only when it actually overflows (365 * 24 * 60 * 60 * 1000). It reports a product that contains a variable when the product of its constant factors is at least the parameter minConstantFactor (default 10,000,000; the product overflows when the variable exceeds 214; for example, when converting days to milliseconds). A product with small constant factors (7 * weeks, 31 * hash) is not reported, because in practice it is used only with values of a limited range, and a product of two or more variables (count * size) can be reported with the parameter reportVariableProducts.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
long millis(int days) {
long ms = days * 24 * 60 * 60 * 1000;
return ms;
}Finding message (the engine's actual output)
days * 24 * 60 * 60 * 1000 is computed in int and only then converted to long (variable ms): a product beyond the int range has already overflowed.
Fix (the engine's suggestion)
Make the first factor a long, e.g. days * 24L * 60 * 60 * 1000 or (long) days * 24 * 60 * 60 * 1000; TimeUnit.DAYS.toMillis(days) or Math.multiplyExact also work.
OK example (code that is not reported)
long safe(int days) {
return days * 24L * 60 * 60 * 1000;
}Making one of the factors a long (24L) makes the whole product be computed in long.
Example that is not reported (boundary or exclusion)
long total(int price, int quantity) {
return price * quantity;
}The range of values of a product of two variables (price * quantity) is unknown, so it is not reported by default (parameter reportVariableProducts).
49Swallowed thread interruptSR-JAVA-INTERRUPT-001WarningGeneral
The rule reports a case where, after an InterruptedException is caught, there is a path that neither restores the interrupt status (does not call Thread.currentThread().interrupt()) nor rethrows the InterruptedException. The thread's interrupt flag has already been cleared when the InterruptedException is thrown, so as it stands the stop request to the thread (shutdown or task cancellation) is lost and the thread does not stop. Conditional branches, assert, early return, infinite loops and the finally of the enclosing try are also examined as paths. A loop with an always-true condition is regarded as not ending only when it has no exit at all (break, labeled break, return, throw, or a declared exception that is not caught inside the loop). A change of the interrupt status and a rethrow are accepted within this method (the same for a constructor, a static or instance initializer block, or a lambda body) and within a lambda that is executed directly; restoring in a helper method is not inferred. Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void loggedInterrupt() { try { Thread.sleep(1); } catch (InterruptedException e) { System.out.println(e); } }Finding message (the engine's actual output)
A catch path for e loses the thread interrupt.
Fix (the engine's suggestion)
Restore with Thread.currentThread().interrupt() or rethrow InterruptedException; logging alone is insufficient.
Note on the NG example: It only writes a log message, so the interrupt request is lost.
OK example (code that is not reported)
void restoredInterrupt() { try { Thread.sleep(1); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }Call Thread.currentThread().interrupt() in the catch to restore the interrupt status.
Example that is not reported (boundary or exclusion)
void finallyInterrupt() { try { Thread.sleep(1); } catch (InterruptedException e) { try { return; } finally { Thread.currentThread().interrupt(); } } }Even on the path that returns, the interrupt is restored in finally, so it is not reported.
50Ignored number of bytes readSR-JAVA-IO-READ-RESULT-001WarningGeneral
The rule reports a case where, with the overloads of read and readNBytes of InputStream/Reader that take an array, the length actually read is discarded and the buffer continues to be used (returned, assigned to another variable, iterated, or passed to a method or constructor such as write(b, off, len), MessageDigest.update or new String(b, off, len)). The return value being used, readFully, reading only the length or a single element, and re-reading into the same buffer do not count as use of the buffer. After a local variable is re-pointed, it is not assumed to refer to the original buffer. The rule only warns of the risk of a partial read and does not infer the length that the business logic requires. The target is statements inside the body of a method, constructor, static or instance initializer block, or lambda (the body of a lambda is an independent unit, and whether the buffer is used later is decided only inside the lambda). Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public String readBad(InputStream in) throws Exception { byte[] b=new byte[8]; in.read(b); return new String(b); }Finding message (the engine's actual output)
Discarded IO read length: read.
Fix (the engine's suggestion)
Keep the result in n and use only what was read (e.g. out.write(buf, 0, n)); a read that returns -1 means the end of the stream, so check for it first. To fill the buffer completely use DataInputStream.readFully(buf); to read everything use readAllBytes() (Java 9 and later).
Note on the NG example: read(b) does not necessarily fill b completely, and the number of bytes actually read is the return value. If the return value is discarded, new String(b) includes the part that was not read (still at its initial value 0).
OK example (code that is not reported)
public String readGood(InputStream in) throws Exception { byte[] b=new byte[8]; int n=in.read(b); return n<0?"":new String(b,0,n); }Use the return value n and use only the part that was read.
Example that is not reported (boundary or exclusion)
public String readFullyGood(DataInputStream in) throws Exception { byte[] b=new byte[8]; in.readFully(b); return new String(b); }readFully always reads the specified length or throws an exception, so the return value is not needed.
51Batch queued with addBatch that is never fully executedSR-JAVA-JDBC-BATCH-001WarningGeneral
For a Statement, PreparedStatement or CallableStatement variable created inside a method, the rule reports the first addBatch when the batch queued with addBatch is not executed to the end by executeBatch (or executeLargeBatch). addBatch only adds to a list of pending work, and when the Statement is closed, the part that has not been executed is discarded without any exception. The rule reports (1) the case where there is no executeBatch at all on that variable in the method, and (2) the case where every executeBatch is under a periodic condition inside the loop that queues the batch (such as if (++n % 1000 == 0)) and none is after the loop, so the last remainder is not executed. The rule does not report the following: the Statement is returned, stored in a field or another variable, or passed to a method that may call executeBatch; a Statement that is a method parameter or a field; clearBatch is present; executeBatch is called after the loop or in a finally; or executeBatch is called under a condition that tests for the last row. Requires type information.
- Category
- SQL and data access
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void neverExecuted(Connection con, List<Row> rows) throws SQLException {
try (PreparedStatement ps = con.prepareStatement(SQL)) {
for (Row row : rows) {
ps.setInt(1, row.id());
ps.setString(2, row.name());
ps.addBatch();
}
}
}Finding message (the engine's actual output)
A JDBC batch built with addBatch may never be executed completely: ps.addBatch().
Fix (the engine's suggestion)
Call executeBatch once more after the loop (for example if (n % 1000 != 0) ps.executeBatch(); to run it only when rows are left), or make every batch run after the loop or in the finally block. If another method is meant to execute the batch, hand the statement to that method instead of filling it here. An API that splits and executes the batches for you, such as JdbcTemplate.batchUpdate, avoids the problem.
OK example (code that is not reported)
void executedAfterLoop(Connection con, List<Row> rows) throws SQLException {
try (PreparedStatement ps = con.prepareStatement(SQL)) {
for (Row row : rows) {
ps.setInt(1, row.id());
ps.addBatch();
}
ps.executeBatch();
}
}Call executeBatch after the loop to execute the whole batch that was queued.
Example that is not reported (boundary or exclusion)
void passedToAnotherMethod(Connection con, List<Row> rows) throws SQLException {
PreparedStatement ps = con.prepareStatement(SQL);
for (Row row : rows) {
ps.setInt(1, row.id());
ps.addBatch();
}
flush(ps);
}The Statement is passed to another method (flush), and executeBatch may be executed inside that method, so it is not reported.
52JDBC column or parameter index of 0SR-JAVA-JDBC-INDEX-001WarningGeneral
Column and parameter indexes of ResultSet getXxx/updateXxx, PreparedStatement setXxx, CallableStatement, ResultSetMetaData and ParameterMetaData start from 1, unlike arrays and Lists. If the index is 0 (or a constant less than 1), this line throws SQLException (such as Invalid column index) every time it runs. Calls made through a driver or a wrapper class are also reported. When a fixed SQL is bound in the same method, SR-SQL-PARAM-001 also reports 0 as an out-of-range index.
- Category
- SQL and data access
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String name(ResultSet rs) throws SQLException {
return rs.getString(0);
}Finding message (the engine's actual output)
rs.getString(0) uses index 0: JDBC numbers columns and parameters from 1.
Fix (the engine's suggestion)
Use 1 for the first column or parameter; when looping, add 1 to the loop index (i + 1).
OK example (code that is not reported)
String first(ResultSet rs) throws SQLException {
return rs.getString(1) + rs.getInt(2);
}Column indexes start from 1.
Example that is not reported (boundary or exclusion)
void loop(PreparedStatement ps, String[] values) throws SQLException {
for (int i = 0; i < values.length; i++) {
ps.setString(i + 1, values[i]);
}
}An index computed at run time (i + 1) has an unknown value, so it is not reported.
53Mismatch between JSF/CDI scope annotation and bean annotation (scope is ignored)SR-JAVA-JSF-SCOPE-MISMATCH-001WarningGeneral
The rule reports a class in which a JSF managed bean and CDI annotations are mixed so that the scope annotation has no effect. @ManagedBean reads only the scope annotations of javax.faces.bean (request scope if there is none) and ignores CDI scope annotations such as those of javax.enterprise.context and javax.faces.view.ViewScoped. @Named (a CDI bean) recognizes only CDI scopes, ignores the scope annotations of javax.faces.bean, and becomes @Dependent (one instance per EL evaluation). The same applies to the annotations of the same names in jakarta.*, and a finding is reported at the position of each ignored annotation. The rule does not report the following: the ignored annotation is the same as the bean's actual scope (such as CDI RequestScoped on a @ManagedBean without a scope), @ManagedBean and @Named are on the same class, the import is ambiguous, interfaces and enums, and scope annotations of other libraries such as OmniFaces.
- Category
- JSF/XHTML
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@javax.faces.bean.ManagedBean
@javax.enterprise.context.SessionScoped
public class QualifiedNames implements java.io.Serializable {
}Finding message (the engine's actual output)
javax.enterprise.context.SessionScoped on a javax.faces.bean.ManagedBean bean is ignored.
Fix (the engine's suggestion)
Use one family of annotations. A JSF managed bean combines @ManagedBean with a javax.faces.bean scope (javax.faces.bean.SessionScoped, javax.faces.bean.ViewScoped for the view scope); a CDI bean combines @Named with a javax.enterprise.context scope (javax.faces.view.ViewScoped for the view scope). Managed beans are deprecated since JSF 2.3, so CDI is the better choice for new code. Jakarta Faces uses the jakarta.* annotations of the same names.
Note on the NG example: @ManagedBean reads only the scope annotations of javax.faces.bean, so the CDI SessionScoped has no effect and this bean is actually request scoped.
OK example (code that is not reported)
@Named
@SessionScoped
public class NamedSession implements java.io.Serializable {
}A consistent CDI combination: @Named with the CDI SessionScoped (javax.enterprise.context).
Example that is not reported (boundary or exclusion)
@ManagedBean
@Named
@SessionScoped
public class BothModels implements java.io.Serializable {
}The same class has both @ManagedBean and @Named, and it cannot be determined which kind of bean it is treated as, so it is not reported.
54Bean in a long-lived scope holding request objectsSR-JAVA-JSF-STALE-CONTEXT-001WarningGeneral
The rule reports a session-, view- or application-scoped bean (for @ManagedBean, the annotations of javax.faces.bean; for CDI, the annotations of javax.enterprise.context and javax.faces.view.ViewScoped; the same for jakarta.*) that has a field (including static) of type FacesContext, ExternalContext, HttpServletRequest, HttpServletResponse, ServletRequest or ServletResponse. These are valid only during the request that created the bean, and in the next request they are invalid objects. The same applies to transient. The rule does not report fields with @Inject, @Resource, @Context or Spring's @Autowired (except for FacesContext and ExternalContext), beans with request, conversation or flow scope, a bean whose class itself has no scope annotation, local variables, parameters and return values, and HttpSession and ServletContext.
- Category
- JSF/XHTML
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@ManagedBean
@SessionScoped
public class SessionFacesContext implements java.io.Serializable {
private FacesContext context;
public void init() {
context = FacesContext.getCurrentInstance();
}
}Finding message (the engine's actual output)
SessionFacesContext is a javax.faces.bean.SessionScoped bean, and its field context holds the request-level object FacesContext.
Fix (the engine's suggestion)
Do not keep request-level objects in fields. Get them where they are used, for example FacesContext.getCurrentInstance(), or pass them as method arguments; if only one value of the request is needed, keep that value. A CDI bean can also have them injected: HttpServletRequest is a proxy supplied by the container that resolves the current request on each call, and FacesContext can be injected since JSF 2.3. JAX-RS uses @Context. In a Spring bean an @Autowired HttpServletRequest or HttpServletResponse is such a proxy too, but FacesContext and ExternalContext are not: Spring injects the instance that is current at that moment.
OK example (code that is not reported)
@ManagedBean
@SessionScoped
public class LocalsAndParameters implements java.io.Serializable {
public String action(HttpServletRequest request) {
FacesContext context = FacesContext.getCurrentInstance();
return context == null || request == null ? "a" : "b";
}
public FacesContext current() {
return FacesContext.getCurrentInstance();
}
}Obtain FacesContext inside the method and receive the request as an argument, without holding them in fields.
Example that is not reported (boundary or exclusion)
@Named
public class ScopeFromSuperclass extends ScopedBase {
private FacesContext context;
}The class has no scope annotation written directly on it (the scope is on the parent class), so its scope cannot be determined and it is not reported.
55Date validation with a lenient SimpleDateFormatSR-JAVA-LENIENT-DATE-001InfoGeneral
SimpleDateFormat (DateFormat) is lenient by default: parse("2023-02-30") throws no exception and gives March 2, and "25:61" of "HH:mm" becomes 02:01 of the next day. Code that validates a date only by whether a ParseException occurs lets dates that do not exist pass. This rule reports only clear validations. The conditions are: the result of parse is discarded (or only compared with null); the call is inside a try and the catch rejects the input (return false, throw, assignment of a boolean, recording an error); and the format is known to be lenient (a new SimpleDateFormat(...) created on the spot, or a local variable or private field on which none of setLenient, setCalendar or getCalendar is called). The rule does not report conversions that use the result, checks that write the value back with format and compare, a catch that only logs, formats that are parameters, method return values or ThreadLocal, year-only patterns, NumberFormat, and java.time. Requires type information.
- Category
- Date and time
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean isDate(String text) {
try {
new SimpleDateFormat("yyyyMMdd").parse(text);
return true;
} catch (ParseException e) {
return false;
}
}Finding message (the engine's actual output)
new SimpleDateFormat("yyyyMMdd").parse(text) validates with the lenient new SimpleDateFormat("yyyyMMdd"): a value out of range such as "2023-02-30" is not rejected.
Fix (the engine's suggestion)
Call setLenient(false) before parse: SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); format.setLenient(false); (set a shared static format in a static initializer). With java.time, LocalDate.parse(text) rejects February 30, but DateTimeFormatter.ofPattern("yyyy-MM-dd") resolves SMART by default and turns it into February 28: use ofPattern("uuuu-MM-dd").withResolverStyle(ResolverStyle.STRICT). SimpleDateFormat is not thread-safe: synchronize a shared one or create it each time.
Note on the NG example: A nonexistent date such as 20230230 also causes no ParseException; it is parsed as 2023-03-02 of the next month, and isDate returns true.
OK example (code that is not reported)
boolean strictLocalFormat(String text) {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.setLenient(false);
try {
format.parse(text);
return true;
} catch (ParseException e) {
return false;
}
}Because setLenient(false) is called, a nonexistent date causes a ParseException.
Example that is not reported (boundary or exclusion)
boolean onlyAYear(String text) {
try {
new SimpleDateFormat("yyyy").parse(text);
return true;
} catch (ParseException e) {
return false;
}
}For a year-only pattern (yyyy), the only extra value that lenient parsing lets through is the year 0, and it does not let through nonexistent dates or times, so it is not reported.
56Lock not reliably released in finallySR-JAVA-LOCK-RELEASE-001WarningGeneral
The rule reports a lock acquired with lock(), lockInterruptibly() or tryLock() of java.util.concurrent.locks.Lock (tryLock() written directly in a condition, or stored in a variable that is tested right after) that is not reliably released with unlock() in a finally. It matches the local protected scope first, and takes into account exceptions, early return, cumulative acquisition in a loop, and changes of the receiver by a lambda that is executed directly. The readLock/writeLock of a ReadWriteLock on the same unchanged receiver, and a no-argument getter that only returns one field in this project's source, are regarded as stable accessors. A loop with an always-true condition is regarded as reaching the finally if it has an exit such as break, return, throw or a declared exception, and a loop with no exit at all does not release. In the finally, releasing after testing the unchanged result of this tryLock, or after testing isHeldByCurrentThread() of a JDK lock, is accepted, and assigning a literal or a variable to a variable or a field of this before the release does not prevent the release. An unrelated flag, an arbitrary factory, a helper method, an alias of a complex boolean value, and ownership across methods are not regarded as proof. The target is statements inside the body of a method, constructor, static or instance initializer block, or lambda (the body of a lambda is an independent unit, and only the lock and release inside it are examined). Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void badLock() { lock.lock(); work(); lock.unlock(); }Finding message (the engine's actual output)
No reliable finally release follows acquisition of lock.
Fix (the engine's suggestion)
Enter try immediately after acquisition and unlock the same lock reliably in finally; guard tryLock success.
Note on the NG example: If work() throws an exception, unlock() is not executed and the lock remains.
OK example (code that is not reported)
void goodLock() { lock.lock(); try { work(); } finally { lock.unlock(); } }Enter try right after lock() and call unlock() in finally.
Example that is not reported (boundary or exclusion)
boolean storedTryLock() { boolean locked = lock.tryLock(); if (!locked) return false; try { work(); return true; } finally { lock.unlock(); } }The result of tryLock() is stored in a variable, the method returns on failure, and the lock is released in try/finally only on success, so it is not reported.
57Different variable updated in a for loopSR-JAVA-LOOP-VAR-001WarningGeneral
The rule reports a for loop whose condition tests a variable declared by the loop itself, while the update part changes a different variable (example: for (int j = 0; j < n; i++)), and the loop body does not change that loop variable either. Because the variable in the condition does not change, the loop does not end, or the index of an outer loop advances unintentionally. This often happens after copying a nested loop.
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int sum(int[][] grid) {
int total = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; i++) {
total += grid[i][j];
}
}
return total;
}Finding message (the engine's actual output)
The loop condition tests j but the update changes i.
Fix (the engine's suggestion)
Check whether the update should be j++ or similar.
OK example (code that is not reported)
int sumOk(int[][] grid) {
int total = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
total += grid[i][j];
}
}
return total;
}Advance j in the inner loop.
Example that is not reported (boundary or exclusion)
int everyOther(int[] a) {
int total = 0;
int steps = 0;
for (int i = 0; i < a.length; steps++) {
total += a[i];
i += 2;
}
return total + steps;
}The loop variable i is advanced in the body (i += 2), so it is not reported.
58SqlSession writes without commitSR-JAVA-MYBATIS-SESSION-001WarningGeneral
The rule reports the last write when the code itself holds, in a local variable, a MyBatis SqlSession that it opened with SqlSessionFactory.openSession() (including the forms that pass ExecutorType and the like, and openSession(false)), has written through it, and has neither a commit() nor a rollback() on the normal path after the last write (a rollback inside a catch is not counted). A write is an insert, update or delete of the session, an annotated method such as @Insert of a Mapper obtained with getMapper, or a method that corresponds to an insert, update or delete element in a Mapper XML inside the project. A session from openSession() is not auto-committed, and close() rolls back uncommitted writes without an exception. The rule does not report openSession(true), a session in a field or a parameter, a session that is passed elsewhere, returned or stored, Spring's SqlSessionTemplate, @Transactional or EJB methods, and test code.
- Category
- SQL and data access
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void insertWithoutCommit(Object order) {
try (SqlSession session = factory.openSession()) {
session.insert("example.session.OrderMapper.addOrder", order);
}
}Finding message (the engine's actual output)
SqlSession writes without a commit: session (insert).
Fix (the engine's suggestion)
Call commit() after the last write and before the session is closed (at the end of the block in a try-with-resources); say rollback() when the changes are meant to be dropped; a session that only reads needs no commit. If Spring or the container manages the transaction, use the injected SqlSession or annotate the method with @Transactional, and turn this rule off for that project.
OK example (code that is not reported)
public void committed(Object order) {
try (SqlSession session = factory.openSession()) {
session.insert("example.session.OrderMapper.addOrder", order);
session.commit();
}
}commit() is called after the write.
Example that is not reported (boundary or exclusion)
public void conditionalCommit(Object order, boolean ok) {
try (SqlSession session = factory.openSession()) {
session.insert("example.session.OrderMapper.addOrder", order);
if (ok) {
session.commit();
}
}
}There is a path that calls commit() after the write (when ok is true), and whether to commit is regarded as the author's decision, so it is not reported.
59Connection without an effective timeoutSR-JAVA-NETWORK-TIMEOUT-001WarningGeneral
For a URLConnection that is newly created inside the body of a method, constructor, static or instance initializer block, field initializer or lambda and whose ownership has not been handed over, the rule examines its first use and checks that both the connect timeout and the read timeout are positive values. Classpath resources (getResource and getSystemResource of Class/ClassLoader), File.toURI().toURL(), Path.toUri().toURL() and file, jar or jrt URLs whose protocol is a constant are not reported, because there is no peer on the network. Connections passed in from outside, shared clients and objects whose settings are unknown are not inferred, and this is not a proof of a timeout across methods either. The body of a lambda is treated as an independent unit, and only connections newly created inside it are tracked. Requires type information.
- Category
- Resource management
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public InputStream timeoutBad(URL url) throws Exception { var c=url.openConnection(); return c.getInputStream(); }Finding message (the engine's actual output)
Local connection has no effective timeout: c.
Fix (the engine's suggestion)
Before the first use set both timeouts to a positive number of milliseconds, e.g. conn.setConnectTimeout(5000); conn.setReadTimeout(10000); choose the values from the wait the caller can accept.
Note on the NG example: A connection with no timeout set keeps waiting indefinitely when the other side does not respond, and keeps holding the thread and the connection.
OK example (code that is not reported)
public InputStream timeoutGood(URL url) throws Exception { var c=url.openConnection(); c.setConnectTimeout(100); c.setReadTimeout(100); return c.getInputStream(); }Set both the connect timeout and the read timeout to positive values.
Example that is not reported (boundary or exclusion)
public InputStream classpathResource() throws IOException {
URL url = getClass().getResource("/config.properties");
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
}A classpath resource (getResource) is a file in the same process and has no peer on the network, so it is not reported.
60Wrong operator in a null check (x == null && x.m())SR-JAVA-NULL-CHECK-001WarningGeneral
The rule reports a case where the same value is dereferenced right after a null check, but because of the operator, evaluation continues exactly when the value is null: x == null && x.m() (should be !=), x != null || x.m() (should be ==), and a null check written with the non-short-circuit & or | (the right-hand side is always evaluated). A NullPointerException occurs when the value is null, that is, in the case this check is meant to prevent. The rule does not report a case where the value is reassigned or re-checked in between, or where the reference is inside a lambda or an anonymous class.
- Category
- Null dereference
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean blank(String value) {
return value == null && value.isEmpty();
}Finding message (the engine's actual output)
value.isEmpty() runs after value == null &&: it throws NullPointerException when value is null.
Fix (the engine's suggestion)
Write value != null && ... (use it only when present) or value == null || ... (skip it when null); replace the non-short-circuit & / | with && / ||.
OK example (code that is not reported)
boolean guarded(String value, List<String> items) {
return (value != null && value.isEmpty()) || (items == null || items.isEmpty());
}The correct combinations: != null with &&, == null with ||.
Example that is not reported (boundary or exclusion)
boolean created() {
return instance == null && create() && instance.getName() != null;
}The create() called in between may set the field instance, so it is not reported.
61Dereference of a variable that is always nullSR-JAVA-NULL-DEREF-001WarningGeneral
The rule reports a local variable that JDT's flow analysis finds to be always null at the position of a dereference (method call, field or array access, auto-unboxing) (examples: calling o.toString() inside the branch of if (o == null), Integer i = null; int n = i;). This line always throws NullPointerException when it runs. A condition such as x == null && x.m() is reported by SR-JAVA-NULL-CHECK-001 (parameter leaveNullChecksToOtherRule). A case where the variable only may be null is not reported. A variable assigned inside an assert and used inside another assert is not reported either (JDT regards an assert as possibly not executed, but the two are always executed together or skipped together). Requires type information.
- Category
- Null dereference
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int size(List<String> items) {
if (items == null) {
throw new IllegalArgumentException("no items: " + items.size());
}
return items.size();
}Finding message (the engine's actual output)
items can only be null here: this line throws NullPointerException when it runs.
Fix (the engine's suggestion)
Check the condition and the branch this line belongs in; if a default is needed, assign it before use.
OK example (code that is not reported)
int length(String text) {
if (text == null) {
return 0;
}
return text.length();
}Check for null before using it.
Example that is not reported (boundary or exclusion)
boolean blank(String value) {
return value == null && value.isEmpty();
}The form x == null && x.m() is reported by SR-JAVA-NULL-CHECK-001, so this rule does not report it again (parameter leaveNullChecksToOtherRule).
62x % 2 == 1 is wrong for negative odd numbersSR-JAVA-ODD-CHECK-001WarningGeneral
x % 2 == 1 tests for an odd number, but Java's % keeps the sign of the dividend, so % 2 of a negative odd number is -1 and the number is judged to be even (x % 2 != 1 takes a negative odd number for an even one). Write x % 2 != 0 or (x & 1) == 1. By default the rule reports only values known to be possibly negative: hashCode(), a number converted from a string (such as Integer.parseInt), nextInt() or nextLong() without an upper bound, a value with its sign inverted, and local variables assigned from these (such as splitting by hash value). In real code, most values tested for odd or even are values that cannot be negative, such as widths, counts and IDs, so those, and values of unknown sign, can be reported with the parameter values.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int bucket(String key) {
return 1 == key.hashCode() % 2 ? 1 : 0;
}Finding message (the engine's actual output)
1 == key.hashCode() % 2 is false for negative odd numbers: key.hashCode() can be negative, and a negative number % 2 is -1.
Fix (the engine's suggestion)
Write key.hashCode() % 2 != 0 or (key.hashCode() & 1) == 1, which work whatever the sign; use Math.floorMod(key.hashCode(), 2) to split by hash code.
OK example (code that is not reported)
boolean oddOk(int n) {
return n % 2 != 0 || (n & 1) == 1 || n % 2 == -1;
}Judgments that are also correct for negative numbers: % 2 != 0, (n & 1) == 1 and so on.
Example that is not reported (boundary or exclusion)
boolean odd(int n) {
return n % 2 == 1;
}It is unknown whether the argument n can be negative, so it is not reported by default (it is reported if the parameter values includes UNKNOWN).
63Mismatch between log or MessageFormat placeholders and the number of argumentsSR-JAVA-PLACEHOLDER-ARGS-001WarningGeneral
The rule reports a case where the number of {} placeholders in an SLF4J or Log4j 2 log message, or of {0}, {1}... of MessageFormat.format, does not match the number of arguments passed. If there are too few arguments, the placeholders are output as they are, and if there are too many, the extra values are not output (a forgotten placeholder is a common cause). When the last argument of a log call is an exception and has no corresponding placeholder, it is recorded as an exception and is not counted as an argument. error("失敗:{}", e) (error(String, Throwable)), which passes only an exception, does not format the message and {} is output as it is, so this is also reported. In MessageFormat, text between single quotes is treated literally, so "Can't open {0}" uses no argument (write a single quote as ''). The rule makes no judgment when the message is not a string literal or when the arguments are passed together in an array variable. printf-style formats are handled by SR-JAVA-FORMAT-ARGS-001.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void missing(String user) {
LOG.info("login {} from {}", user);
}Finding message (the engine's actual output)
The placeholders of LOG.info("login {} from {}", user) take 2 arguments, but 1 are given.
Fix (the engine's suggestion)
Make placeholders and arguments match one to one: add the missing arguments or placeholders, remove the extra arguments.
OK example (code that is not reported)
void matching(String user, Exception e) {
LOG.info("login {} from {}", user, "host");
LOG.error("login failed for {}", user, e);
LOG.error("failed", e);
LOG4J.error("failed", e);
}The placeholders and the arguments match in number. An exception as the last argument is recorded as an exception if there is no corresponding placeholder.
Example that is not reported (boundary or exclusion)
void exceptionInPlaceholder(String user, Exception e) {
LOG.error("failed for {}: {}", user, e);
}The exception corresponds to the last placeholder, and the number of placeholders and arguments match, so it is not reported.
64POI cell styles or fonts created repeatedly inside a loopSR-JAVA-POI-STYLE-LOOP-001WarningPerformance
The rule reports createCellStyle() and createFont() of an Apache POI workbook (HSSFWorkbook, XSSFWorkbook, SXSSFWorkbook) when they are called inside a for, for-each, while or do-while loop, or inside a lambda that runs for each element of a collection or stream, such as forEach or map. Each call adds a style (font) to the workbook, and it is not reused. The message gives the documented limits with their sources (4000 styles for .xls and 64000 for .xlsx; for fonts, the numbers differ depending on the source). The rule does not report creation guarded by a cache lookup (containsKey, a null check, computeIfAbsent), creation that runs only once (outside the loop, break/return/throw after the creation, only in the first iteration), a loop with a constant iteration count of ignoreFixedLoopsUpTo (default 10) or less, and a loop over sheets (counted as once). Creation inside a helper method is not visible. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void styleInRowLoop(Workbook wb, Sheet sheet, List<String> values) {
int rowNum = 0;
for (String value : values) {
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
CellStyle style = wb.createCellStyle();
style.setDataFormat((short) 1);
cell.setCellStyle(style);
cell.setCellValue(value);
}
}Finding message (the engine's actual output)
POI cell styles or fonts are created again in every iteration of a loop: wb.createCellStyle().
Fix (the engine's suggestion)
Create the styles and fonts once, before the loop (CellStyle style = wb.createCellStyle();), and only call cell.setCellStyle(style) inside it. If several styles are needed, create one of each up front or cache them in a Map (styles.computeIfAbsent(key, k -> createStyle(wb))); do not create one per cell.
OK example (code that is not reported)
void createdBeforeTheLoop(Workbook wb, Sheet sheet, List<String> values) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
style.setFont(font);
for (String value : values) {
Cell cell = sheet.createRow(0).createCell(0);
cell.setCellStyle(style);
cell.setCellValue(value);
}
}Create the style and the font only once before the loop and reuse them inside the loop.
Example that is not reported (boundary or exclusion)
void smallFixedLoop(Workbook wb) {
CellStyle[] styles = new CellStyle[3];
for (int i = 0; i < 3; i++) {
styles[i] = wb.createCellStyle();
}
}The loop has a constant iteration count of 3, which is at most ignoreFixedLoopsUpTo (default 10), so it is not reported.
65(int) Math.random() * n is always 0SR-JAVA-RANDOM-INT-001WarningGeneral
A cast is performed before a multiplication. (int) Math.random() * n first converts a random number of at least 0 and below 1 to int (always 0) and then multiplies by n, so the result is always 0. The same applies to nextDouble() and nextFloat() of java.util.Random and the like. Write (int) (Math.random() * n) or random.nextInt(n). Without type information, only Math.random() is judged.
- Category
- Numeric calculation
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int dice() {
return (int) Math.random() * 6 + 1;
}Finding message (the engine's actual output)
(int) Math.random() * 6 is always 0: (int) turns Math.random() (at least 0, below 1) into an integer first.
Fix (the engine's suggestion)
Put the multiplication in parentheses: (int) (Math.random() * n); better, use ThreadLocalRandom.current().nextInt(n) or random.nextInt(n).
OK example (code that is not reported)
int diceOk() {
return (int) (Math.random() * 6) + 1;
}Cast the whole result of the multiplication.
Example that is not reported (boundary or exclusion)
int input(Scanner in) {
return (int) in.nextDouble() * 2;
}Scanner.nextDouble() reads a number from the input and is not a random number, so it is not reported.
66Lone metacharacter as a regular expression argumentSR-JAVA-REGEX-LITERAL-001WarningGeneral
The arguments of String split, replaceAll, replaceFirst and matches, and of Pattern.compile and Pattern.matches, are regular expressions. When only a single metacharacter is written, it is almost certain that its literal meaning was intended. "." matches any single character ("2026.10.19".split(".") gives an empty array), "|" matches the empty string (the string is split into single characters), "$" and "^" match a position, and "+", "*", "?", "(", ")", "[", "{" and a lone backslash cause a PatternSyntaxException. Because "." also has intentional uses, the rule reports it only for split and for replaceAll when it replaces with an empty string or a separator ("/", File.separator and so on). Masking such as replaceAll(".", "*"), replaceFirst(".", ...) (replacing the first character) and matches(".") (testing whether there is a single character) are not reported.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String[] splitDate(String date) {
return date.split(".");
}Finding message (the engine's actual output)
date.split(".") takes a regular expression: "." does not match that character itself.
Fix (the engine's suggestion)
Escape it to mean the character, e.g. split("\\.") or split("\\|"), or use Pattern.quote("."); use replace() to replace plain text.
OK example (code that is not reported)
String[] splitDateEscaped(String date) {
return date.split("\\.");
}Escape "." (Pattern.quote(".") also works).
Example that is not reported (boundary or exclusion)
String mask(String password) {
return password.replaceAll(".", "*");
}A masking operation that replaces every character with * uses "." intentionally as any single character, so it is not reported.
67Invalid replacement string in a regular expression (backslash, $)SR-JAVA-REGEX-REPLACEMENT-001WarningGeneral
In the replacement string of String replaceAll and replaceFirst, and of Matcher replaceAll, replaceFirst and appendReplacement, a backslash escapes the next character and $ denotes a group reference ($1, ${name}). If a constant replacement string violates this syntax, an exception occurs as soon as the regular expression matches (it does not occur for input that does not match). The rule reports: a backslash left alone at the end (such as path.replaceAll("/", "\\")), a $ followed by neither a digit nor {name}, an unclosed ${, and a group number or name that the regular expression does not have (when the regular expression is a constant). A file separator such as File.separator is a single backslash on Windows, and if the replacement string is only that or ends with it, an exception occurs only on Windows, so the rule judges by the Windows value and reports it. The result of Matcher.quoteReplacement, a replacement string decided at run time, String.replace and replaceAll(Function) are not reported. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String slashesToBackslashes(String path) {
return path.replaceAll("/", "\\");
}Finding message (the engine's actual output)
The replacement "\\" in path.replaceAll("/", "\\") is illegal on Windows, Linux, macOS: once the regex matches, it throws IllegalArgumentException.
Fix (the engine's suggestion)
To use the replacement as plain text, wrap it in Matcher.quoteReplacement(...) (Matcher.quoteReplacement("\\") is a legal replacement) or escape it in the literal: a single backslash is "\\\\", a dollar sign is "\\$". When you only replace fixed text and need no regex, use String.replace(CharSequence, CharSequence) (path.replace("/", "\\")). For File.separator write Matcher.quoteReplacement(File.separator). To refer to a group, make sure the regex has that capturing or named group.
Note on the NG example: The value of the string literal "\\" is just one backslash. In a replacement string a backslash escapes the next character, but nothing follows it, so an exception occurs as soon as "/" matches.
OK example (code that is not reported)
String escapedBackslash(String path) {
return path.replaceAll("/", "\\\\");
}The replacement string is escaped as "\\\\" and is replaced with a single backslash.
Example that is not reported (boundary or exclusion)
String groupOfAComputedRegex(String text, String regex) {
return text.replaceAll(regex, "$1");
}The regular expression is not a constant (the parameter regex), so the number of groups is unknown, and it cannot be determined whether $1 is correct; therefore it is not reported.
68Resource not closed (streams, JDBC, etc.)SR-JAVA-RESOURCE-LEAK-001WarningGeneral
The rule reports a resource that JDT's flow analysis finds not to be closed: a stream, Reader, Writer, Socket, ZipFile or similar created with new that is not closed with close() on every path, or that is not closed at some return or throw (including before a reassignment). It also reports a resource created inside the body of a loop whose close() is skipped by continue or break, and a case where the same variable outside the loop is assigned again on every iteration and is closed only once after the loop (in the latter, the resources of the earlier iterations are not closed; the rule decides this only when the loop merely calls ordinary methods on that resource, and does not report it when the resource is passed to a method, stored, compared, closed, closed in a finally, or is a ResultSet or the like). JDT itself does not track these two cases. When the same resource is not closed at several returns, only one finding is reported (the other positions are shown as related positions). A JDBC Connection, Statement, PreparedStatement, CallableStatement or ResultSet is obtained from a factory method, so JDT can only judge that it "may not be closed". Those obtained from the JDBC API itself (getConnection of DriverManager/DataSource, prepareStatement, createStatement, executeQuery and so on) are reported by default (parameter potentialLeaks), connections returned by a project's own helper methods are not reported, and other resources that "may not be closed" are not reported by default. However, a stream that is obtained from a JDK constructor or from a stream-returning factory of java.nio.file.Files (lines, list, walk, find, newBufferedReader and so on) and is passed only to JDK methods is reported as usual (examples: props.load(new FileInputStream(f)), Files.lines(p).collect(..), and the style where close() is at the end of the try and the catch returns null directly). Connections, cursors and file handles leak, and the connection pool runs out under high load. The rule does not report known false positives of JDT: variables of objects that merely refer to this or other variables; resources that use only memory (a Formatter over a StringBuilder, a Scanner over a String (including chained calls that return itself, such as useDelimiter), wrappers such as ByteArrayInputStream and the pipe stream PipedInputStream, and so on); streams that wrap a parameter or a field (such as System.in); a ResultSet whose Statement is closed; a Statement and its ResultSet when the Connection they belong to is always closed by the try that encloses them (by try-with-resources, by calling close() in a finally without any condition other than a null check, or by passing it to a method named close, release, cleanup or dispose; this includes a Statement created before this try), because they are closed together with the connection (JDBC specification 13.1.4; a Statement created inside a loop is not covered, because it keeps accumulating until the connection is closed); and a resource that is not assigned to a variable and is passed to a constructor or converted to another resource (getChannel()). The following three kinds of JDBC resources are also not reported, because their owner releases them (these three can be disabled with the parameter ignoreOwnerReleased): (1) a ResultSet obtained from a Connection that the method always closes as above, by way of DatabaseMetaData or a Statement created in the same expression (con.getMetaData().getTables(..), con.createStatement().executeQuery(..); one obtained inside a loop is not covered, because every iteration yields a new result set); (2) a ResultSet obtained by executing the same Statement repeatedly inside a loop (when that Statement is a parameter, or a local variable that is created outside the loop and not reassigned inside the loop; because the previous result set is closed at each execution (as specified for java.sql.Statement), at most one is left open, and it is closed together with the Statement or the connection; if the Statement itself is not closed, that is reported as usual); (3) a Statement of a Connection received as a parameter of a private method, and its ResultSet (only when every call of that method in this file closes the connection it passes, in its own try-with-resources or finally; because the method is private, all calls are inside this file; it is not covered when the method creates the Statement inside a loop, a lambda or an anonymous class, when the method is recursive, or when a call is inside a loop under a try; in the other cases, only a finite number of statements remain per call, and they are released when the caller closes the connection; passing the connection one more level through a private method is also covered, up to 3 levels). Resources that the method has already handed over are not reported either: objects that are returned, and those put into a field, a collection, a ThreadLocal or a request attribute; those passed to a method that closes or stores them (a method of the same class is judged by its body, and a method whose body is not visible is regarded as taking it over); those closed or handed over inside a lambda or an inner class; and those whose variable may hold an object passed in by the caller (the method closes only a connection it opened itself). A connection that is a parameter of the method is handled separately (parameter borrowedConnection, default INFO): when a Statement, PreparedStatement, CallableStatement or ResultSet is obtained from the Connection parameter of that method (con.prepareStatement(..), con.createStatement().executeQuery(..) in the same expression, the result set of con.getMetaData(), and such a Statement or the DatabaseMetaData result set stored in a local variable; the visibility of the method does not matter) and none of the reasons above applies, it is reported, but the connection of the evidence is set to borrowed and the severity is INFO at most. The connection is held and closed by the caller, so no "connection pool exhaustion" occurs here. The remaining problem is that the statements and result sets stay open until the caller closes the connection and can accumulate within one request. This cap cannot be raised by configuration: even if the rule's severity is set to ERROR in ruleOverrides, these findings stay at INFO (if the rule's severity is lower, the lower one is taken). If borrowedConnection is set to REPORT, they are reported with the rule's severity (as with an ordinary leak), and if it is set to IGNORE, they are not reported. A statement that is reported again by disabling ignoreOwnerReleased is also handled this way if the connection is a parameter. In the following cases it is not handled this way and is reported as an ordinary leak: when created inside a loop, a lambda or an anonymous class (one remains for every iteration or callback and they accumulate), when the method is recursive, when the method assigns another value to that parameter (it may be a connection it obtained itself), when the values of the local variable cannot all be said to come from the connection of the same parameter, when the connection was obtained by the method itself or is a field, when the Statement itself is the parameter (its connection is not visible), and for resources other than JDBC. A connection parameter that is put into another local variable (Connection c = con) is not tracked, and is likewise reported as an ordinary leak. When a project's own method closes the connection (parameter connectionCloseMethods, empty by default; nothing changes unless it is set): some projects have a method that closes the connection used by the current request or thread, and the connection is not passed as an argument, so the rule cannot know that the method closes the connection. If such methods are written in connectionCloseMethods (comma-separated; a method name, or ClassName.methodName, where the class name may carry a package name), then when the finally block of a try statement calls any of them on every path (only blocks, try and a null check on the connection may come in between), the statements and result sets created from a connection that is a local variable or a parameter inside this try statement (or earlier in the same block) are not reported. This is the same as closing the connection directly in the finally. What is created in a loop inside this try statement is still reported (the statements accumulate until the connection is closed), and it is also reported when the connection is a field. Resources other than JDBC are not affected. The rule does not check what these methods actually do, so a wrongly written entry results in a false negative. That responsibility lies with the project. For a method that contains references that cannot be resolved (missing dependency libraries, Lombok not processed, and so on), JDT skips the flow analysis entirely. Such a method is inspected after the unresolvable parts are removed (the confidence drops to medium or lower), and when a method that still cannot be inspected has content that could be inspected, the rule reports the coverage limitation TYPES_UNRESOLVED and treats the inspection result for that file as incomplete. Not reported: the case where close() appears only at the end of the method and there is no finally (it leaks only when an exception occurs; JDT's explicit-close check also reports correct ways of writing finally, so it is not enabled). Requires type information.
- Category
- Resource management
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String firstLine(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
return reader.readLine();
}Finding message (the engine's actual output)
reader (BufferedReader) is not reliably closed: the resource leaks.
Fix (the engine's suggestion)
Manage it with try-with-resources, e.g. try (Connection con = ...; PreparedStatement ps = ...) { ... }, or close it in finally.
OK example (code that is not reported)
String firstLineSafely(File file) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
return reader.readLine();
}
}Always close with try-with-resources.
Example that is not reported (boundary or exclusion)
int countRows(DataSource ds, boolean skip) throws SQLException {
Connection con = ds.getConnection();
try {
PreparedStatement ps = con.prepareStatement("SELECT COUNT(*) FROM orders");
if (skip) {
return 0;
}
ResultSet rs = ps.executeQuery();
rs.next();
int n = rs.getInt(1);
rs.close();
ps.close();
return n;
} finally {
con.close();
}
}An early return leaves the PreparedStatement unclosed, but this method always closes the connection in a finally, and closing the connection also closes its statements and result sets (JDBC specification), so it is not reported.
69Variable assigned to itselfSR-JAVA-SELF-ASSIGN-001WarningGeneral
The rule reports an assignment whose two sides are the same variable, field or array element (the same declaration, the same receiver, no side effects). The statement has no effect. A common cause is forgetting this. when a parameter and a field have the same name, or forgetting to correct the variable on the right-hand side after copy and paste.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void setName(String name) {
name = name;
}Finding message (the engine's actual output)
name is assigned to itself; the statement has no effect.
Fix (the engine's suggestion)
Check the intended target and source; assign fields as this.field = parameter.
OK example (code that is not reported)
public void rename(String name) {
this.name = name;
}Assign to the field with a this. prefix.
Example that is not reported (boundary or exclusion)
public void advance() {
count = count++;
}An assignment whose right-hand side has a side effect (count++) is out of scope for this rule (it is a different kind of mistake).
70Duplicated and missing numbers in numbered variablesSR-JAVA-SEQUENCE-001InfoGeneral
The rule reports a case where, inside the same ordered container (an array initializer, an addition chain, or the arguments of a call), a number of numbered variables with the same prefix is duplicated while another number in the range is missing at the same time. This is evidence based on a rule of thumb and is used only as a prompt for checking. Which one should be filled in cannot be inferred from this.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] values = {
value1, value2, value3,
value4, value5, value6,
value7, value7, value9
};
return values;
}Finding message (the engine's actual output)
Numbered family value*: number 7 repeats while 8 is missing; check for a missing input.
Fix (the engine's suggestion)
Check against the specification or the surrounding code whether the repeated item should be the missing number and correct it (for example the second value7 should be value8). If the gap is intended, suppress the finding with smartreviewer:disable-next-line and a reason, or exclude the module in the project configuration.
OK example (code that is not reported)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] values = {
value1, value2, value3,
value4, value5, value6,
value7, value8, value9
};
return values;
}The version with value8 in the eighth position, with neither duplicates nor missing numbers.
Example that is not reported (boundary or exclusion)
Object[] gapsOnly(Integer v1, Integer v3, Integer v5, Integer v7, Integer v9) {
return new Object[] {v1, v3, v5, v7, v9};
}A gap without a duplicate (skipped numbers such as v1, v3, v5...) may be correct, so it is not reported.
71Setter that ignores its parameterSR-JAVA-SETTER-PARAM-001WarningGeneral
Reports a setter with only one statement that assigns to the field matching its name when what it assigns is not the parameter (the parameter is not used at all), for example setTitle(String title) { this.title = name; }. The value passed in is discarded. It is common to copy a setter and forget to change the right-hand side to the parameter.
- Category
- Copy-and-paste mistakes
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void setTitle(String title) {
this.title = name;
}Finding message (the engine's actual output)
Setter setTitle(String) ignores its parameter and assigns name to field title.
Fix (the engine's suggestion)
Check whether field title should receive the parameter value.
OK example (code that is not reported)
public void setMemo(String memo) {
this.memo = memo;
}An ordinary setter that assigns its parameter memo.
Example that is not reported (boundary or exclusion)
public void setName(String name) {
this.name = name == null ? "" : name.trim();
}A setter that processes its parameter and assigns the result does use the parameter, so it is not reported.
72Non-thread-safe format object shared in a static fieldSR-JAVA-SHARED-FORMAT-001WarningGeneral
SimpleDateFormat, DecimalFormat, MessageFormat and Calendar change their internal state when formatting or parsing, so they are not thread-safe. If they are placed in a static field and shared by several request threads, wrong dates or numbers are occasionally produced, and the problem is hard to reproduce. A format object held per instance, a ThreadLocal, and java.time's DateTimeFormatter are not reported.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd");Finding message (the engine's actual output)
Static field DATE_FORMAT (SimpleDateFormat) is shared by all threads, and SimpleDateFormat is not thread-safe.
Fix (the engine's suggestion)
Create one per use or use a ThreadLocal; on Java 8 and later use the immutable, thread-safe java.time.format.DateTimeFormatter.
OK example (code that is not reported)
private final SimpleDateFormat local = new SimpleDateFormat("HH:mm");Hold it per instance instead of making it static (when it is not shared between threads).
Example that is not reported (boundary or exclusion)
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE;java.time's DateTimeFormatter is immutable and thread-safe, so it is not reported even when shared as a static field.
73Request data kept in an instance field of a servlet or similarSR-JAVA-SINGLETON-FIELD-001WarningGeneral
A Servlet, a Filter, a Struts 1 Action, a Spring Controller that is not request, session or prototype scoped, and an HttpHandler each have only one instance, which handles the requests of all users at the same time. If a method that handles requests (doGet, doPost, execute, a method with @RequestMapping or the like, or a method with a request object as a parameter) assigns to an instance field, another request that arrives at the same time reads or overwrites that value, and one user's data is shown to another user. Fields that are final, static or volatile, and assignments inside synchronized, are not reported.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
customerId = req.getParameter("customer");
resp.getWriter().println(greeting + " " + customerId);
}Finding message (the engine's actual output)
OrderServlet.doGet(HttpServletRequest,HttpServletResponse) assigns the instance field customerId: there is one Servlet for all requests, which share the field.
Fix (the engine's suggestion)
Keep the value in a local variable, or in the request (request.setAttribute) or the session; handle values meant to be shared in a thread-safe way and say so.
Note on the NG example: A request parameter is assigned to the instance field customerId of OrderServlet (a subclass of HttpServlet).
OK example (code that is not reported)
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("customer");
hits.incrementAndGet();
resp.getWriter().println(id);
}Keep the request value in a local variable, and use the thread-safe AtomicInteger for the counter.
Example that is not reported (boundary or exclusion)
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
synchronized (this) {
count++;
}
total++;
resp.getWriter().println(count);
}An assignment inside synchronized and a static field (total) are not reported by this rule.
74Stream without a terminal operationSR-JAVA-STREAM-NO-TERMINAL-001WarningGeneral
Checks only the case where a chain of intermediate operations built directly from a collection, Arrays.stream or a JDK Stream factory is discarded as a statement (nothing is executed because there is no terminal operation). A pipeline that is stored or returned, a Stream passed in from outside, and a custom factory are not reported. Methods, constructors and static and instance initializer blocks are covered, as are lambdas in field initializers and in enum constant arguments. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void streamBad(List<String> list) { list.stream().filter(x->!x.isEmpty()).map(String::trim); }Finding message (the engine's actual output)
Discarded lazy stream pipeline: map.
Fix (the engine's suggestion)
Add a terminal operation such as forEach(...) or collect(Collectors.toList()) and use the result. If the aim was to change a list in place, use list.replaceAll(...) or list.removeIf(...) instead.
Note on the NG example: filter and map are intermediate operations, and nothing is executed without a terminal operation (collect, forEach, count and so on). The result is also discarded, so this line does nothing.
OK example (code that is not reported)
public List<String> streamGood(List<String> list) { return list.stream().filter(x->!x.isEmpty()).toList(); }Execute it with the terminal operation toList() and return the result.
Example that is not reported (boundary or exclusion)
public Stream<String> streamReturned(List<String> list) { return list.stream().map(String::trim); }The pipeline is returned and the caller performs the terminal operation, so it is not reported.
75Stream consumed twiceSR-JAVA-STREAM-REUSE-001WarningGeneral
Reports duplicate consumption: within the body of the same method, constructor, initializer block or lambda, aliases of local variables and the results of intermediate operations are followed, and a terminal operation is performed twice on the same Stream (in a lambda body, only its parameters and the variables it declares itself are followed, and outer variables are not inferred). Mutually exclusive branches, reassignments and early returns are distinguished. When different Streams are assigned to the same variable in the two branches of a conditional expression or on each path of an if/else, the variable is followed as one variable if all the branches are Streams, and the second terminal operation on each path is regarded as duplicate consumption. A loop body is treated as executed twice, so consuming inside a loop a Stream that is declared outside the loop and not reassigned inside it results in duplicate consumption in the second iteration (not reported when the body ends with break, return or throw). The Stream in a for-each variable is a different Stream in each iteration. Each branch of a switch is followed separately, a Stream consumed or a variable assigned inside a branch is not counted after the switch, and fall-through to the next branch without break is not followed. A Stream in a field and consumption across methods are not inferred.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void reusedStream() { Stream<String> a = Stream.of("a"); Stream<String> b = a; a.count(); b.findFirst(); }Finding message (the engine's actual output)
A second terminal operation consumes b on the same path.
Fix (the engine's suggestion)
Create a fresh stream for each consumption or collect the data for reuse.
Note on the NG example: b is an alias of a, so b.findFirst() after a.count() throws IllegalStateException.
OK example (code that is not reported)
void freshStream() { Stream<String> a = Stream.of("a"); a.count(); a = Stream.of("b"); a.count(); }The second time, a new Stream is created again with Stream.of(...).
Example that is not reported (boundary or exclusion)
void branchStream(boolean flag) { Stream<String> a = Stream.of("a"); if(flag) a.count(); else a.findFirst(); }Only one of if and else is executed, so the Stream is consumed only once.
76Strings compared with ==SR-JAVA-STRING-EQ-001WarningGeneral
Comparing two Strings with == or != compares object references, not contents. Literals may happen to be equal to each other, but values obtained from request parameters, databases or string concatenation are not equal even when their contents are the same. A comparison where both sides are compile-time constants is not reported, and a comparison with the empty string literal "" is handled by SR-JAVA-EMPTY-STRING-EQ-001. Comparing interned constant strings (such as Swing property names) happens to work, but it is not recommended because it depends on interning.
- Category
- Comparison and equality
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
boolean sameKbn(String kbn, String expected) {
return kbn == expected;
}Finding message (the engine's actual output)
kbn == expected compares string references, not contents.
Fix (the engine's suggestion)
Use equals() (with the constant on the left to avoid NullPointerException, e.g. "1".equals(code)) or Objects.equals().
OK example (code that is not reported)
boolean isTwo(String kbn) {
return "2".equals(kbn);
}Compare with equals (writing the constant on the left is safe even for null).
Example that is not reported (boundary or exclusion)
boolean constants() {
return Constants.A == Constants.B;
}Both sides are compile-time constants (Constants.A and Constants.B), so it is not reported.
77Missing break in a switch case (fall-through)SR-JAVA-SWITCH-FALLTHROUGH-001WarningGeneral
Reports a traditional switch in which execution flows from a case that has statements (with no break, return or throw) into the statements of the next case, and the next case immediately reassigns the same variable, so the value set by the previous case is lost (an intentional fall-through does not behave like this). A fall-through with an explanatory comment and an arrow-form switch are not reported. If the parameter requireOverwrite is set to false, every fall-through without a comment is reported.
- Category
- Control flow
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String subject(int code) {
String name = "";
switch (code) {
case 1:
name = "国語";
case 2:
name = "数学";
break;
default:
name = "?";
}
return name;
}Finding message (the engine's actual output)
case 1: continues into the statements of case 2: (no break).
Fix (the engine's suggestion)
Add a break at the end of the case; if the fall-through is needed, add a comment (e.g. // fall through).
OK example (code that is not reported)
String ok(int code) {
switch (code) {
case 1:
return "a";
case 2: {
return "b";
}
default:
return "c";
}
}End each case with return (or break).
Example that is not reported (boundary or exclusion)
int commented(int code) {
int n = 0;
switch (code) {
case 1:
n++;
// fall through: case 1 also counts as case 2
case 2:
n++;
break;
default:
break;
}
return n;
}A fall-through whose intent is explained in a comment is not reported.
78Calling interrupted through an instanceSR-JAVA-THREAD-INSTANCE-INTERRUPTED-001WarningGeneral
Reports a call bound to the JDK's Thread.interrupted (a static method) when the receiver is an instance expression. This method reads and clears the interrupt status of the current thread; the receiver's thread is not its target. Thread.interrupted, isInterrupted, and a receiver that is Thread.currentThread() (directly or through a local variable) are not reported, because the behavior is the same. Methods, constructors, static and instance initializer blocks, field initializers and enum constant arguments are covered. Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public boolean interruptBad(Thread worker) { return worker.interrupted(); }Finding message (the engine's actual output)
Thread.interrupted called through an instance: worker.
Fix (the engine's suggestion)
To ask another thread whether it was interrupted, use worker.isInterrupted() (it does not clear the status). To test and clear the status of the current thread, write Thread.interrupted() itself instead of calling it through an instance.
Note on the NG example: interrupted() is a static method, and it reads and clears the interrupt status of the current thread, not of worker.
OK example (code that is not reported)
public boolean interruptGood(Thread worker) { return worker.isInterrupted(); }isInterrupted() reads the status of that thread itself and does not clear it.
Example that is not reported (boundary or exclusion)
@SuppressWarnings("static-access")
public boolean currentThreadInterrupted() {
return Thread.currentThread().interrupted();
}The receiver is Thread.currentThread(), so the thread that is read is the current thread, as intended (Thread.interrupted() is the appropriate way to write it).
79Request or task ThreadLocal not removedSR-JAVA-THREADLOCAL-CLEANUP-001WarningGeneral
Checks only methods that handle requests or tasks (methods with a ServletRequest or HttpExchange parameter, methods with Spring's @RequestMapping, @GetMapping or the like, Runnable.run and Callable.call), and reports a value set on a ThreadLocal that is not unconditionally removed in a finally on the same unchanged object. An unrelated boolean flag and repeated calls to an arbitrary factory are not regarded as proof of removal. A loop whose condition is always true reaches the finally if it has an exit. Methods such as those for a context held for the whole process are not reported, and removal in common processing such as a filter is not inferred. Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void requestLocal(HttpServletRequest request) { local.set(request.getParameter("user")); work(); }Finding message (the engine's actual output)
Request/task ThreadLocal local has no reliable finally remove.
Fix (the engine's suggestion)
Remove ThreadLocal data in request/task try/finally; document an exclusion when framework cleanup owns it.
Note on the NG example: The thread returns to the pool with the request's user still in the ThreadLocal.
OK example (code that is not reported)
void cleanedLocal(HttpServletRequest request) { try { local.set(request.getParameter("user")); work(); } finally { local.remove(); } }Remove it in the finally of a try.
Example that is not reported (boundary or exclusion)
void persistentLocal() { local.set("process context"); }This is not a method that handles a request or task (it has no request parameter), so it is out of scope.
80Self-invocation of a Spring transactional methodSR-JAVA-TRANSACTION-SELF-001WarningGeneral
Examines the correspondence between Spring's @Transactional annotations and the methods of the same class, and reports a method without a transaction that directly calls a @Transactional method (through this or with the receiver omitted; the callee may be a method of a generic class or a method inherited from a superclass or interface, and a call inside a lambda, method reference, anonymous class or inner class is covered as long as it refers to an instance method of the enclosing Bean). Annotations are looked up with Spring's composition rules, and class annotations also include those found on superclasses, interfaces and meta-annotations (composed annotations). Anonymous classes and local classes are not Beans, so calls between them are not reported. Out of scope are the case where the same file has an AspectJ configuration and entry points that are already inside a transaction with the same attributes; a call that crosses a new boundary such as REQUIRES_NEW is reported even if a transaction already exists. AspectJ configured in another file must be declared with adviceMode.
- Category
- SQL and data access
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void selfCall() { save(); }Finding message (the engine's actual output)
Self-invocation of save bypasses the transactional proxy.
Fix (the engine's suggestion)
Place the transaction boundary on a service invoked through its proxy; set adviceMode to ASPECTJ when using weaving.
Note on the NG example: save() is @Transactional, but when it is called through this from selfCall(), which has no transaction, the call does not go through the proxy and no transaction is started.
OK example (code that is not reported)
void externalCall(TransactionCases proxy) { proxy.save(); }It is called through the proxy (the one injected as a Bean), so a transaction is started.
Example that is not reported (boundary or exclusion)
@Transactional void existingTransaction() { save(); }The caller is already inside a transaction with the same attributes, and save() only joins that transaction, so the result does not change and it is not reported.
81Transactional method declaring a checked exception without a rollback settingSR-JAVA-TRANSACTIONAL-ROLLBACK-001WarningGeneral
Reports a @Transactional method that declares a checked exception in throws when the rollback settings do not cover it. The default rollback targets are RuntimeException and Error for Spring's @Transactional and only RuntimeException for JTA's @Transactional, so a checked exception is committed, and the updates remain although the call is treated as a failure. Only the first annotation found, in the order of the method, the overridden method, the class and so on, is applied; annotations are not combined. If rollbackFor or noRollbackFor (rollbackOn or dontRollbackOn for JTA) contains the exception or its superclass, or if a checked exception listed in rollbackFor is a subclass of an exception in throws (throws Exception with rollbackFor = IOException.class), it is regarded as dealt with and is not reported. Non-public methods, static methods, lifecycle methods, test code, and methods with readOnly = true or with NEVER or NOT_SUPPORTED are out of scope. Requires type information.
- Category
- SQL and data access
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@Transactional
public void plainChecked() throws IOException { }Finding message (the engine's actual output)
A transactional method declares a checked exception without a rollback rule: plainChecked throws IOException.
Fix (the engine's suggestion)
Name the exceptions of the throws clause in rollbackFor of the annotation (the simplest is rollbackFor = Exception.class for Spring, rollbackOn = Exception.class for JTA), or make the exception unchecked. If the checked exception really stands for a business result that should be committed, say so with noRollbackFor (dontRollbackOn for JTA) so the intent is visible.
OK example (code that is not reported)
@Transactional(rollbackFor = Exception.class)
public void everythingRollsBack() throws IOException { }With rollbackFor = Exception.class, checked exceptions are also rolled back.
Example that is not reported (boundary or exclusion)
@Transactional(rollbackFor = IOException.class)
public void partiallyListed() throws Exception { }rollbackFor lists IOException, which is taken as the author having explicitly named the exception that should roll back, so throws Exception is not reported.
82Collection method argument that does not match the element typeSR-JAVA-UNLIKELY-ARG-001WarningGeneral
Reports a call to a method whose parameter is Object, such as get, containsKey and remove of Map or contains and remove of Collection, when the argument has a type that can never be equal to the keys or elements (example: get(Integer) on a Map<String, ...>). The result is always null or false, but it is not a compile error. This often happens when a numeric code is used as a string key, or when an ID and an entity are mixed up. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Customer find(Map<String, Customer> byCode, Integer code) {
return byCode.get(code);
}Finding message (the engine's actual output)
The argument code (Integer) of byCode.get(code) cannot match the keys or elements of java.util.Map<java.lang.String,example.UnlikelyArgumentCases.Customer>: the result is always null or false.
Fix (the engine's suggestion)
Pass a value of the key or element type, e.g. map.get(String.valueOf(code)) or list.contains(item.getId()).
OK example (code that is not reported)
Customer findById(Map<String, Customer> byId, String id) {
return byId.get(id);
}Look up with a String, the same type as the key.
Example that is not reported (boundary or exclusion)
boolean listed(List<String> names, CharSequence name) {
return names.contains(name);
}CharSequence is a supertype of String, and the two can be equal if the actual object is a String, so it is not reported.
83Modification of an unmodifiable collectionSR-JAVA-UNMODIFIABLE-MODIFY-001WarningGeneral
Reports modifications such as add, remove and put on a local variable that holds the result of the JDK's List/Set/Map.of, copyOf, Collections.unmodifiable/empty/singleton, Stream.toList or a toUnmodifiable collector, and on its aliases (including unmodifiable Map views, List sublists and the lambda's own local variables). Running it throws UnsupportedOperationException. Reassignments are tracked, nothing is inferred when branches leave the origin undetermined, and the JDK's contract is not applied to a custom factory with the same name. Arrays.asList's set is valid. Methods, constructors and static and instance initializer blocks are covered, as are lambdas in field initializers and in enum constant arguments. Requires type information.
- Category
- API misuse
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void immutableBad() { var list=List.of("a"); list.add("b"); }Finding message (the engine's actual output)
Mutation of an unmodifiable collection: add.
Fix (the engine's suggestion)
If it has to change, copy it into a mutable collection first, e.g. new ArrayList<>(list), new HashSet<>(set) or new HashMap<>(map), or create it as a mutable collection from the start. To collect a stream use Collectors.toCollection(ArrayList::new) instead of Stream.toList().
Note on the NG example: The list returned by List.of cannot be modified, and add throws UnsupportedOperationException.
OK example (code that is not reported)
public void mutableGood() { var list=new ArrayList<String>(); list.add("a"); }Use an ArrayList, which can be modified.
Example that is not reported (boundary or exclusion)
public void fixedSetGood() { var list=Arrays.asList("a"); list.set(0,"b"); }Arrays.asList's set replaces an element, so it is valid (operations that change the size are covered by SR-JAVA-FIXED-LIST-001).
84Exception created but not thrownSR-JAVA-UNTHROWN-EXCEPTION-001WarningGeneral
Reports a statement consisting only of new XxxException(...); that creates an exception object without throwing it (a forgotten throw). The object is discarded, and the method goes on processing a value that it should have rejected. Whether something is an exception is decided by its type, and when the type cannot be resolved, by its name (ending in Exception).
- Category
- Exception handling
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int doubled(int amount) {
if (amount < 0) {
new IllegalArgumentException("amount must not be negative: " + amount);
}
return amount * 2;
}Finding message (the engine's actual output)
new IllegalArgumentException("amount must not be negative: " + amount) creates a IllegalArgumentException without throwing it: nothing is thrown and the method goes on.
Fix (the engine's suggestion)
Add throw (throw new ...); if the intent was only to record the problem, log it instead.
OK example (code that is not reported)
int checked(int amount) {
if (amount < 0) {
throw new IllegalArgumentException("negative");
}
return amount;
}The exception is thrown.
Example that is not reported (boundary or exclusion)
void trace() {
new Exception("trace").printStackTrace();
}The created exception is used right away (printStackTrace prints the call location), so it is not reported.
85Wait condition not recheckedSR-JAVA-WAIT-CONDITION-001WarningGeneral
Reports Object.wait or Condition.await guarded by an if condition (user-written overloads of the same name are out of scope). Because a wait can return without the condition holding (spurious wakeup), a loop that rechecks the condition after returning from the wait is needed. If the wait is inside any loop (while, do, for or enhanced for), the loop goes back to recheck the condition or guard, so it is not reported; only an if-guarded wait that is not inside a loop is reported. Other contracts such as CountDownLatch are out of scope. Methods, constructors and static and instance initializer blocks are covered, as are lambdas in field initializers and in enum constant arguments. Requires type information.
- Category
- Threads and concurrency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void waitBad(Object lock,boolean ready) throws Exception { synchronized(lock) { if(!ready)lock.wait(); } }Finding message (the engine's actual output)
Wait condition is not rechecked in a loop: wait.
Fix (the engine's suggestion)
Change the if into a while that rechecks the condition: while (!ready) lock.wait(); (for a Condition: while (!ready) condition.await();). Check the condition and wait under the same lock.
Note on the NG example: With an if, the condition is not rechecked after returning from the wait. If a spurious wakeup returns without any notify, or another thread has changed the condition first, processing continues even though the condition does not hold.
OK example (code that is not reported)
public void waitGood(Object lock,boolean ready) throws Exception { synchronized(lock) { while(!ready)lock.wait(); } }Recheck the condition in a while.
Example that is not reported (boundary or exclusion)
public void latchGood(CountDownLatch c,boolean ready) throws Exception { if(!ready)c.await(); }CountDownLatch.await does not follow the condition variable contract; it only waits until the count reaches 0, so a loop is not needed.
86Duplicate mapper IDSR-MYBATIS-DUP-ID-001WarningGeneral
Reports duplicate ids within the same mapper file, for each registry of statement, sql and resultMap. Legitimate variations with different databaseId values are allowed, and the fully qualified id and the local id of this namespace are treated as the same registration. The detail shows the registry (and the databaseId), and the related location shows the first registration. A malformed mapper is recorded as one that cannot be inspected. Does not require type information.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<mapper namespace="case_dup_statement"><select id="find">select 1</select><select id="find">select 2</select></mapper>Finding message (the engine's actual output)
Duplicate mapper registration: find (statement).
Fix (the engine's suggestion)
Remove or rename the duplicate, or tell the variants apart by databaseId, and add positive and negative regression cases.
Note on the NG example: The same namespace has two select elements with id="find", and MyBatis throws an exception at startup.
OK example (code that is not reported)
<mapper namespace="case_unique_statement"><select id="one">select 1</select><select id="two">select 2</select></mapper>All ids are different.
Example that is not reported (boundary or exclusion)
<mapper namespace="case_database_variant"><select id="find" databaseId="mysql">select 1</select><select id="find" databaseId="oracle">select 2</select></mapper>Statements with the same name and different databaseId values are legitimate variations, one for each database they run on.
87Possible loss of all conditions in a MyBatis update or deleteSR-MYBATIS-DYNAMIC-WHERE-001WarningGeneral
Reports a MyBatis update or delete in which all the WHERE conditions can disappear. It builds the concrete SQL for the case where all the referenced input properties are null, and inspects dynamic where, trim and choose elements and includes in the same file (the SQL may be written on several lines). Input properties also include the property paths of @Param objects (cond.xid != null). OGNL that cannot be decided (including method calls), includes in another file, bind, and the empty-collection path of a foreach that cannot be executed are not judged but recorded as an explanation (DYNAMIC_SQL_UNRESOLVED), and the review coverage is not lowered. Only an XML format error becomes an analysis limitation. A static unconditional update or delete with no dynamic elements is out of scope. A statement in which only a part such as SET is dynamic and which has no WHERE in any rendering result (when all optional parts are output) is also out of scope. Only MyBatis 3 <mapper> is inspected; iBatis <sqlMap> is out of scope.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="example.Users">
<update id="rename">
UPDATE users
SET name = #{name},
updated_at = CURRENT_TIMESTAMP
<where>
<if test="id != null">id = #{id}</if>
</where>
</update>
</mapper>Finding message (the engine's actual output)
Dynamic predicates of example.Users#rename can disappear, leaving an unbounded update or delete.
Fix (the engine's suggestion)
Require the key predicate, reject empty filters, or use a safe otherwise branch such as WHERE 1=0.
Note on the NG example: If id is null, the where becomes empty and the statement becomes an UPDATE that updates name and updated_at of every row.
OK example (code that is not reported)
<mapper namespace="example.Users"><delete id="remove">DELETE FROM users WHERE id = #{id}<if test="name != null"> AND name = #{name}</if></delete></mapper>The condition on id is written as a fixed part, so even if name is null the only target is the one row with that id.
Example that is not reported (boundary or exclusion)
<mapper namespace="example.Users"><delete id="remove">DELETE FROM users <where><choose><when test="id != null">id = #{id}</when><otherwise>1=0</otherwise></choose></where></delete></mapper>When id is null, the otherwise branch 1=0 applies and nothing is deleted, so it is not reported.
88Invalid statement generated by dynamic SQLSR-MYBATIS-INVALID-SQL-001WarningGeneral
Checks for a SET that has disappeared (is empty) and for an IN without operands, using concrete example inputs in which the scalar parameters in a statement are null and the foreach collections are empty. SQL strings, comments and placeholders are told apart correctly; unknown OGNL, custom language drivers, database-dependent fragments and external includes are recorded as not decidable, and SQL dialects are not guessed. Statements marked @mbg.generated that MyBatis Generator outputs are not inspected (because a selective update assumes that the caller passes at least one value). A malformed mapper is recorded as one that cannot be inspected. Does not require type information.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<mapper namespace="case_empty_set"><update id="update">UPDATE users <set><if test="name != null">name=#{name},</if></set> WHERE id=#{id}</update></mapper>Finding message (the engine's actual output)
Dynamic SQL can generate an invalid statement: case_empty_set#update.
Fix (the engine's suggestion)
In an UPDATE keep at least one column in the set element that is always updated (for example update_time = now()), or reject all-empty arguments before the call. For an IN, check in Java whether the collection is empty and return early, or test ids.size() > 0 with a choose element in the XML and use an always-false condition such as 1 = 0 when it is empty.
Note on the NG example: If name is null, the content of <set> is empty, and the SQL becomes an invalid statement without SET (UPDATE users WHERE id=...).
OK example (code that is not reported)
<mapper namespace="case_required_set"><update id="update">UPDATE users <set>name=#{name},</set> WHERE id=#{id}</update></mapper><set> contains an item that is always output.
Example that is not reported (boundary or exclusion)
<mapper namespace="case_guarded_in"><select id="query">SELECT * FROM users <if test="ids != null and ids.size() > 0">WHERE id IN <foreach collection="ids" item="id" open="(" close=")" separator=",">#{id}</foreach></if></select></mapper>When ids is null or empty, the if that contains the foreach is false and the whole IN condition is not output, so the SQL does not become invalid.
89OGNL comparison in a dynamic SQL test not evaluated as writtenSR-MYBATIS-OGNL-TEST-001WarningGeneral
Reports a comparison with a string literal using == or != in the test of an if or when in a MyBatis 3 mapper when it does not mean what it says for the Java type of the value (verified with MyBatis 3.5.16). (1) When a number or boolean is compared with '', 0 and false are equal to the empty string, so status != '' is false when status is 0 and the condition is silently dropped. (2) A single character in single quotes (such as '1') is a char, so a number is compared with the character code ('1' is 49), and a String is interpreted as a number and either does not match or throws an exception. (3) Comparing a number, boolean or char with a non-numeric string and (4) comparing a date, time, UUID or enum with a string throw an exception when the value is not null. The type is taken from the parameters of the mapper interface method and from the properties of the parameter classes in the project, and nothing is reported when it cannot be determined (the interface is not in the source, overloads, Map, foreach variables). If the same test also compares with 0, as in status == 0, it is regarded as intentional handling of 0 and (1) is not reported.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.ognl.ZeroEmptyMapper">
<select id="find" resultType="string">
SELECT code FROM orders
<where>
<if test="status != null and status != ''">AND status = #{status}</if>
<if test="name != null and name != ''">AND name = #{name}</if>
</where>
</select>
</mapper>Finding message (the engine's actual output)
OGNL does not evaluate status != '' as it reads: status has the type Integer (statement find).
Fix (the engine's suggestion)
Test numbers and booleans with != null only (so that 0 stays a value), or compare them with a number (status != 0). Write a one-character String in double quotes (test='flag == "Y"') or as 'Y'.toString(), compare a char or Character with a single-quoted character (c == 'Y'), and compare numbers with numbers (type == 1). Test a date with != null only, and compare an enum by its name (status.name() == 'OPEN').
Note on the NG example: The type of status, Integer, is taken from the method declaration (@Param("status") Integer status) of the interface example.ognl.ZeroEmptyMapper that corresponds to the namespace. OGNL evaluates 0 as equal to the empty string, so when status is 0, status != '' is false and the condition is silently dropped.
OK example (code that is not reported)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.ognl.ExplicitZeroMapper">
<select id="find" resultType="string">
SELECT code FROM orders
<where>
<if test="status != null and status != '' or status == 0">AND status = #{status}</if>
<if test="count == null or count == '' or count == 0">AND count = 0</if>
</where>
</select>
</mapper>The same test also compares status == 0, so 0 is regarded as handled intentionally.
Example that is not reported (boundary or exclusion)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.ognl.NoInterface">
<select id="find" resultType="string">
SELECT code FROM orders
<where>
<if test="status != ''">AND status = #{status}</if>
</where>
</select>
</mapper>The mapper interface example.ognl.NoInterface is not in the project's sources, so the type of status cannot be determined and it is not reported.
90Mapper parameter name mismatchSR-MYBATIS-PARAM-NAME-001WarningGeneral
Checks whether the names in #{} are provided, against the method of the unique Java interface that corresponds to the namespace and its explicit @Param parameters. Fully qualified statement IDs, Unicode names, paramN, and the local names of foreach and bind are supported. The root name of ${} may be a configuration property that MyBatis substitutes when it loads the mapper (<properties>, configurationProperties), so it is recorded only as an explanation and is not reported. Nothing is inferred for custom language drivers, shadowing by annotations, overloads, inherited interfaces, or incomplete context. When the interface cannot be read, it is recorded as one that cannot be inspected. Annotations must be written with the fully qualified name or an unambiguous single-type import. Does not require type information.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<mapper namespace="example.Mapper"><select id="find">SELECT * FROM users WHERE id=#{orderId}</select></mapper>Finding message (the engine's actual output)
Mapper explicit parameter name mismatch: orderId (available: id, param1).
Fix (the engine's suggestion)
Correct the name in #{} or the @Param annotation, and add positive and negative regression cases.
Note on the NG example: The interface method is find(@Param("id") String id), and there is no parameter named #{orderId} (a BindingException is thrown at run time).
OK example (code that is not reported)
<mapper namespace="example.Mapper"><select id="find">SELECT * FROM users WHERE id=#{id}</select></mapper>#{id} corresponds to @Param("id").
Example that is not reported (boundary or exclusion)
<mapper namespace="example.Mapper"><select id="find">SELECT * FROM users WHERE id IN <foreach collection="id" item="item" open="(" close=")">#{item}</foreach></select></mapper>The local name #{item} declared by item="item" of a foreach is valid even though it is not a parameter name.
91Mapper reference with no targetSR-MYBATIS-REFERENCE-001WarningGeneral
Checks, as MyBatis resolves them, whether the targets of include/refid, resultMap, resultMap/extends and cache-ref/namespace references exist. In the resultMap list of a statement, only the first item is completed with the file's own namespace, and the remaining short names must be globally unique. An include of a fragment is resolved in the namespace of the statement that contains it. The @Results(id) and @CacheNamespace annotations are also treated as registrations. A reference to the file's own namespace is reported when all of the project's mappers can be read (the class path has no effect). A reference to another namespace is reported only when the class path is empty. Unreadable files, malformed mappers, size limits, the context of past versions and dynamic references are recorded as not decidable. Does not require type information.
- Category
- MyBatis Mapper
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<mapper namespace="case_missing_fragment"><select id="find">SELECT <include refid="missing"/> FROM users</select></mapper>Finding message (the engine's actual output)
Unresolved mapper reference: missing (sql).
Fix (the engine's suggestion)
Correct the referenced id or namespace, or add the missing registration, and add positive and negative regression cases.
Note on the NG example: There is no <sql id="missing"> for <include refid="missing"/> to refer to, and an error occurs when the mapper is loaded.
OK example (code that is not reported)
<mapper namespace="case_local_fragment"><sql id="columns">id</sql><select id="find">SELECT <include refid="columns"/> FROM users</select></mapper>The same namespace has <sql id="columns">.
Example that is not reported (boundary or exclusion)
<mapper namespace="case_external_fragment"><select id="find">SELECT <include refid="example.Shared.columns"/> FROM users</select></mapper>A fragment in another namespace (example.Shared) is not judged and is not reported, because its file may be outside this project.
92Mapper interface method with no corresponding SQL statementSR-MYBATIS-UNBOUND-METHOD-001WarningGeneral
In a MyBatis mapper interface in the project's sources, reports an abstract method that has no annotation such as @Select (including @*Provider) and no @Flush, and for which the mapper XML whose namespace is the full name of the interface also has no statement with an id equal to the method name. MyBatis looks up a statement by "full interface name.method name" (case-sensitive; overloads with the same name share a statement), so when there is no statement, calling the method throws BindingException (Invalid bound statement (not found)). Methods that are default, static or private are not inspected, and nothing is reported if any of the overloads has an annotation. A method is reported only when the project has a mapper XML for the corresponding namespace and all of it could be read, so an interface without XML (the XML may be in a jar or another module) and an interface that extends one outside the project, such as MyBatis-Plus's BaseMapper, are out of scope. Requires type information.
- Category
- MyBatis Mapper
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
List<Object> findByName(@Param("name") String name);Finding message (the engine's actual output)
Mapper interface method has no SQL statement: example.unbound.OrderMapper#findByName (XML: src/main/resources/example/unbound/OrderMapper.xml, src/main/resources/example/unbound/OrderMapperExtra.xml).
Fix (the engine's suggestion)
Add a statement whose id is exactly the method name to the mapper XML, or give the method its SQL with @Select, @Insert, @Update or @Delete; delete the method if nobody uses it.
Note on the NG example: findByName has no annotation such as @Select, and the mapper XML whose namespace is example.unbound.OrderMapper (the 2 files in the message) has no statement with the id findByName either, so calling it throws BindingException.
OK example (code that is not reported)
@Select("SELECT COUNT(*) FROM orders")
int count();The SQL is attached with @Select, so there is a corresponding statement.
Example that is not reported (boundary or exclusion)
public interface PlusMapper extends BaseMapper<Object> {
List<Object> custom();
}An interface that extends BaseMapper (MyBatis-Plus), which is not in the project's sources, is not inspected and not reported, because the framework generates its methods.
93Formatter created on every loop iterationSR-PERF-FORMAT-IN-LOOP-001InfoPerformance
Reports the creation of a SimpleDateFormat, DecimalFormat, MessageFormat or ChoiceFormat with arguments that do not change, or a call to DateTimeFormatter.ofPattern, inside a loop. The pattern is parsed and initialized every time (SimpleDateFormat also creates a Calendar), which costs far more than the formatting itself. It is not reported when a different pattern is used in each iteration, when the loop is exited with return, throw or break right after the object is created (so it runs only once), or for a loop with a constant number of iterations at or below ignoreFixedLoopsUpTo. SimpleDateFormat and DecimalFormat are not thread-safe, so when moving them out of the loop, make them local variables in the method and not shared static fields (see SR-JAVA-SHARED-FORMAT-001). Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
List<String> dates(List<Date> values) {
List<String> out = new ArrayList<>();
for (Date d : values) {
out.add(new SimpleDateFormat(DATE, Locale.JAPAN).format(d));
}
return out;
}Finding message (the engine's actual output)
The same formatter is created in every iteration: new SimpleDateFormat(DATE, Locale.JAPAN).
Fix (the engine's suggestion)
Create it once before the loop (a local variable) and reuse it. DateTimeFormatter is immutable and thread-safe and can be a static final constant; SimpleDateFormat and DecimalFormat are not thread-safe and must not become shared static fields.
OK example (code that is not reported)
List<String> once(List<Date> values) {
SimpleDateFormat f = new SimpleDateFormat(DATE);
List<String> out = new ArrayList<>();
for (Date d : values) {
out.add(f.format(d));
}
return out;
}Create the formatter only once, before the loop (a local variable in the method).
Example that is not reported (boundary or exclusion)
List<String> quarters(long[] totals) {
List<String> out = new ArrayList<>();
for (int q = 0; q < 4; q++) {
out.add(new DecimalFormat("#,##0").format(totals[q]));
}
return out;
}A loop with a fixed count of 4 is at or below ignoreFixedLoopsUpTo (default 10), so it is not reported.
94Value fetched with get() while iterating keySet()SR-PERF-KEYSET-GET-001InfoPerformance
Reports a call to get(key) on the same Map while iterating map.keySet() (an enhanced for, or a while loop over keySet().iterator()). The value is looked up again for every key (log n for a TreeMap). Iterating entrySet() gives the key and the value at the same time. It is reported only when the key variable comes from the keySet() of the same Map; using that key to look up a different Map (including a same-named field of a different object, such as src.entries and dst.entries) is not reported. The same Map in the same loop is reported only once, and a call after which the loop is exited with return, throw or break (so it runs only once) is not reported. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int total(Map<String, Integer> counts) {
int total = 0;
for (String key : counts.keySet()) {
total += counts.get(key);
}
return total;
}Finding message (the engine's actual output)
Values looked up with counts.get(key) while iterating the key set.
Fix (the engine's suggestion)
Iterate entrySet() instead: for (Map.Entry<K, V> e : map.entrySet()), using e.getKey() and e.getValue().
OK example (code that is not reported)
int totalEntries(Map<String, Integer> counts) {
int total = 0;
for (Map.Entry<String, Integer> e : counts.entrySet()) {
total += e.getValue();
}
return total;
}Iterate entrySet() to get the key and the value at the same time.
Example that is not reported (boundary or exclusion)
int join(Map<String, Integer> left, Map<String, Integer> right) {
int total = 0;
for (String key : left.keySet()) {
Integer r = right.get(key);
total += r == null ? 0 : r;
}
return total;
}The Map looked up with the key is a different one (right), so the lookup is not duplicated and it is not reported.
95LinkedList accessed by index in a loopSR-PERF-LINKEDLIST-GET-001WarningPerformance
Reports a call to LinkedList.get(i) with the loop index. LinkedList's get walks from an end of the list to the i-th element on every call, so iterating over the whole list by index takes time proportional to n². The decision is based on the static type of the variable (declared as LinkedList or one of its subclasses); a variable declared as List whose actual object is a LinkedList is not reported. A constant index (get(0)) is not reported. The same list in the same loop is reported only once, and a call after which the loop is exited with return, throw or break (so it runs only once) is not reported. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
long sumLinked(LinkedList<Long> values) {
long total = 0;
for (int i = 0; i < values.size(); i++) {
total += values.get(i);
}
return total;
}Finding message (the engine's actual output)
LinkedList accessed by index in a loop: values.get(i).
Fix (the engine's suggestion)
Iterate with an enhanced for loop or an Iterator; use ArrayList where random access by index is needed.
OK example (code that is not reported)
long sumArray(ArrayList<Long> values) {
long total = 0;
for (int i = 0; i < values.size(); i++) {
total += values.get(i);
}
return total;
}ArrayList's get(i) takes constant time, so it is not a problem.
Example that is not reported (boundary or exclusion)
long firstTimes(LinkedList<Long> values, int times) {
long total = 0;
for (int i = 0; i < times; i++) {
total += values.get(0);
}
return total;
}A constant index get(0) only looks at the first element and does not walk the list, so it is not reported.
96Search in a List that keeps growing in the same loopSR-PERF-LIST-SEARCH-001InfoPerformance
Reports a call to contains, indexOf, lastIndexOf or remove(Object) on a List inside a loop when the same loop also adds elements to that List (the typical de-duplication if (!list.contains(x)) list.add(x)). Every search scans the whole list, which keeps growing with the loop, so the total time grows in proportion to n². It is reported only when it can be confirmed that the list grows with the loop (the list is a field or a variable declared before the loop, and the loop continues after the addition); a fixed list of unknown size, a Set and remove(int) are not reported. The same list in the same loop is reported only once, and a call after which the loop is exited with return, throw or break (so it runs only once) is not reported. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
List<String> distinct(List<String> codes) {
List<String> out = new ArrayList<>();
for (String code : codes) {
if (!out.contains(code)) {
out.add(code);
}
}
return out;
}Finding message (the engine's actual output)
Search in a list that grows in the same loop: out.contains(code).
Fix (the engine's suggestion)
De-duplicate with a LinkedHashSet (keeps the order) or HashSet; keep a Map from element to index where the position is needed.
OK example (code that is not reported)
Set<String> distinctSet(List<String> codes) {
Set<String> out = new LinkedHashSet<>();
for (String code : codes) {
if (!out.contains(code)) {
out.add(code);
}
}
return out;
}Use a Set to remove duplicates (a LinkedHashSet also keeps the order).
Example that is not reported (boundary or exclusion)
int known(List<String> codes, List<String> allowed) {
int n = 0;
for (String code : codes) {
if (allowed.contains(code)) {
n++;
}
}
return n;
}The list being searched, allowed, does not grow inside the loop (its size is constant), so it is not reported.
97Debug log built by string concatenation without a level checkSR-PERF-LOG-CONCAT-001InfoPerformance
Reports a log message at debug or trace level (fine, finer or finest in java.util.logging) that is built by string concatenation and is not inside a level check such as isDebugEnabled(). Even if debug logging is disabled in production, the string concatenation and the toString() of each object run on every call. SLF4J, Log4j 1 and 2, commons-logging, JBoss Logging and java.util.logging are covered. It is not reported inside a check such as if (log.isDebugEnabled()) (including the case where the method checks and returns), when the condition has a variable whose name contains debug, trace or log (such as if (DEBUG)), when the {} placeholders of SLF4J or Log4j 2 are used, for a concatenation of constants only, or for levels of info and above. Setting onlyInLoops to true reports only logging inside loops. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void save(Order order) {
LOG.debug("save order: id=" + order.getId() + ", customer=" + order.getCustomerCode());
}Finding message (the engine's actual output)
Debug log message built outside a level check: LOG.debug("save order: id=" + order.getId() + ", customer=" + order.getCustomerCode()).
Fix (the engine's suggestion)
With SLF4J/Log4j 2 use placeholders: log.debug("order {}", id); with commons-logging/Log4j 1 wrap it in if (log.isDebugEnabled()); with java.util.logging use log.fine(() -> ...) or isLoggable(Level.FINE).
OK example (code that is not reported)
void guarded(Order order) {
if (LOG.isDebugEnabled()) {
LOG.debug("save order: id=" + order.getId());
}
}Concatenate inside an isDebugEnabled() check (with SLF4J, the {} placeholders also work).
Example that is not reported (boundary or exclusion)
void early(Order order) {
if (!SLF.isDebugEnabled()) {
return;
}
SLF.debug("order " + order.getId() + " " + order.getCustomerCode());
}Because the method returns first when debug is disabled, the later log call is regarded as already checked and is not reported.
98Database access one item at a time in a loop (N+1)SR-PERF-QUERY-IN-LOOP-001InfoPerformance
Reports SQL execution or DAO calls inside a loop (for, while, enhanced for, lambdas or method references of forEach, map and so on that run once per element of a collection or stream, and function arguments of Collectors.toMap, groupingBy and so on). The covered calls are: JDBC execute, executeQuery, executeUpdate, prepareStatement and prepareCall; JPA find and getReference, and getResultList, getSingleResult and executeUpdate of queries; Hibernate get and load, and queries; Spring JdbcTemplate query and update; statements of MyBatis SqlSession and iBatis SqlMapClient; any method with arguments (create, list, markPaid and so on) of Spring Data repositories and of objects whose type name ends in Dao or DAO (including Impl implementation classes such as OrderDaoImpl, and subtypes of this kind of type); and methods whose names start with find, get, select, load, search, query, count, exists, read, fetch, insert, update, delete, save, remove or regist of objects whose type name ends in Repository or Mapper. With n elements the database is accessed n times (N+1), and processing becomes much slower as the data grows. The following are not reported: batch processing (addBatch and executeBatch, and MyBatis sessions opened with ExecutorType.BATCH); a single lookup outside the loop; getters without arguments (such as getDataSource); setters; methods of Object; bulk methods of a DAO whose names start with batch or bulk; mappers that only copy between objects (MapStruct style, such as updateEntityFromDto; those whose type name contains Dto, Converter or the like, or that carry @org.mapstruct.Mapper); classes whose names end in Repo (they are not necessarily databases); Optional.map; a call after which the loop is exited with return, throw or break (so it runs only once; the same applies to a try-with-resources resource when its body returns); and a call inside a loop (a retry) whose enclosing loops all run a constant number of times at or below ignoreFixedLoopsUpTo. Calls inside a class that itself declares main(String[]) (a command-line program) and its nested classes are not reported either (parameter ignoreEntryPointClasses). Calls inside a class whose simple name contains any of Installer, Migration or Upgrade (a nested class follows its enclosing class) are not reported either (parameter ignoredClassNameParts; case-sensitive, and if it is emptied, everything is reported). Such programs and installation, migration and upgrade code run through only once per execution and are not on a path that requests pass through repeatedly. Because this rule judges by "becomes slower as the data grows", these are excluded. A business class whose name happens to contain these words (for example MembershipUpgradeService for member ranks) is also no longer reported, so to check such classes, set ignoredClassNameParts to empty. The APIs can be limited with databaseApis. When the type of the receiver is not on the class path, the decision is made by the written type name (a type name that ends in Dao, DAO or Repository and is not imported from a library; the analysis quality is RECOVERED (analyzed after recovery)). In other cases, requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
List<String> names(Connection c, List<Long> ids) throws SQLException {
List<String> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("select name from customer where id = ?")) {
for (Long id : ids) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
out.add(rs.getString(1));
}
}
}
}
return out;
}Finding message (the engine's actual output)
Database access per element in a loop: ps.executeQuery().
Fix (the engine's suggestion)
Load what is needed at once (IN list, JOIN, bulk lookup by keys) and match it in memory; batch updates with addBatch/executeBatch or set-based SQL. If one-by-one processing is intended (e.g. a commit per row), suppress with a reason.
OK example (code that is not reported)
List<String> codes(String customer) {
List<String> out = new ArrayList<>();
for (Order o : orderDao.selectByCustomer(customer)) {
out.add(o.getCustomerCode());
}
return out;
}Fetch everything together with one lookup, and only read the already fetched objects in the loop.
Example that is not reported (boundary or exclusion)
int retry(Connection c, long id) throws SQLException {
SQLException last = null;
for (int attempt = 0; attempt < 3; attempt++) {
try (PreparedStatement ps = c.prepareStatement("update orders set status = 'DONE' where id = ?")) {
ps.setLong(1, id);
return ps.executeUpdate();
} catch (SQLException e) {
last = e;
}
}
throw last;
}A retry of at most 3 attempts has a fixed count (at or below ignoreFixedLoopsUpTo, default 10) and returns right away on success, so it is not reported.
99Regular expression compiled on every loop iterationSR-PERF-REGEX-IN-LOOP-001InfoPerformance
Reports a call to Pattern.compile or Pattern.matches, or to String's matches, replaceAll, replaceFirst or split, inside a loop with a regular expression that does not change (a constant, or a variable that does not change outside the loop). The regular expression is compiled again on every call. String.split is not reported for an ordinary single character (such as ",") or a single escaped non-alphanumeric character (such as "\\|"), because it has a fast path that does not compile a regular expression. A loop that uses a different regular expression in each iteration, and a call after which the loop is exited with return, throw or break (so it runs only once), are not reported either. An escape of a letter (such as "\\t" or "\\s+") does not take the fast path, so it is reported. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int numbers(List<String> values) {
int n = 0;
for (String v : values) {
if (Pattern.compile("[0-9]+").matcher(v).matches()) {
n++;
}
}
return n;
}Finding message (the engine's actual output)
The same regular expression is compiled in every iteration: Pattern.compile("[0-9]+").
Fix (the engine's suggestion)
Compile it once (private static final Pattern P = Pattern.compile(...)) and use P.matcher(s).matches(), P.matcher(s).replaceAll(...) or P.split(s) in the loop.
OK example (code that is not reported)
int precompiled(List<String> values) {
int n = 0;
for (String v : values) {
n += DIGITS.matcher(v).matches() ? 1 : 0;
}
return n;
}Make the compiled Pattern a constant (DIGITS) and reuse it.
Example that is not reported (boundary or exclusion)
int fields(List<String> lines) {
int n = 0;
for (String line : lines) {
n += line.split(",").length + line.split("\t").length + line.split("\\|").length;
}
return n;
}When the delimiter of split is an ordinary single character (",", a tab) or a single escaped non-alphanumeric character ("\\|"), String.split does not compile a regular expression, so it is not reported.
100String concatenation with + in a loopSR-PERF-STRING-CONCAT-001InfoPerformance
Reports concatenation with += or s = s + ... inside a loop onto a String variable (a local variable or a field) declared outside the loop. String is immutable, so every concatenation copies all the content so far, and with n iterations time and memory grow in proportion to n² (for example, when a CSV, a report or an SQL condition is concatenated one line at a time). It is not reported when only constants are appended (zero padding, separators), when the loop condition reads the string itself (while (s.length() < 8)), when the concatenation is always followed by an exit from the loop with return, throw or break (a break that only leaves a switch does not count), when the string is reassigned before the concatenation in the same iteration (the old value is not carried over, for example when it is assigned first inside the if block that contains the concatenation), for a field of another object (obj.f, which may be a new object each time), or for a loop with a constant number of iterations at or below ignoreFixedLoopsUpTo. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String csv(List<String> rows) {
String out = "";
for (String row : rows) {
out += row;
out += "\r\n";
}
return out;
}Finding message (the engine's actual output)
out is concatenated in a loop (appending row); every iteration copies everything appended so far.
Fix (the engine's suggestion)
Create a StringBuilder before the loop, append in the loop and call toString() after it; String.join or StringJoiner also work for lists.
OK example (code that is not reported)
String builder(List<String> rows) {
StringBuilder sb = new StringBuilder();
for (String row : rows) {
sb.append(row).append("\r\n");
}
return sb.toString();
}Concatenate with a StringBuilder.
Example that is not reported (boundary or exclusion)
String pad(String code) {
String s = code;
while (s.length() < 8) {
s = "0" + s;
}
return s;
}Zero padding: the loop condition limits the number of iterations by the length of the string itself, and only a constant is appended, so it is not reported.
101Unbuffered file stream read or written one byte at a timeSR-PERF-UNBUFFERED-IO-001WarningPerformance
Reports a call to read() or write(int) of a FileInputStream, FileOutputStream or RandomAccessFile inside a loop (by static type, or through an InputStream or OutputStream variable that is created in the same method with new FileInputStream or the like and not reassigned). A system call is made for every byte, which is hundreds of times slower than buffered reading and writing. A stream wrapped in BufferedInputStream or BufferedOutputStream, reading and writing in units of arrays, a single read or write outside the loop, and a read or write after which the loop is exited right away are not reported. Requires type information.
- Category
- Efficiency
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void copy(File from, File to) throws IOException {
try (FileInputStream in = new FileInputStream(from); FileOutputStream out = new FileOutputStream(to)) {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
}Finding message (the engine's actual output)
Unbuffered file stream read or written byte by byte: in.read(). Unbuffered file stream read or written byte by byte: out.write(b).
Fix (the engine's suggestion)
Wrap the stream in BufferedInputStream/BufferedOutputStream (or BufferedReader/BufferedWriter) or read and write blocks with a byte[] buffer; Files.copy or InputStream.transferTo copy files.
OK example (code that is not reported)
void buffered(File from, File to) throws IOException {
try (InputStream in = new BufferedInputStream(new FileInputStream(from));
OutputStream out = new BufferedOutputStream(new FileOutputStream(to))) {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
}Wrap it in BufferedInputStream or BufferedOutputStream.
Example that is not reported (boundary or exclusion)
int magic(File f) throws IOException {
try (FileInputStream in = new FileInputStream(f)) {
return in.read();
}
}Reading just one byte outside a loop (for example, to determine the file format) is not a problem, so it is not reported.
102Request data in an OS command (command injection)SR-SEC-COMMAND-INJECTION-001ErrorSecurity
Reports a request string that goes into the command or arguments of Runtime.exec or ProcessBuilder (constructor arguments or command). A command in string form is split on whitespace, so an attacker can add arguments, and can run any command if a shell is involved (sh -c, cmd /c). Request data means: the parameters, headers, cookies, path and body of HttpServletRequest; arguments with Spring's @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS's @QueryParam, @FormParam, @PathParam and so on; JSF's getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces's @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The data flow inside the same method (assignment, string concatenation, StringBuilder, collections) is tracked, and it is not tracked after the data is passed to another method. A value checked against an allow-list is not reported. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
String ping(HttpServletRequest request) throws IOException {
Process p = Runtime.getRuntime().exec("ping -c 1 " + request.getParameter("host"));
return new String(p.getInputStream().readAllBytes());
}Finding message (the engine's actual output)
Request data request.getParameter("host") goes into an operating system command (Runtime.exec).
Fix (the engine's suggestion)
Avoid external commands where a Java library can do the work; otherwise fix the command and options, pass arguments as an array to ProcessBuilder and check request values against an allow-list.
OK example (code that is not reported)
void uptime() throws IOException {
Runtime.getRuntime().exec(new String[] {"uptime"});
}A fixed command that contains no request data.
Example that is not reported (boundary or exclusion)
void pingKnown(HttpServletRequest request) throws IOException {
String host = request.getParameter("host");
if (HOSTS.contains(host)) {
Runtime.getRuntime().exec(new String[] {"ping", "-c", "1", host});
}
}The host name is used only after it is confirmed to be in a fixed allow-list (HOSTS), so it is not reported.
103Cookie without Secure or HttpOnlySR-SEC-COOKIE-FLAGS-001InfoSecurity
Reports a cookie added to the response (a servlet Cookie, Spring's ResponseCookie, or a hand-written Set-Cookie header) for which Secure (sent only over HTTPS) or HttpOnly (cannot be read from scripts) is not set. Without Secure, the cookie may leak over plain-text HTTP, and without HttpOnly, the cookie can be stolen through XSS. The flag is regarded as set unless the argument of setSecure or setHttpOnly is the literal false (example: setSecure(request.isSecure())). Deleting a cookie (setMaxAge(0)) and a cookie that this method does not add to the response (it may be set elsewhere) are not reported. The cookie-config in web.xml applies only to the session cookie and does not affect cookies created here. A cookie that has to be read from scripts (such as an SPA's CSRF token) can be without HttpOnly, so suppress the finding. With cookieFlags, only one of the attributes can be checked. Requires type information.
- Category
- Communication and cookies
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void remember(HttpServletResponse response, String token) {
Cookie c = new Cookie("REMEMBER_ME", token);
c.setMaxAge(60 * 60 * 24 * 14);
c.setPath("/");
response.addCookie(c);
}Finding message (the engine's actual output)
Cookie "REMEMBER_ME" lacks Secure, HttpOnly.
Fix (the engine's suggestion)
Call cookie.setSecure(true) and cookie.setHttpOnly(true) (.secure(true).httpOnly(true) for ResponseCookie; add Secure; HttpOnly to a Set-Cookie header), and SameSite where needed.
OK example (code that is not reported)
void session(HttpServletResponse response, String id) {
Cookie c = new Cookie("SID", id);
c.setSecure(true);
c.setHttpOnly(true);
response.addCookie(c);
}Set both Secure and HttpOnly.
Example that is not reported (boundary or exclusion)
void logout(HttpServletResponse response) {
Cookie c = new Cookie("REMEMBER_ME", "");
c.setMaxAge(0);
response.addCookie(c);
}setMaxAge(0) is used to delete a cookie, so it is not reported.
104Deserialization of external dataSR-SEC-DESERIALIZATION-001WarningSecurity
Reports a call to readObject or readUnshared of an ObjectInputStream (or XMLDecoder) created inside the method when the data comes from the request body, a Socket or URL, a method parameter, a field, or another method (adjustable with origins; files are not included by default). Deserializing untrusted data lets an attacker run any code using gadget classes on the class path. It is not reported when an ObjectInputFilter is set inside the method, when a subclass of ObjectInputStream (normally a look-ahead stream that checks class names) is used, for a copy of an object serialized in the same method (ByteArrayOutputStream), or for a readObject(ObjectInputStream) hook. A JVM-wide filter (jdk.serialFilter) cannot be checked statically. Requires type information.
- Category
- Parsing external data
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Object fromRequest(HttpServletRequest request) throws IOException, ClassNotFoundException {
try (ObjectInputStream in = new ObjectInputStream(request.getInputStream())) {
return in.readObject();
}
}Finding message (the engine's actual output)
ObjectInputStream.readObject deserializes data that may come from outside: request.getInputStream().
Fix (the engine's suggestion)
Do not exchange data with Java serialization; use a data-only format such as JSON. Where it must be used, allow only the expected classes with an ObjectInputFilter (JDK 9+/8u121+) or use a stream that checks resolveClass.
OK example (code that is not reported)
static Object filtered(InputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(stream);
in.setObjectInputFilter(ObjectInputFilter.Config.createFilter("example.*;!*"));
return in.readObject();
}Restrict the classes that can be read with an ObjectInputFilter (JDK 9 and later).
Example that is not reported (boundary or exclusion)
static Object copy(Serializable value) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(value);
}
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
return in.readObject();
}
}This is a copy of an object serialized in the same method (a deep copy) and does not read external data, so it is not reported.
105Server-internal dispatch target decided by request data (RequestDispatcher)SR-SEC-DISPATCH-001WarningSecurity
Reports request data that decides the target of a server-internal forward or include. The covered targets are getRequestDispatcher of ServletRequest and ServletContext, PageContext.forward and include of JSP, ExternalContext.dispatch of JSF, and Spring view names that start with "forward:". Files under WEB-INF cannot be requested directly by a client, but they can be referenced from a RequestDispatcher, and the security constraints of web.xml do not apply to a forward or include target either, so if any part of the path comes from the request, views under /WEB-INF/, web.xml and pages protected by authentication can be obtained. Placing the value between a fixed directory and extension does not help, because ../ gets past them. It is not reported for a constant, the result of looking up a fixed map with a request value, a value that has passed an allow-list or an alphanumeric or numeric check, a value confirmed to contain no .., / or backslash in the file name, or a value that goes only into the query string after a fixed path. startsWith is not regarded as a check. Requires type information.
- Category
- XSS and redirects
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void forwardInDirectory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String page = request.getParameter("page");
request.getRequestDispatcher("/WEB-INF/views/" + page + ".jsp").forward(request, response);
}Finding message (the engine's actual output)
The forward/include target comes from request data request.getParameter("page") (ServletRequest.getRequestDispatcher).
Fix (the engine's suggestion)
Do not let a request value become the path: map it to a view through a fixed table or compare it with an allow-list. If a path must be built, use only the file name part (FilenameUtils.getName) and check that it has no .., / or backslash.
Note on the NG example: Even when the value is sandwiched between a fixed directory (/WEB-INF/views/) and extension (.jsp), a request value that contains ../ gets past both, and web.xml and the like under /WEB-INF/ can be obtained.
OK example (code that is not reported)
void table(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String view = TARGETS.getOrDefault(request.getParameter("page"), ERROR_VIEW);
request.getRequestDispatcher(view).forward(request, response);
}The request value is only the key used to look up a fixed map (TARGETS), and the dispatch target is either a value from the map or a fixed default.
Example that is not reported (boundary or exclusion)
void plainName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String page = request.getParameter("page");
if (page.contains("..") || page.contains("/") || page.contains("\\")) {
return;
}
request.getRequestDispatcher("/WEB-INF/views/" + page + ".jsp").forward(request, response);
}The value is used only after it is confirmed that the file name contains no .., / or backslash, so it is not reported.
106Passwords and other secrets written in the source codeSR-SEC-HARDCODED-CREDENTIAL-001WarningSecurity
Reports passwords and keys written as string literals: fields, constants and variables whose name contains password, passwd, pwd, pass, passphrase, secret, credential, apiKey, accessKey, secretKey, privateKey or clientSecret; the password argument of DriverManager.getConnection; the password of KeyStore and KeyManagerFactory; PasswordAuthentication, UsernamePasswordCredentials and methods such as setPassword; and properties whose key name ends with password or the like (such as mail.smtp.password). Source code is copied, committed to version control and included in releases, so the secret values spread with it, and they cannot differ per environment. A name that is a label, key, parameter name, column name or the like (such as PASSWORD_PARAM, PASSWORD_KEY or passwordField) is not reported, and neither is a value that is a placeholder (${...}), a property key, a path, an empty string, the same word as the name, or a sentence containing spaces. The warning does not show the secret value itself, only its first characters and its length. Test code (under src/test, *Test.java) is excluded. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
private static final String DB_PASSWORD = "Tiger#2024";Finding message (the engine's actual output)
A secret of DB_PASSWORD is written in the source code (field: T******** (10 characters)).
Fix (the engine's suggestion)
Read them from environment variables, a protected configuration file, a JNDI data source or a key management service; treat values that were in the source as leaked and change them.
OK example (code that is not reported)
static String password() {
String password = "";
String fromEnv = System.getenv("APP_PASSWORD");
return fromEnv != null ? fromEnv : password;
}The password is read from an environment variable. An empty string as a default value is not a secret.
Example that is not reported (boundary or exclusion)
private static final String PASSWORD_PARAM = "password";It is the name of a form field (a parameter name), not the password itself, so it is not reported.
107Encryption key or password written in the source codeSR-SEC-HARDCODED-KEY-001WarningSecurity
Reports key bytes of SecretKeySpec, DESKeySpec and DESedeKeySpec, and password characters of PBEKeySpec, that are built only from constants. The covered forms are getBytes() and toCharArray() of string constants (including literals, static final constants, local variables and fields), byte array and char array literals, Base64 or hex decoding of a constant string, and clone and Arrays.copyOf of these. A variable or field is covered only when all of its assignments are constants, and an array only when it is not modified. An all-zero array is reported for AES, DES and similar algorithms, but not for algorithms that use it as the initial value of key derivation, such as HMAC, HKDF and TLS. Values obtained from a KeyStore, a KeyGenerator, an environment variable, configuration, a file, an argument or random numbers, empty strings and placeholders are not reported either. A literal put into a variable with a name such as password or secretKey is reported by SR-SEC-HARDCODED-CREDENTIAL-001 at the declaration, so it is not reported again. Test code is excluded. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public SecretKeySpec literalKey() {
return new SecretKeySpec("0123456789abcdef".getBytes(StandardCharsets.UTF_8), "AES");
}Finding message (the engine's actual output)
Encryption key or password written in the source code: SecretKeySpec(AES).
Fix (the engine's suggestion)
Do not write keys into the code: generate a random key with KeyGenerator or SecureRandom, keep it in a KeyStore, an environment variable, a protected configuration file or a key management service, and read it at run time. When a key is derived from a password (PBKDF2), the password too must come from user input or a protected configuration, together with a random salt. Treat a key that was in the source code as leaked and replace it.
OK example (code that is not reported)
public SecretKey generated() throws Exception {
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(128);
return generator.generateKey();
}A random key is generated at run time with KeyGenerator.
Example that is not reported (boundary or exclusion)
public SecretKeySpec hkdfZeroSalt() {
return new SecretKeySpec(new byte[32], "HmacSHA256");
}For HMAC algorithms such as HmacSHA256 and HKDF-family algorithms, an all-zero array is the initial value of key derivation (such as the default salt of HKDF), not a key written in the code, so it is not reported.
108Data access by request ID with no visible authorization checkSR-SEC-IDOR-001InfoSecurity
Notifies when a value in the request that looks like an identifier (the last word of the parameter name, path variable name or form field name is id, no, cd, code, key, seq, num, number, uuid, bango or the like; for example orderId, kokyakuNo, shohinCd) is used to read, update or delete data (DAO/Repository/Mapper, JPA, Hibernate, JDBC parameters, Spring JdbcTemplate, MyBatis, iBatis), but the method and its class show no check of "who is accessing". A check means a Principal or Authentication argument, a session attribute (session.getAttribute, getSessionMap), getUserPrincipal, getRemoteUser or isUserInRole, SecurityContextHolder, @PreAuthorize, @Secured or @RolesAllowed, or a call or field whose name relates to permissions or owners (permission, owner, loginUser and so on). If a user rewrites the ID in a link or form, they may be able to view or change other people's data (missing authorization / IDOR). Request data means the parameters, headers, cookies, path and body of HttpServletRequest; Spring arguments annotated with @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS @QueryParam, @FormParam, @PathParam and the like; JSF getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The rule follows the data flow within the same method (assignment, string concatenation, StringBuilder, collections) and does not follow it after the data is passed to another method. The absence of an authorization check cannot be proved statically, and a filter, an interceptor, AOP, the service layer or a SQL condition may be doing the check. This is a notice for a person to check (confidence: low). Requires type information.
- Category
- Access control
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@GetMapping("/orders/{id}")
public String show(@PathVariable Long id, Model model) {
Optional<Order> order = orders.findById(id);
model.addAttribute("order", order.orElse(null));
return "order";
}Finding message (the engine's actual output)
Request value id (id) is used for data access example.OrderRepository.findById with no authorization check in the method.
Fix (the engine's suggestion)
Make sure access is checked for the current user: for example add the logged-in user to the query (WHERE owner = ?) or compare the loaded data with the logged-in user. If a framework checks centrally, suppress with a note on where.
OK example (code that is not reported)
@GetMapping("/my/orders/{id}")
public String mine(@PathVariable long id, Principal principal, Model model) {
model.addAttribute("orders", orderDao.findByIdAndOwner(id, principal.getName()));
return "order";
}The logged-in user (Principal) is included in the search condition.
Example that is not reported (boundary or exclusion)
Order view(HttpServletRequest request) {
String user = request.getRemoteUser();
Order order = orderDao.findById(Long.parseLong(request.getParameter("id")));
return order != null && user.equals(order.getOwner()) ? order : null;
}It gets the logged-in user with getRemoteUser() and compares it with the owner, which is a sign of an authorization check, so it is not reported.
109Request data reaching an LDAP filter or search base (LDAP injection)SR-SEC-LDAP-INJECTION-001WarningSecurity
Reports request data that enters an LDAP search filter or the distinguished name (DN) of the search base. The covered calls are DirContext.search of JNDI; search, authenticate and similar methods of LdapTemplate in Spring LDAP (only the base and filter arguments); filter and base of LdapQueryBuilder; and Filter.create of UnboundID. The characters * ( ) in a filter change the structure of the query, and a comma in a DN changes where the search starts. Only escaping that suits the position is effective: Rdn.escapeValue, which is for DNs, does not handle * ( ), so it is reported even when used in a filter, and filterEncode, which is for filters, is also reported in a DN. A parameterized search that passes a filter expression with placeholders and an array of values is not reported when the request value enters only the array, because the provider escapes the values. Constants, values looked up in a fixed table, values checked with an allow-list or the like, numbers, and forms that escape, such as where(..).is(..), are not reported either. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
NamingEnumeration<SearchResult> filterConcat(HttpServletRequest request) throws NamingException {
return ctx.search(BASE, "(uid=" + request.getParameter("uid") + ")", controls);
}Finding message (the engine's actual output)
Request data request.getParameter("uid") reaches an LDAP filter or search base (DirContext.search).
Fix (the engine's suggestion)
Escape a filter value with LdapEncoder.filterEncode (or ESAPI encodeForLDAP) and a value inside a distinguished name with Rdn.escapeValue (or LdapEncoder.nameEncode). Better, let the library do it: the parameterized DirContext.search(name, a filter expression using {0}, an Object array of the values, controls), or Spring LDAP's LdapQueryBuilder.query().where(attribute).is(value).
OK example (code that is not reported)
NamingEnumeration<SearchResult> parameterized(HttpServletRequest request) throws NamingException {
return ctx.search(BASE, "(&(objectClass=person)(uid={0}))", new Object[] {request.getParameter("uid")}, controls);
}A parameterized search passes a filter expression with placeholders and an array of values; the request value enters only the array, and the provider escapes it.
Example that is not reported (boundary or exclusion)
boolean templateAuthenticateFixed(HttpServletRequest request) {
return template.authenticate("ou=people", "(uid=admin)", request.getParameter("password"));
}The only request value in authenticate is the password (the third argument); it is used only for the bind and does not enter the search filter or the search base, so it is not reported.
110Passwords and other secrets written to the logSR-SEC-LOG-SECRET-001WarningSecurity
Reports log messages (SLF4J, Log4j, commons-logging, java.util.logging, JBoss Logging, System.out/err) that contain the value of a variable, field or getter whose name is password, passwd, pwd, passphrase, secret, credential, apiKey, accessKey, secretKey, privateKey, clientSecret or the like. Logs have many readers, are kept for a long time and are also forwarded to other systems, so a secret value written to them leaks. It does not report a message that contains only the word password, one that writes the length or whether the value is empty (password.length(), isEmpty()), a name such as passwordHash (whose last word stands for a length, hash, label or the like), or a whole object (it is not known whether toString() contains the password). Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static void login(String user, String password) {
LOG.info("login user=" + user + " password=" + password);
}Finding message (the engine's actual output)
A secret is written to the log: password.
Fix (the engine's suggestion)
Do not log secrets; where needed for troubleshooting, log only whether a value is set, its length or a masked value (e.g. ****).
OK example (code that is not reported)
static void changed(String user) {
LOG.info("password changed for " + user);
}Only the word password is written; the value is not output.
Example that is not reported (boundary or exclusion)
static void whole(Order order) {
LOG.info("order " + order);
}Writing a whole object is not reported, because it is not known whether toString() contains the password.
111Request data reaching a mail header (mail header injection)SR-SEC-MAIL-HEADER-INJECTION-001WarningSecurity
Reports request data that can contain line breaks and enters a mail header. The covered calls are setHeader, addHeader and addHeaderLine of JavaMail (javax.mail, jakarta.mail) classes such as MimeMessage, the methods of the same names of InternetHeaders, and the setters for the subject, description and address. A line break (CR/LF) ends the header, so an attacker can add headers such as Bcc or write into the body. The covered request data is request parameters, the body, the decoded path and the like; values of request headers and cookies cannot contain a raw line break, and getRequestURI and similar are percent-encoded, so they are not covered. The setHeader family is reported regardless of version; the setters for the subject and address are dangerous only in old JavaMail (before 1.5.6) and Commons Email (before 1.5), so whether they are reported is decided by the parameter legacyLibraries (the default, auto, decides by the jar names on the class path). Values for which both CR and LF have been removed or rejected, constants, values checked with an allow-list, and numbers are not reported. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void setHeaderValue(HttpServletRequest request) throws MessagingException {
message.setHeader("X-Origin", request.getParameter("origin"));
}Finding message (the engine's actual output)
Request data request.getParameter("origin") reaches a mail header (MimeMessage.setHeader).
Fix (the engine's suggestion)
Remove the line breaks (for example value.replaceAll("[\\r\\n]", "")) or reject values that contain them, parse addresses strictly with InternetAddress and validate() them, and never let the request choose the name of a header. When the finding is about a subject or an address setter, also upgrade JavaMail to 1.5.6 or later (or jakarta.mail) and Commons Email to 1.5 or later.
OK example (code that is not reported)
void strippedWithRegex(HttpServletRequest request) throws MessagingException {
message.setHeader("X-Origin", request.getParameter("origin").replaceAll("[\\r\\n]", ""));
}Both CR and LF are removed with replaceAll.
Example that is not reported (boundary or exclusion)
void fromRequestHeader(HttpServletRequest request) throws MessagingException {
message.setHeader("X-Agent", request.getHeader("User-Agent"));
}A request header value cannot contain a raw line break, so it does not lead to header injection and is not reported.
112${} substitution in MyBatis annotation SQLSR-SEC-MYBATIS-DOLLAR-001WarningSecurity
Reports ${...} used in the SQL of a MyBatis @Select, @Insert, @Update or @Delete annotation. MyBatis pastes the value into the SQL statement as it is (a bind parameter is #{...}), so if the value comes from user input, it becomes SQL injection. For places where only ${} can be used, such as a sort column or a table name, choose the value from a fixed allow-list in Java code before passing it. Only SQL in Java annotations is checked; ${...} and $...$ in MyBatis/iBatis Mapper XML files are checked by SR-SEC-MYBATIS-XML-DOLLAR-001. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
@Select("SELECT * FROM orders WHERE owner = #{owner} ORDER BY ${sort}")
List<Order> findByOwner(String owner, String sort);Finding message (the engine's actual output)
MyBatis SQL pastes values into the statement with ${sort} (@Select).
Fix (the engine's suggestion)
Use #{...} for values; for parts that only ${} can express, such as sort columns or table names, choose the value from a fixed allow-list in Java before passing it.
OK example (code that is not reported)
@Select("SELECT * FROM orders WHERE id = #{id}")
Order findById(long id);Only #{} bind parameters are used.
Example that is not reported (boundary or exclusion)
@Select("SELECT price FROM item WHERE currency = '$' AND id = #{id}")
long priceInDollars(long id);A $ inside a SQL string literal is not a substitution, so it is not reported.
113${} and $...$ substitution in MyBatis/iBatis Mapper XML SQLSR-SEC-MYBATIS-XML-DOLLAR-001WarningSecurity
Reports ${...} used in the SQL of select, insert, update, delete and sql elements of a MyBatis Mapper XML (including elements inside them such as where, if, foreach, choose, trim, set and selectKey, and CDATA), and $...$ used in the SQL of an iBatis SqlMap. The framework pastes the value into the SQL statement as it is (the bind parameters are #{...} and #...#), so if the value comes from user input, it becomes SQL injection. For places where only substitution can be used, such as a sort column or a table name, choose the value from a fixed allow-list in Java code before passing it. The following are not reported: #{} and #...#; ${} that is substituted when the Mapper is loaded (a ${} in a sql fragment where every place in the same file that includes the fragment gives a value with a property; a property of an outer fragment being passed to an inner one, and a ${} in the value of refid or property being substituted first, are also handled as MyBatis expands an include); ${} in iBatis (the properties of SqlMapConfig); ${} in comments and attribute values; an escaped \${ and $$ in iBatis; expressions listed in ignoredExpressions (such as a schema given by the properties of mybatis-config.xml; the engine does not read this configuration); and, when ignoreFrameworkSegments is true, ${criterion.condition} of MyBatis Generator and ${ew.sqlSegment}, ${ew.customSqlSegment} and the like of MyBatis-Plus wrappers (they are built from column names and operators in the code, and the values are bind parameters). In addition, when ignoreGenerated is true and a comment that the element directly contains has the MyBatis Generator marker @mbg.generated, the whole statement or sql fragment is not reported (it was written by the generator and is overwritten by the next generation, so a fix in this file does not remain. Whether the ${orderByClause} of selectByExample in it is dangerous depends on what the Java code passes to Example.setOrderByClause, and that is not in this file. In a Mapper file in the MyBatis Generator format that has no such marker, ${orderByClause} is still reported. A marker written in a comment of a child element or outside the element does not count as a marker). Only .xml files whose root element is <mapper namespace="..."> or <sqlMap> are checked, and other XML files are not covered. For a fragment that is included only from other Mapper files, the property given there is not taken into account. For SQL in Java annotations, see SR-SEC-MYBATIS-DOLLAR-001. Does not require type information.
- Category
- Injection
- Target
- XML (MyBatis/iBatis Mapper)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.OrderMapper">
<resultMap id="order" type="example.Order">
<id column="id" property="id"/>
<result column="owner" property="owner"/>
</resultMap>
<select id="findByOwner" resultMap="order">
SELECT id, owner, total
FROM orders
WHERE owner = #{owner}
ORDER BY ${sort}
</select>
</mapper>Finding message (the engine's actual output)
MyBatis SQL pastes values into the statement with ${sort} (<select id="findByOwner">).
Fix (the engine's suggestion)
Use #{sort} for values; for parts that only a text substitution can express, such as sort columns or table names, choose the value from a fixed allow-list in Java before passing it.
OK example (code that is not reported)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.ProductMapper">
<select id="search" resultType="example.Product">
<bind name="pattern" value="'%' + name + '%'"/>
SELECT * FROM product
<where>
<if test="name != null">AND name LIKE #{pattern}</if>
<if test="categories != null and categories.size() > 0">
AND category IN
<foreach collection="categories" item="category" open="(" separator="," close=")">#{category}</foreach>
</if>
</where>
ORDER BY
<choose>
<when test="sort == 'price'">price</when>
<otherwise>id</otherwise>
</choose>
</select>
<insert id="add" useGeneratedKeys="true" keyProperty="id">
INSERT INTO product (name, price) VALUES (#{name}, #{price,jdbcType=DECIMAL})
</insert>
<update id="update">
UPDATE product
<set>
<if test="name != null">name = #{name},</if>
<if test="price != null">price = #{price},</if>
</set>
WHERE id = #{id}
</update>
<delete id="remove">DELETE FROM product WHERE id = #{id}</delete>
</mapper>Only #{} bind parameters are used, also inside dynamic SQL (where, if, foreach, choose) and bind, and for sorting one of the fixed columns is chosen with choose.
Example that is not reported (boundary or exclusion)
<?xml version="1.0" encoding="UTF-8" ?>
<mapper namespace="example.ColumnsMapper">
<sql id="userColumns">${alias}.id, ${alias}.name, <include refid="auditColumns"/></sql>
<sql id="auditColumns">${alias}.created_by, ${alias}.created_at</sql>
<select id="selectUsers" resultType="map">
SELECT
<include refid="userColumns"><property name="alias" value="t1"/></include>,
<include refid="example.ColumnsMapper.userColumns"><property name="alias" value="t2"/></include>
FROM some_table t1
CROSS JOIN some_table t2
</select>
</mapper>A ${alias} in a sql fragment is not reported, because every place that includes it gives a value with a property and it is substituted when the Mapper is loaded (the same applies to an inner fragment that is included through an outer fragment).
114Redirect target decided by request data (open redirect)SR-SEC-OPEN-REDIRECT-001WarningSecurity
Reports when the beginning of the redirect target comes from the request: HttpServletResponse.sendRedirect, ExternalContext.redirect of JSF, the Location header, "redirect:" view names of Spring, and RedirectView. An attacker can create a link that leads users to an external phishing site. Request data means the parameters, headers, cookies, path and body of HttpServletRequest; Spring arguments annotated with @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS @QueryParam, @FormParam, @PathParam and the like; JSF getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The rule follows the data flow within the same method (assignment, string concatenation, StringBuilder, collections) and does not follow it after the data is passed to another method. When the request value comes after a fixed path (request.getContextPath() + "/list?id=" + id, "redirect:/orders/" + id and the like), the destination host cannot be changed, so it is not reported, and values checked beforehand (startsWith("/"), an allow-list) are not reported either. Requires type information.
- Category
- XSS and redirects
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void back(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = request.getParameter("returnUrl");
response.sendRedirect(url);
}Finding message (the engine's actual output)
The redirect target comes from request data request.getParameter("returnUrl") (HttpServletResponse.sendRedirect).
Fix (the engine's suggestion)
Allow only paths within the application (one leading / and not //) or choose the target from a fixed allow-list; the return address can also be a value kept in the session or a page ID.
OK example (code that is not reported)
void backChecked(HttpServletRequest request, HttpServletResponse response) throws IOException {
String url = request.getParameter("returnUrl");
if (url != null && url.startsWith("/") && !url.startsWith("//")) {
response.sendRedirect(url);
}
}It redirects only after checking that the target is a path within the application (it starts with / and does not start with //).
Example that is not reported (boundary or exclusion)
void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect(request.getContextPath() + "/orders?page=" + request.getParameter("page"));
}The request value is a query parameter after a fixed path and cannot change the destination host, so it is not reported.
115Request data used in a file path (path traversal)SR-SEC-PATH-TRAVERSAL-001WarningSecurity
Reports a request string that enters a file path: new File, Paths.get or Path.of, Path.resolve or resolveSibling, the path of FileInputStream, FileOutputStream, FileReader, FileWriter or RandomAccessFile, and getRealPath, getResource or getResourceAsStream of ServletContext. With ../ or an absolute path, an attacker can read and write files outside the intended directory (such as WEB-INF/web.xml and configuration files). Request data means the parameters, headers, cookies, path and body of HttpServletRequest; Spring arguments annotated with @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS @QueryParam, @FormParam, @PathParam and the like; JSF getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The rule follows the data flow within the same method (assignment, string concatenation, StringBuilder, collections) and does not follow it after the data is passed to another method. Values from which only the file name part has been extracted (FilenameUtils.getName, File.getName, Path.getFileName) and values checked beforehand with an allow-list or a regular expression are not reported. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void download(HttpServletRequest request, HttpServletResponse response) throws IOException {
File file = new File(BASE, request.getParameter("file"));
try (InputStream in = new FileInputStream(file)) {
in.transferTo(response.getOutputStream());
}
}Finding message (the engine's actual output)
Request data request.getParameter("file") is used as a file path (new java.io.File).
Fix (the engine's suggestion)
Use only the file name part (FilenameUtils.getName or Paths.get(name).getFileName()), or map an ID to a file name kept on the server; where subdirectories are needed, check that the normalize()d path still starts with the base directory.
OK example (code that is not reported)
void downloadName(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = FilenameUtils.getName(request.getParameter("file"));
Files.copy(Paths.get(BASE, name), response.getOutputStream());
}Only the file name part is extracted with FilenameUtils.getName.
Example that is not reported (boundary or exclusion)
void downloadChecked(HttpServletRequest request, HttpServletResponse response) throws IOException {
String name = request.getParameter("file");
if (name == null || !name.matches("[A-Za-z0-9_.-]+")) {
response.sendRedirect(request.getContextPath() + "/error");
return;
}
Files.copy(new File(BASE, name).toPath(), response.getOutputStream());
}The file name is checked with a regular expression (only alphanumeric characters, _, . and -) before it is used, so it is not reported.
116Predictable seed set on SHA1PRNG (setSeed)SR-SEC-SECURERANDOM-SEED-001WarningSecurity
Reports a SecureRandom.getInstance("SHA1PRNG") generator that is given a predictable seed with setSeed before it generates its first random number. A predictable seed is a constant or the current time (System.currentTimeMillis(), new Date() and the like). SHA1PRNG uses only this seed as its state, so the output becomes reproducible and tokens and keys can be guessed. setSeed on new SecureRandom(), NativePRNG, DRBG and getInstanceStrong is not reported, because the seed only adds to the system entropy. A seed that comes from a parameter, a method call (such as generateSeed) or configuration, a setSeed after the first random number, and setSeed(0) (ignored by the JDK) are not reported either. new SecureRandom(seed) is a problem only in environments where SHA1PRNG is the default algorithm (such as Java 8 on Windows), so it is not reported by default and is reported only when the parameter includeSeededConstructor is true. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public int constantLong() throws Exception {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(12345L);
return random.nextInt();
}Finding message (the engine's actual output)
SecureRandom is seeded with a predictable value before its first output: SHA1PRNG.
Fix (the engine's suggestion)
Do not call setSeed on SHA1PRNG and do not give new SecureRandom(...) a seed: use new SecureRandom() as it is (the system provides the entropy), or SecureRandom.getInstanceStrong() when more is needed. To get a key from a password use PBKDF2 (SecretKeyFactory) with a random salt, never the password as the seed of a SecureRandom. When entropy really has to be added, pass an unpredictable value such as the result of generateSeed. When reproducible output is the purpose (test data, simulations), use java.util.Random or SplittableRandom instead of SecureRandom.
Note on the NG example: If setSeed is called on SHA1PRNG before it generates its first random number, it uses only that seed as its state and mixes in no system entropy. With a constant seed the random sequence is the same every time, so tokens and keys can be reproduced.
OK example (code that is not reported)
public int defaultGenerator() {
SecureRandom random = new SecureRandom();
random.setSeed(12345L);
return random.nextInt();
}With the default generator (new SecureRandom()), the seed given to setSeed is only added to the system entropy.
Example that is not reported (boundary or exclusion)
public int seedFromAnotherGenerator() throws Exception {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(new Random().nextLong());
return random.nextInt();
}The seed is the result of the method call new Random().nextLong(), which is neither a constant nor the current time, so it is not reported.
117Text of unknown origin concatenated into SQLSR-SEC-SQL-DYNAMIC-001InfoSecurity
Notifies when a method argument, a field or a string returned by another method is concatenated into SQL that is passed to JDBC, JPA, Hibernate or Spring JdbcTemplate. This method cannot tell where the value comes from, and if a caller passes request data, it becomes SQL injection. When request data is concatenated directly in this method, SR-SEC-SQL-INJECTION-001 reports it, and this rule does not report it again. Numbers, dates, constants (including static final fields) and values that were SQL-escaped are not reported. It is meant for reviewing how the dynamic SQL is written, its confidence is low, and the finding may be suppressed once it is confirmed that the origin is trustworthy. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
int deleteByCode(String code) throws SQLException {
try (Statement st = connection.createStatement()) {
return st.executeUpdate("DELETE FROM item WHERE code = '" + code + "'");
}
}Finding message (the engine's actual output)
Text of unknown origin, code, is concatenated into SQL passed to java.sql.Statement.executeUpdate.
Fix (the engine's suggestion)
Bind values with ? placeholders and choose identifiers such as table and column names from a fixed allow-list. If the origin is trusted, suppress with a reason.
Note on the NG example: code is an argument of this method, and its origin is not known. If a caller passes a request value, it becomes SQL injection.
OK example (code that is not reported)
List<String> safe(HttpServletRequest request) throws SQLException {
List<String> out = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement("SELECT id FROM customer WHERE name = ?")) {
ps.setString(1, request.getParameter("name"));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
}
return out;
}Bind parameters with ? are used.
Example that is not reported (boundary or exclusion)
List<String> search(HttpServletRequest request) throws SQLException {
String name = request.getParameter("name");
List<String> out = new ArrayList<>();
try (Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT id FROM customer WHERE name = '" + name + "'")) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
return out;
}The request value is concatenated directly in this method, so SR-SEC-SQL-INJECTION-001 reports it, and this rule does not report it again.
118Request data concatenated into SQL (SQL injection)SR-SEC-SQL-INJECTION-001ErrorSecurity
Reports a request string that enters SQL through string concatenation or StringBuilder and is passed to JDBC (execute, executeQuery, executeUpdate, executeLargeUpdate and addBatch of Statement; prepareStatement and prepareCall of Connection), createQuery and createNativeQuery of JPA, createQuery, createSQLQuery and createNativeQuery of Hibernate, or Spring JdbcTemplate. An attacker can rewrite the SQL and read or tamper with any data in the database. Request data means the parameters, headers, cookies, path and body of HttpServletRequest; Spring arguments annotated with @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS @QueryParam, @FormParam, @PathParam and the like; JSF getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The rule follows the data flow within the same method (assignment, string concatenation, StringBuilder, collections) and does not follow it after the data is passed to another method. Values converted to a number or date (Integer.parseInt and the like) and SQL-escaped values (StringEscapeUtils.escapeSql) are not reported, and neither are values checked beforehand with a regular expression or an allow-list (this can be changed with includeValidated). When a request value is passed as an argument to another method and concatenated there, SR-SEC-SQL-DYNAMIC-001 notifies at the place of concatenation. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
List<String> search(HttpServletRequest request) throws SQLException {
String name = request.getParameter("name");
List<String> out = new ArrayList<>();
try (Statement st = connection.createStatement();
ResultSet rs = st.executeQuery("SELECT id FROM customer WHERE name = '" + name + "'")) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
return out;
}Finding message (the engine's actual output)
Request data request.getParameter("name") is concatenated into SQL passed to java.sql.Statement.executeQuery (SQL injection).
Fix (the engine's suggestion)
Use ? placeholders (named :parameters in JPA) and bind the values with setXxx/setParameter; choose parts that cannot be bound, such as column names or the sort order, from a fixed allow-list.
OK example (code that is not reported)
List<String> safe(HttpServletRequest request) throws SQLException {
List<String> out = new ArrayList<>();
try (PreparedStatement ps = connection.prepareStatement("SELECT id FROM customer WHERE name = ?")) {
ps.setString(1, request.getParameter("name"));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
out.add(rs.getString(1));
}
}
}
return out;
}Values are passed with ? bind parameters.
Example that is not reported (boundary or exclusion)
PreparedStatement sorted(HttpServletRequest request) throws SQLException {
String column = request.getParameter("column");
if (!column.matches("[A-Za-z_]{1,30}")) {
throw new IllegalArgumentException("column");
}
return connection.prepareStatement("SELECT * FROM orders ORDER BY " + column);
}The column name is checked with a regular expression before it is concatenated, so it is not reported (this is how to write a place that cannot be bound, such as a sort column).
119Server HTTP destination decided by request data (SSRF)SR-SEC-SSRF-001WarningSecurity
Reports request data that enters the destination of an HTTP request sent from the server (SSRF). It reuses the taint tracking within a method and covers URL connections, the destination of the JDK HttpRequest, Spring RestOperations, OkHttp and Apache HTTP clients. A path or query after a fixed HTTP host is not reported: a string after a literal protocol and host (including one built with String.format, MessageFormat or StringBuilder), and a constant string that starts with /, ? or # after a configured base URL (a field or a local variable). Choosing the destination from a fixed table by a request value (Map.get) is not reported either. URL encoding and generic string checks do not indicate safety against SSRF. Flows across methods, DNS resolution results and chains of redirects are not inferred.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void requested(HttpServletRequest request) throws Exception { String target = request.getParameter("url"); URL u = new URL(target); u.openConnection(); }Finding message (the engine's actual output)
HTTP target of URL.openConnection comes from request data request.getParameter("url").
Fix (the engine's suggestion)
Choose destinations from a fixed mapping or validate scheme, host and resolved addresses; constrain redirects and network egress.
OK example (code that is not reported)
void fixedHost(HttpServletRequest request) throws Exception { new URL("https://example.org/search?q=" + request.getParameter("q")).openStream(); }The destination is the fixed https://example.org/ and the request value enters only the query, so it is not reported.
Example that is not reported (boundary or exclusion)
void fixedHostClient(HttpServletRequest request) throws Exception {
HttpRequest.newBuilder(URI.create("https://example.org/search?q=" + request.getParameter("q"))).GET().build();
}With the JDK HttpRequest too, it is not reported when the request value enters only the query after a fixed host.
120Fixed IV (nonce) used for encryptionSR-SEC-STATIC-IV-001WarningSecurity
Reports an IV or nonce that is a fixed byte sequence when it is passed to IvParameterSpec, GCMParameterSpec (the IV is the second argument) or ChaCha20ParameterSpec (the nonce). What is regarded as fixed is getBytes() of a string constant, a byte array literal, the result of Base64 or hex decoding of a constant, clone or Arrays.copyOf of these, and an all-zero array made with new byte[n]. A variable or field is covered only when all of its assignments are constants, and an array only when it is never written to within the file. An array filled with SecureRandom or the like, Cipher.getIV(), the leading part of the ciphertext, and an IV obtained from a parameter, a method call or configuration are not reported. An array filled in a loop, a value chosen by a conditional expression and an array in another file are not tracked and are not reported. Bouncy Castle's ParametersWithIV and the like are not checked. A fixed initial IV in CBC where each message starts with a random block (such as TLS 1.1 records) cannot be told apart and is reported. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public byte[] literalString(SecretKey key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec("0123456789abcdef".getBytes(StandardCharsets.UTF_8)));
return cipher.doFinal(data);
}Finding message (the engine's actual output)
Fixed IV (nonce) used for encryption: IvParameterSpec.
Fix (the engine's suggestion)
Generate a new random IV for every message (new SecureRandom().nextBytes(iv); 12 bytes for GCM, 16 bytes for CBC), or pass no IV and let the Cipher create one and read it with cipher.getIV(). Store the IV next to the ciphertext (usually in front of it) and read it from there when decrypting; never write it into the code.
OK example (code that is not reported)
public IvParameterSpec randomLocal() {
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
return new IvParameterSpec(iv);
}The IV is generated randomly with SecureRandom.
Example that is not reported (boundary or exclusion)
public SecretKeySpec keyIsNotAnIv() {
return new SecretKeySpec("0123456789abcdef".getBytes(), "AES");
}It is a fixed string, but what is passed to SecretKeySpec is a key, not an IV, so this rule does not report it (a fixed key is covered by SR-SEC-HARDCODED-KEY-001).
121Deprecated SSL/TLS protocol version usedSR-SEC-TLS-PROTOCOL-001WarningSecurity
Reports deprecated protocol versions chosen in the code (SSLv2, SSLv3, TLSv1, TLSv1.1, DTLSv1.0). The covered places are names passed to SSLContext.getInstance, setEnabledProtocols of SSLSocket, SSLServerSocket and SSLEngine and the protocol arrays of SSLParameters (including SSLv2Hello), the system properties https.protocols, jdk.tls.client.protocols and jdk.tls.server.protocols, mail.smtp.ssl.protocols of JavaMail, and so on. A name is judged even when it is held in a constant or variable. The name "SSL" does not choose a version and is an alias of TLS in OpenJDK, so it is not reported (in old JSSE and the like it is not necessarily TLS, so write TLS in such an environment). TLSv1.2 and later, and names obtained from a parameter, configuration or method call, are not reported either, and protocol settings specific to libraries such as Apache HttpClient and OkHttp are not checked. Requires type information.
- Category
- Communication and cookies
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public SSLContext contextTlsV1(TrustManager[] trust) throws Exception {
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(null, trust, new SecureRandom());
return context;
}Finding message (the engine's actual output)
Deprecated SSL/TLS protocol version used: TLSv1.
Fix (the engine's suggestion)
Use SSLContext.getInstance("TLS") (or "TLSv1.2", "TLSv1.3") and let the JDK choose by jdk.tls.client.protocols and jdk.tls.disabledAlgorithms; list only TLSv1.2 and TLSv1.3 in setEnabledProtocols. When the peer supports only an old protocol, upgrade the peer instead of lowering this side.
OK example (code that is not reported)
public SSLContext contextTls() throws Exception {
return SSLContext.getInstance("TLS");
}The protocol is specified only as TLS, and the choice of version is left to the JDK.
Example that is not reported (boundary or exclusion)
public SSLContext contextSsl() throws Exception {
return SSLContext.getInstance("SSL");
}SSL is only a name, not a version; in OpenJDK (SunJSSE) it is an alias of TLS, and on JDK 17 TLS 1.3 and 1.2 are enabled by default, so it is not reported.
122Trusting all certificates and host names (TLS verification disabled)SR-SEC-TRUST-ALL-001WarningSecurity
Reports a TrustManager whose checkServerTrusted checks nothing (it has no throw and calls no method other than logging), a HostnameVerifier or TrustStrategy that returns true unconditionally (as a method or a lambda), and the use of Apache HttpClient's NoopHostnameVerifier, AllowAllHostnameVerifier, ALLOW_ALL_HOSTNAME_VERIFIER, TrustAllStrategy or TrustSelfSignedStrategy. The other side of an HTTPS connection is no longer verified, so an attacker in the network path can impersonate the server and eavesdrop on or tamper with the traffic (a man-in-the-middle attack). detail is one of EMPTY_CHECK (a checkServerTrusted that checks nothing), RETURNS_TRUE (returns true) and ALLOW_ALL_CONSTANT (a constant or class that allows everything). Requires type information.
- Category
- Communication and cookies
- Target
- Java
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static SSLContext trustAll() throws Exception {
TrustManager[] all = {new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, all, null);
return ctx;
}Finding message (the engine's actual output)
TLS verification is switched off: X509TrustManager.checkServerTrusted.
Fix (the engine's suggestion)
Use the default TrustManager and host name verification; for self-signed certificates in test environments, import them into a dedicated truststore used only there.
OK example (code that is not reported)
static X509TrustManager pinned(X509TrustManager delegate, String expected) {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
delegate.checkClientTrusted(chain, authType);
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {
delegate.checkServerTrusted(chain, authType);
if (!chain[0].getSubjectX500Principal().getName().contains(expected)) {
throw new java.security.cert.CertificateException("unexpected server");
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return delegate.getAcceptedIssuers();
}
};
}It delegates to the default verification and then also checks the server.
Example that is not reported (boundary or exclusion)
static HostnameVerifier only(String expected) {
return (host, session) -> host.equalsIgnoreCase(expected);
}It compares the host name and does not return true unconditionally, so it is not reported.
123Use of a library version with a known serious vulnerabilitySR-SEC-VULN-DEPENDENCY-001WarningSecurity
Reports when a dependent library is a version affected by a known serious vulnerability (CVSS 7.0 or higher, of the kinds remote code execution, authentication or authorization bypass, deserialization attack chain and arbitrary file write). The covered sources are dependency elements in pom.xml (the version is taken from a direct entry, from the properties of the same file, or from log4j-bom or spring-framework-bom imported in the same file), jars of lib and var entries in an Eclipse .classpath, and jars in WEB-INF/lib of a web application; for jars only the file name is looked at. The list matched against is the vulnerability list built into the engine (log4j-core, Spring Framework, Struts 2 and so on; only advisories whose source could be verified are included), and a finding is made once per dependency and shows the numbers of all applicable advisories, the highest severity, the preconditions for exploitation and the versions to upgrade to. Versions managed by a parent POM or other BOMs, properties of other files, version ranges, LATEST and the test scope (by default) are not reported. The absence of a finding does not mean that a version is safe.
- Category
- Configuration and dependencies
- Target
- Configuration files (web.xml, pom.xml, .classpath, jar file names in WEB-INF/lib)
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>demo</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.14.1</version>
</dependency>
</dependencies>
</project>Finding message (the engine's actual output)
A library version with a known serious vulnerability is used: org.apache.logging.log4j:log4j-core 2.14.1 (CVE-2021-44228, GHSA-jfh8-c2jp-5v3q, CVE-2021-45046, GHSA-7rjr-3q55-vv33).
Fix (the engine's suggestion)
Upgrade org.apache.logging.log4j:log4j-core to at least one of these versions (the Java version or branch each is for is in brackets): 2.26.1 (Java 8+), 2.12.4 (Java 7). If a parent POM or a BOM manages the dependency, upgrade it where it is managed; for a jar file, replace the jar with the new version. Run the regression tests afterwards and check the result with a dependency scanner: this list gives a floor and does not guarantee that the new version has no other known vulnerability. If you have confirmed that the way the library is used is not affected by this vulnerability, suppress the finding in suppressions.yaml with the reason.
Note on the NG example: The four numbers in the message are the CVE and GHSA numbers of two advisories (CVE-2021-44228 of Log4Shell, and CVE-2021-45046, which came from the incomplete fix for it). log4j-core 2.14.1 is within the affected range of both, so the findings are merged into one.
OK example (code that is not reported)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>demo</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.20.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
</dependencies>
</project>spring-beans 5.2.20.RELEASE (the fixed version of the 5.2 line) and 5.2.25.RELEASE are not within the affected range.
Example that is not reported (boundary or exclusion)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>demo</artifactId>
<version>1.0</version>
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
</dependencies>
</project>The version is managed by a parent POM or a BOM and is not written in this POM, so it cannot be determined and is not reported (only an explanation is put in the information on the scope of the check).
124Insecure cipherSR-SEC-WEAK-CIPHER-001WarningSecurity
Reports an explicit constant passed to Cipher.getInstance that is DES, DESede (including TripleDES as an alias), RC2, RC4 or ARCFOUR, the ECB mode of AES and AES_128/192/256, or a PBE algorithm based on DES, DESede, RC2 or RC4. RSA/ECB is not regarded as symmetric-key ECB, and the default mode of a provider and dynamic algorithm names are not inferred. Methods, constructors, static and instance initializer blocks, field initializers and enum constant arguments are covered. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public Cipher weakCipher() throws Exception { return Cipher.getInstance("AES/ECB/PKCS5Padding"); }Finding message (the engine's actual output)
Weak cipher or symmetric ECB mode: AES/ECB/PKCS5Padding.
Fix (the engine's suggestion)
Switch to an authenticated AES mode such as Cipher.getInstance("AES/GCM/NoPadding") with a key of at least 128 bits and a new random IV for every message (never reuse an IV with the same key in GCM), and store the IV next to the ciphertext.
Note on the NG example: Even with AES, ECB mode encrypts equal plaintext blocks to equal ciphertext, and the structure of the data leaks.
OK example (code that is not reported)
public Cipher strongCipher() throws Exception { return Cipher.getInstance("AES/GCM/NoPadding"); }AES/GCM, which is authenticated encryption, is used.
Example that is not reported (boundary or exclusion)
public Cipher rsaGood() throws Exception { return Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding"); }RSA/ECB/... is not the ECB mode of a symmetric key but the customary notation for RSA, so it is not reported.
125Passwords hashed with MD5 or SHA-1SR-SEC-WEAK-HASH-001WarningSecurity
Reports password hashes computed with MD5 or SHA-1 (adjustable with algorithms; the default is MD2, MD4, MD5, SHA-1 and encoders that do nothing), and the use of Spring's Md5PasswordEncoder, ShaPasswordEncoder, LdapShaPasswordEncoder, NoOpPasswordEncoder and the like. Whether something is a password is judged from the surrounding names (when the method name, an argument name, the variable being hashed or the variable that receives the result contains a word such as password, passwd, pwd, pass, passphrase or credential). These algorithms are fast and have no salt or iterations, so if the hash values leak, the original passwords are quickly found with dictionary attacks or rainbow tables. MD5 used for checksums and the like that have nothing to do with passwords is not reported. A hash applied only once, such as SHA-256, is also unsuitable for passwords, so it can be added to algorithms. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static String hashPassword(String password) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(password.getBytes(StandardCharsets.UTF_8));
return toHex(digest);
}Finding message (the engine's actual output)
Passwords are hashed with MD5 (java.security.MessageDigest.getInstance).
Fix (the engine's suggestion)
Use a dedicated slow password hash: bcrypt (Spring Security's BCryptPasswordEncoder), PBKDF2 (PBKDF2WithHmacSHA256 with enough iterations and a random salt), scrypt or Argon2; existing hashes can be migrated at the user's next login.
OK example (code that is not reported)
static String checksum(byte[] content) throws NoSuchAlgorithmException {
return toHex(MessageDigest.getInstance("MD5").digest(content));
}MD5 used as a checksum of file contents has nothing to do with passwords, so it is not reported.
Example that is not reported (boundary or exclusion)
static String sha256(String password) {
return DigestUtils.sha256Hex(password);
}SHA-256 is not in the default algorithms, so it is not reported. However, a hash applied only once is unsuitable for passwords, so add it to algorithms if needed.
126Tokens and other secret values generated with java.util.RandomSR-SEC-WEAK-RANDOM-001WarningSecurity
Reports values generated with java.util.Random, ThreadLocalRandom, Math.random() or commons-lang RandomStringUtils that are stored or passed on as a token, session ID, nonce, salt, password, one-time password, CSRF token, authentication code, activation code or the like (judged by the words in the receiving variable, field, method name, call name or key name). These generators allow other values to be inferred from a few outputs, so an attacker can predict the token. Random numbers for games, sampling, backoff and the like, and numbers whose purpose is unknown, are not reported. Requires type information.
- Category
- Secrets and cryptography
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
static String newToken() {
String token = Long.toHexString(new Random().nextLong());
return token;
}Finding message (the engine's actual output)
token, newToken generated with a predictable random number generator (Random.nextLong).
Fix (the engine's suggestion)
Use java.security.SecureRandom (e.g. new SecureRandom().nextBytes(bytes), then encode) or UUID.randomUUID().
OK example (code that is not reported)
static String secureToken() {
return Long.toHexString(new SecureRandom().nextLong());
}It is generated with SecureRandom.
Example that is not reported (boundary or exclusion)
static int dice() {
return RANDOM.nextInt(6) + 1;
}Random numbers unrelated to security, such as a die roll, are not reported.
127EL value written with escape="false" in JSF (XSS)SR-SEC-XSS-ESCAPE-001WarningSecurity
Reports a component with escape="false" (h:outputText, h:outputFormat, PrimeFaces components and so on) in a Facelets page that writes a value with EL. The value is not HTML-escaped and is written into the page as HTML. When the EL reads the request directly (param, paramValues, header, headerValues, cookie), it is reflected XSS (source is REQUEST); when it reads a bean property, it is stored XSS if that property holds a string that a user entered earlier (source is BEAN; the origin has to be checked). Strings from a resource bundle (the variable of f:loadBundle or of resource-bundle in faces-config) are the application's own strings and are not reported, and constant values without EL are not reported either. With sources, only one of the two origins can be reported.
- Category
- XSS and redirects
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:body>
<h:outputText value="Result: #{param.message}" escape="false"/>
</h:body>
</html>Finding message (the engine's actual output)
h:outputText writes Result: #{param.message} with escape="false" (source: REQUEST).
Fix (the engine's suggestion)
Remove escape="false" (values are escaped by default); where formatted text must be shown, sanitize the HTML on the server with an allow-list (e.g. the OWASP Java HTML Sanitizer or Jsoup.clean) first.
OK example (code that is not reported)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:body>
<h:outputText value="#{notice.message}"/>
<h:outputText value="#{param.message}" escape="true"/>
</h:body>
</html>The value is written with the default (escape="true") so that it is HTML-escaped.
Example that is not reported (boundary or exclusion)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core">
<f:loadBundle basename="texts" var="texts"/>
<h:body>
<h:outputText value="#{texts.welcomeHtml}" escape="false"/>
</h:body>
</html>A message from f:loadBundle is the application's own string (including HTML), so it is not reported.
128Request data written to the response without escaping (XSS)SR-SEC-XSS-WRITER-001WarningSecurity
Reports a request string that is written to the response without HTML escaping: print, println, write, append, printf and format of response.getWriter() or getOutputStream() (or a variable that holds it), the JspWriter of JSP, and ResponseWriter.write of JSF (writeText escapes). An attacker can run arbitrary script in the page (reflected XSS). Request data means the parameters, headers, cookies, path and body of HttpServletRequest; Spring arguments annotated with @RequestParam, @PathVariable, @RequestHeader, @CookieValue, @RequestBody or @ModelAttribute, and handler arguments without annotations; JAX-RS @QueryParam, @FormParam, @PathParam and the like; JSF getRequestParameterMap() and @ManagedProperty("#{param.x}"); OmniFaces @Param; and the ActionForm of Struts 1 and the action properties of Struts 2. The rule follows the data flow within the same method (assignment, string concatenation, StringBuilder, collections) and does not follow it after the data is passed to another method. Values that have been HTML-escaped (StringEscapeUtils.escapeHtml, Spring's HtmlUtils, OWASP Encoder, URLEncoder and the like) or converted to a number are not reported, and neither are cases where the method sets a content type other than HTML, such as JSON or plain text. Requires type information.
- Category
- XSS and redirects
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void hello(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().println("<p>Hello, " + request.getParameter("name") + "</p>");
}Finding message (the engine's actual output)
Request data request.getParameter("name") is written to the response without escaping (PrintWriter.println).
Fix (the engine's suggestion)
HTML-escape before writing (StringEscapeUtils.escapeHtml4, HtmlUtils.htmlEscape, the OWASP Encoder's Encode.forHtml); better, use templates that escape automatically (JSF, JSP <c:out>, Thymeleaf).
OK example (code that is not reported)
void helloEscaped(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().println("<p>Hello, " + StringEscapeUtils.escapeHtml(request.getParameter("name")) + "</p>");
}The value is written after escaping it with StringEscapeUtils.escapeHtml.
Example that is not reported (boundary or exclusion)
void json(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.getWriter().write("{\"name\":\"" + request.getParameter("name") + "\"}");
}The content type is application/json and is not interpreted as HTML, so it is not reported.
129XML parser that does not forbid external entities (XXE)SR-SEC-XXE-001WarningSecurity
Reports DocumentBuilderFactory, SAXParserFactory, XMLInputFactory, TransformerFactory, SchemaFactory, XMLReaderFactory, dom4j's SAXReader and JDOM's SAXBuilder that are used without any setting that forbids DTDs and external entities (disallow-doctype-decl set to true; external-general-entities, external-parameter-entities and load-external-dtd set to false; FEATURE_SECURE_PROCESSING; ACCESS_EXTERNAL_DTD/SCHEMA/STYLESHEET set to ""; SUPPORT_DTD and IS_SUPPORTING_EXTERNAL_ENTITIES set to false). When XML passed in from outside is parsed, an attacker can read files on the server, access the internal network or exhaust resources (XXE). A factory in a local variable is judged by the settings in the same method, and a factory in a field by the settings in the whole class. A factory that is returned to the caller or passed to another method is not reported (because it may be configured there). A factory that is used only to create a document for output (newDocument, getDOMImplementation) or only to write out a DOM tree (newTransformer() without a stylesheet, with DOMSource) does not read XML, so it is not reported. Only the standard JAXP implementation of the JDK rejects external DTDs and entities with FEATURE_SECURE_PROCESSING; when WEB-INF/lib contains another implementation such as an old Xerces, XXE is not prevented, so set disallow-doctype-decl. Whether external data is parsed cannot be determined statically, so the finding may be suppressed when an internal fixed file is parsed. Requires type information.
- Category
- Parsing external data
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
Document parse(InputStream in) throws Exception {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
}Finding message (the engine's actual output)
DocumentBuilderFactory parses XML without blocking DTDs and external entities.
Fix (the engine's suggestion)
Right after creating it, set factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); where DOCTYPE must be allowed, turn off external entities (external-general-entities and external-parameter-entities false) and set ACCESS_EXTERNAL_DTD to "". For XMLInputFactory set SUPPORT_DTD to false.
OK example (code that is not reported)
Document safe(InputStream in) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setXIncludeAware(false);
return dbf.newDocumentBuilder().parse(in);
}DOCTYPE declarations are rejected with disallow-doctype-decl.
Example that is not reported (boundary or exclusion)
Document newExport() throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
return db.newDocument();
}It only creates a document for output (newDocument) and does not parse XML, so it is not reported.
130Missing validation of ZIP extraction pathsSR-SEC-ZIP-PATH-001WarningSecurity
Tracks the value of ZipEntry.getName until it reaches a local path (in any part of a string concatenation), a write with Files, or FileOutputStream or FileWriter (writes inside lambdas are also checked). It does not report the case where only the last element of the name is taken (Path.getFileName, File.getName). A path normalized with normalize, toRealPath or getCanonicalFile/getCanonicalPath is regarded as validated when it is dominated by a startsWith guard against the directory it was resolved against (including toPath/toFile conversions and combinations with || and &&), and so is a guard that appends File.separator to the string of the canonical path. Using only normalize, a wrong root, resolve().startsWith without normalization, and a prefix match of a string without a separator are not regarded as validation. Races involving symbolic links are not handled. Methods, constructors, static and instance initializer blocks, and also lambdas in field initializers and in the arguments of enum constants are covered. Requires type information.
- Category
- Injection
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
public void zipBad(ZipEntry entry,Path root,byte[] bytes) throws Exception { var target=root.resolve(entry.getName()); Files.write(target,bytes); }Finding message (the engine's actual output)
Archive entry path reaches a file write: target.
Fix (the engine's suggestion)
Normalize the extraction directory, resolve the entry against it and normalize that too, and reject the entry unless the result still starts with the directory: Path dest = destDir.toAbsolutePath().normalize(); Path target = dest.resolve(entry.getName()).normalize(); if (!target.startsWith(dest)) throw new IOException("Bad entry: " + entry.getName());
Note on the NG example: If an entry name contains ../, a file outside root can be overwritten (Zip Slip).
OK example (code that is not reported)
public void zipGood(ZipEntry entry,Path root,byte[] bytes) throws Exception { var target=root.resolve(entry.getName()).normalize(); if(!target.startsWith(root))throw new IOException(); Files.write(target,bytes); }The path is normalized, and it is written only after checking that it is under root.
Example that is not reported (boundary or exclusion)
public void zipBaseName(ZipInputStream zis, ZipEntry entry, Path root) throws IOException {
String name = Paths.get(entry.getName()).getFileName().toString();
Files.copy(zis, root.resolve(name));
}Only the last element of the entry name (the file name) is used, so it cannot climb up the directories.
131Mismatch between JDBC parameter numbers and SQL placeholdersSR-SQL-PARAM-001WarningGeneral
Trial rule: for a PreparedStatement with a fixed SQL string whose parameters are bound with constant indices in the same method, it checks whether an index beyond the number of placeholders is set and whether any placeholder is never bound. Dynamic SQL, indices computed at run time, named parameters and binding across methods are not covered. It only parses text and does not execute SQL or connect to a database.
- Category
- SQL and data access
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void tooMany(Connection c, int a, int b, int d) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("insert into score (pupil, subject, value) values (?, ?, ?)")) {
ps.setInt(1, a);
ps.setInt(2, b);
ps.setInt(4, d);
}
}Finding message (the engine's actual output)
SQL has 3 placeholders, bound indices [1, 2, 4]; excess: [4], unbound: [3].
Fix (the engine's suggestion)
Compare the index of every setXxx with the order of the ? in the SQL (indices start at 1, stay within the number of placeholders, and every placeholder gets a value), and change them together when the SQL columns change. The tool does not execute SQL, so add a database test that runs this statement.
OK example (code that is not reported)
void matching(Connection c, int id, int year) throws SQLException {
PreparedStatement ps = c.prepareStatement(BY_ID);
ps.setInt(1, id);
ps.setInt(2, year);
}The 2 placeholders match the bound numbers 1 and 2 (BY_ID is the constant "select name from pupil where id = ? and year = ?").
Example that is not reported (boundary or exclusion)
void dynamic(Connection c, String table, int id) throws SQLException {
PreparedStatement ps = c.prepareStatement("select * from " + table + " where id = ?");
ps.setInt(2, id);
}Dynamic SQL built by string concatenation is not covered by the check.
132One input increased and another disappeared in an aggregation region across a changeSR-SVN-REFDELTA-001WarningGeneral
Compares the number of direct references between old and new ordered input regions that can be matched reliably (for example, a place where a chain of additions was rewritten as an array), and reports when references to one variable increased while another variable disappeared from the region. It runs only when two snapshots are compared (two SVN revisions, or a local modification and BASE), and it draws no conclusion when the matching is ambiguous.
- Category
- SVN revision comparison
- Target
- Java
- Confidence
- Medium
- When it runs
- Only when two revisions are compared
- Default
- Enabled
NG example (code that is reported)
// Before the change (revision 1)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Integer total = value1 + value2 + value3
+ value4 + value5 + value6
+ value7 + value8 + value9;
return new Object[] {total};
}
// After the change (revision 2)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] values = {
value1, value2, value3,
value4, value5, value6,
value7, value7, value9
};
return values;
}Finding message (the engine's actual output)
Compared with r1, the matched aggregation region changed value7: 1→2, value8: 1→0 (reads 9→9).
Fix (the engine's suggestion)
Check whether value8 belongs at this position; add regression tests that use a distinct value per input.
Note on the NG example: When a chain of additions was rewritten as an array, value7 ended up in the eighth position and value8 disappeared.
OK example (code that is not reported)
// Before the change (revision 2)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] values = {
value1, value2, value3,
value4, value5, value6,
value7, value7, value9
};
return values;
}
// After the change (revision 3)
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] values = {
value1, value2, value3,
value4, value5, value6,
value7, value8, value9
};
return values;
}In a comparison with the version where value8 is restored, no input has disappeared, so it is not reported.
Example that is not reported (boundary or exclusion)
// Before the change
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Integer total = value1 + value2 + value3
+ value4 + value5 + value6
+ value7 + value8 + value9;
return new Object[] {total};
}
// After the change
Object[] aggregate(Integer value1, Integer value2, Integer value3, Integer value4, Integer value5,
Integer value6, Integer value7, Integer value8, Integer value9) {
Object[] first = {value1, value2, value3, value4, value5, value7, value7};
Object[] second = {value3, value4, value5, value6, value7, value9};
return new Object[] {first, second};
}When the old and new regions cannot be matched uniquely, for example when one region is split into two arrays, it draws no conclusion and does not report.
133Code still runs after a redirect or forward (missing return)SR-WEB-EXEC-AFTER-REDIRECT-001WarningSecurity
Reports when, after HttpServletResponse.sendRedirect or RequestDispatcher.forward of the Servlet API (javax.servlet and jakarta.servlet) is called as a statement, code that runs until the end of the method remains in the same block or an enclosing block. These calls return normally and the method does not end there, so without a return or throw the rest is executed (CWE-698). If chain.doFilter follows a redirect in a filter, the request reaches the protected page and the authentication check becomes ineffective. It follows the code out through nested if, try, switch and so on, and for the body of a loop it looks only at the rest of the same iteration. It does not report when a return or throw follows immediately, when all branches of an if/else exit, when the redirect is the last statement, when it is inside a lambda, or when what follows is only logging and close/flush. Assignments and other method calls (including session.invalidate()) are regarded as code that is executed. A redirect inside a helper method is not looked at.
- Category
- XSS and redirects
- Target
- Java
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
void filterMissingReturn(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (!loggedIn(request)) {
response.sendRedirect("/login");
}
chain.doFilter(req, res);
}Finding message (the engine's actual output)
Code still runs after a redirect or forward: response.sendRedirect("/login").
Fix (the engine's suggestion)
Return right after sendRedirect (or forward), and do not call chain.doFilter after it in a filter. Keep the branch that redirects and the branch that goes on apart with if/else, and make every path of the redirecting branch end with return.
Note on the NG example: The message points to the sendRedirect call, but the problem is what comes after it. sendRedirect does not end the method, so even for a request that is not logged in, chain.doFilter(req, res) after the if is executed and the request reaches the protected page (authentication bypass).
OK example (code that is not reported)
void guardWithReturn(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!loggedIn(request)) {
response.sendRedirect("/login");
return;
}
chain.doFilter(request, response);
}Because it returns right after the redirect, a request that is not logged in does not proceed to chain.doFilter.
Example that is not reported (boundary or exclusion)
void loopBodyEndsWithRedirect(HttpServletResponse response, String[] urls) throws IOException {
for (String url : urls) {
response.sendRedirect(url);
}
doMore();
}The redirect is the last statement of the loop body, and the next iteration and the code after the loop are not followed, so it is not reported.
134Unresolved JSF component referenceSR-XHTML-COMPONENT-REF-001WarningGeneral
In a complete local view, it checks the for of h:message, h:messages and h:outputLabel and the execute and render of f:ajax. f:ajax is resolved from the nearest naming container, as findComponent does, and the first part of the path may also be the id of the naming container itself (render="f" and execute="f:qty" inside form f). for searches the ancestors and the whole view as Mojarra does, and it reports only when it cannot be resolved in any naming container of the view. Fragment pages (a ui:composition without a template, ui:component, and pages that are included in other pages or used as templates), includes, templates, definitions of composite components, iterations, JSTL conditions, unknown component libraries, dynamic IDs and search keywords are not judged.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:form id="edit"><h:inputText id="name"/><h:message for="nmae"/></h:form></body></html>Finding message (the engine's actual output)
Unresolved static JSF component reference: nmae (for).
Fix (the engine's suggestion)
Correct the component id or the reference path (an absolute one starting with : where needed), and add positive and negative regression cases.
Note on the NG example: There is no component with id="nmae", which <h:message for="nmae"/> refers to (a typo for the input with id="name").
OK example (code that is not reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:form id="edit"><h:inputText id="name"/><h:message for="name"/></h:form></body></html>for matches the id="name" of an input in the same form.
Example that is not reported (boundary or exclusion)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:form id="edit"><h:commandButton><f:ajax render="@form @none"/></h:commandButton></h:form></body></html>@form and @none are JSF search keywords, not component ids, so they are not reported.
135JSF date converter without timeZone (converts in GMT)SR-XHTML-DATETIME-TZ-001WarningGeneral
Reports a JSF date converter in a Facelets page (f:convertDateTime, or javax.faces.DateTime specified in a converterId or converter attribute) that has no timeZone (always reported for a converterId or converter attribute, because timeZone cannot be written there). Without timeZone, java.util.Date is interpreted and written in GMT, so a date from 0:00 to 8:59 Japan time is displayed as the previous day, and a time that is entered is also off by 9 hours. A blank timeZone also results in GMT, so it is reported. A timeZone that is a literal or EL, a type that is a java.time type (such as localDate), a converter that is replaced by a later converter of the same component, and PrimeFaces p:calendar are not reported. When the context parameter javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE is set to true in web.xml, nothing except a blank timeZone is reported. No judgment is made either when the standard date converter is replaced in the Faces configuration: if a converter whose converter-id is javax.faces.DateTime (jakarta.faces.DateTime) has a converter-class in WEB-INF/faces-config.xml, or in a file listed in the web.xml context parameter javax.faces.CONFIG_FILES (jakarta.faces.CONFIG_FILES), the rule does not analyze that class, so it does not report, and it outputs the note DATE_CONVERTER_REPLACED (the check remains complete; a blank timeZone is reported). When a configuration file cannot be read, it does not report and outputs the coverage note FACES_CONFIG_UNREADABLE. META-INF/faces-config.xml in a library, @FacesConverter and registration in code are not visible, so it reports as usual.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:body>
<!-- the order time is a java.util.Date: the converter shows it in GMT -->
<h:outputText value="#{order.orderedAt}">
<f:convertDateTime pattern="yyyy/MM/dd HH:mm"/>
</h:outputText>
</h:body>
</html>Finding message (the engine's actual output)
f:convertDateTime has no time zone: dates are converted in GMT, which is 9 hours off Japan.
Fix (the engine's suggestion)
Give the converter a time zone, for example <f:convertDateTime pattern="yyyy/MM/dd" timeZone="Asia/Tokyo"/> (an expression works too). If the whole application should use the time zone of the server, set javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE=true in web.xml (jakarta.faces. in Jakarta Faces). If the system time zone is made the default some other way, set this rule's parameter systemTimeZone to true under ruleOverrides in .smartreviewer/project.yaml. A converter declared by a converter attribute or a converterId cannot take a timeZone: use the f:convertDateTime tag instead. A timeZone that is empty needs a time zone or has to go.
OK example (code that is not reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:body>
<h:outputText value="#{order.orderedAt}"><f:convertDateTime pattern="yyyy/MM/dd" timeZone="Asia/Tokyo"/></h:outputText>
<h:outputText value="#{order.shippedAt}"><f:convertDateTime pattern="yyyy/MM/dd" timeZone="JST"/></h:outputText>
<h:outputText value="#{order.paidAt}"><f:convertDateTime type="both" timeZone="GMT+9"/></h:outputText>
</h:body>
</html>A timeZone is specified (the literals Asia/Tokyo, JST and GMT+9).
Example that is not reported (boundary or exclusion)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:body>
<h:inputText value="#{order.count}" converter="javax.faces.DateTime"><f:convertNumber/></h:inputText>
<h:inputText value="#{order.day}" converter="javax.faces.DateTime"><f:convertDateTime type="localDate"/></h:inputText>
<h:inputText value="#{order.when}"><f:converter converterId="javax.faces.DateTime"/><f:converter converterId="app.JapaneseDateConverter"/></h:inputText>
<h:inputText value="#{order.when}" converter="javax.faces.DateTime"><f:converter binding="#{orderBean.dateConverter}"/></h:inputText>
</h:body>
</html>The javax.faces.DateTime of a converter attribute or of f:converter is replaced by a later converter of the same component (a numeric converter, a java.time type, another id, or one with binding) and is not used, so it is not reported.
136Duplicate component ID in the same naming containerSR-XHTML-DUP-ID-001ErrorGeneral
Reports two JSF components in a Facelets page (tags of component libraries such as h:, f: and p:, composite components, and HTML pass-through elements that have a jsf: attribute and are converted to components by JSF, whose id is jsf:id) that use the same id within the same naming container (h:form and the pass-through element form, h:dataTable, ui:repeat, f:subview, PrimeFaces p:dataTable, p:tabView and so on; if there is none, the whole view). "Duplicate component ID" (IllegalStateException) occurs when the view is built or saved, and the page cannot be displayed. rendered="false" does not avoid it (the component stays in the component tree). Components that are in different c:if, c:when/c:otherwise or ui:define and may not be built at the same time, components in ui:remove, and components whose id contains EL are not reported. Only the inside of one file is checked; parts that are combined with ui:include or templates are not checked.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- High
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
xmlns:my="http://xmlns.jcp.org/jsf/composite/components">
<h:body>
<h:form id="order">
<h:outputLabel for="name" value="Customer"/>
<h:inputText id="name" value="#{order.customerName}"/>
<h:outputLabel for="name" value="Delivery"/>
<h:inputText id="name" value="#{order.deliveryName}"/>
<h:commandButton id="save" value="Save" action="#{order.save}"/>
</h:form>
</h:body>
</html>Finding message (the engine's actual output)
The component id name is used twice in h:form#order (h:inputText on line 13 has it already).
Fix (the engine's suggestion)
Give one of the components another id; if only one of them is ever needed, keep the other out of the tree with c:if or c:choose.
OK example (code that is not reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
xmlns:my="http://xmlns.jcp.org/jsf/composite/components">
<h:body>
<h:form id="first">
<h:inputText id="name" value="#{order.customerName}"/>
</h:form>
<h:form id="second">
<h:inputText id="name" value="#{order.deliveryName}"/>
<h:dataTable id="lines" value="#{order.lines}" var="line">
<h:column>
<h:inputText id="name" value="#{line.name}"/>
</h:column>
</h:dataTable>
<ui:repeat value="#{order.notes}" var="note">
<h:outputText id="name" value="#{note}"/>
</ui:repeat>
<p:dataTable id="history" value="#{order.history}" var="h">
<p:column>
<h:outputText id="name" value="#{h}"/>
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>The same id is not a duplicate if the components are in different forms, data tables or ui:repeat (each of which is a separate naming container).
Example that is not reported (boundary or exclusion)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:p="http://primefaces.org/ui"
xmlns:my="http://xmlns.jcp.org/jsf/composite/components">
<h:body>
<h:form id="profile">
<c:choose>
<c:when test="#{user.admin}">
<h:inputText id="role" value="#{user.role}"/>
</c:when>
<c:otherwise>
<h:outputText id="role" value="#{user.role}"/>
</c:otherwise>
</c:choose>
</h:form>
</h:body>
</html>c:when and c:otherwise are not built at the same time, so they are not reported.
137EL referencing a property or method that does not exist in the beanSR-XHTML-EL-001InfoGeneral
Notifies when, in #{bean.member} of a Facelets page, bean is a bean that can be identified statically (CDI @Named or @Model, JSF @ManagedBean, a managed bean of faces-config) but member is neither a JavaBeans property nor a public method of that class or any of its supertypes. Supertypes are read from the sources and from the bytecode on the class path (jars, JDK). Variables set to a bean with c:set or ui:param, and variables passed from another page (when the type on every route is the same), are also checked. In EL of value attributes and body text a JavaBeans property is required, and a method name alone such as isFull is not accepted; checkout() and method expressions (such as action) are checked as methods. Deep members are also checked, through the type returned by a getter and the element type of an iteration variable (ui:repeat, h:dataTable, c:forEach and so on). EL is resolved against run-time objects, so it is reported only when the declared type can be fixed as the run-time type (a final class, a record, a class of the project without subclasses and so on); for an interface, an abstract class or a type with subclasses, only a note (EL_TYPE_NOT_EXACT) is recorded. Implicit objects, custom EL resolvers, dynamic EL, beans whose supertypes cannot be found, Lombok accessors, beans that are a Map, List or ResourceBundle, the content of ui:remove and design-time markup outside ui:composition are not covered. Entities and DTDs in XHTML are not resolved, and external resources are not loaded.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- Low
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:body>
<h:outputText value="#{orders.totl}"/>
</h:body>
</html>Finding message (the engine's actual output)
#{orders.totl}: example.OrderBean has no totl.
Fix (the engine's suggestion)
Check the member name (closest member: total); exercise the page after the change.
Note on the NG example: #{orders} is an OrderBean (@Named("orders")), which has getTotal() but no property named totl.
OK example (code that is not reported)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions">
<h:body>
<h:outputText value="#{orders.total}" rendered="#{orders.paid and not empty orders.items}"/>
<h:outputText value="#{orders.locale} #{orders['total']} #{orders.items.size()}"/>
<h:commandButton value="#{msg.save}" action="#{orders.save}"/>
<ui:repeat var="item" value="#{orders.items}">#{item.length()} #{fn:length(item)}</ui:repeat>
<h:outputText value="#{facesContext.viewRoot.locale} #{legacy.name} #{orders.total gt 0 ? orders.total : 0}"/>
</h:body>
</html>Only members that exist are referenced (getters, boolean isX, inherited properties, action methods, method calls, page variables, resource bundles, implicit objects, faces-config beans, access with square brackets, and so on).
Example that is not reported (boundary or exclusion)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:body>
<h:outputText value="#{labels.greeting}"/>
</h:body>
</html>#{labels} is a bean that is a java.util.Map, so #{labels.greeting} is a key lookup at run time and is not checked.
138Nested JSF formsSR-XHTML-NESTED-FORM-001WarningGeneral
Reports nested h:form or HTML form elements that are certain to be rendered on the same page. Ancestors with ui:remove, rendered=false or a dynamic rendered are not covered, and external templates are not expanded. The subject is the inner form (h:form#id if it has a static id) and the detail is the outer form.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:form><h:form/></h:form></body></html>Finding message (the engine's actual output)
Nested rendered forms: h:form inside h:form.
Fix (the engine's suggestion)
Move the inner form out of the outer one or split them into sibling forms, and add positive and negative regression cases.
Note on the NG example: In HTML, forms cannot be nested, and submitting the inner form no longer works correctly.
OK example (code that is not reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:form/><h:form/></body></html>The forms are placed side by side (not nested).
Example that is not reported (boundary or exclusion)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"><h:form><c:if test="#{enabled}"><h:form/></c:if></h:form></html>A form inside c:if is not reported, because it cannot be determined whether the condition holds.
139JSF property read/write contractSR-XHTML-PROPERTY-ACCESS-001WarningGeneral
Examines the value expressions of standard HTML input and output components and checks that each property that is read has a public getter and that the terminal property to which an input assigns has a public setter. An input that ends with an index (#{bean.map[key]}) assigns through a collection, so only the getter of the collection property is required; when a further reference follows the index (#{bean.rows[i].name}), the assignment target is not judged. Expressions inside indices, operands and arguments are only read. Only exact and complete types are checked, and read-only and disabled inputs are exempt from the setter only. Variables passed from other pages (ui:param and so on), EL implicit objects, resource bundle variables of faces-config and local variables are not regarded as beans, and nothing is checked when a dynamic resolver or the rendering condition is uncertain.
- Category
- JSF/XHTML
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:inputText value="#{orders.readOnly}"/></body></html>Finding message (the engine's actual output)
JSF property access mismatch: #{orders.readOnly} has no public setReadOnly(…).
Fix (the engine's suggestion)
Add the public getter or setter, or make the input read-only, and add positive and negative regression cases.
Note on the NG example: The readOnly property has only a getter, so a value cannot be assigned when the input component is submitted, which results in a PropertyNotWritableException.
OK example (code that is not reported)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:inputText value="#{orders.name}"/></body></html>Both a getter and a setter exist.
Example that is not reported (boundary or exclusion)
<html xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core" xmlns:ui="http://xmlns.jcp.org/jsf/facelets"><body><h:inputText disabled="true" value="#{orders.readOnly}"/></body></html>A disabled input is not submitted and does not assign a value, so a missing setter is not reported (a getter for display is still required).
140EL written into script elements and event attributes (XSS)SR-XHTML-SCRIPT-EL-001WarningSecurity
Reports EL (#{...} and ${...}) written in a Facelets page at a position where it is executed as JavaScript. The covered positions are the body of a script element, on* event attributes of elements and components (onclick and so on; also onevent of f:ajax and oncomplete of PrimeFaces), and attribute values that start with javascript:. At these positions HTML escaping does not help (the content of a script is output as it is, and a quote escaped inside an attribute is turned back into the original quote before the browser runs it), and when a value that a user can manipulate (a request parameter, stored input, a string property of a bean) gets in, an attacker can run arbitrary script. The following are not reported: constants; values of a bean property whose declared type is a number, boolean, enum, date-time or UUID; resource bundles; values fixed at deployment time such as request.contextPath; calls that return a number such as size(); and values wrapped in of:escapeJS inside quotes. fn:escapeXml is not a substitute for escapeJS. script with src and style are not checked.
- Category
- XSS and redirects
- Target
- XHTML (JSF/Facelets)
- Confidence
- Medium
- When it runs
- Every review
- Default
- Enabled
NG example (code that is reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions"
xmlns:of="http://omnifaces.org/functions"
xmlns:app="http://example.com/functions"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<script type="text/javascript">
var name = '#{order.name}';
</script>
</h:body>
</html>Finding message (the engine's actual output)
The EL #{order.name} in <script> is written into JavaScript, where HTML escaping does not protect it.
Fix (the engine's suggestion)
Do not put data into script. Write the value into a data-* attribute (JSF escapes it as an attribute) and read it with dataset or an event listener, or write JSON and parse it with JSON.parse (write < in the JSON as \u003c). If it has to go into a string literal, use a JavaScript escaping function and keep it inside the quotes, for example '#{of:escapeJS(bean.name)}' of OmniFaces (fn:escapeXml is not enough: it leaves backslashes and line breaks alone). Make the property a number, a boolean or an enum.
Note on the NG example: The value of an EL expression inside a script element is output as it is, without escaping. If order.name contains a string such as '; alert(1); //, it can end the string literal and run arbitrary script.
OK example (code that is not reported)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions"
xmlns:of="http://omnifaces.org/functions"
xmlns:app="http://example.com/functions"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<script type="text/javascript">
var a = '#{of:escapeJS(order.name)}', b = "#{of:escapeJS(param.q)}";
</script>
<a href="#" onclick="go('#{of:escapeJS(order.name)}')">go</a>
</h:body>
</html>Inside the quotes, the value is passed through a JavaScript escaping function (of:escapeJS of OmniFaces).
Example that is not reported (boundary or exclusion)
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions"
xmlns:of="http://omnifaces.org/functions"
xmlns:app="http://example.com/functions"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<script type="text/javascript">
var d = '#{order.date}';
var day = '#{order.day}';
var at = '#{order.moment}';
var id = '#{order.uuid}';
</script>
</h:body>
</html>When the declared type of a bean property is a date-time or a UUID, the string of the value consists only of digits, letters and date symbols and cannot break a string literal, so it is not reported.
No rule matches.