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 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 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-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/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-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/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() 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 a58f8c06b7e..060cc981c4a 100644 --- a/java-frontend/pom.xml +++ b/java-frontend/pom.xml @@ -21,7 +21,7 @@ ${project.groupId} jdt-package - 1.10.0.12296 + 1.9.0.12280 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 4e001d09122..46a38e28f76 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 992dd4f39cb..c05aa6fe170 100644 --- a/java-frontend/src/main/java/org/sonar/java/SonarComponents.java +++ b/java-frontend/src/main/java/org/sonar/java/SonarComponents.java @@ -105,6 +105,13 @@ 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. + * 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"; + /** * 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 @@ -502,6 +509,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(true); + } + 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 250505e02af..f2149ee9458 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 @@ -108,8 +108,10 @@ private void scan(Iterable inputFiles, Consumer 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; 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, - AnalysisProgress analysisProgress, BiConsumer action); + AnalysisProgress analysisProgress, BiConsumer action); public enum Mode { BATCH(Batch::new), @@ -84,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); } } @@ -128,14 +141,20 @@ public ASTParser astParser() { JProblem.compilerOptions() .forEach(option -> options.put(option, "warning")); + List environment = classpath; + if (shouldUseJdkReleaseOption) { + options.put(SystemReleaseClasspath.OPTION_RELEASE, javaVersion.effectiveJavaVersionAsString()); + 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,16 +162,63 @@ 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(); + } + 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; + } + } + 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 { - 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 public void parse(Iterable inputFiles, BooleanSupplier isCanceled, - AnalysisProgress analysisProgress, BiConsumer action) { + AnalysisProgress analysisProgress, BiConsumer action) { List sourceFilePaths = new ArrayList<>(); Set notYetAnalyzedFiles = new LinkedHashSet<>(); @@ -224,13 +290,14 @@ 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 public void parse(Iterable inputFiles, BooleanSupplier isCanceled, - AnalysisProgress analysisProgress, BiConsumer action) { + AnalysisProgress analysisProgress, BiConsumer action) { boolean successfullyCompleted = false; boolean cancelled = false; @@ -280,9 +347,10 @@ 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); + 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 ea268b97501..022eb620692 100644 --- a/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java +++ b/java-frontend/src/test/java/org/sonar/java/SonarComponentsTest.java @@ -1129,6 +1129,19 @@ void shouldIgnoreUnnamedModuleForSplitPackage_returns_false_by_default() { assertThat(sonarComponents.shouldIgnoreUnnamedModuleForSplitPackage()).isFalse(); } + @Test + 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(); + } + @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 78d488f74b7..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 @@ -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, false, true); + } + + 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 d6d8a3af6a1..76d45c77ab8 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.doReturn; import static org.mockito.Mockito.doThrow; @@ -111,6 +113,95 @@ 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_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).semanticProblems().stream().map(Problem::message) + .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"); + 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(), false, true) + .parse(Set.of(TestUtils.inputFile(file.toFile())), () -> false, new AnalysisProgress(1), (inputFile, result) -> { + try { + undefinedTypes.add(result.get().semanticProblems().stream().map(Problem::message).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, false, true).astParser(); + return JParser.parse(astParser, release, "Example", source).semanticProblems().stream().map(Problem::message) + .collect(Collectors.toSet()); + } + @Test void should_throw_RecognitionException_in_case_of_syntax_error() { // Note that without check for syntax errors will cause IndexOutOfBoundsException @@ -823,7 +914,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..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 @@ -125,6 +125,27 @@ 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." + + "

" + + "

" + + "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("True") + .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); }