A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://docs.sonarsource.com/sonarqube-server/latest/analyzing-source-code/languages/java/ below:

Java | SonarQube Server Documentation

Supported versions

The level of support for a language is defined as follows: 

LTS 8, 11, 17, 21 and all intermediary versions up to Java 22 are fully supported. 

Web/Application Frameworks

Struts, Spring, JSP

Test Frameworks

JUnit 4/5, AssertJ, Mockito, Spring Test, TestNG

ORMs

Hibernate, Spring JDBC Template, JDO, VertX SQL

Language-specific properties

You can discover and update the Java-specific properties in Administration > Configuration > General Settings > Languages > Java

Java analysis and bytecode

Compiled .class files are required for Java projects with more than one Java file. If not provided properly, analysis will fail with the message:

Your project contains .java files, please provide compiled classes with sonar.java.binaries property, or exclude them from the analysis with sonar.exclusions property.

If only some .class files are missing, you'll see warnings like this:

Class 'XXXXXX' is not accessible through the ClassLoader.

If you are not using Maven or Gradle for analysis, you must manually provide bytecode to the analysis. You can also analyze test code, and for that you need to provide tests binaries and test libraries properties.

Note that manually providing the sonar.java.binaries is very error-prone. We highly recommend using Scanner for Gradle if you’re building with Gradle, or Scanner for Maven if you’re using Maven.

Key Value sonar.java.binaries (required) Comma-separated paths to directories containing the compiled bytecode files corresponding to your source files. sonar.java.libraries Comma-separated paths to files with third-party libraries (JAR or Zip files) used by your project. Wildcards can be used: sonar.java.libraries=path/to/Library.jar,directory/**/*.jar sonar.java.test.binaries Comma-separated paths to directories containing the compiled bytecode files corresponding to your test files sonar.java.test.libraries Comma-separated paths to files with third-party libraries (JAR or Zip files) used by your tests. (For example, this should include the junit jar). Wildcards can be used: sonar.java.test.libraries=directory/**/*.jar

Android users, Jack doesn't provide the required .class files.

Project's specific JDK

In some situations, you might have to analyze a project built with a different version of Java than the one executing the analysis. The most common case is to run the analysis with Java 17, while the project itself uses Java 11 or before for its build.

If this is your case, you will need to set the sonar.java.jdkHome property manually to point the appropriate JDK (see below). By doing this you will specify which JDK classes the analyzer must refer to during the analysis. Not setting this property, while it would have been required, usually leads to inconsistent or even impossible to fix issues being reported, especially in relation with native JDK classes.

When setting sonar.java.jdkHome, you need to provide the path to the JDK directory used by the project being analyzed, if different from the Java runtime executing the analysis. For example, for a Java 11 project, by setting it as follows: sonar.java.jdkHome=/usr/lib/jvm/jdk11/

# Here maven uses the default version of Java on the system but we specify that we want to analyze a Java 11 project.
mvn org.sonarsource.scanner.maven:sonar-maven-plugin:sonar \
  # other analysis parameters
  -Dsonar.java.jdkHome=/usr/lib/jvm/jdk11/
  # other analysis parameters

This option can of course be added to your sonar.properties configuration.

JDK preview features

To enable the JDK preview features in your instance of SonarQube Server, you can set the sonar.java.enablePreview analysis parameter to true (default is false). 

Turning issues off

The best way to deactivate an individual issue you don't intend to fix is to mark it as accepted or false positive through the SonarQube Server UI.

If you need to deactivate a rule (or all rules) for an entire file, then issue exclusions are the way to go. But if you only want to deactivate a rule across a subset of a file - all the lines of a method or a class - you can use @SuppressWarnings("all") or @SuppressWarnings with rule keys: @SuppressWarnings("java:S2077") or @SuppressWarnings({"java:S1118", "java:S3546"}).

Handling Java source version

Java analysis is able to react to the Java version used for sources. This feature allows the deactivation of rules that target higher versions of Java than the one in use in the project so that false positives aren't generated from irrelevant rules.

The feature relies entirely on the sonar.java.source property, which is automatically filled by most of the scanners used for analyses (Maven, Gradle). Java version-specific rules are not disabled when sonar.java.source is not provided. Concretely, rules that are designed to target specific Java versions (tagged "java8" or "java11") are activated by default in the Sonar Way Java profile. From a user perspective, the feature is fully automatic, but it means that you probably want your projects to be correctly configured.

When using SonarScanner to perform analyses of project, the property sonar.java.source can be set manually in sonar-project.properties. Accepted formats are:

Example: sonar.java.source=11

If the property is provided, the analysis will take the source version into account, and execute related rules accordingly. At run time, each of these rules will be executed – or not – depending upon the Java version used by sources within the project. For instance, on a correctly configured project built with Java 11, rules targeting Java 17 and Java 21 will never raise issues, even though they are enabled in the associated rule profile.

Batch mode settings

