SonarSource Rules
  • Products

    In-IDE

    Code Quality and Security in your IDE with SonarQube Ide

    IDE extension that lets you fix coding issues before they exist!

    Discover SonarQube for IDE

    SaaS

    Code Quality and Security in the cloud with SonarQube Cloud

    Setup is effortless and analysis is automatic for most languages

    Discover SonarQube Cloud

    Self-Hosted

    Code Quality and Security Self-Hosted with SonarQube Server

    Fast, accurate analysis; enterprise scalability

    Discover SonarQube Server
  • SecretsSecrets
  • ABAPABAP
  • AnsibleAnsible
  • ApexApex
  • AzureResourceManagerAzureResourceManager
  • CC
  • C#C#
  • C++C++
  • CloudFormationCloudFormation
  • COBOLCOBOL
  • CSSCSS
  • DartDart
  • DockerDocker
  • FlexFlex
  • GitHub ActionsGitHub Actions
  • GoGo
  • HTMLHTML
  • JavaJava
  • JavaScriptJavaScript
  • JSONJSON
  • JCLJCL
  • KotlinKotlin
  • KubernetesKubernetes
  • Objective CObjective C
  • PHPPHP
  • PL/IPL/I
  • PL/SQLPL/SQL
  • PythonPython
  • RPGRPG
  • RubyRuby
  • RustRust
  • ScalaScala
  • ShellShell
  • SwiftSwift
  • TerraformTerraform
  • TextText
  • TypeScriptTypeScript
  • T-SQLT-SQL
  • VB.NETVB.NET
  • VB6VB6
  • XMLXML
  • YAMLYAML
Java

Java static code analysis

Unique rules to find Bugs, Vulnerabilities, Security Hotspots, and Code Smells in your JAVA code

  • All rules 733
  • Vulnerability60
  • Bug175
  • Security Hotspot40
  • Code Smell458

  • Quick Fix 65
