Skip to main content

Java Coding Violations

Cyclopt analyzes your Java code to identify coding and security violations. Each check below lists its Rule ID, a description, a severity, and its category.

tip

Use a check's Rule ID to silence a finding in code with a cyclopt-ignore comment, or to exclude it project-wide in the configuration file.


Avoid Branching Statement As Last In Loop

Rule ID: PMD_ABSALIL

Description: Using a branching statement as the last part of a loop may be a bug, and/or is confusing

Label Label

Bad Example
for (int j = 0; j < 5; j++) {
if (j*j <= 12) {
continue;
}
break;
}
Good Example
for (int j = 0; j < 5; j++) {
if (j*j > 12) {
break;
}
}

Avoid Decimal Literals In Big Decimal Constructor

Rule ID: PMD_ADLIBDC

Description: "One might assume that the result of ""new BigDecimal(0.1)"" is exactly equal to 0.1, but it is not because 0.1 cannot be represented exactly as a double (or as a binary fraction of any finite length)"

Label Label

Bad Example
BigDecimal bd = new BigDecimal(2.456);
Good Example
BigDecimal bd = new BigDecimal("2.456");

Avoid Multiple Unary Operators

Rule ID: PMD_AMUO

Description: Avoid Multiple Unary Operators

Label Label

Bad Example
int k = - -1;
int l = + - +1;
int m = ~~4;
boolean a = !!true;
boolean b = !!!true;

Avoid Thread Group

Rule ID: PMD_ATG

Description: Avoid using java.lang.ThreadGroup. Although it is intended to be used in a threaded environment it contains methods that are not thread-safe

Label Label

Bad Example
public class Beta {
void beta() {
ThreadGroup tg = new ThreadGroup("My threadgroup");
tg = new ThreadGroup(tg, "my thread group");
tg = Thread.currentThread().getThreadGroup();
tg = System.getSecurityManager().getThreadGroup();
}
}

Avoid Using Hard Coded IP

Rule ID: PMD_AUHCIP

Description: Application with hard-coded IP addresses can become impossible to deploy in some cases. Externalizing IP adresses is preferable

Label Label

Bad Example
public class Alpha {
private String ip = "127.0.0.1";
}

Avoid Using Octal Values

Rule ID: PMD_AUOV

Description: Integer literals should not start with zero since this denotes that the rest of literal will be interpreted as an octal value

Label Label

Bad Example
int i = 010;
Good Example
int i = 10;

Big Integer Instantiation

Rule ID: PMD_BII

Description: Don’t create instances of already existing BigInteger

Label Label

Bad Example
BigInteger bf = new BigInteger(1);
Good Example
bf = BigInteger.ONE;

Boolean Instantiation

Rule ID: PMD_BI

Description: Avoid instantiating Boolean objects

Label Label

Bad Example
Boolean foo = new Boolean("true");

Broken Null Check

Rule ID: PMD_BNC

Description: The null check is broken since it will throw a NullPointerException itself

Label Label

Bad Example
public String foo(String string) {
if (string!=null || !string.equals(""))
return string;
if (string==null && string.equals(""))
return string;
}
Good Example
public String foo(String string) {
if (string!=null && !string.equals(""))
return string;
if (string==null || string.equals(""))
return string;
}

Check Result Set

Rule ID: PMD_CRS

Description: Always check the return values of navigation methods (next, previous, first, last) of a ResultSet. If the value return is ‘false’, it should be handled properly

Label Label

Bad Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT testvalue FROM testtable");
rst.next();
String testName = rst.getString(1);
Good Example
Statement stat = conn.createStatement();
ResultSet rst = stat.executeQuery("SELECT name FROM person");
if (rst.next()) {
String firstName = rst.getString(1);
} else {
// handle else
}

Check Skip Result

Rule ID: PMD_CSR

Description: The skip() method may skip a smaller number of bytes than requested

Label Label

Bad Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}
}
Good Example
public class Alpha {

private FileInputStream _s = new FileInputStream("file");

public void skip(int n) throws IOException {
_s.skip(n);
}

public void skipExactly(int n) throws IOException {
while (n != 1) {
long skipped = _s.skip(n);
if (skipped == 1)
throw new EOFException();
n -= skipped;
}
}
}

Class Cast Exception With To Array

Rule ID: PMD_CCEWTA

Description: When deriving an array of a specific class from your Collection, one should provide an array of the same class as the parameter of the toArray() method. Doing otherwise you will will result in a ClassCastException

Label Label

Bad Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray();
Good Example
Collection a = new ArrayList();
Integer obj = new Integer(1);
a.add(obj);
Integer[] b = (Integer [])a.toArray(new Integer[a.size()]);

Collapsible If Statements

Rule ID: PMD_CIS

Description: Sometimes two consecutive ‘if’ statements can be consolidated by separating their conditions with a boolean short-circuit operator

Label Label

Bad Example
void foo() {
if (a) {
if (b) {
// doSomething
}
}
}
Good Example
void foo() {
if (a && b) {
// doSomething
}
}

Explicitly calling Thread.run()

Rule ID: PMD_DCTR

Description: Explicitly calling Thread.run() method will execute in the caller’s thread of control. Instead, call Thread.start() for the intended behavior

Label Label

Bad Example
Thread a = new Thread();
a.run();
Good Example
Thread a = new Thread();
a.start();

Dont Use Float Type For Loop Indices

Rule ID: PMD_DUFTFLI

Description: Don’t use floating point for loop indices

Label Label

Bad Example
public class Count {
public static void main(String[] args) {
final int START = 5000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
System.out.println(count);
}
}

Double Checked Locking

Rule ID: PMD_DCL

Description: Partially created objects can be returned by the Double Checked Locking pattern when used in Java

Label Label

Bad Example
public class Alpha {
Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}
Good Example
public class Alpha {
/*volatile */ Object beta = null;
Object gamma() {
if (beta == null) {
synchronized(this) {
if (beta == null) {
beta = new Object();
}
}
}
return beta;
}
}

Empty Catch Block

Rule ID: PMD_ECB

Description: Empty Catch Block finds instances where an exception is caught, but nothing is done

Label Label

Bad Example
public void doThis() {
try {
FileInputStream fil = new FileInputStream("/tmp/test");
} catch (IOException ioe) {
}
}

Empty Finally Block

Rule ID: PMD_EFB

Description: Empty finally blocks serve no purpose and should be removed

Label Label

Bad Example
public class Alpha {
public void beta() {
try {
int x = 5;
} finally {
// empty!
}
}
}
Good Example
public class Alpha {
public void beta() {
try {
int x = 5;
}
}
}

Empty If Stmt

Rule ID: PMD_EIS

Description: Empty If Statement finds instances where a condition is checked but nothing is done about it

Label Label

Bad Example
public class Alpha {
void beta(int y) {
if (y == 2) {
// empty!
}
}
}
Good Example
public class Alpha {
void beta(int y) {
if (y == 2) {
//doSomething
}
}
}

Empty Statement Block

Rule ID: PMD_EmSB

Description: Empty block statements serve no purpose and should be removed.

Label Label

Bad Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
{}
}

}
Good Example
public class Alpha {

private int _beta;

public void setBeta(int beta) {
{ _beta = beta; }
}

}

Empty Statement Not In Loop

Rule ID: PMD_ESNIL

Description: An empty statement (or a semicolon by itself) that is not used as the sole body of a ‘for’ or ‘while’ loop is probably a bug

Label Label

Bad Example
public void doThis() {
System.out.println("look at the extra semicolon");;
}
Good Example
public void doThis() {
System.out.println("look at the extra semicolon");
}

Empty Static Initializer

Rule ID: PMD_ESI

Description: Empty initializers serve no purpose and should be removed

Label Label

Bad Example
public class Alpha {
static {}
}
Good Example
public class Alpha {
static {
//doSomething
}
}

Empty Switch Statements

Rule ID: PMD_ESS

Description: Empty switch statements serve no purpose and should be removed

Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
//doSomething
}
}

Empty Synchronized Block

Rule ID: PMD_ESB

Description: Empty synchronized blocks serve no purpose and should be removed

Label Label

Bad Example
public class Alpha {
public void beta() {
synchronized (this) {
}
}
}
Good Example
public class Alpha {
public void beta() {
synchronized (this) {
//doSomething
}
}
}

Empty Try Block

Rule ID: PMD_ETB

Description: Avoid empty try blocks

Label Label

Bad Example
public class Alpha {
public void beta() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}

Empty While Stmt

Rule ID: PMD_EWS

Description: Empty While Statement finds all instances where a while statement does nothing.If it is a timing loop, then you should use Thread.sleep() for it

Label Label

Bad Example
void beta(int x, int y) {
while (x == y) {
}
}
Good Example
void beta(int x, int y) {
while (x == y) {
//doSomething
}
}

Extends Object

Rule ID: PMD_EO

Description: No need to explicitly extend Object

Label Label

Bad Example
public class Alpha extends Object {
}

For Loop Should Be While Loop

Rule ID: PMD_FLSBWL

Description: Some for loops can be simplified to while loops, this makes them more concise

Label Label

Bad Example
public class Alpha {
void beta() {
for (;true;) true;
}
}
Good Example
public class Alpha {
void beta() {
while (true) true;
}
}

Jumbled Incrementer

Rule ID: PMD_JI

Description: Avoid jumbled loop incrementers - its usually a mistake, and is confusing even if intentional

Label Label

Bad Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; j++) {
System.out.println("Hello World");
}
}
}
}
Good Example
public class Alpha {
public void beta() {
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 12; k++) {
System.out.println("Hello World");
}
}
}
}

Misplaced Null Check

Rule ID: PMD_MNC

Description: "The null check here is misplaced. If the variable is null a NullPointerException will be thrown. Either the check is useless (the variable will never be ""null"") or it is incorrect"

Label Label

Bad Example
public class Alpha {
void beta() {
if (b.equals(theta) && b != null) {}
}
}
Good Example
public class Alpha {
void beta() {
if (b == null && b.equals(theta)) {}
}
}

Override Both Equals And Hashcode

Rule ID: PMD_OBEAH

Description: Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or override neither

Label Label

Bad Example
public class Alpha {
public boolean equals(Object a) {
//someComparison
}
}
Good Example
public class Alpha {
public boolean equals(Object b) {
// someComparison
}
public int hashCode() {
// return hash value
}
}

Return From Finally Block

Rule ID: PMD_RFFB

Description: Avoid returning from a finally block, this can discard exceptions

Label Label

Bad Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
return "This";
}
}
}
Good Example
public class Alpha {
public String beta() {
try {
throw new Exception( "Exception" );
} catch (Exception e) {
throw e;
} finally {
//doSomething
}
}
}

Unconditional If Statement

Rule ID: PMD_UIS

Description: "Do not use ""if"" statements whose conditionals are always true or always false"

Label Label

Bad Example
public class Alpha {
public void close() {
if (false) {
//doSomething
}
}
}
Good Example
public class Alpha {
public void close() {
//doSomething
}
}

Unnecessary Conversion Temporary

Rule ID: PMD_UCT

Description: Avoid the use temporary objects when converting primitives to Strings. Use the static conversion methods on the wrapper classes instead

Label Label

Bad Example
public String convert(int a) {
String alpha = new Integer(a).toString();
}
Good Example
public String convert(int a) {
return Integer.toString(a);
}

Unused Null Check In Equals

Rule ID: PMD_UNCIE

Description: After checking an object reference for null, you should invoke equals() on that object rather than passing it to another object’s equals() method

Label Label

Bad Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(x)) {
//doSomething
}
}
}
Good Example
public class Alpha {

public String alpha1() { return "done";}
public String alpha2() { return null;}

public void method(String x) {
String y;
if (x!=null && alpha1().equals(y)) {
//doSomething
}
}
}

Useless Operation On Immutable

Rule ID: PMD_UOOI

Description: An operation on an Immutable object (String, BigDecimal or BigInteger) won’t change the object itself since the result of the operation is a new object

Label Label

Bad Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd.add(new BigDecimal(4));
}
}
Good Example
class Alpha {
void alpha1() {
BigDecimal bd=new BigDecimal(20);
bd = bd.add(new BigDecimal(4));
}
}

Useless Overriding Method

Rule ID: PMD_UOM

Description: The overriding method merely calls the same method defined in a superclass

Label Label

Bad Example
public void alpha(String beta) {
super.alpha(beta);
}
Good Example
public Long getId() {
return super.getId();
}

For Loops Must Use Braces

Rule ID: PMD_FLMUB

Description: For Loops Must Use Braces

Label Label

Bad Example
for (int j = 0; j < 34; j++)
alpha();
Good Example
for (int j = 0; j < 34; j++) {
alpha()
};

If Else Stmts Must Use Braces

Rule ID: PMD_IESMUB

Description: If Else Stmts Must Use Braces

Label Label

Bad Example
if (alpha)
i = i + 1;
else
i = i - 1;
Good Example
if (alpha) {
i = i + 1;
} else {
i = i - 1;
}

If Stmts Must Use Braces

Rule ID: PMD_ISMUB

Description: If Stmts Must Use Braces

Label Label

Bad Example
if (alpha)
i++;
Good Example
if (alpha) {
i++;
}

While Loops Must Use Braces

Rule ID: PMD_WLMUB

Description: While Loops Must Use Braces

Label Label

Bad Example
while (true)
i++;
Good Example
while (true) {
i++;
}

Clone Throws Clone Not Supported Exception

Rule ID: PMD_CTCNSE

Description: The method clone() should throw a CloneNotSupportedException

Label Label

Bad Example
public class Alpha implements Cloneable{
public Object clone() {
Alpha clone = (Alpha)super.clone();
return clone;
}
}

Proper Clone Implementation

Rule ID: PMD_PCI

Description: Object clone() should be implemented with super.clone()

Label Label

Bad Example
class Alpha{
public Object clone(){
return new Alpha();
}
}

Assignment In Operand

Rule ID: PMD_AIO

Description: Avoid assignments in operands. This can make code more complicated and harder to read

Label Label

Bad Example
public void beta() {
int a = 2;
if ((a = getA()) == 3) {
System.out.println("3!");
}
}

Avoid Accessibility Alteration

Rule ID: PMD_AAA

Description: Methods such as getDeclaredConstructors(), getDeclaredConstructor(Class[]) and setAccessible(), as the interface PrivilegedAction, allow for the runtime alteration of variable, class, or method visibility, even if they are private. This violates the principle of encapsulation

Label Label

