From 7509a6bbb06e4e98940d01cb60dd8f3a62d8c381 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 2 Nov 2026 15:52:49 +0100 Subject: [PATCH 01/11] SONARJAVA-7279 Resolve the JDK API of the target release through the new jdt-package option --- .../checks/CollectorsToListCheckSample.java | 8 +- ...ctorsToListCheckSampleWithoutSemantic.java | 8 +- .../StringIsBlankCheckSample_java10.java | 11 +- .../java/checks/RunFinalizersCheckTest.java | 7 +- java-frontend/pom.xml | 2 +- .../org/sonar/java/model/JParserConfig.java | 94 +++++++++--- .../sonar/java/model/JParserConfigTest.java | 145 ++++++++++++++++++ .../org/sonar/java/model/JParserTest.java | 75 +++++++++ 8 files changed, 308 insertions(+), 42 deletions(-) diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java index f6e4636a7b6..6b10c9139c8 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSample.java @@ -123,22 +123,22 @@ void compliant() { List list6 = Stream.of("B", "C", "D") .collect(Collectors.toList()); // Compliant, list6 needs to be mutable - list6.addFirst("A"); + list6.add(0, "A"); List list7 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list7 needs to be mutable - list7.addLast("D"); + list7.add("D"); List list8 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list8 needs to be mutable - list8.removeFirst(); + list8.remove(0); List list9 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list9 needs to be mutable - list9.removeLast(); + list9.remove("C"); } void addX() { diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSampleWithoutSemantic.java b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSampleWithoutSemantic.java index a5a3514ecd7..cec32cebcd0 100644 --- a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSampleWithoutSemantic.java +++ b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSampleWithoutSemantic.java @@ -118,22 +118,22 @@ void compliant() { List list6 = Stream.of("B", "C", "D") .collect(Collectors.toList()); // Compliant, list6 needs to be mutable - list6.addFirst("A"); + list6.add(0, "A"); List list7 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list7 needs to be mutable - list7.addLast("D"); + list7.add("D"); List list8 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list8 needs to be mutable - list8.removeFirst(); + list8.remove(0); List list9 = Stream.of("A", "B", "C") .collect(Collectors.toList()); // Compliant, list9 needs to be mutable - list9.removeLast(); + list9.remove("C"); } void addX() { diff --git a/java-checks-test-sources/default/src/main/java/checks/StringIsBlankCheckSample_java10.java b/java-checks-test-sources/default/src/main/java/checks/StringIsBlankCheckSample_java10.java index cece611f17c..449d8a5d8f5 100644 --- a/java-checks-test-sources/default/src/main/java/checks/StringIsBlankCheckSample_java10.java +++ b/java-checks-test-sources/default/src/main/java/checks/StringIsBlankCheckSample_java10.java @@ -4,16 +4,7 @@ public class StringIsBlankCheckSample_java10 { public boolean sample(String s) { boolean b; - // `String.isBlank()` does not exist before Java 11, so these stay emptiness checks on the trimmed string - - b = s.strip().length() == 0; // Noncompliant {{Use "isEmpty()" to check whether a "String" is empty or not.}} [[quickfixes=qf1]] - // fix@qf1 {{Replace with "isEmpty()"}} - // edit@qf1 [[sc=19;ec=32]]{{isEmpty()}} - - b = s.strip().length() > 0; // Noncompliant {{Use "isEmpty()" to check whether a "String" is empty or not.}} [[quickfixes=qf2]] - // fix@qf2 {{Replace with "isEmpty()"}} - // edit@qf2 [[sc=9;ec=9]]{{!}} - // edit@qf2 [[sc=19;ec=31]]{{isEmpty()}} + // `String.isBlank()` does not exist before Java 11, so trimmed strings are plain emptiness checks b = s.trim().length() == 0; // Noncompliant {{Use "isEmpty()" to check whether a "String" is empty or not.}} [[quickfixes=qf3]] // fix@qf3 {{Replace with "isEmpty()"}} diff --git a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java index 8442bd53f08..568039fa06d 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java @@ -47,7 +47,8 @@ void test() { .withJavaVersion(11) .verifyNoIssues(); } else { - // No issue raised starting JDK 11 as the related APIs were removed from JDK and cannot be resolved + // No issue raised by default starting JDK 11 as the related APIs were removed from JDK and cannot be resolved, + // unless the analyzed Java version is 10, for which the APIs of that release are visible CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) .withCheck(new RunFinalizersCheck()) @@ -58,10 +59,10 @@ void test() { .withJavaVersion(javaVersion) .verifyNoIssues(); CheckVerifier.newVerifier() - .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) + .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckSample.java")) .withCheck(new RunFinalizersCheck()) .withJavaVersion(10) - .verifyNoIssues(); + .verifyIssues(); } } diff --git a/java-frontend/pom.xml b/java-frontend/pom.xml index 016dbbde0b9..060cc981c4a 100644 --- a/java-frontend/pom.xml +++ b/java-frontend/pom.xml @@ -21,7 +21,7 @@ ${project.groupId} jdt-package - 1.9.0.1840 + 1.9.0.12280 diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java index 79cffd79a90..0da977a8a50 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java @@ -16,25 +16,13 @@ */ package org.sonar.java.model; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.BooleanSupplier; -import java.util.stream.StreamSupport; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FileASTRequestor; +import org.eclipse.jdt.core.dom.SystemReleaseClasspath; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.fs.InputFile; @@ -47,6 +35,21 @@ import org.sonarsource.analyzer.commons.ProgressReport; import org.sonarsource.performance.measure.PerformanceMeasure; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.BooleanSupplier; +import java.util.stream.StreamSupport; + public abstract class JParserConfig { public static final JavaVersion MAXIMUM_SUPPORTED_JAVA_VERSION = new JavaVersionImpl(JavaVersionImpl.MAX_SUPPORTED, true); @@ -54,7 +57,9 @@ public abstract class JParserConfig { private static final Logger LOG = LoggerFactory.getLogger(JParserConfig.class); private static final String MAXIMUM_ECJ_WARNINGS = "42000"; - private static final Set JRE_JARS = new HashSet<>(Arrays.asList("rt.jar", "jrt-fs.jar", "android.jar")); + private static final String JRT_FS_JAR = "jrt-fs.jar"; + private static final Set NON_MODULAR_JRE_JAR = new HashSet<>(Arrays.asList("rt.jar", "android.jar")); + private static final Set JRE_JARS = new HashSet<>(Arrays.asList("rt.jar", JRT_FS_JAR, "android.jar")); final JavaVersion javaVersion; final List classpath; @@ -67,7 +72,7 @@ private JParserConfig(JavaVersion javaVersion, List classpath, boolean sho } public abstract void parse(Iterable inputFiles, BooleanSupplier isCanceled, - AnalysisProgress analysisProgress, BiConsumer action); + AnalysisProgress analysisProgress, BiConsumer action); public enum Mode { BATCH(Batch::new), @@ -128,14 +133,17 @@ public ASTParser astParser() { JProblem.Type.compilerOptions() .forEach(option -> options.put(option, "warning")); + options.put(SystemReleaseClasspath.OPTION_RELEASE, javaVersion.effectiveJavaVersionAsString()); + List environment = useReleaseApiOfConfiguredJdk(options); + astParser.setCompilerOptions(options); - boolean includeRunningVMBootclasspath = classpath.stream() + boolean includeRunningVMBootclasspath = environment.stream() .noneMatch(f -> JRE_JARS.contains(f.getName())); - astParser.setEnvironment(classpath.stream() + astParser.setEnvironment(environment.stream() .map(File::getAbsolutePath) - .toArray(String[]::new), new String[] {}, new String[] {}, includeRunningVMBootclasspath); + .toArray(String[]::new), new String[]{}, new String[]{}, includeRunningVMBootclasspath); astParser.setResolveBindings(true); astParser.setBindingsRecovery(true); @@ -143,6 +151,51 @@ public ASTParser astParser() { return astParser; } + /** + * When the classpath carries the runtime image of a modular JDK (the {@code lib/jrt-fs.jar} added for + * {@code sonar.java.jdkHome}), ECJ would see the whole API of that JDK whatever the analyzed Java version is. + * If the requested release is older than that JDK, the image is removed from the classpath and the JDK is + * registered in {@code options} as the provider of the release API, which {@link SystemReleaseClasspath} then + * serves from its {@code ct.sym}. + * + *

Nothing changes when another JDK-like entry is present ({@code rt.jar}, {@code android.jar}), since it is + * the actual platform to analyze against, or when the release cannot be served by that JDK. + * + * @param options the compiler options, to which the JDK home is added when the release API is used + * @return the classpath to give to ECJ + */ + @VisibleForTesting + List useReleaseApiOfConfiguredJdk(Map options) { + boolean hasOtherPlatformJar = classpath.stream() + .anyMatch(f -> NON_MODULAR_JRE_JAR.contains(f.getName())); + if (hasOtherPlatformJar) { + return classpath; + } + for (File runtimeImage : classpath) { + Optional jdkHome = jdkHomeOfRuntimeImage(runtimeImage); + if (jdkHome.isPresent()) { + Map candidate = new HashMap<>(options); + candidate.put(SystemReleaseClasspath.OPTION_JAVA_HOME, jdkHome.get().getAbsolutePath()); + if (SystemReleaseClasspath.isApplicable(candidate)) { + options.put(SystemReleaseClasspath.OPTION_JAVA_HOME, jdkHome.get().getAbsolutePath()); + return classpath.stream().filter(f -> !f.equals(runtimeImage)).toList(); + } + LOG.debug("The API of Java {} is not served from the JDK '{}': using the API of that JDK as is.", + javaVersion.effectiveJavaVersionAsString(), jdkHome.get()); + return classpath; + } + } + return classpath; + } + + private static Optional jdkHomeOfRuntimeImage(File file) { + File lib = file.getParentFile(); + if (JRT_FS_JAR.equals(file.getName()) && lib != null && "lib".equals(lib.getName())) { + return Optional.ofNullable(lib.getParentFile()); + } + return Optional.empty(); + } + @VisibleForTesting static class Batch extends JParserConfig { @@ -152,7 +205,7 @@ static class Batch extends JParserConfig { @Override public void parse(Iterable inputFiles, BooleanSupplier isCanceled, - AnalysisProgress analysisProgress, BiConsumer action) { + AnalysisProgress analysisProgress, BiConsumer action) { List sourceFilePaths = new ArrayList<>(); Set notYetAnalyzedFiles = new LinkedHashSet<>(); @@ -230,7 +283,7 @@ private FileByFile(JavaVersion javaVersion, List classpath, boolean should @Override public void parse(Iterable inputFiles, BooleanSupplier isCanceled, - AnalysisProgress analysisProgress, BiConsumer action) { + AnalysisProgress analysisProgress, BiConsumer action) { boolean successfullyCompleted = false; boolean cancelled = false; @@ -280,6 +333,7 @@ private static void parse(ASTParser astParser, InputFile inputFile, JavaVersion static boolean shouldEnablePreviewFlag(JavaVersion currentVersion) { return currentVersion.arePreviewFeaturesEnabled(); } + @FunctionalInterface public interface ParserConfigConstructor { JParserConfig apply(JavaVersion version, List files, Boolean shouldIgnoreUnnamedModuleForSplitPackage); diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java index 78d488f74b7..1aaa3b75dd6 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java @@ -16,9 +16,18 @@ */ package org.sonar.java.model; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.jdt.core.dom.SystemReleaseClasspath; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.event.Level; import org.sonar.java.testing.ThreadLocalLogTester; @@ -29,6 +38,9 @@ class JParserConfigTest { @RegisterExtension public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.INFO); + @TempDir + Path temp; + @Test void should_enable_preview() { assertThat(shouldEnablePreviewFlag(new JavaVersionImpl())).isFalse(); @@ -55,4 +67,137 @@ void a_debug_message_is_logged_when_shouldIgnoreUnnamedModuleForSplitPackage_is_ JParserConfig.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList(), true); assertThat(logTester.logs()).containsExactly("The Java analyzer will ignore the unnamed module for split packages."); } + + @Test + void runtime_image_of_a_jdk_is_replaced_by_its_release_api_when_the_release_is_older() throws IOException { + File runtimeImage = runtimeImageOf(fakeJdk("jdk21", "21.0.2", true)); + File library = new File("lib.jar"); + Map options = releaseOptions("11"); + + List environment = config("11", List.of(library, runtimeImage)).useReleaseApiOfConfiguredJdk(options); + + assertThat(environment).containsExactly(library); + assertThat(options).containsEntry(SystemReleaseClasspath.OPTION_JAVA_HOME, runtimeImage.getParentFile().getParent()); + } + + @Test + void the_other_entries_of_the_classpath_are_kept_in_order() throws IOException { + File runtimeImage = runtimeImageOf(fakeJdk("jdk21", "21.0.2", true)); + List classpath = List.of(new File("a.jar"), runtimeImage, new File("b.jar"), new File("target/classes")); + + List environment = config("11", classpath).useReleaseApiOfConfiguredJdk(releaseOptions("11")); + + assertThat(environment).containsExactly(new File("a.jar"), new File("b.jar"), new File("target/classes")); + } + + @Test + void runtime_image_is_kept_when_the_release_is_not_older_than_the_jdk() throws IOException { + File runtimeImage = runtimeImageOf(fakeJdk("jdk21", "21.0.2", true)); + List classpath = List.of(runtimeImage); + + assertKept("21", classpath); + assertKept("22", classpath); + assertKept("26", classpath); + } + + @Test + void runtime_image_is_kept_when_the_release_is_below_9() throws IOException { + List classpath = List.of(runtimeImageOf(fakeJdk("jdk21", "21.0.2", true))); + + assertKept("8", classpath); + assertKept("7", classpath); + } + + @Test + void runtime_image_is_kept_when_the_jdk_cannot_serve_the_release() throws IOException { + assertKept("11", List.of(runtimeImageOf(fakeJdk("without-ct-sym", "21.0.2", false)))); + + Path withoutReleaseFile = Files.createDirectories(temp.resolve("without-release-file/lib")); + Files.createFile(withoutReleaseFile.resolve("ct.sym")); + assertKept("11", List.of(runtimeImageOf(withoutReleaseFile.getParent()))); + } + + @Test + void a_debug_message_explains_why_the_release_api_is_not_used() throws IOException { + logTester.setLevel(Level.DEBUG); + File runtimeImage = runtimeImageOf(fakeJdk("jdk21", "21.0.2", true)); + + config("21", List.of(runtimeImage)).useReleaseApiOfConfiguredJdk(releaseOptions("21")); + + assertThat(logTester.logs(Level.DEBUG)).hasSize(1); + assertThat(logTester.logs(Level.DEBUG).get(0)).contains("Java 21").contains(runtimeImage.getParentFile().getParent()); + } + + @Test + void runtime_image_is_kept_when_a_platform_jar_is_on_the_classpath() throws IOException { + File runtimeImage = runtimeImageOf(fakeJdk("jdk21", "21.0.2", true)); + + assertKept("11", List.of(new File("jdk8/jre/lib/rt.jar"), runtimeImage)); + assertKept("11", List.of(runtimeImage, new File("android-sdk/platforms/android-34/android.jar"))); + } + + @Test + void rt_jar_alone_is_not_modified() { + assertKept("11", List.of(new File("jdk8/jre/lib/rt.jar"))); + } + + @Test + void jar_named_as_runtime_image_outside_of_a_lib_folder_is_not_considered_as_a_jdk() throws IOException { + Path home = Files.createDirectories(temp.resolve("not-a-jdk")); + Files.createFile(home.resolve("jrt-fs.jar")); + + assertKept("11", List.of(home.resolve("jrt-fs.jar").toFile())); + } + + @Test + void classpath_without_jdk_is_not_modified() { + Map options = releaseOptions("11"); + List classpath = List.of(new File("a.jar"), new File("b.jar")); + + assertThat(config("11", classpath).useReleaseApiOfConfiguredJdk(options)).isSameAs(classpath); + assertThat(options).doesNotContainKey(SystemReleaseClasspath.OPTION_JAVA_HOME); + } + + @Test + void empty_classpath_is_not_modified() { + assertKept("11", List.of()); + } + + private void assertKept(String release, List classpath) { + Map options = releaseOptions(release); + + List environment = config(release, classpath).useReleaseApiOfConfiguredJdk(options); + + assertThat(environment).isSameAs(classpath); + assertThat(options).doesNotContainKey(SystemReleaseClasspath.OPTION_JAVA_HOME); + } + + private static JParserConfig config(String release, List classpath) { + return JParserConfig.Mode.FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath); + } + + private static Map releaseOptions(String release) { + Map options = new HashMap<>(); + options.put(SystemReleaseClasspath.OPTION_RELEASE, release); + return options; + } + + private static File runtimeImageOf(Path jdkHome) throws IOException { + Path image = jdkHome.resolve("lib/jrt-fs.jar"); + Files.createDirectories(image.getParent()); + if (!Files.exists(image)) { + Files.createFile(image); + } + return image.toFile(); + } + + private Path fakeJdk(String name, String version, boolean withCtSym) throws IOException { + Path home = Files.createDirectories(temp.resolve(name)); + Path lib = Files.createDirectories(home.resolve("lib")); + Files.writeString(home.resolve("release"), "JAVA_VERSION=\"" + version + "\"\n"); + if (withCtSym) { + Files.createFile(lib.resolve("ct.sym")); + } + return home; + } } diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java index 57d8dfeb19b..4aea4c7eded 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java @@ -38,6 +38,7 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; +import java.util.stream.Collectors; import org.apache.commons.io.FileUtils; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.JavaCore; @@ -91,6 +92,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doReturn; @@ -111,6 +113,79 @@ class JParserTest { @RegisterExtension public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.DEBUG); + @Test + void should_only_see_the_jdk_api_of_the_requested_release() { + assumeRunningJdkCanServeOlderReleases(); + String source = """ + class Example { + java.util.jar.Pack200 removedInJdk14; + java.lang.Record addedInJdk16; + } + """; + Set undefinedAt11 = undefinedTypes("11", source); + assertThat(undefinedAt11).containsExactly("java.lang.Record cannot be resolved to a type"); + assertThat(undefinedTypes("17", source)).containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); + } + + @Test + void should_use_the_release_api_of_the_jdk_provided_in_the_classpath() { + File runtimeImage = new File(System.getProperty("java.home"), "lib/jrt-fs.jar"); + assumeTrue(runtimeImage.isFile()); + assumeRunningJdkCanServeOlderReleases(); + String source = """ + class Example { + java.util.jar.Pack200 removedInJdk14; + java.lang.Record addedInJdk16; + } + """; + List classpath = List.of(runtimeImage); + int jdkVersion = Runtime.version().feature(); + + assertThat(undefinedTypes("11", source, classpath)).containsExactly("java.lang.Record cannot be resolved to a type"); + assertThat(undefinedTypes(Integer.toString(jdkVersion), source, classpath)).containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); + assertThat(undefinedTypes(Integer.toString(jdkVersion + 1), source, classpath)).containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); + } + + @Test + void should_only_see_the_jdk_api_of_the_requested_release_in_batch_mode(@TempDir Path temp) throws Exception { + assumeRunningJdkCanServeOlderReleases(); + Path file = Files.writeString(temp.resolve("Example.java"), """ + class Example { + java.util.jar.Pack200 removedInJdk14; + java.lang.Record addedInJdk16; + } + """); + List> undefinedTypes = new ArrayList<>(); + + BATCH + .create(JavaVersionImpl.fromString("11"), List.of()) + .parse(Set.of(TestUtils.inputFile(file.toFile())), () -> false, new AnalysisProgress(1), (inputFile, result) -> { + try { + undefinedTypes.add(result.get().sema.undefinedTypes.stream().map(Object::toString).collect(Collectors.toSet())); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + + assertThat(undefinedTypes).containsExactly(Set.of("java.lang.Record cannot be resolved to a type")); + } + + private static void assumeRunningJdkCanServeOlderReleases() { + assumeTrue(new File(System.getProperty("java.home"), "lib/ct.sym").isFile(), "the running JVM has no lib/ct.sym"); + assumeTrue(Runtime.version().feature() > 17, "the running JVM must be newer than Java 17"); + } + + private static Set undefinedTypes(String release, String source) { + return undefinedTypes(release, source, List.of()); + } + + private static Set undefinedTypes(String release, String source, List classpath) { + ASTParser astParser = FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath).astParser(); + return JParser.parse(astParser, release, "Example", source).sema.undefinedTypes.stream() + .map(Object::toString) + .collect(Collectors.toSet()); + } + @Test void should_throw_RecognitionException_in_case_of_syntax_error() { // Note that without check for syntax errors will cause IndexOutOfBoundsException From 132d6b47996ba2bcbd54ef1c965cce9a4effde80 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 2 Nov 2026 16:09:22 +0100 Subject: [PATCH 02/11] SONARJAVA-7279 Keep coverage of the SequencedCollection mutators in CollectorsToListCheck The main sample runs at Java 16, where addFirst, addLast, removeFirst and removeLast no longer resolve, so it uses the older List methods instead. A dedicated sample checked at Java 21 keeps one compliant case for each of the four methods, and a noncompliant case as a control. Co-Authored-By: Claude Sonnet 5.5 --- .../CollectorsToListCheckSequencedSample.java | 38 +++++++++++++++++++ .../checks/CollectorsToListCheckTest.java | 9 +++++ 2 files changed, 47 insertions(+) create mode 100644 java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSequencedSample.java diff --git a/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSequencedSample.java b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSequencedSample.java new file mode 100644 index 00000000000..e5621b3cad9 --- /dev/null +++ b/java-checks-test-sources/default/src/main/java/checks/CollectorsToListCheckSequencedSample.java @@ -0,0 +1,38 @@ +package checks; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CollectorsToListCheckSequencedSample { + + void noncompliant() { + List list = Stream.of("A", "B", "C") + .collect(Collectors.toList()); // Noncompliant {{Replace this usage of 'Stream.collect(Collectors.toList())' with 'Stream.toList()' and ensure that the list is unmodified.}} +// ^^^^^^^^^^^^^^^^^^^ + + list.getFirst(); + } + + void compliant() { + List addFirst = Stream.of("B", "C", "D") + .collect(Collectors.toList()); // Compliant, addFirst needs to be mutable + + addFirst.addFirst("A"); + + List addLast = Stream.of("A", "B", "C") + .collect(Collectors.toList()); // Compliant, addLast needs to be mutable + + addLast.addLast("D"); + + List removeFirst = Stream.of("A", "B", "C") + .collect(Collectors.toList()); // Compliant, removeFirst needs to be mutable + + removeFirst.removeFirst(); + + List removeLast = Stream.of("A", "B", "C") + .collect(Collectors.toList()); // Compliant, removeLast needs to be mutable + + removeLast.removeLast(); + } +} diff --git a/java-checks/src/test/java/org/sonar/java/checks/CollectorsToListCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/CollectorsToListCheckTest.java index 5df09c6fd2c..d6875606d0c 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/CollectorsToListCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/CollectorsToListCheckTest.java @@ -28,6 +28,15 @@ void test() { .verifyIssues(); } + @Test + void test_sequenced_collection_mutators() { + CheckVerifier.newVerifier() + .onFile(mainCodeSourcesPath("checks/CollectorsToListCheckSequencedSample.java")) + .withCheck(new CollectorsToListCheck()) + .withJavaVersion(21) + .verifyIssues(); + } + @Test void test_no_issues_for_older_versions() { createCheckVerifier() From b00b4397958b71af836ecf83db9da758975766a6 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 2 Nov 2026 16:24:26 +0100 Subject: [PATCH 03/11] SONARJAVA-7279 Update ruling expectations for Guava Guava is analyzed with sonar.java.source=17, so the API of Java 17 is now seen instead of the one of the JDK running the analysis: - ThreadDeath (deprecated for removal in 20) and Object.finalize() (in 18) are no longer reported by S5738, - the unsynchronized mark() and reset() overrides in HashingInputStream are now reported by S3551, as FilterInputStream declares them synchronized in 17. Co-Authored-By: Claude Sonnet 5.5 --- .../src/test/resources/expected/guava/java-S3551.json | 6 ++++++ .../src/test/resources/expected/guava/java-S5738.json | 8 -------- 2 files changed, 6 insertions(+), 8 deletions(-) create mode 100644 its/ruling/src/test/resources/expected/guava/java-S3551.json diff --git a/its/ruling/src/test/resources/expected/guava/java-S3551.json b/its/ruling/src/test/resources/expected/guava/java-S3551.json new file mode 100644 index 00000000000..07f09f6cc06 --- /dev/null +++ b/its/ruling/src/test/resources/expected/guava/java-S3551.json @@ -0,0 +1,6 @@ +{ +"guava:src/com/google/common/hash/HashingInputStream.java": [ +88, +95 +] +} diff --git a/its/ruling/src/test/resources/expected/guava/java-S5738.json b/its/ruling/src/test/resources/expected/guava/java-S5738.json index 1aff35a77db..df812fefdce 100644 --- a/its/ruling/src/test/resources/expected/guava/java-S5738.json +++ b/its/ruling/src/test/resources/expected/guava/java-S5738.json @@ -1,15 +1,7 @@ { -"guava:src/com/google/common/base/Throwables.java": [ -337, -367, -370 -], "guava:src/com/google/common/cache/Striped64.java": [ 321 ], -"guava:src/com/google/common/io/FileBackedOutputStream.java": [ -103 -], "guava:src/com/google/common/primitives/UnsignedBytes.java": [ 364 ], From ad95d3aec4f02b1e0c492d1e046c038e4947e706 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 2 Nov 2026 16:42:13 +0100 Subject: [PATCH 04/11] SONARJAVA-7279 Remove ruling expectations that no longer have any issue The analysis now sees the API of the Java release it targets instead of the one of the JDK running it, so two sets of expected issues disappear: - eclipse-jetty S5738: Jetty targets Java 11, where SecurityManager and AccessController are not yet deprecated for removal (Java 17), - guava S2387: the shadowed fields (Reference.next, AbstractMap.keySet) are not public API, and are not part of the API of the release anymore. Co-Authored-By: Claude Sonnet 5.5 --- .../expected/eclipse-jetty/java-S5738.json | 28 ------------------- .../resources/expected/guava/java-S2387.json | 17 ----------- 2 files changed, 45 deletions(-) delete mode 100644 its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.json delete mode 100644 its/ruling/src/test/resources/expected/guava/java-S2387.json diff --git a/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.json b/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.json deleted file mode 100644 index e14b0890cc3..00000000000 --- a/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.json +++ /dev/null @@ -1,28 +0,0 @@ -{ -"eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java": [ -212, -320, -2509, -2518, -3041 -], -"eclipse-jetty:jetty-slf4j-impl/src/main/java/org/eclipse/jetty/logging/JettyLoggerConfiguration.java": [ -169 -], -"eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/MemoryUtils.java": [ -37 -], -"eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java": [ -680 -], -"eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/TypeUtilTest.java": [ -198, -216 -], -"eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/thread/QueuedThreadPoolTest.java": [ -730 -], -"eclipse-jetty:jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java": [ -1761 -] -} diff --git a/its/ruling/src/test/resources/expected/guava/java-S2387.json b/its/ruling/src/test/resources/expected/guava/java-S2387.json deleted file mode 100644 index b2438d3406c..00000000000 --- a/its/ruling/src/test/resources/expected/guava/java-S2387.json +++ /dev/null @@ -1,17 +0,0 @@ -{ -"guava:src/com/google/common/cache/LocalCache.java": [ -1370, -4230, -4239 -], -"guava:src/com/google/common/collect/MapMakerInternalMap.java": [ -1241, -1499, -3566, -3574 -], -"guava:src/com/google/common/collect/Maps.java": [ -3384, -3395 -] -} From 13b317613372d9844d07d2883a7a1006e9978ddf Mon Sep 17 00:00:00 2001 From: lpilastri Date: Mon, 2 Nov 2026 17:03:17 +0100 Subject: [PATCH 05/11] SONARJAVA-7279 Remove the S5738 ruling expectations of eclipse-jetty-similar-to-main Same reason as for eclipse-jetty: Jetty targets Java 11, where SecurityManager is not deprecated for removal yet, so the issues of ContextHandler are gone. Co-Authored-By: Claude Sonnet 5.5 --- .../eclipse-jetty-similar-to-main/java-S5738.json | 9 --------- 1 file changed, 9 deletions(-) delete mode 100644 its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.json diff --git a/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.json b/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.json deleted file mode 100644 index 0277d1f2890..00000000000 --- a/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.json +++ /dev/null @@ -1,9 +0,0 @@ -{ -"eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java": [ -212, -320, -2509, -2518, -3041 -] -} From ac3fd7c04407f55dbee922a661a7ca730a73d99e Mon Sep 17 00:00:00 2001 From: Leonardo Pilastri Date: Tue, 3 Nov 2026 15:12:52 +0100 Subject: [PATCH 06/11] SONARJAVA-7279 Guard the debug log of the release API fallback with isDebugEnabled Co-Authored-By: Claude Sonnet 5.5 --- .../src/main/java/org/sonar/java/model/JParserConfig.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java index 0da977a8a50..cd81d499c33 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JParserConfig.java @@ -180,8 +180,10 @@ List useReleaseApiOfConfiguredJdk(Map options) { options.put(SystemReleaseClasspath.OPTION_JAVA_HOME, jdkHome.get().getAbsolutePath()); return classpath.stream().filter(f -> !f.equals(runtimeImage)).toList(); } - LOG.debug("The API of Java {} is not served from the JDK '{}': using the API of that JDK as is.", - javaVersion.effectiveJavaVersionAsString(), jdkHome.get()); + if (LOG.isDebugEnabled()) { + LOG.debug("The API of Java {} is not served from the JDK '{}': using the API of that JDK as is.", + javaVersion.effectiveJavaVersionAsString(), jdkHome.get()); + } return classpath; } } From 81bd8ce9f04328782df7386013cd00143b7b7307 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Wed, 11 Nov 2026 11:08:09 +0100 Subject: [PATCH 07/11] Add sonar.java.useJdkReleaseOption to control ECJ --release option --- .../org/sonar/java/it/JavaRulingTest.java | 1 + .../java/checks/RunFinalizersCheckTest.java | 7 ++--- .../java/org/sonar/java/JavaFrontend.java | 3 +- .../java/org/sonar/java/SonarComponents.java | 9 ++++++ .../org/sonar/java/ast/JavaAstScanner.java | 4 ++- .../org/sonar/java/model/JParserConfig.java | 30 +++++++++++++------ .../org/sonar/java/SonarComponentsTest.java | 11 +++++++ .../sonar/java/model/JParserConfigTest.java | 2 +- .../org/sonar/java/model/JParserTest.java | 24 +++++++++++++-- .../org/sonar/plugins/java/JavaPlugin.java | 16 ++++++++++ .../sonar/plugins/java/JavaPluginTest.java | 6 ++-- 11 files changed, 91 insertions(+), 22 deletions(-) diff --git a/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java b/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java index baf85dbf4d2..b3373e5c81b 100644 --- a/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java +++ b/its/ruling/src/test/java/org/sonar/java/it/JavaRulingTest.java @@ -474,6 +474,7 @@ private static BuildResult executeBuildWithCommonProperties(Build build, Stri Paths.get("target/performance/sonar.java.performance.measure.json").toAbsolutePath().toString()) .setProperty("sonar.import_unknown_files", "true") .setProperty("sonar.skipPackageDesign", "true") + .setProperty("sonar.java.useJdkReleaseOption", "true") .setProperty("sonar.lits.dump.old", effectiveDumpOldFolder.resolve(projectName).toString()) .setProperty("sonar.lits.dump.new", FileLocation.of("target/actual/" + projectName).getFile().getAbsolutePath()) .setProperty("sonar.lits.differences", litsDifferencesPath(projectName)) diff --git a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java index 568039fa06d..8442bd53f08 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java @@ -47,8 +47,7 @@ void test() { .withJavaVersion(11) .verifyNoIssues(); } else { - // No issue raised by default starting JDK 11 as the related APIs were removed from JDK and cannot be resolved, - // unless the analyzed Java version is 10, for which the APIs of that release are visible + // No issue raised starting JDK 11 as the related APIs were removed from JDK and cannot be resolved CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) .withCheck(new RunFinalizersCheck()) @@ -59,10 +58,10 @@ void test() { .withJavaVersion(javaVersion) .verifyNoIssues(); CheckVerifier.newVerifier() - .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckSample.java")) + .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) .withCheck(new RunFinalizersCheck()) .withJavaVersion(10) - .verifyIssues(); + .verifyNoIssues(); } } diff --git a/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java b/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java index 09c44fc0ac2..4671a1fe80e 100644 --- a/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java +++ b/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java @@ -238,7 +238,8 @@ private void scanBatch(BatchModeContext context, List b analysisProgress.startBatch(batchFiles.size()); Set environmentsCleaners = new HashSet<>(); JParserConfig.Mode.BATCH - .create(javaVersion, context.getClasspath(), sonarComponents.shouldIgnoreUnnamedModuleForSplitPackage()) + .create(javaVersion, context.getClasspath(), sonarComponents.shouldIgnoreUnnamedModuleForSplitPackage(), + sonarComponents.shouldUseJdkReleaseOption()) .parse(batchFiles, sonarComponents::analysisCancelled, analysisProgress, (input, result) -> scanAsBatchCallback(input, result, context, environmentsCleaners)); // Due to a bug in ECJ, JAR files remain locked after the analysis on Windows, we unlock them manually, at the end of each batches. See SONARJAVA-3609. environmentsCleaners.forEach(Runnable::run); diff --git a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java index e57da7ea757..60013a2c8db 100644 --- a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java +++ b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java @@ -104,6 +104,11 @@ public class SonarComponents extends CheckRegistrar.RegistrarContext { */ public static final String SONAR_IGNORE_UNNAMED_MODULE_FOR_SPLIT_PACKAGE = "sonar.java.ignoreUnnamedModuleForSplitPackage"; + /** + * When enabled, the JDK API visible to the parser is the one of the analyzed Java release, instead of the API of the JDK running the analysis. + */ + public static final String SONAR_USE_JDK_RELEASE_OPTION = "sonar.java.useJdkReleaseOption"; + /** * Describes whether the analysis should fail and halt when a StackOverflowError is encountered. * True by default, we still want to give the possibility to disable this behavior in case of large projects @@ -501,6 +506,10 @@ public boolean shouldIgnoreUnnamedModuleForSplitPackage() { return context.config().getBoolean(SONAR_IGNORE_UNNAMED_MODULE_FOR_SPLIT_PACKAGE).orElse(false); } + public boolean shouldUseJdkReleaseOption() { + return context.config().getBoolean(SONAR_USE_JDK_RELEASE_OPTION).orElse(false); + } + public boolean shouldFailOnStackOverflow() { return context.config().getBoolean(SONAR_FAIL_ON_STACKOVERFLOW).orElse(true); } diff --git a/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java b/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java index fcd39ab2a21..304d13f9f3c 100644 --- a/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java +++ b/java-frontend/src/main/java/org/sonar/java/ast/JavaAstScanner.java @@ -109,8 +109,10 @@ private void scan(Iterable inputFiles, Consumer classpath; final boolean shouldIgnoreUnnamedModuleForSplitPackage; + final boolean shouldUseJdkReleaseOption; - private JParserConfig(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { + private JParserConfig(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, + boolean shouldUseJdkReleaseOption) { this.javaVersion = javaVersion; this.classpath = classpath; this.shouldIgnoreUnnamedModuleForSplitPackage = shouldIgnoreUnnamedModuleForSplitPackage; + this.shouldUseJdkReleaseOption = shouldUseJdkReleaseOption; } public abstract void parse(Iterable inputFiles, BooleanSupplier isCanceled, @@ -89,10 +92,15 @@ public JParserConfig create(JavaVersion javaVersion, List classpath) { } public JParserConfig create(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { + return create(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, false); + } + + public JParserConfig create(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, + boolean shouldUseJdkReleaseOption) { if (shouldIgnoreUnnamedModuleForSplitPackage) { LOG.info("The Java analyzer will ignore the unnamed module for split packages."); } - return supplier.apply(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + return supplier.apply(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); } } @@ -133,8 +141,11 @@ public ASTParser astParser() { JProblem.Type.compilerOptions() .forEach(option -> options.put(option, "warning")); - options.put(SystemReleaseClasspath.OPTION_RELEASE, javaVersion.effectiveJavaVersionAsString()); - List environment = useReleaseApiOfConfiguredJdk(options); + List environment = classpath; + if (shouldUseJdkReleaseOption) { + options.put(SystemReleaseClasspath.OPTION_RELEASE, javaVersion.effectiveJavaVersionAsString()); + environment = useReleaseApiOfConfiguredJdk(options); + } astParser.setCompilerOptions(options); @@ -201,8 +212,8 @@ private static Optional jdkHomeOfRuntimeImage(File file) { @VisibleForTesting static class Batch extends JParserConfig { - Batch(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { - super(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + Batch(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) { + super(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); } @Override @@ -279,8 +290,9 @@ private void fallbackToFileByFileMode(List inputFiles, BooleanSupplie private static class FileByFile extends JParserConfig { - private FileByFile(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { - super(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + private FileByFile(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, + boolean shouldUseJdkReleaseOption) { + super(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); } @Override @@ -338,7 +350,7 @@ static boolean shouldEnablePreviewFlag(JavaVersion currentVersion) { @FunctionalInterface public interface ParserConfigConstructor { - JParserConfig apply(JavaVersion version, List files, Boolean shouldIgnoreUnnamedModuleForSplitPackage); + JParserConfig apply(JavaVersion version, List files, Boolean shouldIgnoreUnnamedModuleForSplitPackage, Boolean shouldUseJdkReleaseOption); } } diff --git a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java index 2574563e9bd..ea8253c63b3 100644 --- a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java @@ -1127,6 +1127,17 @@ void shouldIgnoreUnnamedModuleForSplitPackage_returns_false_by_default() { assertThat(sonarComponents.shouldIgnoreUnnamedModuleForSplitPackage()).isFalse(); } + @Test + void shouldUseJdkReleaseOption_is_false_by_default_and_true_when_analysis_parameter_is_set() { + MapSettings settings = new MapSettings(); + SonarComponents sonarComponents = new SonarComponents(null, null, null, null, null, null); + sonarComponents.setSensorContext(SensorContextTester.create(new File("")).setSettings(settings)); + + assertThat(sonarComponents.shouldUseJdkReleaseOption()).isFalse(); + settings.setProperty("sonar.java.useJdkReleaseOption", "true"); + assertThat(sonarComponents.shouldUseJdkReleaseOption()).isTrue(); + } + @Test void shouldIgnoreUnnamedModuleForSplitPackage_returns_true_when_analysis_parameter_is_set() { MapSettings settings = new MapSettings(); diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java index 1aaa3b75dd6..7e05e244291 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserConfigTest.java @@ -173,7 +173,7 @@ private void assertKept(String release, List classpath) { } private static JParserConfig config(String release, List classpath) { - return JParserConfig.Mode.FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath); + return JParserConfig.Mode.FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath, false, true); } private static Map releaseOptions(String release) { diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java index 4aea4c7eded..270a8ae07f5 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserTest.java @@ -127,6 +127,24 @@ class Example { assertThat(undefinedTypes("17", source)).containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); } + @Test + void should_see_the_whole_jdk_api_when_the_release_option_is_not_used() { + assumeRunningJdkCanServeOlderReleases(); + String source = """ + class Example { + java.util.jar.Pack200 removedInJdk14; + java.lang.Record addedInJdk16; + } + """; + ASTParser astParser = FILE_BY_FILE.create(JavaVersionImpl.fromString("11"), List.of()).astParser(); + + Set undefinedTypes = JParser.parse(astParser, "11", "Example", source).sema.undefinedTypes.stream() + .map(Object::toString) + .collect(Collectors.toSet()); + + assertThat(undefinedTypes).containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); + } + @Test void should_use_the_release_api_of_the_jdk_provided_in_the_classpath() { File runtimeImage = new File(System.getProperty("java.home"), "lib/jrt-fs.jar"); @@ -158,7 +176,7 @@ class Example { List> undefinedTypes = new ArrayList<>(); BATCH - .create(JavaVersionImpl.fromString("11"), List.of()) + .create(JavaVersionImpl.fromString("11"), List.of(), false, true) .parse(Set.of(TestUtils.inputFile(file.toFile())), () -> false, new AnalysisProgress(1), (inputFile, result) -> { try { undefinedTypes.add(result.get().sema.undefinedTypes.stream().map(Object::toString).collect(Collectors.toSet())); @@ -180,7 +198,7 @@ private static Set undefinedTypes(String release, String source) { } private static Set undefinedTypes(String release, String source, List classpath) { - ASTParser astParser = FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath).astParser(); + ASTParser astParser = FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath, false, true).astParser(); return JParser.parse(astParser, release, "Example", source).sema.undefinedTypes.stream() .map(Object::toString) .collect(Collectors.toSet()); @@ -899,7 +917,7 @@ static class BatchWithException extends JParserConfig.Batch { Deque exceptions = new LinkedList<>(); public BatchWithException() { - super(MAXIMUM_SUPPORTED_JAVA_VERSION, DEFAULT_CLASSPATH, false); + super(MAXIMUM_SUPPORTED_JAVA_VERSION, DEFAULT_CLASSPATH, false, false); } @Override diff --git a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java index 848a8b32af5..a519b01f72a 100644 --- a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java +++ b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java @@ -125,6 +125,22 @@ public void define(Context context) { .type(PropertyType.BOOLEAN) .defaultValue("False") .build(), + PropertyDefinition.builder(SonarComponents.SONAR_USE_JDK_RELEASE_OPTION) + .name("Use the JDK release option") + .description( + "

" + + "Make the Java parser see the JDK API of the analyzed Java version, instead of the API of the JDK used to run the analysis." + + "

" + + "

" + + "By default, the whole API of the available JDK is visible, whatever the Java version of the analyzed project is." + + "

" + ) + .category(JavaConstants.JAVA_CATEGORY) + .subCategory("Language") + .onConfigScopes(Set.of(PropertyDefinition.ConfigScope.PROJECT)) + .type(PropertyType.BOOLEAN) + .defaultValue("False") + .build(), JavaSensor.class, PostAnalysisIssueFilter.class)); diff --git a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaPluginTest.java b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaPluginTest.java index b371b31b74b..8c05af4f148 100644 --- a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaPluginTest.java +++ b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/JavaPluginTest.java @@ -41,7 +41,7 @@ void sonarLint_9_9_extensions() { Plugin.Context context = new Plugin.Context(runtime); javaPlugin.define(context); assertThat(context.getExtensions()) - .hasSize(22) + .hasSize(23) .contains(SonarLintCache.class, SpringContextGatheringModel.class) .doesNotContain(SpringContextModelSensor.class); } @@ -53,7 +53,7 @@ void sonarqube_9_9_extensions() { Plugin.Context context = new Plugin.Context(sqCommunity); javaPlugin.define(context); assertThat(context.getExtensions()) - .hasSize(40) + .hasSize(41) .contains(SpringContextGatheringModel.class, SpringContextModelSensor.class) .doesNotContain(Jasper.class); } @@ -64,7 +64,7 @@ void sonarqube_9_9_commercial_extensions() { Plugin.Context context = new Plugin.Context(sqEnterprise); javaPlugin.define(context); assertThat(context.getExtensions()) - .hasSize(41) + .hasSize(42) .contains(Jasper.class, SpringContextGatheringModel.class, SpringContextModelSensor.class); } From e6fac6ae48b646a60bc63c37644441d3ec5bc53d Mon Sep 17 00:00:00 2001 From: lpilastri Date: Fri, 13 Nov 2026 11:14:25 +0100 Subject: [PATCH 08/11] SONARJAVA-7279 Enable sonar.java.useJdkReleaseOption by default The release API of the analyzed Java version is now used by default. The property stays as the way out for a project whose analysis regressed: setting it to false makes the whole API of the JDK visible again. The parser already falls back to that when the JDK cannot serve the release. Co-Authored-By: Claude Sonnet 5.5 --- .../src/main/java/org/sonar/java/SonarComponents.java | 4 +++- .../test/java/org/sonar/java/SonarComponentsTest.java | 4 +++- .../src/main/java/org/sonar/plugins/java/JavaPlugin.java | 9 +++++++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java index 67be9c4964a..c05aa6fe170 100644 --- a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java +++ b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java @@ -107,6 +107,8 @@ public class SonarComponents extends CheckRegistrar.RegistrarContext { /** * When enabled, the JDK API visible to the parser is the one of the analyzed Java release, instead of the API of the JDK running the analysis. + * Enabled by default. When the JDK cannot serve the release, the parser falls back to the API of that JDK. + * Setting it to false is the way out for a project whose analysis regressed because of it. */ public static final String SONAR_USE_JDK_RELEASE_OPTION = "sonar.java.useJdkReleaseOption"; @@ -508,7 +510,7 @@ public boolean shouldIgnoreUnnamedModuleForSplitPackage() { } public boolean shouldUseJdkReleaseOption() { - return context.config().getBoolean(SONAR_USE_JDK_RELEASE_OPTION).orElse(false); + return context.config().getBoolean(SONAR_USE_JDK_RELEASE_OPTION).orElse(true); } public boolean shouldFailOnStackOverflow() { diff --git a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java index dd62f8bcab5..022eb620692 100644 --- a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java @@ -1130,11 +1130,13 @@ void shouldIgnoreUnnamedModuleForSplitPackage_returns_false_by_default() { } @Test - void shouldUseJdkReleaseOption_is_false_by_default_and_true_when_analysis_parameter_is_set() { + void shouldUseJdkReleaseOption_is_true_by_default_and_false_when_analysis_parameter_disables_it() { MapSettings settings = new MapSettings(); SonarComponents sonarComponents = new SonarComponents(null, null, null, null, null, null); sonarComponents.setSensorContext(SensorContextTester.create(new File("")).setSettings(settings)); + assertThat(sonarComponents.shouldUseJdkReleaseOption()).isTrue(); + settings.setProperty("sonar.java.useJdkReleaseOption", "false"); assertThat(sonarComponents.shouldUseJdkReleaseOption()).isFalse(); settings.setProperty("sonar.java.useJdkReleaseOption", "true"); assertThat(sonarComponents.shouldUseJdkReleaseOption()).isTrue(); diff --git a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java index a519b01f72a..4a132e05ffe 100644 --- a/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java +++ b/sonar-java-plugin/src/main/java/org/sonar/plugins/java/JavaPlugin.java @@ -132,14 +132,19 @@ public void define(Context context) { "Make the Java parser see the JDK API of the analyzed Java version, instead of the API of the JDK used to run the analysis." + "

" + "

" + - "By default, the whole API of the available JDK is visible, whatever the Java version of the analyzed project is." + + "Enabled by default. When the JDK cannot provide the API of that version (Java 8 and older, or a JDK without " + + "lib/ct.sym), the whole API of the JDK is visible, as when this property is disabled." + + "

" + + "

" + + "Disable it if the analysis of a project regressed: the whole API of the JDK is then visible, whatever the Java version " + + "of the analyzed project is." + "

" ) .category(JavaConstants.JAVA_CATEGORY) .subCategory("Language") .onConfigScopes(Set.of(PropertyDefinition.ConfigScope.PROJECT)) .type(PropertyType.BOOLEAN) - .defaultValue("False") + .defaultValue("True") .build(), JavaSensor.class, PostAnalysisIssueFilter.class)); From 6290a70fdede9ad734e0ab56bb1ec9b5305764a1 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Fri, 13 Nov 2026 15:04:13 +0100 Subject: [PATCH 09/11] SONARJAVA-7279 Update the tests and the ruling expectations for the release API being enabled by default RunFinalizersCheckTest: for Java 10, the APIs of that release are visible, so the issues are raised on the sample. Ruling: with the API of the analyzed release, guava and eclipse-jetty no longer raise the issues of S5738 and S2387 that depended on APIs of later JDKs, and guava gets two new S3551 issues. The expectations are those of the ruling run of the PR. Co-Authored-By: Claude Sonnet 5.5 --- .../expected/eclipse-jetty/java-S5738.sarif | 306 ------------------ .../resources/expected/guava/java-S2387.sarif | 234 -------------- 2 files changed, 540 deletions(-) delete mode 100644 its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.sarif delete mode 100644 its/ruling/src/test/resources/expected/guava/java-S2387.sarif diff --git a/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.sarif b/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.sarif deleted file mode 100644 index a9f994628c8..00000000000 --- a/its/ruling/src/test/resources/expected/eclipse-jetty/java-S5738.sarif +++ /dev/null @@ -1,306 +0,0 @@ -{ - "$schema" : "https://json.schemastore.org/sarif-2.1.0.json", - "version" : "2.1.0", - "runs" : [ { - "tool" : { - "driver" : { - "name" : "LITS", - "language" : "en-US", - "contents" : [ "localizedData", "nonLocalizedData" ], - "isComprehensive" : false - } - }, - "language" : "en-US", - "results" : [ { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 212, - "startColumn" : 52, - "endLine" : 212, - "endColumn" : 70 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 320, - "startColumn" : 44, - "endLine" : 320, - "endColumn" : 62 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 2509, - "startColumn" : 33, - "endLine" : 2509, - "endColumn" : 49 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 2518, - "startColumn" : 24, - "endLine" : 2518, - "endColumn" : 42 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 3041, - "startColumn" : 41, - "endLine" : 3041, - "endColumn" : 56 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-slf4j-impl/src/main/java/org/eclipse/jetty/logging/JettyLoggerConfiguration.java", - "index" : -1 - }, - "region" : { - "startLine" : 169, - "startColumn" : 16, - "endLine" : 169, - "endColumn" : 32 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/MemoryUtils.java", - "index" : -1 - }, - "region" : { - "startLine" : 37, - "startColumn" : 38, - "endLine" : 37, - "endColumn" : 54 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-util/src/main/java/org/eclipse/jetty/util/TypeUtil.java", - "index" : -1 - }, - "region" : { - "startLine" : 680, - "startColumn" : 39, - "endLine" : 680, - "endColumn" : 55 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/TypeUtilTest.java", - "index" : -1 - }, - "region" : { - "startLine" : 198, - "startColumn" : 58, - "endLine" : 198, - "endColumn" : 69 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/TypeUtilTest.java", - "index" : -1 - }, - "region" : { - "startLine" : 216, - "startColumn" : 58, - "endLine" : 216, - "endColumn" : 69 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-util/src/test/java/org/eclipse/jetty/util/thread/QueuedThreadPoolTest.java", - "index" : -1 - }, - "region" : { - "startLine" : 730, - "startColumn" : 27, - "endLine" : 730, - "endColumn" : 38 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-xml/src/main/java/org/eclipse/jetty/xml/XmlConfiguration.java", - "index" : -1 - }, - "region" : { - "startLine" : 1761, - "startColumn" : 13, - "endLine" : 1761, - "endColumn" : 29 - } - } - } ], - "rank" : -1.0 - } ], - "newlineSequences" : [ "\r\n", "\n" ], - "columnKind" : "utf16CodeUnits" - } ] -} \ No newline at end of file diff --git a/its/ruling/src/test/resources/expected/guava/java-S2387.sarif b/its/ruling/src/test/resources/expected/guava/java-S2387.sarif deleted file mode 100644 index a127e1a73f7..00000000000 --- a/its/ruling/src/test/resources/expected/guava/java-S2387.sarif +++ /dev/null @@ -1,234 +0,0 @@ -{ - "$schema" : "https://json.schemastore.org/sarif-2.1.0.json", - "version" : "2.1.0", - "runs" : [ { - "tool" : { - "driver" : { - "name" : "LITS", - "language" : "en-US", - "contents" : [ "localizedData", "nonLocalizedData" ], - "isComprehensive" : false - } - }, - "language" : "en-US", - "results" : [ { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"next\" is the name of a field in \"Reference\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/cache/LocalCache.java", - "index" : -1 - }, - "region" : { - "startLine" : 1370, - "startColumn" : 32, - "endLine" : 1370, - "endColumn" : 36 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"keySet\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/cache/LocalCache.java", - "index" : -1 - }, - "region" : { - "startLine" : 4230, - "startColumn" : 10, - "endLine" : 4230, - "endColumn" : 16 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"values\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/cache/LocalCache.java", - "index" : -1 - }, - "region" : { - "startLine" : 4239, - "startColumn" : 17, - "endLine" : 4239, - "endColumn" : 23 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"next\" is the name of a field in \"Reference\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/MapMakerInternalMap.java", - "index" : -1 - }, - "region" : { - "startLine" : 1241, - "startColumn" : 32, - "endLine" : 1241, - "endColumn" : 36 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"next\" is the name of a field in \"Reference\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/MapMakerInternalMap.java", - "index" : -1 - }, - "region" : { - "startLine" : 1499, - "startColumn" : 32, - "endLine" : 1499, - "endColumn" : 36 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"keySet\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/MapMakerInternalMap.java", - "index" : -1 - }, - "region" : { - "startLine" : 3566, - "startColumn" : 20, - "endLine" : 3566, - "endColumn" : 26 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"values\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/MapMakerInternalMap.java", - "index" : -1 - }, - "region" : { - "startLine" : 3574, - "startColumn" : 27, - "endLine" : 3574, - "endColumn" : 33 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"keySet\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/Maps.java", - "index" : -1 - }, - "region" : { - "startLine" : 3384, - "startColumn" : 30, - "endLine" : 3384, - "endColumn" : 36 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S2387", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "\"values\" is the name of a field in \"AbstractMap\"." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/collect/Maps.java", - "index" : -1 - }, - "region" : { - "startLine" : 3395, - "startColumn" : 37, - "endLine" : 3395, - "endColumn" : 43 - } - } - } ], - "rank" : -1.0 - } ], - "newlineSequences" : [ "\r\n", "\n" ], - "columnKind" : "utf16CodeUnits" - } ] -} \ No newline at end of file From 71f416595d175e37ad36e8eb6f3fa158c37a8f57 Mon Sep 17 00:00:00 2001 From: lpilastri Date: Fri, 13 Nov 2026 15:04:53 +0100 Subject: [PATCH 10/11] SONARJAVA-7279 Complete the update of the tests and ruling expectations (RunFinalizers, guava S5738 and S3551) The previous commit only contained the deletion of the two ruling expectation files. This one adds the rest: - RunFinalizersCheckTest: for Java 10, the APIs of that release are visible, so the issues are raised on the sample; - guava: S5738 no longer raises 4 issues that depended on APIs of later JDKs, and S3551 has 2 new issues. Co-Authored-By: Claude Sonnet 5.5 --- .../resources/expected/guava/java-S3551.sarif | 66 +++++++++++++ .../resources/expected/guava/java-S5738.sarif | 96 ------------------- .../java/checks/RunFinalizersCheckTest.java | 7 +- 3 files changed, 70 insertions(+), 99 deletions(-) create mode 100644 its/ruling/src/test/resources/expected/guava/java-S3551.sarif diff --git a/its/ruling/src/test/resources/expected/guava/java-S3551.sarif b/its/ruling/src/test/resources/expected/guava/java-S3551.sarif new file mode 100644 index 00000000000..4bbd11a42ce --- /dev/null +++ b/its/ruling/src/test/resources/expected/guava/java-S3551.sarif @@ -0,0 +1,66 @@ +{ + "$schema" : "https://json.schemastore.org/sarif-2.1.0.json", + "version" : "2.1.0", + "runs" : [ { + "tool" : { + "driver" : { + "name" : "LITS", + "language" : "en-US", + "contents" : [ "localizedData", "nonLocalizedData" ], + "isComprehensive" : false + } + }, + "language" : "en-US", + "results" : [ { + "ruleId" : "java:S3551", + "ruleIndex" : -1, + "kind" : "fail", + "level" : "warning", + "message" : { + "text" : "Make this method \"synchronized\" to match the parent class implementation." + }, + "locations" : [ { + "id" : -1, + "physicalLocation" : { + "artifactLocation" : { + "uri" : "guava:src/com/google/common/hash/HashingInputStream.java", + "index" : -1 + }, + "region" : { + "startLine" : 88, + "startColumn" : 15, + "endLine" : 88, + "endColumn" : 19 + } + } + } ], + "rank" : -1.0 + }, { + "ruleId" : "java:S3551", + "ruleIndex" : -1, + "kind" : "fail", + "level" : "warning", + "message" : { + "text" : "Make this method \"synchronized\" to match the parent class implementation." + }, + "locations" : [ { + "id" : -1, + "physicalLocation" : { + "artifactLocation" : { + "uri" : "guava:src/com/google/common/hash/HashingInputStream.java", + "index" : -1 + }, + "region" : { + "startLine" : 95, + "startColumn" : 15, + "endLine" : 95, + "endColumn" : 20 + } + } + } ], + "rank" : -1.0 + } ], + "newlineSequences" : [ "\r\n", "\n" ], + "columnKind" : "utf16CodeUnits" + } ] +} \ No newline at end of file diff --git a/its/ruling/src/test/resources/expected/guava/java-S5738.sarif b/its/ruling/src/test/resources/expected/guava/java-S5738.sarif index 20aaa4e39fc..fe7e9124df1 100644 --- a/its/ruling/src/test/resources/expected/guava/java-S5738.sarif +++ b/its/ruling/src/test/resources/expected/guava/java-S5738.sarif @@ -12,78 +12,6 @@ }, "language" : "en-US", "results" : [ { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/base/Throwables.java", - "index" : -1 - }, - "region" : { - "startLine" : 337, - "startColumn" : 14, - "endLine" : 337, - "endColumn" : 25 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/base/Throwables.java", - "index" : -1 - }, - "region" : { - "startLine" : 367, - "startColumn" : 86, - "endLine" : 367, - "endColumn" : 97 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/base/Throwables.java", - "index" : -1 - }, - "region" : { - "startLine" : 370, - "startColumn" : 14, - "endLine" : 370, - "endColumn" : 25 - } - } - } ], - "rank" : -1.0 - }, { "ruleId" : "java:S5738", "ruleIndex" : -1, "kind" : "fail", @@ -107,30 +35,6 @@ } } ], "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Don't override this deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "guava:src/com/google/common/io/FileBackedOutputStream.java", - "index" : -1 - }, - "region" : { - "startLine" : 103, - "startColumn" : 34, - "endLine" : 103, - "endColumn" : 42 - } - } - } ], - "rank" : -1.0 }, { "ruleId" : "java:S5738", "ruleIndex" : -1, diff --git a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java index 8442bd53f08..568039fa06d 100644 --- a/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java +++ b/java-checks/src/test/java/org/sonar/java/checks/RunFinalizersCheckTest.java @@ -47,7 +47,8 @@ void test() { .withJavaVersion(11) .verifyNoIssues(); } else { - // No issue raised starting JDK 11 as the related APIs were removed from JDK and cannot be resolved + // No issue raised by default starting JDK 11 as the related APIs were removed from JDK and cannot be resolved, + // unless the analyzed Java version is 10, for which the APIs of that release are visible CheckVerifier.newVerifier() .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) .withCheck(new RunFinalizersCheck()) @@ -58,10 +59,10 @@ void test() { .withJavaVersion(javaVersion) .verifyNoIssues(); CheckVerifier.newVerifier() - .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckNoIssue.java")) + .onFile(nonCompilingTestSourcesPath("checks/RunFinalizersCheckSample.java")) .withCheck(new RunFinalizersCheck()) .withJavaVersion(10) - .verifyNoIssues(); + .verifyIssues(); } } From 5b66d3d9260d22c1e09911b6d3d1845c63cb7b5b Mon Sep 17 00:00:00 2001 From: lpilastri Date: Fri, 13 Nov 2026 15:57:58 +0100 Subject: [PATCH 11/11] SONARJAVA-7279 Remove the S5738 ruling expectations of eclipse-jetty-similar-to-main With the API of the analyzed release, the 5 issues of ContextHandler.java are no longer raised, as for eclipse-jetty. Checked by running JavaRulingTest#eclipse_jetty_incremental locally: it passes without this file. Co-Authored-By: Claude Sonnet 5.5 --- .../java-S5738.sarif | 138 ------------------ 1 file changed, 138 deletions(-) delete mode 100644 its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.sarif diff --git a/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.sarif b/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.sarif deleted file mode 100644 index 37fd0172fa4..00000000000 --- a/its/ruling/src/test/resources/expected/eclipse-jetty-similar-to-main/java-S5738.sarif +++ /dev/null @@ -1,138 +0,0 @@ -{ - "$schema" : "https://json.schemastore.org/sarif-2.1.0.json", - "version" : "2.1.0", - "runs" : [ { - "tool" : { - "driver" : { - "name" : "LITS", - "language" : "en-US", - "contents" : [ "localizedData", "nonLocalizedData" ], - "isComprehensive" : false - } - }, - "language" : "en-US", - "results" : [ { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 212, - "startColumn" : 52, - "endLine" : 212, - "endColumn" : 70 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 320, - "startColumn" : 44, - "endLine" : 320, - "endColumn" : 62 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 2509, - "startColumn" : 33, - "endLine" : 2509, - "endColumn" : 49 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated method, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 2518, - "startColumn" : 24, - "endLine" : 2518, - "endColumn" : 42 - } - } - } ], - "rank" : -1.0 - }, { - "ruleId" : "java:S5738", - "ruleIndex" : -1, - "kind" : "fail", - "level" : "warning", - "message" : { - "text" : "Remove this call to a deprecated class, it has been marked for removal." - }, - "locations" : [ { - "id" : -1, - "physicalLocation" : { - "artifactLocation" : { - "uri" : "eclipse-jetty:jetty-server/src/main/java/org/eclipse/jetty/server/handler/ContextHandler.java", - "index" : -1 - }, - "region" : { - "startLine" : 3041, - "startColumn" : 41, - "endLine" : 3041, - "endColumn" : 56 - } - } - } ], - "rank" : -1.0 - } ], - "newlineSequences" : [ "\r\n", "\n" ], - "columnKind" : "utf16CodeUnits" - } ] -} \ No newline at end of file