Filtered: 139 rules found
Tags
    Impact
      consistency
        1. Literal suffixes should be upper case

           Code Smell
        2. When a defaultFinisher is passed to a Gatherer factory, use the overload that does not take a finisher

           Code Smell
        3. Don't provide an initializer for a stateless stream gatherer

           Code Smell
        4. Comments should start with the appropriate number of slashes

           Code Smell
        5. Markdown, HTML and Javadoc tags should be consistent

           Code Smell
        6. Methods returning "Page" or "Slice" must take "Pageable" as an input parameter

           Code Smell
        7. Motion Sensor should not use gyroscope

           Code Smell
        8. Use when instead of a single if inside a pattern match body

           Code Smell
        9. "setDaemon", "setPriority" and "getThreadGroup" should not be invoked on virtual threads

           Bug
        10. Use built-in "Math.clamp" methods

           Code Smell
        11. Reverse view should be used instead of reverse copy in read-only cases

           Code Smell
        12. Reverse iteration should utilize reversed view

           Code Smell
        13. SpEL expression should have a valid syntax

           Bug
        14. "@Controller" should be replaced with "@RestController"

           Code Smell
        15. Bean names should adhere to the naming conventions

           Code Smell
        16. Optional REST parameters should have an object type

           Code Smell
        17. Field dependency injection should be avoided

           Code Smell
        18. Async methods should return void or Future

           Bug
        19. Methods with Spring proxy should not be called via "this"

           Code Smell
        20. "@Value" annotation should inject property or SpEL expression

           Code Smell
        21. XML signatures should be validated securely

           Vulnerability
        22. XML parsers should not load external schemas

           Vulnerability
        23. XML parsers should not allow inclusion of arbitrary files

           Vulnerability
        24. Enabling file access for WebViews is security-sensitive

           Security Hotspot
        25. Enabling JavaScript support for WebViews is security-sensitive

           Security Hotspot
        26. Deprecated annotations should include explanations

           Code Smell
        27. Authorizing non-authenticated users to use keys in the Android KeyStore is security-sensitive

           Security Hotspot
        28. String multiline concatenation should be replaced with Text Blocks

           Code Smell
        29. Similar tests should be grouped in a single Parameterized test

           Code Smell
        30. Spring's ModelAndViewAssert assertions should be used instead of other assertions

           Code Smell
        31. A new session should be created during user authentication

           Vulnerability
        32. Methods setUp() and tearDown() should be correctly annotated starting with JUnit4

           Code Smell
        33. Authorizations should be based on strong decisions

           Vulnerability
        34. Class members annotated with "@VisibleForTesting" should not be accessed from production code

           Code Smell
        35. Migrate your tests from JUnit4 to the new JUnit5 annotations

           Code Smell
        36. Whitespace for text block indent should be consistent

           Code Smell
        37. Configuring loggers is security-sensitive

           Security Hotspot
        38. Java features should be preferred to Guava

           Code Smell
        39. "StandardCharsets" constants should be preferred

           Code Smell
        40. Persistent entities should not be used as arguments of "@RequestMapping" methods

           Vulnerability
        41. "HttpSecurity" URL patterns should be correctly ordered

           Vulnerability
        42. Enum values should be compared with "=="

           Code Smell
        43. "default" clauses should be last

           Code Smell
        44. Delivering code in production with debug features activated is security-sensitive

           Security Hotspot
        45. Disabling CSRF protections is security-sensitive

           Security Hotspot
        46. "equals" method parameters should not be marked "@Nonnull"

           Code Smell
        47. Allowing deserialization of LDAP objects is security-sensitive

           Security Hotspot
        48. Spring components should use constructor injection

           Code Smell
        49. Local constants should follow naming conventions for constants

           Code Smell
        50. "java.nio.Files#delete" should be preferred

           Code Smell
        51. Track uses of disallowed constructors

           Code Smell
        52. A conditionally executed single line should be denoted by indentation

           Code Smell
        53. Conditionals should start on new lines

           Code Smell
        54. Number patterns should be regular

           Code Smell
        55. "Stream.peek" should be used with caution

           Code Smell
        56. Track uses of disallowed classes

           Code Smell
        57. Test methods should comply with a naming convention

           Code Smell
        58. Test classes should comply with a naming convention

           Code Smell
        59. Loggers should be named for their enclosing classes

           Code Smell
        60. "ThreadGroup" should not be used

           Code Smell
        61. Static non-final field names should comply with a naming convention

           Code Smell
        62. "clone" should not be overridden

           Code Smell
        63. Classes without "public" constructors should be "final"

           Code Smell
        64. Unnecessary semicolons should be omitted

           Code Smell
        65. Multiline blocks should be enclosed in curly braces

           Code Smell
        66. Classes should not be loaded dynamically

           Vulnerability
        67. Setting loose POSIX file permissions is security-sensitive

           Security Hotspot
        68. "Thread" should not be used where a "Runnable" argument is expected

           Code Smell
        69. Mutable fields should not be "public static"

           Code Smell
        70. "Iterator.next()" methods should throw "NoSuchElementException"

           Bug
        71. Track uses of disallowed methods

           Code Smell
        72. Methods with Spring proxying annotations should be public

           Bug
        73. Methods should not call same-class methods with incompatible "@Transactional" values

           Bug
        74. Classes named like "Exception" should extend "Exception" or a subclass

           Code Smell
        75. "runFinalizersOnExit" should not be called

           Bug
        76. Underscores should be used to make large numbers readable

           Code Smell
        77. "java.time" classes should be used for dates and times

           Code Smell
        78. Parsing should be used to convert "Strings" to primitives

           Code Smell
        79. Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes

           Code Smell
        80. "URL.hashCode" and "URL.equals" should be avoided

           Code Smell
        81. Try-with-resources should be used

           Code Smell
        82. Comparators should be "Serializable"

           Code Smell
        83. The names of methods with boolean return values should start with "is" or "has"

           Code Smell
        84. Exceptions should not be thrown from servlet methods

           Vulnerability
        85. Classes and methods that rely on the default system encoding should not be used

           Code Smell
        86. Simple class names should be used

           Code Smell
        87. Boolean checks should not be inverted

           Code Smell
        88. "@Deprecated" code should not be used

           Code Smell
        89. Methods and field names should not be the same or differ only by capitalization

           Code Smell
        90. The ternary operator should not be used

           Code Smell
        91. A field should not duplicate the name of its containing class

           Code Smell
        92. "NullPointerException" should not be caught

           Code Smell
        93. "NullPointerException" should not be explicitly thrown

           Code Smell
        94. An abstract class should have both abstract and concrete methods

           Code Smell
        95. Multiple variables should not be declared on the same line

           Code Smell
        96. Abstract classes without fields should be converted to interfaces

           Code Smell
        97. Package declaration should match source file directory

           Code Smell
        98. "Collections.EMPTY_LIST", "EMPTY_MAP", and "EMPTY_SET" should not be used

           Code Smell
        99. Comments should not be located at the end of lines of code

           Code Smell
        100. Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "LinkedList"

           Code Smell
        101. Track uses of "CHECKSTYLE:OFF" suppression comments

           Code Smell
        102. Loggers should be "private static final" and should share a naming convention

           Code Smell
        103. Track comments matching a regular expression

           Code Smell
        104. Packages should have a javadoc file 'package-info.java'

           Code Smell
        105. Statements should be on separate lines

           Code Smell
        106. The members of an interface or class declaration should appear in a pre-defined order

           Code Smell
        107. Package names should comply with a naming convention

           Code Smell
        108. Array designators "[]" should be on the type, not the variable

           Code Smell
        109. Array designators "[]" should be located after the type in method signatures

           Code Smell
        110. Exception types should not be tested using "instanceof" in catch blocks

           Code Smell
        111. Classes from "sun.*" packages should not be used

           Code Smell
        112. Future keywords should not be used as names

           Code Smell
        113. Type parameter names should comply with a naming convention

           Code Smell
        114. Throwable and Error should not be caught

           Code Smell
        115. Abstract class names should comply with a naming convention

           Code Smell
        116. Local variable and method parameter names should comply with a naming convention

           Code Smell
        117. Exception handlers should preserve the original exceptions

           Code Smell
        118. Exception classes should have final fields

           Code Smell
        119. Checked exceptions should not be thrown

           Code Smell
        120. Field names should comply with a naming convention

           Code Smell
        121. "Enumeration" should not be implemented

           Code Smell
        122. Constant names should comply with a naming convention

           Code Smell
        123. Synchronized classes "Vector", "Hashtable", "Stack" and "StringBuffer" should not be used

           Code Smell
        124. Exit methods should not be called

           Code Smell
        125. Interface names should comply with a naming convention

           Code Smell
        126. Files should end with a newline

           Code Smell
        127. Boolean literals should not be redundant

           Code Smell
        128. Source code should be indented consistently

           Code Smell
        129. Labels should not be used

           Code Smell
        130. A close curly brace should be located at the beginning of a line

           Code Smell
        131. Close curly brace and the next "else", "catch" and "finally" keywords should be on two different lines

           Code Smell
        132. Close curly brace and the next "else", "catch" and "finally" keywords should be located on the same line

           Code Smell
        133. An open curly brace should be located at the beginning of a line

           Code Smell
        134. An open curly brace should be located at the end of a line

           Code Smell
        135. URIs should not be hardcoded

           Code Smell
        136. Tabulation characters should not be used

           Code Smell
        137. Lines should not be too long

           Code Smell
        138. Class names should comply with a naming convention

           Code Smell
        139. Method names should comply with a naming convention

           Code Smell

        Configuring loggers is security-sensitive

        consistency - conventional
        security
        Security Hotspot

          This rule is deprecated, and will eventually be removed.

          Configuring loggers is security-sensitive. It has led in the past to the following vulnerabilities:

          • CVE-2018-0285
          • CVE-2000-1127
          • CVE-2017-15113
          • CVE-2015-5742

          Logs are useful before, during and after a security incident.

          • Attackers will most of the time start their nefarious work by probing the system for vulnerabilities. Monitoring this activity and stopping it is the first step to prevent an attack from ever happening.
          • In case of a successful attack, logs should contain enough information to understand what damage an attacker may have inflicted.

          Logs are also a target for attackers because they might contain sensitive information. Configuring loggers has an impact on the type of information logged and how they are logged.

          This rule flags for review code that initiates loggers configuration. The goal is to guide security code reviews.

          Ask Yourself Whether

          • unauthorized users might have access to the logs, either because they are stored in an insecure location or because the application gives access to them.
          • the logs contain sensitive information on a production server. This can happen when the logger is in debug mode.
          • the log can grow without limit. This can happen when additional information is written into logs every time a user performs an action and the user can perform the action as many times as he/she wants.
          • the logs do not contain enough information to understand the damage an attacker might have inflicted. The loggers mode (info, warn, error) might filter out important information. They might not print contextual information like the precise time of events or the server hostname.
          • the logs are only stored locally instead of being backuped or replicated.

          There is a risk if you answered yes to any of those questions.

          Recommended Secure Coding Practices

          • Check that your production deployment doesn’t have its loggers in "debug" mode as it might write sensitive information in logs.
          • Production logs should be stored in a secure location which is only accessible to system administrators.
          • Configure the loggers to display all warnings, info and error messages. Write relevant information such as the precise time of events and the hostname.
          • Choose log format which is easy to parse and process automatically. It is important to process logs rapidly in case of an attack so that the impact is known and limited.
          • Check that the permissions of the log files are correct. If you index the logs in some other service, make sure that the transfer and the service are secure too.
          • Add limits to the size of the logs and make sure that no user can fill the disk with logs. This can happen even when the user does not control the logged information. An attacker could just repeat a logged action many times.

          Remember that configuring loggers properly doesn’t make them bullet-proof. Here is a list of recommendations explaining on how to use your logs:

          • Don’t log any sensitive information. This obviously includes passwords and credit card numbers but also any personal information such as user names, locations, etc…​ Usually any information which is protected by law is good candidate for removal.
          • Sanitize all user inputs before writing them in the logs. This includes checking its size, content, encoding, syntax, etc…​ As for any user input, validate using whitelists whenever possible. Enabling users to write what they want in your logs can have many impacts. It could for example use all your storage space or compromise your log indexing service.
          • Log enough information to monitor suspicious activities and evaluate the impact an attacker might have on your systems. Register events such as failed logins, successful logins, server side input validation failures, access denials and any important transaction.
          • Monitor the logs for any suspicious activity.

          Sensitive Code Example

          This rule supports the following libraries: Log4J, java.util.logging and Logback

          // === Log4J 2 ===
          import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
          import org.apache.logging.log4j.Level;
          import org.apache.logging.log4j.core.*;
          import org.apache.logging.log4j.core.config.*;
          
          // Sensitive: creating a new custom configuration
          abstract class CustomConfigFactory extends ConfigurationFactory {
              // ...
          }
          
          class A {
              void foo(Configuration config, LoggerContext context, java.util.Map<String, Level> levelMap,
                      Appender appender, java.io.InputStream stream, java.net.URI uri,
                      java.io.File file, java.net.URL url, String source, ClassLoader loader, Level level, Filter filter)
                      throws java.io.IOException {
                  // Creating a new custom configuration
                  ConfigurationBuilderFactory.newConfigurationBuilder();  // Sensitive
          
                  // Setting loggers level can result in writing sensitive information in production
                  Configurator.setAllLevels("com.example", Level.DEBUG);  // Sensitive
                  Configurator.setLevel("com.example", Level.DEBUG);  // Sensitive
                  Configurator.setLevel(levelMap);  // Sensitive
                  Configurator.setRootLevel(Level.DEBUG);  // Sensitive
          
                  config.addAppender(appender); // Sensitive: this modifies the configuration
          
                  LoggerConfig loggerConfig = config.getRootLogger();
                  loggerConfig.addAppender(appender, level, filter); // Sensitive
                  loggerConfig.setLevel(level); // Sensitive
          
                  context.setConfigLocation(uri); // Sensitive
          
                  // Load the configuration from a stream or file
                  new ConfigurationSource(stream);  // Sensitive
                  new ConfigurationSource(stream, file);  // Sensitive
                  new ConfigurationSource(stream, url);  // Sensitive
                  ConfigurationSource.fromResource(source, loader);  // Sensitive
                  ConfigurationSource.fromUri(uri);  // Sensitive
              }
          }
          
          // === java.util.logging ===
          import java.util.logging.*;
          
          class M {
              void foo(LogManager logManager, Logger logger, java.io.InputStream is, Handler handler)
                      throws SecurityException, java.io.IOException {
                  logManager.readConfiguration(is); // Sensitive
          
                  logger.setLevel(Level.FINEST); // Sensitive
                  logger.addHandler(handler); // Sensitive
              }
          }
          
          // === Logback ===
          import ch.qos.logback.classic.util.ContextInitializer;
          import ch.qos.logback.core.Appender;
          import ch.qos.logback.classic.joran.JoranConfigurator;
          import ch.qos.logback.classic.spi.ILoggingEvent;
          import ch.qos.logback.classic.*;
          
          class M {
              void foo(Logger logger, Appender<ILoggingEvent> fileAppender) {
                  System.setProperty(ContextInitializer.CONFIG_FILE_PROPERTY, "config.xml"); // Sensitive
                  JoranConfigurator configurator = new JoranConfigurator(); // Sensitive
          
                  logger.addAppender(fileAppender); // Sensitive
                  logger.setLevel(Level.DEBUG); // Sensitive
              }
          }
          

          Exceptions

          Log4J 1.x is not covered as it has reached end of life.

          See

          • OWASP - Top 10 2021 Category A9 - Security Logging and Monitoring Failures
          • OWASP - Top 10 2017 Category A3 - Sensitive Data Exposure
          • OWASP - Top 10 2017 Category A10 - Insufficient Logging & Monitoring
          • CWE - CWE-117 - Improper Output Neutralization for Logs
          • CWE - CWE-532 - Information Exposure Through Log Files
            Available In:
          • SonarQube IdeCatch issues on the fly,
            in your IDE
          • SonarQube CloudDetect issues in your GitHub, Azure DevOps Services, Bitbucket Cloud, GitLab repositories
          • SonarQube Community BuildAnalyze code in your
            on-premise CI
            Available Since
            9.1
          • SonarQube ServerAnalyze code in your
            on-premise CI
            Developer Edition
            Available Since
            9.1

          © 2025 SonarSource Sàrl. All rights reserved.

          Privacy Policy | Cookie Policy | Terms of Use