Bad Example
public class Violation {
private void invalidSetAccessCalls() throws NoSuchMethodException, SecurityException {
Constructor<?> constructor = this.getClass().getDeclaredConstructor(String.class);
constructor.setAccessible(true);

Method privateMethod = this.getClass().getDeclaredMethod("aPrivateMethod");
privateMethod.setAccessible(true);
}
}

Avoid Prefixing Method Parameters

Rule ID: PMD_APMP

Description: Prefixing parameters by ‘in’ or ‘out’ pollutes the name of the parameters and reduces code readability

Label Label

Bad Example
public class Alpha {
public void beta(
int inLeftOperand,
Result outRightOperand) {
outRightOperand.setValue(inLeftOperand * outRightOperand.getValue());
}
}
Good Example
public class Alpha {
public void beta(
int leftOperand,
Result rightOperand) {
rightOperand.setValue(leftOperand * rightOperand.getValue());
}
}

Avoid Using Native Code

Rule ID: PMD_AUNC

Description: Unnecessary reliance on Java Native Interface (JNI) calls directly reduces application portability and increases the maintenance burden

Label Label

Bad Example
public class SomeNativeClass {
public SomeNativeClass() {
System.loadLibrary("nativelib");
}

static {
System.loadLibrary("nativelib");
}

public void invalidCallsInMethod() throws SecurityException, NoSuchMethodException {
System.loadLibrary("nativelib");
}
}

Default Package

Rule ID: PMD_DP

Description: Use explicit scoping instead of accidental usage of default package private level

Label Label

Bad Example
File saveFile = new File("C:/Upload/");
Good Example
private File saveFile = new File("C:/Upload/");

Do Not Call Garbage Collection Explicitly

Rule ID: PMD_DNCGCE

Description: Calls to System.gc(), Runtime.getRuntime().gc(), and System.runFinalization() are not advised. Code should have the same behavior whether the garbage collection is disabled using the option -Xdisableexplicitgc or not

Label Label

Bad Example
public class AlphaGC {
public explicitAlphaGC() {
// Explicit garbage collector call
System.gc();
}
}

Dont Import Sun

Rule ID: PMD_DIS

Description: Avoid importing anything from the ‘sun.*’ packages. These packages are not portable and are likely to change

Label Label

Bad Example
import sun.misc.bar;

One Declaration Per Line

Rule ID: PMD_ODPL

Description: Java allows the use of several variables declaration of the same type on one line. However, it can lead to quite messy code

Label Label

Bad Example
String first, last;
Good Example
String first;
String last;

Suspicious Octal Escape

Rule ID: PMD_SOE

Description: A suspicious octal escape sequence was found inside a String literal

Label Label

Bad Example
public void beta() {
System.out.println("suspicious: \128");
}

Unnecessary Constructor

Rule ID: PMD_UC

Description: When there is only one constructor and the constructor is identical to the default constructor, then it is not necessary

Label Label

Bad Example
public class Alpha {
public Alpha() {}
}
Good Example
public class Alpha {
public Beta() {}
}

Abstract Class Without Abstract Method

Rule ID: PMD_ACWAM

Description: The abstract class does not contain any abstract methods. An abstract class suggests an incomplete implementation, which is to be completed by subclasses implementing the abstract methods

Label Label

Bad Example
public abstract class Alpha {
void int method1() { ... }
void int method2() { ... }
}

Abstract Class Without Any Method

Rule ID: PMD_AbCWAM

Description: If an abstract class does not provides any methods, it may be acting as a simple data container that is not meant to be instantiated

Label Label

Bad Example
public abstract class Alpha {
String field;
int otherField;
}

Assignment To Non Final Static

Rule ID: PMD_ATNFS

Description: Possible unsafe usage of a static field

Label Label

Bad Example
public class StaticField {
static int a;
public FinalFields(int b) {
a = b;
}
}

Avoid Constants Interface

Rule ID: PMD_ACI

Description: Avoid constants in interfaces. Interfaces should define types, constants are implementation details better placed in classes or enums

Label Label

Bad Example
public interface AlphaInterface {
public static final int CONST1 = 1;
static final int CONST2 = 1;
final int CONST3 = 1;
int CONST4 = 1;
}
Good Example
public interface BetaInterface {
public static final int CONST1 = 1;

int anyMethod();
}

Avoid Instanceof Checks In Catch Clause

Rule ID: PMD_AICICC

Description: Each caught exception type should be handled in its own catch clause

Label Label

Bad Example
try {
//doSomething
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
Good Example
try {
//doSomething
} catch (IOException ee) {
cleanup();
}

Avoid Protected Field In Final Class

Rule ID: PMD_APFIFC

Description: Do not use protected fields in final classes since they cannot be subclassed

Label Label

Bad Example
public final class Alpha {
private int a;
protected int b;
Alpha() {}
}
Good Example
public final class Alpha {
private int a;
private int b;
Alpha() {}
}

Avoid Protected Method In Final Class Not Extending

Rule ID: PMD_APMIFCNE

Description: Do not use protected methods in most final classes since they cannot be subclassed

Label Label

Bad Example
public final class Alpha {
private int beta() {}
protected int beta() {}
}
Good Example
public final class Alpha {
private int beta() {}
private int beta() {}
}

Avoid Reassigning Parameters

Rule ID: PMD_ARP

Description: Reassigning values to incoming parameters is not recommended. Use temporary local variables instead

Label Label

Bad Example
public class Boo {
private void boo(String tab) {
tab = "changed string";
}
}
Good Example
public class Boo {
private void foo(String tab) {
String tab2 = String.join("A local value of tab: ", tab);;
}
}

Avoid Synchronized At Method Level

Rule ID: PMD_ASAML

Description: Method-level synchronization can cause problems when new code is added to the method. Block-level synchronization helps to ensure that only the code that needs synchronization gets it

Label Label

Bad Example
public class Alpha {
synchronized void alpha() {
}
}
Good Example
public class Alpha {
void beta() {
synchronized(this) {
}
}

Bad Comparison

Rule ID: PMD_BC

Description: BadComparison

Label Label

Bad Example
boolean x = (y == Double.NaN);

Class With Only Private Constructors Should Be Final

Rule ID: PMD_CWOPCSBF

Description: Avoid equality comparisons with Double.NaN due to the implicit lack of representation precision

Label Label


Close Resource

Rule ID: PMD_ClR

Description: Ensure that resources (like java.sql.Connection, java.sql.Statement, and java.sql.ResultSet objects and any subtype of java.lang.AutoCloseable) are always closed after use. Failing to do so might result in resource leaks

Label Label

Bad Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
//forgotToClose
}
}
}
Good Example
public class Beta {
public void alpha() {
Connection a = pool.getConnection();
try {
// doSomething
} catch (SQLException ex) {
//exception
} finally {
a.close();
}
}
}

Constructor Calls Overridable Method

Rule ID: PMD_CCOM

Description: Calling overridable methods during construction poses a risk of invoking methods on an incompletely constructed object and can be difficult to debug

Label Label

Bad Example
public class SeniorClass {
public SeniorClass() {
toString();
}
public String toString(){
return "ThatSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass() {
super();
name = "JuniorClass";
}
public String toString(){
return name.toUpperCase();
}
}

Default Label Not Last In Switch Stmt

Rule ID: PMD_DLNLISS

Description: By convention, the default label should be the last label in a switch statement

Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
default:
break;
case 2:
break;
}
}
}
Good Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1: // doSomething
break;
case 2:
break;
default:
break;
}
}
}

Empty Method In Abstract Class Should Be Abstract

Rule ID: PMD_EMIACSBA

Description: Empty or auto-generated methods in an abstract class should be tagged as abstract

Label Label

Bad Example
public abstract class NeedsToBeAbstract {
public Object mayBeAbstract() {
return null;
}
}
Good Example
public abstract class NeedsToBeAbstract {
public void mayBeAbstract() {
}
}

Equals Null

Rule ID: PMD_EN

Description: Tests for null should not use the equals() method. The ‘==’ operator should be used instead

Label Label

Bad Example
String a = "alpha";

if (a.equals(null)) {
doSomething();
}
Good Example
String a = "alpha";

if (a == null) {
doSomething();
}

Field Declarations Should Be At Start Of Class

Rule ID: PMD_FDSBASOC

Description: Fields should be declared at the top of the class, before any method declarations, constructors, initializers or inner classes

Label Label

Bad Example
public class Alpha {

public String getMessage() {
return "Hello";
}
private String _something;
}
Good Example
public class Alpha {
private String _fieldSomething;
public String getMessage() {
return "Hello";
}
}

Final Field Could Be Static

Rule ID: PMD_FFCBS

Description: If a final field is assigned to a compile-time constant, it could be made static, thus saving overhead in each object at runtime

Label Label

Bad Example
public class Alpha {
public final int BETA = 18;
}
Good Example
public class Alpha {
public static final int BETA = 18;
}

Idempotent Operations

Rule ID: PMD_IO

Description: Avoid idempotent operations - they have no effect

Label Label

Bad Example
public class Alpha {
public void beta() {
int a = 10;
a = a;
}
}
Good Example
public class Alpha {
public void beta() {
int a = 10;
}
}

Immutable Field

Rule ID: PMD_IF

Description: Private fields whose values never change once object initialization ends either in the declaration of the field or by a constructor should be final

Label Label

Bad Example
public class Alpha {
private int x; // could be final
public Alpha() {
x = 7;
}
public void alpha() {
int a = x + 2;
}
}

Instantiation To Get Class

Rule ID: PMD_ITGC

Description: Avoid instantiating an object just to call getClass() on it use the .class public member instead

Label Label

Bad Example
Class a = new String().getClass();
Good Example
Class a = String.class;

Logic Inversion

Rule ID: PMD_LI

Description: Use opposite operator instead of negating the whole expression with a logic complement operator

Label Label

Bad Example
public boolean beta(int x, int y) {
if (!(x == y)) {
return false;
}
return true;
}
Good Example
public boolean beta(int x, int y) {
if (x != y) {
return false;
}
return true;
}

Missing Break In Switch

Rule ID: PMD_MBIS

Description: Switch statements without break or return statements for each case option may indicate problematic behaviour. Empty cases are ignored as these indicate an intentional fall-through

Label Label

Bad Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
// break;
case OTHER:
case ERROR:
doSomethingElse();
break;
}
}
Good Example
public void alpha(int status) {
switch(status) {
case CANCELLED:
doSomething();
break;
case ERROR:
doSomethingElse();
break;
}
}

Missing Static Method In Non Instantiatable Class

Rule ID: PMD_MSMINIC

Description: A class that has private constructors and does not have any static methods or fields cannot be used

Label Label

Bad Example
public class Alpha {
private Alpha() {}
void Alpha() {}
}
Good Example
public class Alpha {
public static void main(String[] args) {
doSomething
}
}

Non Case Label In Switch Statement

Rule ID: PMD_NCLISS

Description: A non-case label (e.g. a named break/continue label) was present in a switch statement. This legal, but confusing. It is easy to mix up the case labels and the non-case labels

Label Label

Bad Example
public class Alpha {
void beta(int x) {
switch (x) {
case 1:
doSomething;
break;
somelabel:
break;
default:
break;
}
}
}

Non Static Initializer

Rule ID: PMD_NSI

Description: A non-static initializer block will be called any time a constructor is invoked (just prior to invoking the constructor)

Label Label

Bad Example
public class Alpha {
{
System.out.println("Construct");
}
}

Non Thread Safe Singleton

Rule ID: PMD_NTSS

Description: Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible by instantiating the object directly. Static singletons are usually not needed as only a single instance exists anyway

Label Label

Bad Example
private static Alpha alpha = null;
public static Alpha getAlpha() {
if (alpha == null) {
alpha = new Alpha();
}
return alpha;
}

Optimizable To Array Call

Rule ID: PMD_OTAC

Description: Calls to a collection’s ‘toArray(E[])’ method should specify a target array of zero size

Label Label

Bad Example
Alpha[] alphaArray = alphas.toArray(new Alpha[alphas.size()]);
Good Example
Alpha[] alphaArray = alphas.toArray(new Alpha[0]);

Position Literals First In Case Insensitive Comparisons

Rule ID: PMD_PLFICIC

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equalsIgnoreCase("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equalsIgnoreCase(a);
}
}

Position Literals First In Comparisons

Rule ID: PMD_PLFIC

Description: Position literals first in comparisons, if the second argument is null then NullPointerExceptions can be avoided, they will just return false

Label Label

Bad Example
class Alpha {
boolean beta(String a) {
return a.equals("2");
}
}
Good Example
class Alpha {
boolean beta(String a) {
return "2".equals(a);
}
}

Preserve Stack Trace

Rule ID: PMD_PST

Description: Throwing a new exception from a catch block without passing the original exception into the new exception will cause the original stack trace to be lost making it difficult to debug effectively

Label Label

Bad Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
}
Good Example
public class Alpha {
void beta() {
try{
Integer.parseInt("x");
} catch (Exception e) {
throw new Exception(e);
}
try {
Integer.parseInt("x");
} catch (Exception e) {
throw (IllegalStateException)new IllegalStateException().initCause(e);
}
}
}

Return Empty Array Rather Than Null

Rule ID: PMD_REARTN

Description: For any method that returns an array, it is a better to return an empty array rather than a null reference. This removes the need for null checking all results and avoids inadvertent NullPointerExceptions

Label Label

Bad Example
public class Alpha {
public int[] beta() {
//doSomething
return null;
}
}
Good Example
public class Alpha {
public String[] beta() {
//doSomething
return new String[0];
}
}

Simple Date Format Needs Locale

Rule ID: PMD_SDFNL

Description: Be sure to specify a Locale when creating SimpleDateFormat instances to ensure that locale-appropriate formatting is used

Label Label

Bad Example
public class Alpha {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}

Simplify Boolean Expressions

Rule ID: PMD_SBE

Description: Avoid unnecessary comparisons in boolean expressions, they serve no purpose and impacts readability

Label Label

Bad Example
public class Beta {
private boolean beta = (isAlpha() == true);

public isAlpha() { return false;}
}
Good Example
public class Beta {
beta = isAlpha();
public isAlpha() { return false;}
}

Simplify Boolean Returns

Rule ID: PMD_SBR

Description: Avoid unnecessary if-then-else statements when returning a boolean. The result of the conditional test can be returned instead

Label Label

Bad Example
public boolean isBetaEqualTo(int a) {
if (beta == a) {
return true;
} else {
return false;
}
}
Good Example
public boolean isBetaEqualTo(int a) {
return beta == a;
}