By default, files are parsed in batches. The size of the batch is dynamically computed based on the maximum memory available. It is possible to manually set this value by using the property sonar.java.experimental.batchModeSizeInKB. Note that the perfect value depends on the project and the ecosystem setup, bigger batch size will not necessarily increase the performance and can even slow things down if the memory is a limiting factor. If needed, it is possible to run the parsing file by file by setting sonar.java.fileByFile=true.

More details can be found here .

Skipping unchanged files

Starting from April 2022, and by default, the Java analyzer optimizes the analysis of unchanged files in pull requests. In practice, this means that on a file that has not changed, the analyzer only runs a restricted list of rules. To get a better understanding of the rule exclusion mechanism, keep in mind that:

This last criteria implies that custom rules  cannot be skipped.

If you wish to disable this optimization, you can set the value of the analysis parameter sonar.java.skipUnchanged to false. Leaving the parameter unset lets the server decide whether the optimization should be enabled.

Cache-enabled rules (experimental)

Starting from April 2022, the Java analyzer offers rule developers a SQ cache that can be used to store and retrieve information from one analysis to the other. The cache is provided by the underlying instance of SonarQube Server and is branch-specific. Please refer to the sonar-java wiki  for additional information.

Analyzing JSP and Thymeleaf for XSS vulnerabilities

In SonarQube Server Commercial editions and on SonarQube Cloud, you can benefit from advanced security rules including XSS vulnerability detection. Java analysis supports analysis of Thymeleaf and JSP views when used with Java Servlets or Spring. To benefit from this analysis you need to make your views part of the project sources using sonar.sources property. In practice, this usually means adding the following in your Maven pom.xml file

     <properties>
        <sonar.sources>src/main/java,src/main/webapp</sonar.sources>
      </properties>

or if you use Gradle

    sonarqube {
        properties {
            property "sonar.sources", "src/main/java,src/main/webapp"
        }
    }

where src/main/webapp is the directory which contains .jsp or Thymeleaf's .html files.

Custom rules Tutorial

The tutorial Writing custom Java rules 101  will help to quickly start writing custom rules for Java.

Configuring plugins for analyzer loading optimization

By default, the loading of analyzers is optimized (see Improving performance), SonarQube Server will only download analyzers and third-party plugins for the detected languages before running an analysis. 

When creating custom plugins, to prevent errors when projects are analyzed, “you must use the requiredForLanguages property in your plugin's pom.xml file (Gradle: Plugin-RequiredForLanguages in the MANIFEST directly) to specify the languages your plugin supports. Without this property, your plugin will be executed unconditionally during analysis, even when its language-specific dependencies are unavailable. See Plugin basics for details on this behavior and the requiredForLanguages property.

<configuration>
   [...]
   <requiredForLanguages>java</requiredForLanguages>
</configuration>
API changes 7.31 7.29

All the API changes are related to ECJ utility methods that were commonly used in the analyzer and could benefit the implementation of custom rules.

7.25

Update custom rules registration API CheckRegistrar.RegistrarContext to allow:

Add custom rules registration API ProfileRegistrar.RegistrarContext to allow:

7.19

All the API changes are related to the support of the preview feature of Java 19/20. These new types and methods are introduced as "deprecated" and will be marked out of deprecation with the introduction of the final features in the JDK.

7.17 7.16 7.15 7.12 7.7 7.6 7.4 7.1 7.0

The following deprecated methods have been dropped:

The following classes have been dropped, since all their methods where already deprecated:

6.15 6.3
/**
 * Check if the current type is a parameterized type or not.
 *
 * @return true in case of Generic and Parameterized types
 *
 * @since SonarJava 6.3
 */
boolean isParameterized();

/**
 * The arguments of a parameterized type, as a parameterization of a generic type.
 *
 * @return the ordered list of type arguments. Returns an empty lists for non-parameterized types.
 *
 * @since SonarJava 6.3
 */
List<Type> typeArguments();
// old test prior to 6.3:
@Test
public void deprecatedCustomRuleTest() {
   JavaCheckVerifier.verify("path/to/my/custom/check/test/file.java", new MyCheck());
}

// new test starting from 6.3:
@Test
public void newCustomRuleTest() {
   JavaCheckVerifier.newVerifier()
     .onFile("path/to/my/custom/check/test/file.java")
     .withCheck(new MyCheck())
     .verifyIssues();
}
6.1
class A {
  public static final String CONSTANT1 = "abc";
  public static final String CONSTANT2 = CONSTANT1 + "def";

  void foo() {
    System.out.println(CONSTANT2);
                    // ^^^^^^^^^ calling 'identifier.asConstant(String.class)' will return 'Optional.of("abcdef")'
  }
}
6.0
class A<T> {
//    ^^^^ Definition of a Generic Type
  boolean equals(Object o) {
    if (o instance of A) {
                   // ^ this is a raw type, not erasure of A<T>
     return true;
    }
    return false;
  }

