What are you trying to accomplish?
Scan for normal execution
Support a new language?
No
Extend an existing one? Which one?
java
Add language-agnostic features?
No
Something else?
Add formatting code checking
What’s your specific coding challenge in developing your plugin?
I use googlejavaformat to format the code. When I deploy the plugin, I run a scan and an error occurs, prompting java.lang.NoClassDefFoundError: com/sun/source/tree/Tree
I build the jar package in jdk17.
My sonarqube is deployed using docker.
And, if relevant, please share the code that’s giving you problems:
@Rule(key = JavaCodeFormatRule.RULE_KEY, name = "code format check", description = "XXXXXXX")
public class JavaCodeFormatRule implements IRule {
private static final Logger LOGGER = Loggers.get(JavaCodeFormatRule.class);
public static final String RULE_KEY = "JavaCodeFormatRule";
@Override
public void execute(SensorContext sensorContext, InputFile file, RuleKey ruleKey) {
try {
String contents = file.contents();
Formatter formatter = new Formatter(JavaFormatterOptions.builder()
.style(JavaFormatterOptions.Style.AOSP)
.formatJavadoc(true)
.reorderModifiers(false)
.build());
String formattedCode = formatter.formatSource(contents);
if (!Objects.equals(contents, formattedCode)) {
LOGGER.error("代码未格式化!");
NewIssue newIssue = sensorContext.newIssue();
newIssue.forRule(ruleKey)
.at(newIssue.newLocation().on(file).at(file.selectLine(1)))
.save();
}
} catch (IOException | FormatterException e) {
throw new RuntimeException(e);
}
}
}
10:31:06.548 INFO Execute PMD 6.15.0 (done) | time=108493ms
10:31:06.652 INFO Sensor PmdSensor [pmd] (done) | time=108598ms
10:31:06.652 INFO Sensor JaCoCo XML Report Importer [jacoco]
10:31:06.654 INFO 'sonar.coverage.jacoco.xmlReportPaths' is not defined. Using default locations: target/site/jacoco/jacoco.xml,target/site/jacoco-it/jacoco.xml,build/reports/jacoco/test/jacocoTestReport.xml
10:31:06.655 INFO No report imported, no coverage information will be imported by JaCoCo XML Report Importer
10:31:06.655 INFO Sensor JaCoCo XML Report Importer [jacoco] (done) | time=3ms
10:31:06.655 INFO Sensor IaC CloudFormation Sensor [iac]
10:31:06.678 INFO 0 source files to be analyzed
10:31:06.690 INFO 0/0 source files have been analyzed
10:31:06.690 INFO Sensor IaC CloudFormation Sensor [iac] (done) | time=35ms
10:31:06.690 INFO Sensor IaC Kubernetes Sensor [iac]
10:31:06.703 INFO 0 source files to be analyzed
10:31:06.704 INFO 0/0 source files have been analyzed
10:31:06.705 INFO Sensor IaC Kubernetes Sensor [iac] (done) | time=15ms
10:31:06.705 INFO Sensor JavaScript inside YAML analysis [javascript]
10:31:06.710 INFO No input files found for analysis
10:31:06.711 INFO Hit the cache for 0 out of 0
10:31:06.713 INFO Miss the cache for 0 out of 0
10:31:06.713 INFO Sensor JavaScript inside YAML analysis [javascript] (done) | time=8ms
10:31:06.713 INFO Sensor CSS Rules [javascript]
10:31:06.719 INFO No CSS, PHP, HTML or VueJS files are found in the project. CSS analysis is skipped.
10:31:06.719 INFO Sensor CSS Rules [javascript] (done) | time=6ms
10:31:06.719 INFO Sensor Analyzer all Java files [example]
10:31:07.029 INFO EXECUTION FAILURE
10:31:07.033 INFO Total time: 2:42.421s
10:31:07.034 ERROR Error during SonarScanner CLI execution
java.lang.NoClassDefFoundError: com/sun/source/tree/Tree
at org.sonarsource.plugins.custom.rules.JavaCodeFormatRule.execute(JavaCodeFormatRule.java:32)
at org.sonarsource.plugins.custom.rules.JavaFilesSensor.lambda$execute$0(JavaFilesSensor.java:58)
at java.base/java.util.HashMap$Values.forEach(Unknown Source)
at org.sonarsource.plugins.custom.rules.JavaFilesSensor.execute(JavaFilesSensor.java:58)
at org.sonar.scanner.sensor.AbstractSensorWrapper.analyse(AbstractSensorWrapper.java:64)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:88)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.lambda$execute$1(ModuleSensorsExecutor.java:61)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.withModuleStrategy(ModuleSensorsExecutor.java:79)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:61)
at org.sonar.scanner.scan.SpringModuleScanContainer.doAfterStart(SpringModuleScanContainer.java:82)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.scanner.scan.SpringProjectScanContainer.scan(SpringProjectScanContainer.java:403)
at org.sonar.scanner.scan.SpringProjectScanContainer.scanRecursively(SpringProjectScanContainer.java:399)
at org.sonar.scanner.scan.SpringProjectScanContainer.doAfterStart(SpringProjectScanContainer.java:368)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.scanner.bootstrap.SpringGlobalContainer.doAfterStart(SpringGlobalContainer.java:137)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.batch.bootstrapper.Batch.doExecute(Batch.java:72)
at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:66)
at org.sonarsource.scanner.lib.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:41)
at java.base/jdk.internal.reflect.NativeMethod
And I also tried to add --add-opens=jdk.compiler/com.sun.source=ALL-UNNAMED to the environment variables SONAR_WEB_JAVAADDITIONALOPTS and SONAR_CE_JAVAADDITIONALOPTS of sonarqube’s docker deployment, but it still doesn’t work
And you can try passing --add-opens=jdk.compiler/com.sun.source=ALL-UNNAMED in the environment variable SONAR_SCANNER_JAVA_OPTS before running the scanner.
See documentation.
10:10:29.586 INFO Scanner configuration file: /work/sonarqub-scanner/sonar-scanner/conf/sonar-scanner.properties
10:10:29.600 INFO Project root configuration file: NONE
10:10:29.640 INFO SonarScanner CLI 6.2.1.4610
10:10:29.644 INFO Java 17.0.12 Eclipse Adoptium (64-bit)
10:10:29.645 INFO Linux 3.10.0-1160.el7.x86_64 amd64
MODULES=()
mvn clean package -Dmaven.test.skip=true -Dxjar.password=io.xjar
mvn dependency:copy-dependencies -DoutputDirectory=./tmplib
for module_dir in */; do
if [ -d "${module_dir}src/main/java" ]; then
MODULE_NAME=$(basename "$module_dir")
MODULES+=("$MODULE_NAME")
if [ ! -d "${module_dir}target" ]; then
echo "Target directory does not exist for module $MODULE_NAME"
continue
fi
echo "Current directory: $(pwd)"
echo "Looking for JAR files in: ${module_dir}target"
JAR_FILE=$(find "${module_dir}target" -maxdepth 1 -name "*.jar" | head -n 1)
if [ -z "$JAR_FILE" ]; then
echo "No JAR file found for module $MODULE_NAME"
continue
fi
for target_module_dir in */; do
if [ "$target_module_dir" != "$module_dir" ]; then
mkdir -p "${target_module_dir}tmplib"
echo "Copy ${JAR_FILE} to ${target_module_dir}tmplib/"
cp -f "$JAR_FILE" "${target_module_dir}tmplib/"
fi
done
fi
done
MODULE_PARAMS=()
for module_dir in */; do
if [ -d "$module_dir/src/main/java" ]; then
MODULE_NAME=$(basename "$module_dir")
MODULE_PARAMS+=(
# "-D${MODULE_NAME}.sonar.projectBaseDir=${module_dir}"
"-D${MODULE_NAME}.sonar.sources=src/main/java"
"-D${MODULE_NAME}.sonar.java.binaries=target/classes"
)
if [ -d "${module_dir}tmplib" ]; then
echo "Found for module ${MODULE_NAME} tmplib"
LIBRARIES=$(find "${module_dir}tmplib" -name "*.jar" | sed "s|^${module_dir}||" | tr '\n' ',')
MODULE_PARAMS+=("-D${MODULE_NAME}.sonar.java.libraries=${LIBRARIES}")
fi
fi
done
SONAR_CMD=(
"/work/sonarqub-scanner/sonar-scanner/bin/sonar-scanner"
"-Dsonar.projectKey=${SONAR_PROJECT_KEY}"
"-Dsonar.projectName=${SONAR_PROJECT_NAME}"
"-Dsonar.branch.name=${CI_COMMIT_REF_NAME}"
"-Dsonar.language=java"
"-Dsonar.java.source=1.8"
"-Dsonar.projectVersion=${SONAR_PROJECT_VERSION}"
"-Dsonar.modules=$(IFS=,; echo "${MODULES[*]}")"
"${MODULE_PARAMS[@]}"
)
"${SONAR_CMD[@]}"
Yes, the plugin is running in the scanner.
The scanner version you are using is providing a JRE from the server, which is Java 17 as you can see in the logs.
I looked at the documentation of google-java-format, and it says to add the JVM options as you suggested.
You need classes from the javac compiler module, which is not included in a JRE.
To get a JDK instead of a JRE you can disable the provisioning with: sonar.scanner.skipJreProvisioning=true
Hi @cglcl,
Sorry I missed that you are on 9.9, in that case, the variable to use is SONAR_SCANNER_OPTS (instead of SONAR_SCANNER_JAVA_OPTS).
It must be an environment variable, you cannot pass it as a property.
Hello, @eric.giffon
I try add environment variable, but still got the same error.
/work/sonarqub-scanner/sonar-scanner/bin/sonar-scanner -Dsonar.projectKey=bill -Dsonar.projectName=bill -Dsonar.branch.name=m-feature-merge-managed -Dsonar.language=java -Dsonar.java.source=1.8 -Dsonar.projectVersion=1.0 -Dsonar.java.binaries=.
WARNING: Unknown module: jdk.compiler specified to --add-exports
WARNING: Unknown module: jdk.compiler specified to --add-exports
WARNING: Unknown module: jdk.compiler specified to --add-exports
WARNING: Unknown module: jdk.compiler specified to --add-exports
WARNING: Unknown module: jdk.compiler specified to --add-exports
WARNING: Unknown module: jdk.compiler specified to --add-exports
14:25:54.374 INFO Scanner configuration file: /work/sonarqub-scanner/sonar-scanner/conf/sonar-scanner.properties
14:25:54.383 INFO Project root configuration file: NONE
14:25:54.414 INFO SonarScanner CLI 6.2.1.4610
14:25:54.422 INFO Java 17.0.12 Eclipse Adoptium (64-bit)
14:25:54.424 INFO Linux 3.10.0-1160.el7.x86_64 amd64
14:25:54.427 INFO SONAR_SCANNER_OPTS=--add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
14:25:54.508 INFO User cache: /work/sonarqub-scanner/sonar-cache/cache
14:25:56.051 INFO Communicating with SonarQube Server 9.9.7.96285
14:25:56.951 INFO Load global settings
14:25:57.384 INFO Load global settings (done) | time=434ms
14:25:57.390 INFO Server id: 70B2A81A-AZKuXpG5TApl3iz-9d9x
14:25:57.410 INFO User cache: /work/sonarqub-scanner/sonar-cache/cache
14:25:57.422 INFO Load/download plugins
14:25:57.422 INFO Load plugins index
14:25:57.501 INFO Load plugins index (done) | time=79ms
14:25:57.629 INFO Load/download plugins (done) | time=207ms
14:25:59.028 INFO Process project properties
14:25:59.032 INFO Process project properties (done) | time=4ms
14:25:59.039 INFO Execute project builders
14:25:59.046 INFO Execute project builders (done) | time=7ms
14:25:59.051 INFO Project key: bill
14:25:59.051 INFO Base dir: /work/workspace/0/mq_gitlab/11986
14:25:59.051 INFO Working dir: /work/workspace/0/mq_gitlab/11986/.scannerwork
14:25:59.079 INFO Load project settings for component key: 'bill'
14:25:59.383 INFO Load project settings for component key: 'bill' (done) | time=304ms
14:25:59.620 INFO Load project branches
14:25:59.691 INFO Load project branches (done) | time=71ms
14:25:59.694 INFO Load branch configuration
14:25:59.701 INFO Load branch configuration (done) | time=7ms
14:25:59.855 INFO Auto-configuring with CI 'Jenkins'
14:25:59.860 INFO Load quality profiles
14:25:59.941 INFO Load quality profiles (done) | time=81ms
14:25:59.949 INFO Load active rules
14:26:03.119 INFO Load active rules (done) | time=3169ms
14:26:03.131 INFO Load analysis cache
14:26:03.153 INFO Load analysis cache (404) | time=22ms
14:26:03.221 INFO Branch name: m-feature-scc-merge-managed
14:26:03.265 INFO Load project repositories
14:26:03.496 INFO Load project repositories (done) | time=231ms
14:26:03.610 INFO Indexing files...
14:26:03.616 INFO Project configuration:
14:26:03.617 INFO Excluded sources: helm-charts/**, job/**, */src/test**, helm-template/**
14:26:05.460 INFO 1405 files indexed
14:26:05.464 INFO 73 files ignored because of inclusion/exclusion patterns
14:26:05.464 INFO 0 files ignored because of scm ignore settings
14:26:05.468 INFO Quality profile for java: p3c-java
14:26:05.469 INFO Quality profile for xml: Sonar way
14:26:05.469 INFO Quality profile for yaml: Sonar way
14:26:05.469 INFO ------------- Run sensors on module bill
14:26:05.772 INFO Load metrics repository
14:26:05.816 INFO Load metrics repository (done) | time=44ms
14:26:08.727 INFO Sensor JavaSensor [java]
14:26:08.740 INFO Configured Java source version (sonar.java.source): 8
14:26:08.774 INFO JavaClasspath initialization
14:26:08.777 INFO JavaClasspath initialization (done) | time=4ms
14:26:08.778 INFO JavaTestClasspath initialization
14:26:08.783 INFO JavaTestClasspath initialization (done) | time=5ms
14:26:08.805 INFO Server-side caching is enabled. The Java analyzer will not try to leverage data from a previous analysis.
14:26:08.871 INFO Using ECJ batch to parse 1267 Main java source files with batch size 208 KB.
14:26:09.523 INFO Starting batch processing.
14:26:10.931 INFO The Java analyzer cannot skip unchanged files in this context. A full analysis is performed for all files.
14:26:32.903 INFO 100% analyzed
14:26:32.905 INFO Batch processing: Done.
14:26:32.906 INFO Did not optimize analysis for any files, performed a full analysis for all 1267 files.
14:26:32.907 WARN Dependencies/libraries were not provided for analysis of SOURCE files. The 'sonar.java.libraries' property is empty. Verify your configuration, as you might end up with less precise results.
14:26:32.914 WARN Unresolved imports/types have been detected during analysis. Enable DEBUG mode to see them.
14:26:32.918 WARN Use of preview features have been detected during analysis. Enable DEBUG mode to see them.
14:26:32.919 INFO No "Test" source files to scan.
14:26:32.920 INFO No "Generated" source files to scan.
14:26:32.920 INFO Sensor JavaSensor [java] (done) | time=24194ms
14:26:32.920 INFO Sensor PmdSensor [pmd]
14:26:32.922 INFO Execute PMD 6.15.0
14:26:32.949 INFO Java version: 1.8
14:26:32.980 INFO PMD configuration: /work/qianliu-agent/workspace/0/mq_gitlab/11986/.scannerwork/pmd.xml
Dec 13, 2024 2:26:34 PM net.sourceforge.pmd.lang.ast.xpath.Attribute getValue
WARNING: Use of deprecated attribute 'FieldDeclaration/@Array' in XPath query
Dec 13, 2024 2:26:34 PM net.sourceforge.pmd.lang.ast.xpath.Attribute getValue
WARNING: Use of deprecated attribute 'LocalVariableDeclaration/@Array' in XPath query
Dec 13, 2024 2:26:36 PM net.sourceforge.pmd.lang.ast.xpath.Attribute getValue
WARNING: Use of deprecated attribute 'ConditionalExpression/@Ternary' in XPath query
Dec 13, 2024 2:26:38 PM net.sourceforge.pmd.lang.ast.xpath.Attribute getValue
WARNING: Use of deprecated attribute 'ReferenceType/@Array' in XPath query
14:27:21.184 INFO Execute PMD 6.15.0 (done) | time=48262ms
14:27:21.200 INFO Sensor PmdSensor [pmd] (done) | time=48280ms
14:27:21.202 INFO Sensor Analyzer all Java files [custom]
14:27:21.654 INFO EXECUTION FAILURE
14:27:21.657 INFO Total time: 1:27.290s
14:27:21.661 ERROR Error during SonarScanner CLI execution
java.lang.NoClassDefFoundError: com/sun/source/tree/Tree
at org.sonarsource.plugins.custom.rules.JavaCodeFormatRule.execute(JavaCodeFormatRule.java:32)
at org.sonarsource.plugins.custom.rules.JavaFilesSensor.lambda$execute$0(JavaFilesSensor.java:58)
at java.base/java.util.HashMap$Values.forEach(Unknown Source)
at org.sonarsource.plugins.custom.rules.JavaFilesSensor.execute(JavaFilesSensor.java:58)
at org.sonar.scanner.sensor.AbstractSensorWrapper.analyse(AbstractSensorWrapper.java:64)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:88)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.lambda$execute$1(ModuleSensorsExecutor.java:61)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.withModuleStrategy(ModuleSensorsExecutor.java:79)
at org.sonar.scanner.sensor.ModuleSensorsExecutor.execute(ModuleSensorsExecutor.java:61)
at org.sonar.scanner.scan.SpringModuleScanContainer.doAfterStart(SpringModuleScanContainer.java:82)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.scanner.scan.SpringProjectScanContainer.scan(SpringProjectScanContainer.java:403)
at org.sonar.scanner.scan.SpringProjectScanContainer.scanRecursively(SpringProjectScanContainer.java:399)
at org.sonar.scanner.scan.SpringProjectScanContainer.doAfterStart(SpringProjectScanContainer.java:368)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.scanner.bootstrap.SpringGlobalContainer.doAfterStart(SpringGlobalContainer.java:137)
at org.sonar.core.platform.SpringComponentContainer.startComponents(SpringComponentContainer.java:188)
at org.sonar.core.platform.SpringComponentContainer.execute(SpringComponentContainer.java:167)
at org.sonar.batch.bootstrapper.Batch.doExecute(Batch.java:72)
at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:66)
at org.sonarsource.scanner.lib.internal.batch.BatchIsolatedLauncher.execute(BatchIsolatedLauncher.java:41)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.base/java.lang.reflect.Method.invoke(Unknown Source)
at org.sonarsource.scanner.lib.internal.IsolatedLauncherProxy.invoke(IsolatedLauncherProxy.java:62)
at jdk.proxy3/jdk.proxy3.$Proxy2.execute(Unknown Source)
at org.sonarsource.scanner.lib.InProcessScannerEngineFacade.doAnalyze(InProcessScannerEngineFacade.java:39)
at org.sonarsource.scanner.lib.ScannerEngineFacade.analyze(ScannerEngineFacade.java:61)
at org.sonarsource.scanner.cli.Main.analyze(Main.java:77)
at org.sonarsource.scanner.cli.Main.main(Main.java:63)
Caused by: java.lang.ClassNotFoundException: com.sun.source.tree.Tree
at org.sonar.classloader.ParentFirstStrategy.loadClass(ParentFirstStrategy.java:39)
at org.sonar.classloader.ClassRealm.loadClass(ClassRealm.java:87)
at org.sonar.classloader.ClassRealm.loadClass(ClassRealm.java:76)
... 33 common frames omitted
14:27:21.667 ERROR
14:27:21.667 ERROR Re-run SonarScanner CLI using the -X switch to enable full debug logging.
I wonder if the jdk I use to run sonar scanner must be jdk17?
From the logs it looks like you are using the scanner with embedded JRE. You need to provide your own JDK to be able to add the exports.
In the download links, you should use the scanner “Any (Requires a pre-installed JVM)”.