Simplify Conditional

Rule ID: PMD_SC

Description: No need to check for null before an instanceof. The instanceof keyword returns false when given a null argument

Label Label

Bad Example
class Alpha {
void beta(Object a) {
if (a != null && a instanceof Beta) {
//doSomething
}
}
}
Good Example
class Alpha {
void beta(Object a) {
if (a instanceof Beta) {
//doSomething
}
}
}

Singular Field

Rule ID: PMD_SF

Description: Fields whose scopes are limited to just single methods do not rely on the containing object to provide them to other methods. They may be better implemented as local variables within those methods

Label Label

Bad Example
public class Alpha {
private int a;
public void alpha(int b) {
a = b + 2;
return a;
}
}
Good Example
public class Alpha {
public void alpha(int b) {
a = b + 2;
return a;
}
}

Switch Stmts Should Have Default

Rule ID: PMD_SSSHD

Description: All switch statements should include a default option to catch any unspecified values

Label Label

Bad Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
}
}
Good Example
public void beta() {
int a = 5;
switch (a) {
case 1: int b = 2;
case 2: int b = 4;
default: break;
}
}

Too Few Branches For ASwitch Statement

Rule ID: PMD_TFBFASS

Description: Switch statements are intended to be used to support complex branching behaviour. Using a switch for only a few cases is ill-advised, since switches are not as easy to understand as if-then statements

Label Label

Bad Example
public class Alpha {
public void beta() {
switch (a) {
case 1:
doSomething;
break;
default:
break;
}
}
}
Good Example
public class Alpha {
public void beta() {
if (something) {
doSomething;
}
}
}

Uncommented Empty Constructor

Rule ID: PMD_UEC

Description: By explicitly commenting empty constructors it is easier to distinguish between intentional (commented) and unintentional empty constructors

Label Label

Bad Example
public Alpha() {
}
Good Example
public Alpha() {
//somethingCommented
}

Uncommented Empty Method

Rule ID: PMD_UEM

Description: By explicitly commenting empty method bodies it is easier to distinguish between intentional (commented) and unintentional empty methods

Label Label

Bad Example
public void alpha() {
}
Good Example
public void alpha() {
//somethingCommented
}

Unnecessary Local Before Return

Rule ID: PMD_ULBR

Description: Avoid the creation of unnecessary local variables

Label Label

Bad Example
public class Alpha {
public int alpha() {
int a = doSomething();
return a;
}
}
Good Example
public class Alpha {
public int alpha() {
return doSomething();
}
}

Unsynchronized Static Date Formatter

Rule ID: PMD_USDF

Description: SimpleDateFormat instances are not synchronized. Sun recommends using separate format instances for each thread. If multiple threads must access a static formatter, the formatter must be synchronized on block leve

Label Label

Bad Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void beta() {
sdf.format();
}
}
Good Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
synchronized void alpha() {
sdf.format();
}
}

Use Collection Is Empty

Rule ID: PMD_UCIE

Description: The isEmpty() method on java.util.Collection is provided to determine if a collection has any elements. Comparing the value of size() to 0 does not convey intent as well as the isEmpty() method

Label Label

Bad Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.size() == 0) {
//doSomething
}
}
}
Good Example
public class Alpha {
void beta() {
List alpha = getList();
if (alpha.isEmpty()) {
//doSomething
}
}
}

Use Locale With Case Conversions

Rule ID: PMD_ULWCC

Description: When doing String::toLowerCase()/toUpperCase() conversions, use an explicit locale argument to specify the case transformation rules

Label Label

Bad Example
class Alpha {
if (a.toLowerCase().equals("list")) { }
}
Good Example
class Alpha {
String x = a.toLowerCase(Locale.EN);
}

Use Notify All Instead Of Notify

Rule ID: PMD_UNAION

Description: Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring, then only one is chosen. The thread chosen is arbitrary and thus its usually safer to call notifyAll() instead

Label Label

Bad Example
void beta() {
a.notify();
}
Good Example
void beta() {
a.notifyAll();
}

Use Varargs

Rule ID: PMD_UV

Description: Java 5 introduced the varargs parameter declaration for methods and constructors. This syntactic sugar provides flexibility for users of these methods and constructors, allowing them to avoid having to deal with the creation of an array

Label Label

Bad Example
public class Alpha {
public void alpha(String a, Object[] args) {
//doSomething
}
}
Good Example
public class Alpha {
public void alpha(String a, Object... args) {
//doSomething
}
}

Avoid Calling Finalize

Rule ID: PMD_ACF

Description: The method Object.finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. It should not be invoked by application logic

Label Label

Bad Example
void alpha() {
Beta a = new Beta();
a.finalize();
}

Empty Finalizer

Rule ID: PMD_EF

Description: Empty finalize methods serve no purpose and should be removed. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label

Bad Example
public class Alpha {
protected void finalize() {}
}

Finalize Does Not Call Super Finalize

Rule ID: PMD_FDNCSF

Description: If the finalize() is implemented, its last action should be to call super.finalize. Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label

Bad Example
protected void finalize() {
doSomething();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Only Calls Super Finalize

Rule ID: PMD_FOCSF

Description: If the finalize() is implemented, it should do something besides just calling super.finalize(). Note that Oracle has declared Object.finalize() as deprecated since JDK 9

Label Label

Bad Example
protected void finalize() {
super.finalize();
}
Good Example
protected void finalize() {
doSomething();
super.finalize();
}

Finalize Overloaded

Rule ID: PMD_FO

Description: Methods named finalize() should not have parameters. It is confusing and most likely an attempt to overload Object.finalize(). It will not be called by the VM

Label Label

Bad Example
public class Alpha {
protected void finalize(int x) {
}
}

Finalize Should Be Protected

Rule ID: PMD_FSBP

Description: When overriding the finalize(), the new method should be set as protected. If made public, other classes may invoke it at inappropriate times

Label Label

Bad Example
public void finalize() {
//doSomething
}
Good Example
protected void finalize() {
//doSomething
}

Dont Import Java Lang

Rule ID: PMD_DIJL

Description: Avoid importing anything from the package ‘java.lang’. These classes are automatically imported

Label Label

Bad Example
import java.lang.String;

Duplicate Imports

Rule ID: PMD_DI

Description: Duplicate or overlapping import statements should be avoided

Label Label

Bad Example
import java.lang.String;
import java.lang.*;
Good Example
import java.lang.*;

Import From Same Package

Rule ID: PMD_IFSP

Description: There is no need to import a type that lives in the same package

Label Label

Bad Example
package alpha;

import alpha.Beta;
Good Example
package alpha;

Too Many Static Imports

Rule ID: PMD_TMSI

Description: If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import

Label Label

Bad Example
import static Alpha;
import static Beta;
import static Theta;
import static Omicron;

Unnecessary Fully Qualified Name

Rule ID: PMD_UFQN

Description: Import statements allow the use of non-fully qualified names. The use of a fully qualified name which is covered by an import statement is redundant

Label Label

Bad Example
public class Alpha {
private java.util.List list1;
private List list2;
}

Do Not Call System Exit

Rule ID: PMD_DNCSE

Description: Web applications should not call System.exit(), since only the web container or the application server should stop the JVM

Label Label

Bad Example
public void beta() {
System.exit(0);
}

Local Home Naming Convention

Rule ID: PMD_LHNC

Description: The Local Home interface of a Session EJB should be suffixed by ‘LocalHome’

Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalHome {}
Good Example
public interface MyBeautifulLocalHome extends javax.ejb.EJBLocalHome {}

Local Interface Session Naming Convention

Rule ID: PMD_LISNC

Description: The Local Interface of a Session EJB should be suffixed by ‘Local’

Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBLocalObject {}
Good Example
public interface MyLocal extends javax.ejb.EJBLocalObject {}

MDBAnd Session Bean Naming Convention

Rule ID: PMD_MDBASBNC

Description: The EJB Specification states that any MessageDrivenBean or SessionBean should be suffixed by ‘Bean’

Label Label

Bad Example
public class MissingTheProperSuffix implements SessionBean {}
Good Example
public class SomeBean implements SessionBean{}

Remote Interface Naming Convention

Rule ID: PMD_RINC

Description: Remote Interface of a Session EJB should not have a suffix

Label Label

Bad Example
public interface BadSuffixSession extends javax.ejb.EJBObject {}

Remote Session Interface Naming Convention

Rule ID: PMD_RSINC

Description: A Remote Home interface type of a Session EJB should be suffixed by ‘Home’

Label Label

Bad Example
public interface MissingProperSuffix extends javax.ejb.EJBHome {}
Good Example
public interface MyHome extends javax.ejb.EJBHome {}

Static EJBField Should Be Final

Rule ID: PMD_SEJBFSBF

Description: According to the J2EE specification, an EJB should not have any static fields with write access. However, static read-only fields are allowed

Label Label

Bad Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static int CountB;
}
Good Example
public class SomeEJB extends EJBObject implements EJBLocalHome {
private static final int CountB;
}

JUnit Assertions Should Include Message

Rule ID: PMD_JUASIM

Description: JUnit assertions should include an informative message - i.e., use the three-argument version of assertEquals(), not the two-argument version

Label Label

Bad Example
public class Alpha extends Beta {
public void theta() {
assertEquals("alpha", "beta");
}
}
Good Example
public class Alpha extends Beta {
public void theta() {
assertEquals("Alpha does not equals beta", "alpha", "beta");
}
}

JUnit Spelling

Rule ID: PMD_JUS

Description: Some JUnit framework methods are easy to misspell

Label Label

Bad Example
import junit.framework.*;
public class Alpha extends Beta {
public void setup() {}
}
Good Example
import junit.framework.*;
public class Alpha extends Beta {
public void setUp() {}
}

JUnit Static Suite

Rule ID: PMD_JUSS

Description: The suite() method in a JUnit test needs to be both public and static

Label Label

Bad Example
import junit.framework.*;

public class Alpha extends Beta {
public void suite() {}
}
Good Example
import junit.framework.*;

public class Alpha extends Beta {
public static void suite() {}
}

JUnit Test Contains Too Many Asserts

Rule ID: PMD_JUTCTMA

Description: Unit tests should not contain too many asserts. Many asserts are indicative of a complex test, for which it is harder to verify correctness

Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("myTheta should be false", myTheta);
assertEquals("should equals false", false, myTheta);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTheta = false;
assertFalse("should be false", myTheta);
}
}

JUnit Tests Should Include Assert

Rule ID: PMD_JUTSIA

Description: JUnit tests should include at least one assertion. This makes the tests more robust, and using assert with messages provide the developer a clearer idea of what the test does

Label Label

Bad Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
b.work();
}
}
Good Example
public class Foo extends TestCase {
public void testSomething() {
Bar b = findBar();
// This is better than having a NullPointerException
assertNotNull("bar not found", b);
}
}

Simplify Boolean Assertion

Rule ID: PMD_SBA

Description: Avoid negation in an assertTrue or assertFalse test

Label Label

Bad Example
assertTrue(!sth);
Good Example
assertFalse(sth);

Test Class Without Test Cases

Rule ID: PMD_TCWTC

Description: Test classes end with the suffix Test. Having a non-test class with that name is not a good practice, since most people will assume it is a test case

Label Label

Bad Example
public class CarTest {
public static void main(String[] args) {
}
}

Unnecessary Boolean Assertion

Rule ID: PMD_UBA

Description: A JUnit test assertion with a boolean literal is unnecessary since it always will evaluate to the same thing. Consider using flow control (in case of assertTrue(false) or similar) or simply removing statements like assertTrue(true) and assertFalse(false)

Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
assertTrue(true);
}
}

Use Assert Equals Instead Of Assert True

Rule ID: PMD_UAEIOAT

Description: The assertions should be made by more specific methods, like assertEquals

Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x.equals(y));
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertEquals("x should equals y", x, y);
}
}

Use Assert Null Instead Of Assert True

Rule ID: PMD_UANIOAT

Description: The assertions should be made by more specific methods, like assertNull, assertNotNull

Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertTrue(x == null);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x = doSomething();
assertNull(x);
}
}

Use Assert Same Instead Of Assert True

Rule ID: PMD_UASIOAT

Description: The assertions should be made by more specific methods, like assertSame, assertNotSame

Label Label

Bad Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertTrue(x == y);
}
}
Good Example
public class Alpha extends Beta {
void testAlpha() {
Object x, y;
assertSame(x, y);
}
}

Use Assert True Instead Of Assert Equals

Rule ID: PMD_UATIOAE

Description: When asserting a value is the same as a literal or Boxed boolean, use assertTrue/assertFalse, instead of assertEquals

Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertEquals("myTest is true", true, myTest);
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
boolean myTest = true;
assertTrue("myTest is true", myTest);
}
}

Guard Debug Logging

Rule ID: PMD_GDL

Description: When log messages are composed by concatenating strings, the whole section should be guarded by a isDebugEnabled() check to avoid performance and memory issues

Label Label

Bad Example
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
Good Example
if (logger.isDebugEnabled()) {
logger.debug("This is a very long message that prints two values." +
" However since the message is long, we still incur the performance hit" +
" of String concatenation when logging {} and {}", value1, value2);
}

Guard Log Statement

Rule ID: PMD_GLS

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label

Bad Example
log.debug("logs here {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("logs here" + param1 + " and " + param2 + "concat strings");
}

Proper Logger

Rule ID: PMD_PL

Description: A logger should normally be defined private static final and be associated with the correct class

Label Label

Bad Example
public class Alpha {
protected Log LOG = LogFactory.getLog(Testalpha.class);
}
Good Example
public class Alpha {
private static final Log LOG = LogFactory.getLog(Alpha.class);
}

Use Correct Exception Logging

Rule ID: PMD_UCEL

Description: To make sure the full stacktrace is printed out, use the logging statement with two arguments: a String and a Throwable

Label Label

Bad Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( Exception e ) {
_LOG.error( e );
}
}
}
Good Example
public class Alpha {
private static final Log _LOG = LogFactory.getLog( Alpha.class );
void beta() {
try {
} catch( OtherException oe ) {
_LOG.error( oe.getMessage(), oe );
}
}
}

Avoid Print Stack Trace

Rule ID: PMD_APST

Description: Avoid printStackTrace() use a logger call instead

Label Label

Bad Example
class Alpha {
void beta() {
try {
//doSomething
} catch (Exception e) {
e.printStackTrace();
}
}
}

Guard Log Statement Java Util