  A<String> foo() {
    return new A<String>();
           //  ^^^^^^^^^ Parameterization of a Generic Type
  }
}
Class A {
  UnknownType<String> myMethod() { /* ... */ }
                  //  ^^^^^^^^  symbol corresponding to the MethodTree will be unknown,
}
5.12
//org.sonar.plugins.java.api.JavaFileScannerContext
/**
* Computes the list of syntax nodes which are contributing to increase the complexity for the given methodTree.
* @deprecated use {@link #getComplexityNodes(Tree)} instead
* @param enclosingClass not used.
* @param methodTree the methodTree to compute the complexity.
* @return the list of syntax nodes incrementing the complexity.
*/
@Deprecated
List<Tree> getMethodComplexityNodes(ClassTree enclosingClass, MethodTree methodTree);
//org.sonar.plugins.java.api.JavaResourceLocator
/**
* get source file key by class name.
* @deprecated since 4.1 : will be dropped with no replacement.
* @param className fully qualified name of the analyzed class.
* @return key of the source file for the given class.
*/
@Deprecated
String findSourceFileKeyByClassName(String className);
//org.sonar.plugins.surefire.api.SurefireUtils
/**
* @deprecated since 4.11
*/
@Deprecated
public static final String SUREFIRE_REPORTS_PATH_PROPERTY = "sonar.junit.reportsPath";
 //org.sonar.plugins.java.api.JavaFileScannerContext
/**
* Report an issue at a specific line of a given file.
* This method is used for one
* @param file File on which to report
* @param check The check raising the issue.
* @param line line on which to report the issue
* @param message Message to display to the user
* @deprecated since SonarJava 5.12 - File are not supported anymore. Use corresponding 'reportIssue' methods, or directly at project level
*/
@Deprecated
void addIssue(File file, JavaCheck check, int line, String message);
/**
* FileKey of currently analyzed file.
* @return the fileKey of the file currently analyzed.
* @deprecated since SonarJava 5.12 - Rely on the InputFile key instead, using {@link #getInputFile()}
*/
@Deprecated
String getFileKey();

/**
* File under analysis.
* @return the currently analyzed file.
* @deprecated since SonarJava 5.12 - File are not supported anymore. Use {@link #getInputFile()} or {@link #getProject()} instead
*/
@Deprecated
File getFile();
//org.sonar.plugins.java.api.tree.CaseLabelTree
/**
* @deprecated (since 5.12) use the {@link #expressions()} method.
*/
@Deprecated
@Nullable
ExpressionTree expression();

/**
* @deprecated (since 5.12) use the {@link #colonOrArrowToken()} method.
*/
@Deprecated
SyntaxToken colonToken();
//JavaFileScannerContext: New methods
/**
* Report an issue at at the project level.
* @param check The check raising the issue.
* @param message Message to display to the user
*/
void addIssueOnProject(JavaCheck check, String message);

/**
* InputFile under analysis.
* @return the currently analyzed inputFile.
*/
InputFile getInputFile();

/**
* InputComponent representing the project being analyzed
* @return the project component
*/
InputComponent getProject();
//org.sonar.plugins.java.api.tree.SwitchExpressionTree
/**
* 'switch' expression.
*
* JLS 14.11
*
* <pre>
*   switch ( {@link #expression()} ) {
*     {@link #cases()}
*   }
* </pre>
*
* @since Java 12
*/
@Beta
public interface SwitchExpressionTree extends ExpressionTree {

SyntaxToken switchKeyword();

SyntaxToken openParenToken();

ExpressionTree expression();

SyntaxToken closeParenToken();

SyntaxToken openBraceToken();

List<CaseGroupTree> cases();

SyntaxToken closeBraceToken();
}
 //org.sonar.plugins.java.api.tree.SwitchStatementTree
/**
* Switch expressions introduced with support Java 12
* @since SonarJava 5.12
*/
SwitchExpressionTree asSwitchExpression();
 //org.sonar.plugins.java.api.tree.CaseLabelTree
/**
* @return true for case with colon: "case 3:" or "default:"
*         false for case with arrow: "case 3 ->" or "default ->"
* @since 5.12 (Java 12 new features)
*/
boolean isFallThrough();

/**
* @since 5.12 (Java 12 new features)
*/
SyntaxToken colonOrArrowToken();
 //org.sonar.plugins.java.api.tree.BreakStatementTree
/**
* @since 5.12 (Java 12 new features)
*/
@Nullable
ExpressionTree value();
 //org.sonar.plugins.java.api.tree.TreeVisitor
void visitSwitchExpression(SwitchExpressionTree tree);
5.7
@Rule(key = "MyFirstCustomRule")
public class MyFirstCustomCheck extends IssuableSubscriptionVisitor {

    @Override
    public List<Kind> nodesToVisit() {
        return ImmutableList.of(Kind.METHOD);
    }

    @Override
    public void visitNode(Tree tree) {
        MethodTree method = (MethodTree) tree;
        MethodSymbol symbol = method.symbol();
        
        Type returnType = symbol.returnType().type();
        // When analyzing the code "MyClass<Integer> foo() {return null; }"
        // BEFORE: returnType == ClassJavaType
        // NOW: returnType == ParametrizedTypeJavaType

        // Getting back previous type
        Type erasedType = returnType.erasure();
        // erasedType == ClassJavaType
    }
}

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4