Rule ID: PMD_GLSJU

Description: Whenever using a log level, one should check if the loglevel is actually enabled, or otherwise skip the associate String creation and manipulation

Label Label

Bad Example
log.debug("log something {} and {}", param1, param2);
Good Example
if (log.isDebugEnabled()) {
log.debug("log something" + param1 + " and " + param2 + "concat strings");
}

Logger Is Not Static Final

Rule ID: PMD_LINSF

Description: In most cases, the Logger reference can be declared as static and final

Label Label

Bad Example
public class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha{
static final Logger log = Logger.getLogger(Alpha.class.getName());
}

More Than One Logger

Rule ID: PMD_MTOL

Description: Normally only one logger is used in each class

Label Label

Bad Example
public class Alpha {
Logger log1 = Logger.getLogger(Alpha.class.getName());
Logger log2= Logger.getLogger(Alpha.class.getName());
}
Good Example
public class Alpha {
Logger log = Logger.getLogger(Alpha.class.getName());
}

System Println

Rule ID: PMD_SP

Description: References to System.(out|err).print are usually intended for debugging purposes. Use a logger instead

Label Label

Bad Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
System.out.println("This test");
}
}
Good Example
class Alpha{
Logger log = Logger.getLogger(Alpha.class.getName());
public void testAlpha () {
log.fine("This test");
}
}

Missing Serial Version UID

Rule ID: PMD_MSVUID

Description: Serializable classes should provide a serialVersionUID field

Label Label

Bad Example
public class Alpha implements java.io.Serializable {
String test;
//doSomething
}
Good Example
public class Alpha implements java.io.Serializable {
String test;
public static final long serialVersionUID = 4916737;
}

Avoid Dollar Signs

Rule ID: PMD_ADS

Description: Avoid using dollar signs in variable/method/class/interface names

Label Label

Bad Example
public class Alp$ha {
}
Good Example
public class Alpha {
}

Avoid Field Name Matching Method Name

Rule ID: PMD_AFNMMN

Description: It can be confusing to have a field name with the same name as a method

Label Label

Bad Example
public class Alpha {
Object beta;
void beta() {
}
}
Good Example
public class Alpha {
Object beta;
void theta() {
}
}

Avoid Field Name Matching Type Name

Rule ID: PMD_AFNMTN

Description: It is somewhat confusing to have a field name matching the declaring class name

Label Label

Bad Example
public class Alpha extends Beta {
int alpha;
}
Good Example
public class Alpha extends Beta {
int theta;
}

Boolean Get Method Name

Rule ID: PMD_BGMN

Description: Methods that return boolean results should be named as predicate statements to denote this. I.e, ‘isReady()’, ‘hasValues()’, ‘canCommit()’, ‘willFail()’, etc. Avoid the use of the ‘get’ prefix for these methods

Label Label

Bad Example
public boolean getAlpha();
Good Example
public boolean isAlpha();

Class Naming Conventions

Rule ID: PMD_CNC

Description: Configurable naming conventions for type declarations

Label Label

Bad Example
public class Étudiant {}
Good Example
public class AlphaBeta {}

Generics Naming

Rule ID: PMD_GN

Description: Names for references to generic values should be limited to a single uppercase letter

Label Label

Bad Example
public interface GenericDao<e extends BaseModel, K extends Serializable> {
}
Good Example
public interface GenericDao<E extends BaseModel, K extends Serializable> {
}

Method Naming Conventions

Rule ID: PMD_MeNC

Description: Configurable naming conventions for method declarations

Label Label


Method With Same Name As Enclosing Class

Rule ID: PMD_MWSNAEC

Description: Non-constructor methods should not have the same name as the enclosing class

Label Label

Bad Example
public class AlphaT {
public void AlphaT() {}
}
Good Example
public class AlphaT {
public AlphaT() {}
}

No Package

Rule ID: PMD_NP

Description: A class, interface, enum or annotation does not have a package definition

Label Label


Package Case

Rule ID: PMD_PC

Description: The package definition contains uppercase characters

Label Label

Bad Example
package com.MyAlpha;
Good Example
package com.myalpha;

Short Class Name

Rule ID: PMD_SCN

Description: Short Classnames with fewer than e.g. five characters are not recommended

Label Label

Bad Example
public class Alp {
}
Good Example
public class Alpha {
}

Short Method Name

Rule ID: PMD_SMN

Description: Method names that are very short are not helpful to the reader

Label Label

Bad Example
public class Alpha {
public void a( int i ) {
}
}
Good Example
public class Alpha {
public void beta( int i ) {
}
}

Suspicious Constant Field Name

Rule ID: PMD_SCFN

Description: Field names using all uppercase characters - Sun’s Java naming conventions indicating constants - should be declared as final

Label Label

Bad Example
public class Alpha {
double PI = 3.16;
}
Good Example
public class Alpha {
final double PI = 3.16;
}

Suspicious Equals Method Name

Rule ID: PMD_SEMN

Description: The method name and parameter number are suspiciously close to equals(Object), which can denote an intention to override the equals(Object) method

Label Label

Bad Example
public class Alpha {
public int equals(Object a) {
//doSomething
}
}
Good Example
public class Alpha {
public boolean equals(Object a) {
//doSomething
}
}

Suspicious Hashcode Method Name

Rule ID: PMD_SHMN

Description: The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method

Label Label

Bad Example
public class Alpha {
public int hashcode() {
}
}
Good Example
public class Alpha {
public int newname() {
}
}

Variable Naming Conventions

Rule ID: PMD_VNC

Description: Final variables should be fully capitalized and non-final variables should not include underscores

Label Label

Bad Example
public class Alpha {
public static final int my_alp = 0;
}
Good Example
public class Alpha {
public static final int MY_ALP = 0;
}

Add Empty String

Rule ID: PMD_AES

Description: The conversion of literals to strings by concatenating them with empty strings is inefficient. It is much better to use one of the type-specific toString() methods instead

Label Label

Bad Example
String a = "" + 456;
Good Example
String a = Integer.toString(456);

Avoid Array Loops

Rule ID: PMD_AAL

Description: Instead of manually copying data between two arrays, use the efficient Arrays.copyOf or System.arraycopy method instead

Label Label

Bad Example
public class Alpha {
public void beta() {
int[] x = new int[5];
int[]y = new int[5];
for (int i = 0; i < 5 ; i++) {
y[i] = x[i];
}
int[] z = new int[5];
for (int i = 0 ; i < 5 ; i++) {
y[i] = x[z[i]];
}
}
}

Redundant Field Initializer

Rule ID: PMD_RFI

Description: Java will initialize fields with known default values so any explicit initialization of those same defaults is redundant and results in a larger class file (approximately three additional bytecode instructions per field)

Label Label

Bad Example
public class Alpha {
boolean a = false;
}

Unnecessary Wrapper Object Creation

Rule ID: PMD_UWOC

Description: Most wrapper classes provide static conversion methods that avoid the need to create intermediate objects just to create the primitive forms. Using these avoids the cost of creating objects that also need to be garbage-collected later

Label Label

Bad Example
public int convert(String a) {
int x, x2;

x = Integer.valueOf(a).intValue();

x2 = Integer.valueOf(x).intValue();

return x2;
}
Good Example
public int convert(String a) {
int x, x2;
x = Integer.parseInt(a);
x2 = x;

return x2;
}

Use Array List Instead Of Vector

Rule ID: PMD_UALIOV

Description: ArrayList is a much better Collection implementation than Vector if thread-safe operation is not required

Label Label

Bad Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new Vector();
}
}
Good Example
public class Alpha extends Beta {
public void testAlpha() {
Collection b = new ArrayList();
}
}

Use Arrays As List

Rule ID: PMD_UAAL

Description: "The java.util.Arrays class has a ""asList"" method that should be used when you want to create a new List from an array of objects. It is faster than executing a loop to copy all the elements of the array one by one"

Label Label

Bad Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l = new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(ints[i]);
}
}
}
Good Example
public class Alpha {
public void beta(Integer[] ints) {
List<Integer> l= new ArrayList<>(50);
for (int i = 0 ; i < 50; i++) {
l.add(a[i].toString());
}
}
}

Use String Buffer For String Appends

Rule ID: PMD_USBFSA

Description: The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal StringBuffer. If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this

Label Label

Bad Example
public class Alpha {
void beta() {
String c;
c = "alpha";
c += " beta";
}
}
Good Example
public class Alpha {
void beta() {
String c;
StringBuilder c = new StringBuilder("alpha");
c.append(" beta");
}
}

Array Is Stored Directly

Rule ID: PMD_AISD

Description: Constructors and methods receiving arrays should clone objects and store the copy. This prevents future changes from the user from affecting the original array

Label Label

Bad Example
public class Alpha {
private String [] a;
public void beta (String [] param) {
this.a=param;
}
}

Method Returns Internal Array

Rule ID: PMD_MRIA

Description: Exposing internal arrays to the caller violates object encapsulation since elements can be removed or replaced outside of the object that owns it. It is safer to return a copy of the array

Label Label

Bad Example
public class Alpha {
UserChart [] uc;
public UserChart [] getUserChart() {
return uc;
}
}

Avoid Catching Generic Exception

Rule ID: PMD_ACGE

Description: Avoid catching generic exceptions such as NullPointerException, RuntimeException, Exception in try-catch block

Label Label

Bad Example
public class Alpha {

public void Beta() {
try {
System.out.println(" i [" + i + "]");
} catch(Exception e) {
e.printStackTrace();
} catch(RuntimeException e) {
e.printStackTrace();
} catch(NullPointerException e) {
e.printStackTrace();
}
}
}

Avoid Catching NPE

Rule ID: PMD_ACNPE

Description: Code should never throw NullPointerExceptions under normal circumstances. A catch block may hide the original error, causing other, more subtle problems later on

Label Label

Bad Example
public class Alpha {
void beta() {
try {
// do something
} catch (NullPointerException npe) {
}
}
}

Avoid Catching Throwable

Rule ID: PMD_ACT

Description: Catching Throwable errors is not recommended since its scope is very broad. It includes runtime issues such as OutOfMemoryError that should be exposed and managed separately

Label Label

Bad Example
public void beta() {
try {
// do something
} catch (Throwable th) {
th.printStackTrace();
}
}

Avoid Losing Exception Information

Rule ID: PMD_ALEI

Description: Statements in a catch block that invoke accessors on the exception without using the information only add to code size. Either remove the invocation, or use the return result

Label Label

Good Example
public void bar() {
try {
// do something
} catch (SomeException se) {
se.getMessage();
}
}

Avoid Rethrowing Exception

Rule ID: PMD_ARE

Description: Catch blocks that merely rethrow a caught exception only add to code size and runtime complexity

Label Label

Bad Example
public void beta() {
try {
// do something
} catch (SomeException se) {
throw se;
}
}

Avoid Throwing New Instance Of Same Exception

Rule ID: PMD_ATNIOSE

Description: Catch blocks that merely rethrow a caught exception wrapped inside a new instance of the same type only add to code size and runtime complexity

Label Label

Bad Example
public void beta() {
try {
// do something
} catch (SomeException se) {
// harmless comment
throw new SomeException(se);
}
}

Avoid Throwing Null Pointer Exception

Rule ID: PMD_ATNPE

Description: Avoid throwing NullPointerExceptions manually. These are confusing because most people will assume that the virtual machine threw it. To avoid a method being called with a null parameter, you may consider using an IllegalArgumentException instead

Label Label

Bad Example
public class Alpha {
void beta() {
throw new NullPointerException();
}
}
Good Example
public class Alpha {
private String examValue;

void setExamValue(String examValue) {
this.examValue = Objects.requireNonNull(examValue, "examValue must not be null!");
}
}

Avoid Throwing Raw Exception Types

Rule ID: PMD_ATRET

Description: Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable, Exception, or Error, use a subclassed exception or error instead

Label Label

Bad Example
public class Alpha {
public void beta() throws Exception {
throw new Exception();
}
}

Do Not Extend Java Lang Error

Rule ID: PMD_DNEJLE

Description: Errors are system exceptions. Do not extend them

Label Label

Bad Example
public class Alpha extends Error { }

Do Not Throw Exception In Finally

Rule ID: PMD_DNTEIF

Description: "Throwing exceptions within a ‘finally’ block is confusing since they may mask other exceptions or code defects. Note: This is a PMD implementation of the Lint4j rule ""A throw in a finally block"""

Label Label

Bad Example
public class Alpha {
public void beta() {
try {
// Do somthing
} catch( Exception e) {
// Handling the issue
} finally {
throw new Exception();
}
}
}

Exception As Flow Control

Rule ID: PMD_EAFC

Description: Using Exceptions as form of flow control is not recommended as they obscure true exceptions when debugging. Either add the necessary validation or use an alternate control structure

Label Label

Bad Example
public void beta() {
try {
try {
} catch (Exception e) {
throw new WrapperException(e);
}
} catch (WrapperException e) {
// do some more stuff
}
}

Avoid Duplicate Literals

Rule ID: PMD_ADL

Description: Code containing duplicate String literals can usually be improved by declaring the String as a constant field

Label Label

Bad Example
private void alpha() {
beta("Howdy");
beta("Howdy");
}
Good Example
private void beta(String x) {}

Avoid String Buffer Field

Rule ID: PMD_ASBF

Description: StringBuffers/StringBuilders can grow considerably, and so may become a source of memory leaks if held within objects with long lifetimes

Label Label

Bad Example
public class Foo {
private StringBuffer buffer;
}

Consecutive Appends Should Reuse

Rule ID: PMD_CASR

Description: Consecutive calls to StringBuffer/StringBuilder .append should be chained, reusing the target object. This can improve the performance by producing a smaller bytecode, reducing overhead and improving inlining

Label Label

Bad Example
buf.append("Hello");
buf.append(alpha);
buf.append("World");
Good Example
buf.append("Hello").append(alpha).append("World");

Consecutive Literal Appends

Rule ID: PMD_CLA

Description: Consecutively calling StringBuffer/StringBuilder.append(…) with literals should be avoided

Label Label

Bad Example
buf.append("Hello").append(" ").append("World");
Good Example
buf.append("Hello World");

Inefficient String Buffering

Rule ID: PMD_ISB

Description: Avoid concatenating non-literals in a StringBuffer constructor or append() since intermediate buffers will need to be be created and destroyed by the JVM

Label Label

Bad Example
StringBuffer sb = new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
Good Example
StringBuffer sb = new StringBuffer("tmp = ");
sb.append(System.getProperty("java.io.tmpdir"));

String Buffer Instantiation With Char

Rule ID: PMD_SBIWC

Description: Individual character values provided as initialization arguments will be converted into integers. This can lead to internal buffer sizes that are larger than expected

Label Label

Bad Example
StringBuffer sb1 = new StringBuffer('c');
StringBuilder sb2 = new StringBuilder('c');
Good Example
StringBuffer sb3 = new StringBuffer("c");
StringBuilder sb4 = new StringBuilder("c");

String Instantiation

Rule ID: PMD_StI

Description: Avoid instantiating String objects. This is usually unnecessary since they are immutable and can be safely shared

Label Label

Bad Example
private String beta = new String("beta");
Good Example
private String beta = "beta";

String To String

Rule ID: PMD_STS

Description: Avoid calling toString() on objects already known to be string instances. This is unnecessary

Label Label

Bad Example
private String beta() {
String tab = "iamastring";
return tab.toString();
}
Good Example
private String beta() {
String tab = "a string";
return String.join("I am ", tab);
}

Unnecessary Case Change

Rule ID: PMD_UCC

Description: Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()

Label Label

Bad Example
boolean answer = alpha.toUpperCase().equals("beta");
Good Example
boolean answer = alpha.equalsIgnoreCase("beta")

Use Equals To Compare Strings

Rule ID: PMD_UETCS

Description: Using ‘==’ or ‘!=’ to compare strings only works if intern version is used on both sides

Label Label

Bad Example
public boolean test(String s) {
if (s == "one") return true;
return false;
}
Good Example
public boolean test(String s) {
if ("two".equals(s)) return true;
return false;
}

Clone Method Must Implement Cloneable

Rule ID: PMD_ClMMIC

Description: The method clone() should only be implemented if the class implements the Cloneable interface with the exception of a final method that only throws CloneNotSupportedException

Label Label

Bad Example
public class MyClass {
public Object clone() {
return alpha;
}
}
Good Example
public class MyClass {
public Object clone() throws CloneNotSupportedException {
return alpha;
}
}

Loose Coupling

Rule ID: PMD_LoC

Description: The use of implementation types (i.e., HashSet) as object references limits your ability to use alternate implementations in the future as requirements change. Whenever available, referencing objects by their interface types (i.e, Set) provides much more flexibility

Label Label

Bad Example
public class Beta {
private ArrayList<SomeType> list = new ArrayList<>();

public HashSet<SomeType> getAlpha() {
return new HashSet<SomeType>();
}
}
Good Example
public class Beta {
private List<SomeType> list = new ArrayList<>();

public Set<SomeType> getAlpha() {
return new HashSet<SomeType>();
}
}

Signature Declare Throws Exception

Rule ID: PMD_SiDTE

Description: A method/constructor shouldn’t explicitly throw the generic java.lang.Exception, since it is unclear which exceptions that can be thrown from the methods. It might be difficult to document and understand such vague interfaces. Use either a class derived from RuntimeException or a checked exception

Label Label

Bad Example
public void alpha() throws Exception { }

Unused Imports

Rule ID: PMD_UnI

Description: Avoid unused import statements to prevent unwanted dependencies

Label Label

Bad Example
import java.io.File;
import java.util.*;

public class Alpha {}
Good Example
public class ALpha {}

Unused Local Variable

Rule ID: PMD_ULV

Description: The local variable is declared and/or assigned, but not used

Label Label

Bad Example
public class Alpha {
public void doSomething(Int x) {
int i = 5;
return x + 2;
}
}
Good Example
public class Alpha {
public void doSomething(Int x) {
int i = 5;
public int addOne() {
return j + i;
}
}
}

Unused Private Field

Rule ID: PMD_UPF

Description: The private field is declared and/or assigned a value, but not used

Label Label

Bad Example
public class Something {
private static int ALPHA = 2;
private int i = 5;
}
Good Example
public class Something {
private int j = 6;
public int addOne() {
return j++;
}
}

Unused Private Method

Rule ID: PMD_UPM

Description: The private method is declared but is unused

Label Label

Bad Example
public class Something {
private void alpha() {}
}

Accessor Method Generation

Rule ID: PMD_AMG

Description: Avoid autogenerated methods to access private fields and methods of inner/outer classes

Label Label

Bad Example
public class OuterClass {
public class InnerClass {
InnerClass() {
OuterClass.this.counter++;
}
}
}
Good Example
public class OuterClass {
private int counter;
}

Avoid Message Digest Field

Rule ID: PMD_AMDF

Description: It is better to create a new instance, rather than synchronizing access to a shared instance

Label Label

Bad Example
public byte[] calculateHashShared(byte[] data) {
sharedMd.reset();
sharedMd.update(data);
return sharedMd.digest();
}
Good Example
public byte[] calculateHash(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data);
return md.digest();
}

Avoid Reassigning Catch Variables

Rule ID: PMD_ARCV

Description: Reassigning exception variables caught in a catch statement should be avoided

Label Label

Bad Example
public class Alpha {
public void foo() {
try {
// do something
} catch (Exception e) {
e = new NullPointerException();
}
}
}
Good Example
public class Alpha {
public void foo() {
try {
// do something
} catch (MyException | ServerException e) {
e = new RuntimeException();
}
}
}

Avoid Reassigning Loop Variables

Rule ID: PMD_ARLV

Description: Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables can be changed

Label Label

Bad Example
public class Alpha {
private void alpha() {
for (String s : listOfStrings()) {
s = s.trim();
doSomethingWith(s);

s = s.toUpper();
doSomethingElseWith(s);
}
}
}
Good Example
public class Alpha {
private voidalpha() {
for (int i=0; i < 10; i++) {
if (check(i)) {
i++;
}

i = 5;

doSomethingWith(i);
}
}
}

Constants In Interface

Rule ID: PMD_CII

Description: Avoid constants in interfaces. Interfaces define types, constants are implementation details better placed in classes or enums

Label Label

Bad Example
public interface ConstantInterface {
public static final int CONST1 = 1;
static final int CONST2 = 1;
final int CONST3 = 1;
int CONST4 = 1;
}
Good Example
public interface ConstantInterface {
public static final int CONST1 = 1;

int anyMethod();
}

Double Brace Initialization

Rule ID: PMD_DBI

Description: it is preferable to initialize the object normally, rather than usuing double brace initialization

Label Label

Bad Example
List<String> a = new ArrayList<>();
a.add("a");
a.add("b");
a.add("c");
return a;
Good Example
return new ArrayList<String>(){{
add("a");
add("b");
add("c");
}};

For Loop Can Be Foreach

Rule ID: PMD_FLCBF

Description: Reports loops that can be safely replaced with the foreach syntax

Label Label

Bad Example
public class Alpha {
void loop(List<String> l) {
for (int i = 0; i < l.size(); i++) {
System.out.println(l.get(i));
}
}
}
Good Example
public class Alpha {
void loop(List<String> l) {
for (String s : l) {
System.out.println(s);
}
}
}

For Loop Variable Count

Rule ID: PMD_FLVC

Description: Having a lot of control variables in a 'for' loop makes it harder to see what range of values the loop iterates over

Label Label

Bad Example
for (int i = 0, j = 0; i < 10; i++, j += 2) {
alpha();
}
Good Example
for (int i = 0; i < 10; i++) {
alpha();
}

Literals First In Comparisons

Rule ID: PMD_LFIC

Description: Position literals first in all String comparisons

Label Label

Bad Example
class Alpha {
boolean bar(String x) {
return x.equals("3");
}
boolean bar(String x) {
return x.equalsIgnoreCase("3");
}
boolean bar(String x) {
return (x.compareTo("alpha") > 0);
}
boolean bar(String x) {
return (x.compareToIgnoreCase("alpha") > 0);
}
boolean bar(String x) {
return x.contentEquals("alpha");
}
}
Good Example
class Alpha {
boolean bar(String x) {
return "3".equals(x);
}
boolean bar(String x) {
return "3".equalsIgnoreCase(x);
}
boolean bar(String x) {
return ("alpha".compareTo(x) < 0);
}
boolean bar(String x) {
return ("alpha".compareToIgnoreCase(x) < 0);
}
boolean bar(String x) {
return "alpha".contentEquals(x);
}
}

Missing Override

Rule ID: PMD_MO

Description: Annotating overridden methods with @Override helps refactoring and clarifies intent

Label Label

Bad Example
public class Alpha implements Run {
public void run() {
}
}
Good Example
public class Alpha implements Run {
@Override
public void run() {
}
}

Use Try With Resources

Rule ID: PMD_UTWR

Description: Prefer usuing Try With Resources because ensures that each resource is closed at the end of the statement

Label Label

Bad Example
public class Try {
public void run() {
InputStream in = null;
try {
in = openInputStream();
int i = in.read();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (IOException ignored) {
// ignored
}
}
}
}
Good Example
public class Try {
public void run() {
InputStream in = null;
// better use try-with-resources
try (InputStream in2 = openInputStream()) {
int i = in2.read();
}
}
}

While Loop With Literal Boolean

Rule ID: PMD_WLWLB

Description: While loops that include literal booleans are redundant and should be avoided

Label Label

Bad Example
public class Alpha {
{
while (false) { } // disallowed
do { } while (true); // disallowed
do { } while (false); // disallowed
}
}
Good Example
public class Example {
{
while (true) { } // allowed
}
}

Control Statement Braces

Rule ID: PMD_CSB

Description: Enforce a policy for braces on control statements

Label Label

Bad Example
while (true)
x++;
Good Example
while (true) {
x++;
}

Identical Catch Branches

Rule ID: PMD_ICB

Description: Prefer collapsing identical branches into a single multi-catch branch

Label Label

Bad Example
try {
// do something
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalStateException e) {
throw e;
}
Good Example
try {
// do something
} catch (IllegalArgumentException | IllegalStateException e) {
throw e;
}

Unnecessary Annotation Value Element

Rule ID: PMD_UAVE

Description: Avoid the use of value in annotations when it's the only element

Label Label

Bad Example
@TestClassAnnotation(value = "TEST")
public class Alpha {

@TestMemberAnnotation(value = "TEST")
private String alpha;

@TestMethodAnnotation(value = "TEST")
public void beta() {
int gamma = 42;
return;
}
}
Good Example
@TestClassAnnotation("TEST")
public class Alpha {

@TestMemberAnnotation("TEST")
private String alpha;

@TestMethodAnnotation("TEST")
public void beta() {
int gamma = 42;
return;
}
}

Unnecessary Modifier

Rule ID: PMD_UnM

Description: There is no need to modify the interfaces and the annotations

Label Label

Bad Example
public interface Alpha {
public abstract void alpha();
}
Good Example
public interface Alpha {
void alpha();
}

Use Short Array Initializer

Rule ID: PMD_USAI

Description: Define the initial content of the array as a expression in curly braces

Label Label

Bad Example
Alpha[] x = new Alpha[] { ... };
Good Example
Alpha[] x = { ... };

Use Underscores In Numeric Literals

Rule ID: PMD_UUINL

Description: This rule enforces that numeric literals above a certain length should separate every third digit with an underscore

Label Label

Bad Example
public class Alpha {
private int num = 1000000;
}
Good Example
public class Alpha {
private int num = 1_000_000;
}

Useless Qualified This

Rule ID: PMD_UQT

Description: Reports qualified this usages in the same class

Label Label

Bad Example
public class Alpha {
private class Alpha2 {
final Alpha2 Alpha2 = Alpha2.this;
}
}
Good Example
public class Alpha {
private class Alpha2 {
final Alpha myAlpha = Alpha.this;
}
}

Avoid Unchecked Exceptions In Signatures

Rule ID: PMD_AUEIS

Description: Document the exceptional cases with a @throws Javadoc tag, which allows being more descriptive

Label Label

Bad Example
public void foo() throws RuntimeException {
}

Clone Method Must Be Public

Rule ID: PMD_CMMBP

Description: Prefer using a public method for classes that implement this interface should override Object.clone

Label Label

Bad Example
public class Alpha implements Cloneable {
@Override
protected Alpha clone() {
}
}
Good Example
public class Alpha implements Cloneable {
@Override
public Object clone()
}

Clone Method Return Type Must Match Class Name

Rule ID: PMD_CMRTMMCN

Description: If a class implements cloneable the return type of the method clone() must be the class name

Label Label

Bad Example
public class Alpha implements Cloneable {
@Override
protected Object beta() {
}
}
Good Example
public class Alpha implements Cloneable {
@Override
protected Alpha beta() { // Violation, Object must be Foo
}
}

Detached Test Case

Rule ID: PMD_DTC

Description: The method appears to be a test case, but is a member of a class that has one or more JUnit test cases

Label Label

Bad Example
public class MyTest {
@Test
public void someTest() {
}

public void someOtherTest () {
}

}
Good Example
public class MyTest {
@Test
public void someTest() {
}
}

Do Not Extend Java Lang Throwable

Rule ID: PMD_DNEJLT

Description: Extend Exception or RuntimeException instead of Throwable

Label Label

Good Example
public class Alpha extends Throwable { }

Do Not Terminate VM

Rule ID: PMD_DNTVM

Description: Web applications should not call System.exit(), since only the web container or the application server should stop the JVM

Label Label

Bad Example
public void alpha() {
System.exit(0);
}
Good Example
public void alpha() {
Runtime.getRuntime().exit(0);
}

Invalid Log Message Format

Rule ID: PMD_ILMF

Description: Check for messages in slf4j and log4j2 loggers with non matching number of arguments and placeholders

Label Label

Bad Example
LOGGER.error("forget the arg {}");
LOGGER.error("forget the arg %s");
LOGGER.error("too many args {}", "arg1", "arg2");
Good Example
LOGGER.error("param {}", "arg1", new IllegalStateException("arg"));

Single Method Singleton

Rule ID: PMD_SMS

Description: The instance created using the overloaded method is not cached and so, for each call and new objects will be created for every invocation

Label Label

Bad Example
public static Singleton getInstance(Object obj){
Singleton singleton = (Singleton) obj;
return singleton;
}
Good Example
public static Singleton getInstance( ) {
return singleton;
}

Singleton Class Returning New Instance

Rule ID: PMD_SCRNI

Description: getInstance method always creates a new object and hence does not comply to Singleton Design Pattern behaviour

Label Label

Bad Example
class Singleton {
private static Singleton instance = null;
public static Singleton getInstance() {
synchronized(Singleton.class) {
return new Singleton();
}
}
}

Unsynchronized Static Formatter

Rule ID: PMD_USF

Description: Static Formatter objects should be accessed in a synchronized manner

Label Label

Bad Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void alpha() {
sdf.format();
}
}
Good Example
public class Alpha {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void alpha() {
synchronized (sdf) {
sdf.format();
}
}
}

Avoid Calendar Date Creation

Rule ID: PMD_ACDC

Description: Use new Date(), java.time.LocalDateTime.now() or ZonedDateTime.now()

Label Label

Bad Example
public class DateAdd {
private Date bad() {
return Calendar.getInstance().getTime(); // now
}
}
Good Example
public class DateAdd {
private Date good() {
return new Date(); // now
}
}

Avoid File Stream

Rule ID: PMD_AFS

Description: Avoid instantiating FileInputStream, FileOutputStream, FileReader, or FileWriter

Label Label

Bad Example
FileInputStream fis = new FileInputStream(fileName);
Good Example
try(InputStream is = Files.newInputStream(Paths.get(fileName))) {
}

Hard Coded Crypto Key

Rule ID: PMD_HCCK

Description: Do not use hard coded encryption keys. Better store keys outside of source code

Label Label

Bad Example
public class Alpha {
void bad() {
SecretKeySpec secretKeySpec = new SecretKeySpec("my secret here".getBytes(), "AES");
}
}
Good Example
public class Alpha {
void good() {
SecretKeySpec secretKeySpec = new SecretKeySpec(Properties.getKey(), "AES");
}
}

Insecure Crypto Iv

Rule ID: PMD_ICI

Description: Do not use hard coded initialization vector in crypto operations. Better use a randomly generated IV

Label Label

Bad Example
public class Alpha {
void bad() {
byte[] iv = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, };
}
}
Good Example
public class Alpha {
void good() {
SecureRandom random = new SecureRandom();
byte iv[] = new byte[16];
random.nextBytes(bytes);
}
}

Security

Cyclopt scans your Java code for security vulnerabilities, injection, insecure configuration, weak cryptography, data exposure, and more. Each finding below lists its Rule ID, what it detects and how to fix it, a severity, and the relevant CWE/OWASP classification.

note

Security findings are mapped to industry classifications (CWE and OWASP).


Exported Activity

Rule ID: exported_activity

Description: This <activity> is declared exported (either explicitly with android:exported="true" or implicitly by registering an <intent-filter>), so any other app installed on the device can start it via Intent. If the activity performs privileged actions or trusts its inputs, a malicious app can abuse it to bypass your control plane. Set android:exported="false" unless the activity is intentionally part of the public surface, and validate every Intent extra it consumes.

CWE: CWE-926 · OWASP: A5:2021

Severity Category

Tainted SQL String

Rule ID: tainted-sql-string

Description: The Lambda handler's incoming event object is being spliced into a SQL string through + concatenation, String.format, StringBuilder.append, or String.concat. Anything inside $EVENT is attacker-controlled, so an attacker can rewrite the query and exfiltrate or tamper with the database. Bind values through a PreparedStatement with ? placeholders (or an ORM) instead of building the SQL text yourself.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted Sqli

Rule ID: tainted-sqli

Description: Values from the AWS Lambda $EVENT argument reach a JDBC sink such as Statement, PreparedStatement, CallableStatement, JdbcTemplate.queryForObject, queryForMap, or a SqlRowSet, where the SQL text is built by string concatenation. Because the Lambda payload is fully attacker-controlled, this is a classic SQL injection vector. Construct the query with ? bind parameters via connection.prepareStatement (or NamedParameterJdbcTemplate) rather than concatenating the event into the SQL.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Java JWT Decode Without Verify

Rule ID: java-jwt-decode-without-verify

Description: com.auth0.jwt.JWT.decode(...) is being used to read a token without a corresponding JWTVerifier.verify(...) call on the same path. decode only parses the JWT header and payload — it does NOT check the signature, so any claim (including sub, roles, exp) can be forged by the caller. Build a JWTVerifier with the expected algorithm and call .verify(token) before trusting any value from it.

CWE: CWE-345 · OWASP: A08:2021, A08:2025

Severity Category

Java JWT Hardcoded Secret

Rule ID: java-jwt-hardcoded-secret

Description: A string literal is being passed straight into Algorithm.HMAC256/384/512(...) as the JWT signing key. Anyone with read access to the source (or a built artifact) can recover the secret and forge tokens at will. Load the HMAC key from an environment variable, a secrets manager, or an HSM, and never commit it to the repository.

CWE: CWE-798 · OWASP: A07:2021, A07:2025

Severity Category

Java JWT None Alg

Rule ID: java-jwt-none-alg

Description: Tokens here are being signed with com.auth0.jwt.algorithms.Algorithm.none(), which produces an unsigned JWT and lets the verifier accept any forged payload as authentic. The none algorithm exists only for legacy/test scenarios where the JWT integrity is already guaranteed externally — it must never be used in production. Sign with a real algorithm such as Algorithm.HMAC256(...) or Algorithm.RSA256(...) instead.

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Jax Rs Path Traversal

Rule ID: jax-rs-path-traversal

Description: A JAX-RS endpoint passes a @PathParam-bound value straight into new File(...). Because the path segment is taken from the URL, an attacker can include ../ segments and read or write files outside the intended directory. Normalize and validate the user-supplied component before opening it — for example by stripping directory parts with org.apache.commons.io.FilenameUtils.getName(...) or by resolving the path and checking it stays under a fixed base directory.

CWE: CWE-22 · OWASP: A05:2017, A01:2021, A01:2025

Severity Category

Find SQL String Concatenation

Rule ID: find-sql-string-concatenation

Description: Inside $METHOD, the parameter $X is concatenated into a SQL string that is then handed to Session.connection().prepareStatement(...) and executed via executeQuery. Even though a PreparedStatement object is used, the SQL text itself was assembled by string concatenation, so the parameter is interpolated rather than bound — this is SQL injection. Use ? placeholders in the query and call setString/setInt on the PreparedStatement for each parameter.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Jjwt None Alg

Rule ID: jjwt-none-alg

Description: A io.jsonwebtoken.Jwts.builder() chain is being compacted without a signWith(...) step, so jjwt will emit the JWT with the none algorithm and no signature. Any consumer that does not pin an expected algorithm will accept attacker-forged tokens with arbitrary claims. Always call .signWith(SignatureAlgorithm.HS256, key) (or an asymmetric variant) before .compact(), and on the parsing side use Jwts.parser().setSigningKey(...) with a fixed algorithm.

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Assignment Comparison

Rule ID: assignment-comparison

Description: The if condition uses the assignment operator = instead of the equality operator ==, so $X is being overwritten and the branch is decided by the assigned literal rather than by a comparison. This almost certainly hides a typo. Replace = with == (or .equals(...) for objects) to perform the intended test.

Severity Category

Command Injection Formatted Runtime Call

Rule ID: command-injection-formatted-runtime-call

Description: The command passed to Runtime.exec(...) / Runtime.loadLibrary(...) is assembled via string concatenation or String.format(...), often through a shell wrapper such as sh -c or cmd /c. If any concatenated value is reachable from user input, an attacker can append shell metacharacters and execute arbitrary commands. Pass the program and its arguments as a pre-built String[] (no shell wrapper) and validate each argument against an allowlist.

CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Command Injection Process Builder

Rule ID: command-injection-process-builder

Description: A new ProcessBuilder(...) or ProcessBuilder.command(...) invocation is receiving a non-literal command — frequently a shell invocation such as sh -c <arg> or cmd /c <arg> whose final argument is interpolated. When <arg> originates from user input, the shell will happily parse ;, |, backticks, and $(...) to chain additional commands. Provide the executable and its arguments as separate fixed entries, skip the shell wrapper entirely, and reject any argument that does not match a strict allowlist.

CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Crlf Injection Logs

Rule ID: crlf-injection-logs

Description: Untrusted text taken from HttpServletRequest.getParameter(...) is being written to a Logger without stripping \r and \n first. Attackers can embed CR/LF sequences to forge extra log lines, hide their own activity, or break downstream log parsers and SIEM pipelines. Replace newline characters in the value (e.g. value.replaceAll("[\\r\\n]", "_")) or use a structured logging API that escapes them automatically.

CWE: CWE-93 · OWASP: A03:2021, A05:2025

Severity Category

DES Is Deprecated

Rule ID: des-is-deprecated

Description: Legacy DES (56-bit key) is being requested through Cipher.getInstance("DES/..."). The effective key size is small enough that exhaustive search recovers the key in hours on commodity hardware, and NIST formally withdrew the algorithm in 2005. Switch to Cipher.getInstance("AES/GCM/NoPadding") with a 128- or 256-bit key.

CWE: CWE-326 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Desede Is Deprecated

Rule ID: desede-is-deprecated

Description: Triple-DES (DESede / 3DES / TDEA) operates on a 64-bit block, which makes it susceptible to Sweet32-style birthday collisions once a few gigabytes flow through the same key. NIST disallowed TDEA for new applications after 2023. Replace the Cipher.getInstance("DESede/...") call with AES/GCM/NoPadding.

CWE: CWE-326 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Documentbuilderfactory Disallow Doctype Decl False

Rule ID: documentbuilderfactory-disallow-doctype-decl-false

Description: Setting http://apache.org/xml/features/disallow-doctype-decl to false on $DBFACTORY re-enables <!DOCTYPE> parsing without disabling external entities, which exposes the parser to classic XXE (file read, SSRF, billion-laughs DoS). Flip the flag back to true, or alternatively keep DOCTYPE allowed but set both external-general-entities and external-parameter-entities to false.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Documentbuilderfactory Disallow Doctype Decl Missing

Rule ID: documentbuilderfactory-disallow-doctype-decl-missing

Description: A DocumentBuilderFactory instance reaches newDocumentBuilder() without ever calling setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) (and without disabling both external-entity flags), so the resulting parser will resolve external entities declared in the input XML. Configure disallow-doctype-decl to true on the factory before building, or set both external-general-entities and external-parameter-entities to false.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Documentbuilderfactory External General Entities True

Rule ID: documentbuilderfactory-external-general-entities-true

Description: Explicitly turning on http://xml.org/sax/features/external-general-entities on $DBFACTORY instructs the underlying SAX parser to resolve &entity; references, which is the primary vector for XXE-based file disclosure and SSRF. Set this feature to false, or call setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) to reject DOCTYPE entirely.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Documentbuilderfactory External Parameter Entities True

Rule ID: documentbuilderfactory-external-parameter-entities-true

Description: Allowing http://xml.org/sax/features/external-parameter-entities on $DBFACTORY keeps %entity; references inside the DTD active, which lets an attacker stage out-of-band XXE attacks (parameter entities can fetch a remote DTD that triggers further entity expansion). Pass false for this feature, and consider disabling DOCTYPE outright with the disallow-doctype-decl flag.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

ECB Cipher

Rule ID: ecb-cipher

Description: Block ciphers configured in ECB mode encrypt each block independently, so identical plaintext blocks produce identical ciphertext and structural patterns leak directly into the output. ECB also offers no integrity protection, which lets an attacker splice or replay blocks unnoticed. Request an authenticated mode such as Cipher.getInstance("AES/GCM/NoPadding") instead.

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Formatted SQL String

Rule ID: formatted-sql-string

Description: Request data (an HttpServletRequest or a String controller argument) flows into a SQL string built with +, +=, String.format, String.join, String.concat, or StringBuilder.append, and the resulting text is executed through Statement, PreparedStatement, Connection.createStatement/prepareStatement, or EntityManager.createQuery. Even a PreparedStatement is unsafe when the SQL itself was concatenated. Move the user value out of the query text and bind it via setString/setInt or setParameter.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Gcm Nonce Reuse

Rule ID: gcm-nonce-reuse

Description: The IV passed to GCMParameterSpec is a hard-coded byte array, which means the same nonce will be used for every encryption under the key. Reusing a GCM nonce catastrophically breaks the construction: it leaks the XOR of plaintexts and exposes the authentication subkey, letting an attacker forge arbitrary messages. Derive a fresh 96-bit nonce from SecureRandom for each call.

CWE: CWE-323 · OWASP: A02:2021, A04:2025

Severity Category

Hardcoded Conditional

Rule ID: hardcoded-conditional

Description: This if condition reduces to a constant — either a bare true/false, an assignment that yields one, or a boolean short-circuit such as expr && false / expr || true. As written the branch is dead code (or always-taken), which usually points to a logic bug or leftover debugging code. Remove the conditional or fix the predicate so it actually depends on runtime state.

Severity Category

Hibernate Sqli

Rule ID: hibernate-sqli

Description: Hibernate's Session.createQuery, Session.createSQLQuery, or Restrictions.sqlRestriction is being called with HQL/SQL text that was built by + concatenation or String.format. Hibernate does not parameterize what you hand it — the variable becomes part of the query and an attacker can break out of it. Switch to a parameterized HQL/SQL string with :name placeholders and call query.setParameter("name", value) for each one.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

HTTP Response Splitting

Rule ID: http-response-splitting

Description: A request-derived value is being placed inside a new Cookie(..., value, ...) and then handed to HttpServletResponse.addCookie(...). On older servlet containers (and on any container that does not pre-validate cookie values) CR/LF in value can split the Set-Cookie header into additional response headers or a full second response, enabling cache poisoning and XSS. Strip \r\n from the value or reject any input that contains them before it reaches the cookie constructor.

CWE: CWE-113 · OWASP: A03:2021, A05:2025

Severity Category

Httpservlet Path Traversal

Rule ID: httpservlet-path-traversal

Description: Request-derived input flows into a new java.io.File(...), FileOutputStream, or FileInputStream constructor. With segments such as ../ (or their URL-encoded forms) the attacker can escape the intended directory and read or overwrite arbitrary files on the host — /etc/passwd, application config, deployment artifacts, etc. Reduce the input to a bare filename with org.apache.commons.io.FilenameUtils.getName(...), canonicalize the resulting path, and verify it still starts with the expected base directory before opening it.

CWE: CWE-22 · OWASP: A05:2017, A01:2021, A01:2025

Severity Category

Insecure Jms Deserialization

Rule ID: insecure-jms-deserialization

Description: Inside this MessageListener.onMessage(Message) the payload is unwrapped with ObjectMessage.getObject(...), which delegates to native Java serialization. Any peer able to publish to the JMS destination can ship a crafted serialized graph and trigger arbitrary gadget chains on the broker's classpath — i.e. RCE under the consumer's permissions. Switch to TextMessage/BytesMessage with an explicit codec (JSON, Avro), or restrict deserialization via ObjectInputFilter and a class allowlist.

CWE: CWE-502 · OWASP: A08:2017, A08:2021, A08:2025

Severity Category

Insecure Smtp Connection

Rule ID: insecure-smtp-connection

Description: A SimpleEmail instance calls .send(...) without first enabling setSSLCheckServerIdentity(true). With server-identity checking off, Apache Commons Email accepts any TLS certificate the SMTP server presents — including a self-signed one served by a man-in-the-middle — leaking credentials and message contents. Call email.setSSLCheckServerIdentity(true) before sending whenever TLS/SMTPS is used.

CWE: CWE-297 · OWASP: A07:2021, A07:2025

Severity Category

Jackson Unsafe Deserialization

Rule ID: jackson-unsafe-deserialization

Description: This ObjectMapper has enableDefaultTyping() turned on (or a field annotated with @JsonTypeInfo(use = Id.CLASS) on an Object/Serializable/Comparable slot) and is subsequently invoking readValue($JSON, ...). Polymorphic type ids in the JSON tell Jackson which Java class to instantiate, so an attacker who controls $JSON can pick a gadget class on the classpath and pivot to RCE (the same family as CVE-2017-7525). Drop default typing, narrow @JsonTypeInfo to a concrete base class, and configure a PolymorphicTypeValidator that allowlists exactly the subtypes you expect.

CWE: CWE-502 · OWASP: A8:2017, A8:2021

Severity Category

Java Pattern From String Parameter

Rule ID: java-pattern-from-string-parameter

Description: A String method parameter is being handed directly to Pattern.compile(...) or Pattern.matches(...). If the caller can influence that string, they can submit a catastrophic-backtracking pattern such as (a+)+$ and pin a CPU core, causing a Regular Expression Denial of Service. Either keep the regex on the server side as a fixed constant, or validate the caller's pattern (cap its length, reject nested quantifiers) and run it under a timeout.

CWE: CWE-1333 · OWASP: A03:2021

Severity Category

Jdbc SQL Formatted String

Rule ID: jdbc-sql-formatted-string

Description: A Spring JdbcTemplate call (queryForObject, queryForList, update, execute, or insert) is receiving a SQL string that was assembled with +, String.format, or StringBuilder.append. Inlining $VAR directly into the query lets a caller rewrite the statement. Pass the value as a bind argument instead, e.g. jdbc.queryForObject("select * from t where name = ?", Integer.class, parameterName).

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Jdbc Sqli

Rule ID: jdbc-sqli

Description: A raw JDBC java.sql.Statement is invoking executeQuery, execute, executeUpdate, executeLargeUpdate, addBatch, or nativeSQL with a query string assembled via + or String.format. Statement performs no parameter binding, so any concatenated value is interpreted as SQL. Obtain a PreparedStatement from connection.prepareStatement(...) with ? markers and supply the values through setString, setInt, etc.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Jdo Sqli

Rule ID: jdo-sqli

Description: JDO is receiving a JDOQL filter or query that was glued together with + or String.format — either through javax.jdo.Query.setFilter/setGrouping or through PersistenceManager.newQuery(...). Concatenated user data becomes part of the JDOQL expression and can be tampered with. Use a parameterized query (pm.newQuery(cls, "field == :p") plus query.setParameters(value) or named parameter binding) and keep all user values out of the query text.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Jpa Sqli

Rule ID: jpa-sqli

Description: A JPA EntityManager.createQuery or createNativeQuery call is being fed JPQL/SQL text built from + concatenation or String.format. The user-controlled fragment is placed verbatim into the query and can change its structure. Keep the query string static and bind values with query.setParameter("name", value) (or ?1, ?2 positional parameters) so the JPA provider escapes them.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

LDAP Injection

Rule ID: ldap-injection

Description: A search filter built from a non-literal value is being passed to InitialDirContext.search(...) / LdapContext.search(...). Characters such as *, (, ), \, and the NUL byte alter the LDAP filter grammar, so an attacker who controls that value can broaden the query, bypass authentication, or read entries that should be out of scope. Escape the value with javax.naming.ldap.Rdn.escapeValue(...) or build the filter with parameter substitution ({0}, {1}, ...) and a separate arguments array.

CWE: CWE-90 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

MD5 Used As Password

Rule ID: md5-used-as-password

Description: Hashing a password with MessageDigest.getInstance("MD5") and storing the resulting digest on a field whose name contains "password" is a misuse of MD5: the function is fast, unsalted by default, and rainbow tables exist for common inputs, so cracking a leaked digest is cheap. Use a slow, salted password KDF such as SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"), BCryptPasswordEncoder, or Argon2.

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

No Direct Response Writer

Rule ID: no-direct-response-writer

Description: Request data (parameters, headers, cookies, body, or query string) is being written straight to HttpServletResponse.getWriter(), getOutputStream(), or a raw PrintWriter / OutputStream. Bypassing the view layer skips HTML escaping, so any attacker-supplied <script> or event handler renders in the victim's browser. Route the response through a template engine (Thymeleaf, JSF, Mustache) or explicitly encode the value with Encode.forHtml(...) / HtmlUtils.htmlEscape(...) before writing it.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

No Null Cipher

Rule ID: no-null-cipher

Description: javax.crypto.NullCipher is an identity transformation: bytes pass through untouched, so any value encrypted with it is effectively plaintext on the wire and on disk. This class exists only for testing scaffolding and must never reach production code paths. Replace the new NullCipher() call with a real cipher such as Cipher.getInstance("AES/GCM/NoPadding").

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

No Static Initialization Vector

Rule ID: no-static-initialization-vector

Description: The byte array handed to IvParameterSpec is a compile-time literal, so every encryption under the key reuses the exact same IV. Predictable IVs let an attacker detect when two plaintexts are equal (CBC) or recover keystream XORs (CTR/GCM), nullifying the semantic security guarantee. Generate the IV with SecureRandom.nextBytes(iv) immediately before each Cipher.init call.

CWE: CWE-329 · OWASP: A02:2021, A04:2025

Severity Category

No String Eqeq

Rule ID: no-string-eqeq

Description: Two String values are being compared with ==, which checks reference identity rather than character contents. The result depends on whether the JVM happens to intern both operands and therefore differs between literals, new String(...), and values read at runtime. Use a.equals(b) (or Objects.equals(a, b) to also handle nulls) for content comparison.

Severity Category

Object Deserialization

Rule ID: object-deserialization

Description: A new ObjectInputStream(...) is being constructed; any subsequent readObject() call will instantiate arbitrary classes named in the byte stream and run their readObject / readResolve hooks. Combined with a vulnerable gadget on the classpath (CommonsCollections, Spring, etc.), this gives a remote attacker code execution. Replace native Java serialization with a data format that does not invoke constructors (JSON, Protobuf), or wrap the stream with an ObjectInputFilter that allowlists exactly the classes you expect and HMAC the payload to prove its origin.

CWE: CWE-502 · OWASP: A08:2017, A08:2021, A08:2025

Severity Category

Ognl Injection

Rule ID: ognl-injection

Description: An OGNL expression sink (OgnlUtil.getValue/setValue/compile, ValueStack.findValue, TextParseUtil.translateVariables, Struts ReflectionProvider.*, ...) is receiving a dynamic argument rather than a literal. Because OGNL evaluates expressions against the server-side object graph, a user-controlled string can read or mutate any reachable field — the same primitive behind several Apache Struts RCE CVEs. Force the argument to a constant, evaluate against a sandboxed context, or strip OGNL meta-characters before it reaches the sink.

CWE: CWE-94 · OWASP: A03:2021, A05:2025

Severity Category

Rsa No Padding

Rule ID: rsa-no-padding

Description: Calling Cipher.getInstance("RSA/.../NoPadding") selects textbook RSA, where the encryption function is deterministic and multiplicatively homomorphic. Equal plaintexts produce equal ciphertexts and short messages are trivially recovered via cube-root or small-exponent attacks. Switch to OAEP, for example RSA/ECB/OAEPWithSHA-256AndMGF1Padding.

CWE: CWE-326 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Saxparserfactory Disallow Doctype Decl Missing

Rule ID: saxparserfactory-disallow-doctype-decl-missing

Description: This SAXParserFactory flows into newSAXParser() without any call to setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) (and without disabling the two external-*-entities features), so the resulting parser will resolve DOCTYPE-declared external entities and is vulnerable to XXE. Either harden the factory with disallow-doctype-decl=true, or set both external-general-entities and external-parameter-entities to false before use.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Script Engine Injection

Rule ID: script-engine-injection

Description: A javax.script.ScriptEngine instance is calling .eval(...) with a non-constant argument. ScriptEngine.eval interprets the input as full Nashorn/JavaScript source (or whatever engine was instantiated), so any attacker-influenced character lets them execute arbitrary Java via Java.type(...), file I/O, and Runtime.exec. Restrict the argument to a hard-coded template, evaluate inside a sandboxed Bindings/SecurityManager, or replace the scripting engine with a domain-specific parser.

CWE: CWE-94 · OWASP: A03:2021, A05:2025

Severity Category

Servletresponse Writer XSS

Rule ID: servletresponse-writer-xss

Description: Variable $VAR is pulled from HttpServletRequest.getParameter(...) and then written unencoded to HttpServletResponse.getWriter().write(...). Without HTML escaping any <script> tag or event handler in the parameter executes in the victim's browser as a reflected XSS payload. Wrap the value with org.owasp.encoder.Encode.forHtml($VAR) (or the equivalent context-aware encoder for attribute/JS/URL contexts) before it reaches the writer.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

Tainted Cmd From HTTP Request

Rule ID: tainted-cmd-from-http-request

Description: Taint flows from HttpServletRequest (parameters, headers, or cookie values) into the command position of Runtime.exec(...) or ProcessBuilder.command(...). Because that string is handed to the OS process launcher, an attacker who can shape the request can run arbitrary executables or — if a shell wrapper is used — chain shell metacharacters. Resolve the binary path on the server, pass it and its arguments as a fixed String[], and reject any HTTP value that does not match an allowlist.

CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted Env From HTTP Request

Rule ID: tainted-env-from-http-request

Description: HTTP-request data is being routed into the envp (environment-variable) parameter of Runtime.exec(cmd, envp, ...). Overriding the child process environment lets an attacker set LD_PRELOAD, PATH, JAVA_TOOL_OPTIONS, or other loader variables and trivially achieve code execution in the spawned process. Drop the envp argument so the child inherits the JVM environment, or supply a fixed String[] built from server-side constants only.

CWE: CWE-454 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted Ldapi From HTTP Request

Rule ID: tainted-ldapi-from-http-request

Description: Values originating from HttpServletRequest are reaching InitialDirContext.search(...) or DirContext.search(...) and forming part of the LDAP filter. Without escaping, characters such as *, (, ), \ let an attacker rewrite the filter to enumerate directory entries, bypass authentication checks, or push modifications via subsequent DirContext calls. Pass user input only as a SearchControls argument substituted via {N} placeholders, and escape RDN values with javax.naming.ldap.Rdn.escapeValue(...).

CWE: CWE-90 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted Session From HTTP Request

Rule ID: tainted-session-from-http-request

Description: A value taken from HttpServletRequest (parameter, header, cookie, or decoded query string) is being stored on HttpSession via setAttribute(...) / putValue(...) without validation. Once written into the session the value is implicitly trusted by later code paths — a classic trust-boundary violation that lets attackers smuggle payloads (XSS strings, forged roles, malformed objects) across requests. Normalize and validate the value before persisting it, or persist a server-derived representation instead of the raw input.

CWE: CWE-501 · OWASP: A04:2021, A06:2025

Severity Category

Tainted SQL From HTTP Request

Rule ID: tainted-sql-from-http-request

Description: Values pulled from an HttpServletRequest/ServletRequest (getParameter, getHeader, getCookies, getQueryString, getInputStream, etc.) are reaching a SQL execution sink — a Statement/PreparedStatement/CallableStatement, a JdbcTemplate call, or a SqlRowSet. Anything taken directly off the HTTP request must be treated as hostile; concatenating it into SQL is injection. Bind the value through PreparedStatement.setString(...) (or the named-parameter JdbcTemplate API).

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted Xpath From HTTP Request

Rule ID: tainted-xpath-from-http-request

Description: A request-supplied string is being concatenated into a javax.xml.xpath.XPath.evaluate(...) or .compile(...) expression. XPath has its own syntax — quotes, or, not(), // — so untrusted text lets an attacker rewrite the predicate to read sibling nodes, exfiltrate credentials stored in the XML document, or bypass authorization filters. Bind dynamic values through XPath.setXPathVariableResolver(...) and reference them in the expression as $var rather than splicing them in as text.

CWE: CWE-643 · OWASP: A03:2021, A05:2025

Severity Category

Transformerfactory Dtds Not Disabled

Rule ID: transformerfactory-dtds-not-disabled

Description: When this TransformerFactory builds a Transformer, neither XMLConstants.ACCESS_EXTERNAL_DTD nor XMLConstants.ACCESS_EXTERNAL_STYLESHEET has been set to the empty string, so XSLT inputs are free to fetch remote DTDs and stylesheets. That lets an attacker stage XXE or SSRF through a crafted transformation. Set both attributes to "" on the factory before calling newTransformer(...).

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Turbine Sqli

Rule ID: turbine-sqli

Description: Apache Turbine's BasePeer.executeQuery / GroupPeer.executeQuery is being called with a SQL string that was concatenated with + or formatted via String.format. Turbine executes that text directly, so anything interpolated becomes part of the statement and can be manipulated by callers. Build the query with Criteria and the Peer's parameterized APIs, or convert to a PreparedStatement with ? placeholders.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Unencrypted Socket

Rule ID: unencrypted-socket

Description: Plain new Socket(...) and new ServerSocket(...) open a cleartext TCP channel, so any party on the network path can observe or tamper with the bytes in transit. For anything carrying credentials, tokens, or user data, obtain the socket from SSLSocketFactory.getDefault() (or SSLServerSocketFactory) so the connection negotiates TLS with certificate verification enabled.

CWE: CWE-319 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Unvalidated Redirect

Rule ID: unvalidated-redirect

Description: A request-controlled URL flows straight into HttpServletResponse.sendRedirect(...) or addHeader("Location", ...) without any host check. Attackers can craft phishing links pointing at your domain that bounce to a look-alike site, harvesting credentials or distributing malware while keeping the original URL trusted by users and mail filters. Compare the target against an allowlist of internal paths/hosts, or store only an opaque token and resolve it server-side.

CWE: CWE-601 · OWASP: A01:2021, A01:2025

Severity Category

URL Rewriting

Rule ID: url-rewriting

Description: HttpServletResponse.encodeURL(...) / encodeRedirectURL(...) (and the deprecated lowercase variants) embed jsessionid=... in the URL whenever the container thinks the client has cookies disabled. The session identifier then leaks into browser history, Referer headers sent to third-party sites, proxy logs, and bookmarks — anyone who captures the URL can hijack the session. Disable URL rewriting in web.xml (<tracking-mode>COOKIE</tracking-mode>) and stop calling these encode methods.

CWE: CWE-200 · OWASP: A01:2021, A01:2025

Severity Category

Use Of Aes ECB

Rule ID: use-of-aes-ecb

Description: Pairing AES with ECB through Cipher.getInstance("AES/ECB/...") cancels out the benefits of AES: blocks are encrypted in isolation, so repeated 16-byte sections in the plaintext yield repeated ciphertext that an attacker can correlate or swap. There is also no built-in integrity check. Use an authenticated mode such as AES/GCM/NoPadding with a random 96-bit IV.

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Blowfish

Rule ID: use-of-blowfish

Description: Blowfish's 64-bit block size triggers a birthday collision around 32 GB of ciphertext under the same key (the Sweet32 attack), which is well within the reach of long-lived sessions or bulk data flows. The algorithm's own author has recommended dropping it for newer designs. Replace Cipher.getInstance("Blowfish") with Cipher.getInstance("AES/GCM/NoPadding").

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Default Aes

Rule ID: use-of-default-aes

Description: Calling Cipher.getInstance("AES") without specifying a mode or padding causes the SunJCE provider to default to AES/ECB/PKCS5Padding. ECB encrypts each block independently and leaks plaintext structure, making the ciphertext semantically insecure. Always state the mode and padding explicitly, for example Cipher.getInstance("AES/GCM/NoPadding").

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of MD5

Rule ID: use-of-md5

Description: MessageDigest.getInstance("MD5") instantiates a hash function that has been publicly broken since 2004: chosen-prefix collisions are cheap to compute, which voids MD5's value for signatures, fingerprints, or any integrity check. For general hashing pick SHA-256/SHA-512; for password storage use PBKDF2, bcrypt, scrypt, or Argon2.

CWE: CWE-328 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of MD5 Digest Utils

Rule ID: use-of-md5-digest-utils

Description: Apache Commons DigestUtils.getMd5Digest() returns an MD5 instance, but MD5 collisions can be generated on a laptop in seconds, so any signature, integrity tag, or content-addressed identifier built on top of it can be forged. Swap the call for DigestUtils.getSha512Digest() (or getSha256Digest()), or use an HMAC construction when a secret key is involved.

CWE: CWE-328 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Rc2

Rule ID: use-of-rc2

Description: RC2 is a 1980s 64-bit block cipher that succumbs to related-key and chosen -plaintext distinguishers and, like all 64-bit ciphers, falls to Sweet32 birthday attacks under moderate traffic. The 40-bit export-grade variant is completely broken. Replace Cipher.getInstance("RC2") with Cipher.getInstance("AES/GCM/NoPadding").

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Rc4

Rule ID: use-of-rc4

Description: The keystream produced by RC4 has measurable biases in its early bytes (and elsewhere), enabling plaintext recovery attacks such as those that led to RC4 being banned from TLS by RFC 7465. As a stream cipher with no integrity layer it is also trivially malleable. Drop Cipher.getInstance("RC4") in favour of Cipher.getInstance("AES/GCM/NoPadding").

CWE: CWE-327 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of SHA1

Rule ID: use-of-sha1

Description: Practical chosen-prefix collisions against SHA-1 (SHAttered, 2017; Shambles, 2020) mean that MessageDigest.getInstance("SHA-1") and DigestUtils.getSha1Digest() cannot be relied on for signatures, certificate fingerprints, or commitments. Use SHA-256 or SHA-512 for general hashing, and PBKDF2/bcrypt/Argon2 for password storage.

CWE: CWE-328 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Sha224

Rule ID: use-of-sha224

Description: SHA-224 / SHA-512/224 / SHA3-224 deliver only 112 bits of collision resistance, which falls below the 128-bit floor that NIST SP 800-131A and several national cryptographic guidelines mandate for new applications. Calls such as DigestUtils.sha3_224(...) or MessageDigest.getInstance("SHA-224") should be upgraded to SHA-256, SHA-384, or SHA-512.

CWE: CWE-328 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Of Weak Rsa Key

Rule ID: use-of-weak-rsa-key

Description: KeyPairGenerator for RSA is being initialized with fewer than 2048 bits, leaving the modulus within reach of factoring attacks (a 1024-bit key is considered breakable by well-resourced adversaries). NIST SP 800-57 and the OWASP Cryptographic Storage guidance both require at least 2048 bits, and 3072 bits is recommended for keys with a long protection window. Pass 2048 or larger to initialize(...).

CWE: CWE-326 · OWASP: A03:2017, A02:2021, A04:2025

Severity Category

Use Snakeyaml function Object() { [native code] }

Rule ID: use-snakeyaml-constructor

Description: The no-arg new org.yaml.snakeyaml.Yaml() constructor uses SnakeYAML's default Constructor, which honours !!-tagged class names and can instantiate arbitrary types (e.g. javax.script.ScriptEngineManager) when load(...) runs on attacker-supplied input — a well-known RCE primitive. Build the parser with new Yaml(new SafeConstructor()) or a tightly whitelisted custom Constructor.

CWE: CWE-502 · OWASP: A08:2017, A08:2021, A08:2025

Severity Category

Vertx Sqli

Rule ID: vertx-sqli

Description: Vert.x SqlClient / SqlConnection is invoking query, preparedQuery, or prepare with SQL text built from + concatenation or String.format. Even preparedQuery only parameterizes the Tuple arguments — the SQL string itself is executed as-is, so interpolated values become part of the statement. Keep the query literal and pass the user values inside Tuple.of(...) for preparedQuery to bind.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Xmlinputfactory External Entities Enabled

Rule ID: xmlinputfactory-external-entities-enabled

Description: This XMLInputFactory is being switched on to resolve external entities (either via IS_SUPPORTING_EXTERNAL_ENTITIES=true or SUPPORT_DTD=true), which turns the StAX parser into an XXE primitive capable of reading local files and probing internal services. Pass Boolean.FALSE to both properties (or simply leave the secure defaults in place) before parsing untrusted XML.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Xmlinputfactory Possible Xxe

Rule ID: xmlinputfactory-possible-xxe

Description: An XMLInputFactory is being instantiated here without an explicit setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false) call (and no equivalent on SUPPORT_DTD). Because the StAX defaults vary by JDK and provider, parsing attacker-controlled XML may still resolve external entities and lead to file disclosure or SSRF. Lock both properties to Boolean.FALSE immediately after creating the factory.

CWE: CWE-611 · OWASP: A04:2017, A05:2021, A02:2025

Severity Category

Spel Injection

Rule ID: spel-injection

Description: ExpressionParser.parseExpression(...) (Spring's SpEL engine) is being called with a non-literal string. SpEL evaluates arbitrary code — method calls, type references, T(java.lang.Runtime).getRuntime().exec(...) — so any attacker-controlled fragment that reaches the parser turns into remote code execution. Either keep the expression fully static, or evaluate against a hardened SimpleEvaluationContext with a strict allow-list of properties and method resolvers.

CWE: CWE-94 · OWASP: A03:2021, A05:2025

Severity Category

Spring Actuator Dangerous Endpoints Enabled

Rule ID: spring-actuator-dangerous-endpoints-enabled

Description: The application.properties line management.endpoints.web.exposure.include=$...ACTUATORS publishes actuators other than the safe health probe. Endpoints like env, heapdump, loggers, or httptrace disclose secrets or accept runtime changes from unauthenticated callers. Trim the list to only what is needed, and protect /actuator/** with a Spring Security filter that enforces authentication and roles.

CWE: CWE-200 · OWASP: A01:2021, A01:2025

Severity Category

Spring Actuator Dangerous Endpoints Enabled Yaml

Rule ID: spring-actuator-dangerous-endpoints-enabled-yaml

Description: Beyond the safe /actuator/health probe, the YAML configuration explicitly exposes actuator "$ACTUATOR" over HTTP. Many non-health actuators (e.g. env, beans, configprops, heapdump, loggers) leak runtime state or allow runtime mutation. Drop the entry from management.endpoints.web.exposure.include if it is not needed, or place /actuator/** behind Spring Security with an appropriate role check.

CWE: CWE-200 · OWASP: A01:2021, A01:2025

Severity Category

Spring Actuator Fully Enabled

Rule ID: spring-actuator-fully-enabled

Description: application.properties contains management.endpoints.web.exposure.include=*, which turns on every Spring Boot Actuator endpoint at /actuator/**. Endpoints such as env, heapdump, threaddump, loggers, and mappings reveal configuration properties, in-memory secrets, and a full heap snapshot to anyone who can reach the service. Restrict the property to a minimal set (for example health,info) and require authentication on /actuator/** via Spring Security.

CWE: CWE-200 · OWASP: A01:2021, A01:2025

Severity Category

Spring Actuator Fully Enabled Yaml

Rule ID: spring-actuator-fully-enabled-yaml

Description: The application.yml sets management.endpoints.web.exposure.include: "*", which publishes every Spring Boot Actuator endpoint over HTTP — including /actuator/env, /actuator/heapdump, /actuator/threaddump, and /actuator/logfile. Without Spring Security in front of /actuator/**, these are reachable anonymously and leak configuration, secrets, and memory contents. Replace the wildcard with an explicit list (typically just health, info) and guard the rest behind authenticated routes.

CWE: CWE-200 · OWASP: A01:2021, A01:2025

Severity Category

Spring Sqli

Rule ID: spring-sqli

Description: A String argument exposed on a public method signature is being passed as the SQL text into a Spring sink — JdbcTemplate.batchUpdate/other JdbcTemplate methods, new PreparedStatementCreatorFactory(...), NamedParameterBatchUpdateUtils, or BatchUpdateUtils. Any caller controls that string, so it is effectively an injection sink. Hardcode the SQL inside the method and accept the dynamic values as separate parameters bound through ? placeholders.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Spring Unvalidated Redirect

Rule ID: spring-unvalidated-redirect

Description: A Spring MVC controller is returning "redirect:" + $URL (directly or via new ModelAndView(...)), where $URL comes straight from a method parameter. Spring will issue an HTTP 302 to whatever host the caller provides, enabling phishing flows that send users to attacker-controlled domains under your origin's trust. Match $URL against an allow-list of relative paths or known hosts before using it as a redirect target.

CWE: CWE-601 · OWASP: A01:2021, A01:2025

Severity Category

Tainted File Path

Rule ID: tainted-file-path

Description: A value bound through a Spring @RequestBody, @PathVariable, @RequestParam, @RequestHeader, @CookieValue, or @ModelAttribute parameter is reaching a file sink such as new File(...), new FileInputStream(...), new FileOutputStream(...), Paths.get(...), new ClassPathResource(...), ResourceUtils.getFile(...), or getResourceAsStream(...). ../ segments in that input let the caller escape the intended directory. Normalize the path with FilenameUtils.getName(...) or resolve it against a fixed base and reject anything outside that base.

CWE: CWE-23 · OWASP: A01:2021, A01:2025

Severity Category

Tainted HTML String

Rule ID: tainted-html-string

Description: A Spring controller parameter (@RequestBody, @PathVariable, @RequestParam, @RequestHeader, @CookieValue, or @ModelAttribute) flows into an HTML fragment built via +, String.format, or StringBuilder.append, and the resulting markup is returned through ResponseEntity.body(...) / ResponseEntity.ok(...). Concatenating untrusted text into HTML is the textbook XSS pattern. HTML-encode the value with Encode.forHtml(...) (OWASP encoder), or sanitize with PolicyFactory.sanitize, AntiSamy.scan, or JSoup.clean before it joins the markup.

CWE: CWE-79 · OWASP: A07:2017, A03:2021, A05:2025

Severity Category

Tainted SQL String

Rule ID: tainted-sql-string

Description: A value taken from a Spring @RequestBody/@PathVariable/@RequestParam/@RequestHeader/@CookieValue parameter is being woven into a SQL string with +, +=, String.format, or StringBuilder.append containing keywords like SELECT, INSERT, UPDATE, etc. That hand-built statement can be reshaped by the caller, which is SQL injection. Replace the concatenation with a PreparedStatement (or an ORM such as JPA/Hibernate) and bind the request data through setString/setParameter.

CWE: CWE-89 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted System Command

Rule ID: tainted-system-command

Description: Request data from a Spring @RequestBody/@PathVariable/@RequestParam/@RequestHeader/@CookieValue/@ModelAttribute parameter is concatenated into a command line and then handed to Runtime.exec, Runtime.load/loadLibrary, ProcessBuilder.command(...), or ProcessBuilder.start. Whatever the caller submits becomes part of the shell command, giving them OS-level code execution. Drop the concatenation, pin the executable, and pass each argument as its own element — e.g. new ProcessBuilder("ls", "-al", targetDirectory).start() — after validating the inputs against an allow-list.

CWE: CWE-78 · OWASP: A01:2017, A03:2021, A05:2025

Severity Category

Tainted URL Host

Rule ID: tainted-url-host

Description: A Spring controller parameter (@RequestBody, @PathVariable, @RequestParam, @RequestHeader, @CookieValue, or @ModelAttribute) reaches the host position of a URL — either new URL(...) or a string formatted as http(s)://%s... via +, String.format, or StringBuilder.append. If the host is caller-controlled, an outbound request can be redirected to internal services or attacker infrastructure, leaking cookies/auth headers along the way (SSRF). Resolve the request against an explicit allow-list of hosts, or only let user input influence the path or query string of a pinned base URL.

CWE: CWE-918 · OWASP: A10:2021, A01:2025

Severity Category

Ship Fast. Validate Smarter.Protect your reputation.

Cyclopt G2 profile

29A, Ptolemaion Street, Coho Building, Thessaloniki, Greece, Tel: +30 2310 471 030
Copyright © 2026 Cyclopt