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..cf81bfedfc7 100644 --- a/java-frontend/pom.xml +++ b/java-frontend/pom.xml @@ -21,7 +21,7 @@ ${project.groupId} jdt-package - 1.10.0.12296 + 1.11.0.12340 diff --git a/java-frontend/src/main/java/org/sonar/java/JavaConstants.java b/java-frontend/src/main/java/org/sonar/java/JavaConstants.java index a938ba51872..3eea48726f7 100644 --- a/java-frontend/src/main/java/org/sonar/java/JavaConstants.java +++ b/java-frontend/src/main/java/org/sonar/java/JavaConstants.java @@ -19,6 +19,7 @@ public final class JavaConstants { public static final String JAVA_CATEGORY = "java"; + public static final String LANGUAGE_CATEGORY = "Language"; private JavaConstants() { } 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 450b1b507dc..42fb1f5133d 100644 --- a/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java +++ b/java-frontend/src/main/java/org/sonar/java/JavaFrontend.java @@ -239,7 +239,7 @@ private void scanBatch(BatchModeContext context, List batchFiles, Ana analysisProgress.startBatch(batchFiles.size()); Set environmentsCleaners = new HashSet<>(); JParser.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 91ca8ffca3d..41166ff24b1 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 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 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; - public static JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { + public static JParser create(JParser.Mode mode, JavaVersion javaVersion, List classpath, + boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) { if (shouldIgnoreUnnamedModuleForSplitPackage) { LOG.info("The Java analyzer will ignore the unnamed module for split packages."); } return switch (mode) { - case BATCH -> new Batch(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); - case FILE_BY_FILE -> new FileByFile(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + case BATCH -> new Batch(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); + case FILE_BY_FILE -> new FileByFile(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); }; } @@ -75,17 +81,24 @@ static boolean shouldEnablePreviewFlag(JavaVersion currentVersion) { return currentVersion.arePreviewFeaturesEnabled(); } - private JDTParser(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { + private JDTParser(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) { this.javaVersion = javaVersion; this.classpath = classpath; this.shouldIgnoreUnnamedModuleForSplitPackage = shouldIgnoreUnnamedModuleForSplitPackage; + this.shouldUseJdkReleaseOption = shouldUseJdkReleaseOption; } protected ASTParser jdtAstParser() { ASTParser astParser = ASTParser.newParser(AST.getJLSLatest()); Map options = new HashMap<>(JavaCore.getOptions()); - JavaCore.setComplianceOptions(javaVersion.effectiveJavaVersionAsString(), options); + + String javaSourceVersion = javaVersion.effectiveJavaVersionAsString(); + JavaCore.setComplianceOptions(javaSourceVersion, options); options.put(JavaCore.COMPILER_PB_MAX_PER_UNIT, MAXIMUM_ECJ_WARNINGS); + if (shouldUseJdkReleaseOption) { + // This is used by jdt to set the specific --release of the JDK APIs, when applicable + options.put(SystemReleaseClasspath.OPTION_RELEASE, javaSourceVersion); + } if (shouldIgnoreUnnamedModuleForSplitPackage) { options.put(JavaCore.COMPILER_IGNORE_UNNAMED_MODULE_FOR_SPLIT_PACKAGE, "enabled"); } @@ -93,15 +106,23 @@ protected ASTParser jdtAstParser() { options.put(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, "enabled"); } // enabling all supported compiler warnings - JDTProblem.compilerOptions() - .forEach(option -> options.put(option, "warning")); + JDTProblem.compilerOptions().forEach(option -> options.put(option, "warning")); - astParser.setCompilerOptions(options); + List environment = classpath; - boolean includeRunningVMBootclasspath = classpath.stream() - .noneMatch(f -> JRE_JARS.contains(f.getName())); + // IF the classpath has no JRE libraries, we tell jdt to rely on the running one and also try to set --release, if applicable + boolean includeRunningVMBootclasspath = environment.stream().noneMatch(f -> JRE_JARS.contains(f.getName())); - astParser.setEnvironment(classpath.stream() + // If we want to target a specific release for the JDK APIs, and there are already modular JDK libraries in the classpath + if (shouldUseJdkReleaseOption && classpathContainsModularJdk()) { + // We remove those libraries from the classpath, and tell jdt which JDK home we need to use. + // A view of that JDK home with the correct API level will be provided by jdt + environment = removeJdkLibsAndProvideJdtWithJavaHome(options); + } + + astParser.setCompilerOptions(options); + + astParser.setEnvironment(environment.stream() .map(File::getAbsolutePath) .toArray(String[]::new), new String[]{}, new String[]{}, includeRunningVMBootclasspath); @@ -111,11 +132,42 @@ protected ASTParser jdtAstParser() { return astParser; } + /** + * Removes the runtime image of a modular JDK ({@code /lib/jrt-fs.jar}, added to the classpath for + * {@code sonar.java.jdkHome}), and provides JDT with the JAVA_HOME where it should apply the --release option + * to only have a specific version of the APIs in the classpath. (SystemReleaseClasspath.resolveTargetRelease) + * + * @return the original classpath, without the jrt-fs.jar + */ + @VisibleForTesting + List removeJdkLibsAndProvideJdtWithJavaHome(Map options) { + for (File runtimeImage : classpath) { + Optional jdkHome = jdkHomeOfRuntimeImage(runtimeImage); + if (jdkHome.isPresent()) { + options.put(SystemReleaseClasspath.OPTION_JAVA_HOME, jdkHome.get().getAbsolutePath()); + return classpath.stream().filter(f -> !f.equals(runtimeImage)).toList(); + } + } + 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(); + } + + private boolean classpathContainsModularJdk() { + return classpath.stream().anyMatch(f -> JRT_FS_JAR.equals(f.getName())); + } + @VisibleForTesting static class Batch extends JDTParser { - 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 @@ -179,15 +231,16 @@ public void acceptAST(String sourceFilePath, CompilationUnit ast) { private void fallbackToFileByFileMode(List inputFiles, BooleanSupplier isCanceled, AnalysisProgress analysisProgress, BiConsumer action) { LOG.warn("Fallback to file by file analysis for {} files", inputFiles.size()); - FileByFile fileByFile = new FileByFile(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + FileByFile fileByFile = new FileByFile(javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, shouldUseJdkReleaseOption); fileByFile.parse(inputFiles, isCanceled, analysisProgress, action); } } private static class FileByFile extends JDTParser { - 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 diff --git a/java-frontend/src/main/java/org/sonar/java/model/JParser.java b/java-frontend/src/main/java/org/sonar/java/model/JParser.java index 6e1f1af0dd4..88c0e1eed8c 100644 --- a/java-frontend/src/main/java/org/sonar/java/model/JParser.java +++ b/java-frontend/src/main/java/org/sonar/java/model/JParser.java @@ -34,11 +34,11 @@ enum Mode { FILE_BY_FILE; public JParser create(JavaVersion javaVersion, List classpath) { - return create(javaVersion, classpath, false); + return create(javaVersion, classpath, false, true); } - public JParser create(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage) { - return JDTParser.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage); + public JParser create(JavaVersion javaVersion, List classpath, boolean shouldIgnoreUnnamedModuleForSplitPackage, boolean shouldUseJdkReleaseOption) { + return JDTParser.create(this, javaVersion, classpath, shouldIgnoreUnnamedModuleForSplitPackage, 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/jdt/JDTParserTest.java b/java-frontend/src/test/java/org/sonar/java/jdt/JDTParserTest.java index 9f43a98afdb..f1ce75891eb 100644 --- a/java-frontend/src/test/java/org/sonar/java/jdt/JDTParserTest.java +++ b/java-frontend/src/test/java/org/sonar/java/jdt/JDTParserTest.java @@ -16,13 +16,17 @@ */ package org.sonar.java.jdt; +import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Deque; +import java.util.HashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiConsumer; import org.eclipse.core.runtime.OperationCanceledException; @@ -30,6 +34,7 @@ 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.SystemReleaseClasspath; import org.eclipse.jdt.internal.compiler.parser.TerminalToken; import org.eclipse.jdt.internal.formatter.Token; import org.eclipse.jdt.internal.formatter.TokenManager; @@ -64,6 +69,9 @@ class JDTParserTest { + @TempDir + Path temp; + @RegisterExtension public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.DEBUG); @@ -158,7 +166,7 @@ void failing_batch_mode_should_continue_file_by_file() { logTester.clear(); try { JavaTree.CompilationUnitTreeImpl tree = result.get(); - trace.add("[action] analyse class " + ((ClassTree)tree.types().get(0)).simpleName().name() + " in " + inputFile.filename()); + trace.add("[action] analyse class " + ((ClassTree) tree.types().get(0)).simpleName().name() + " in " + inputFile.filename()); } catch (Exception e) { trace.add("[action] handle " + e.getClass().getSimpleName() + ": " + e.getMessage()); } @@ -181,9 +189,9 @@ void successful_batch_mode_with_missing_analyzed_files_should_continue_file_by_f List inputFiles = Arrays.asList( TestUtils.inputFile("src/test/files/metrics/Classes.java"), TestUtils.inputFile("src/test/files/metrics/Methods.java")); - BiConsumer doNothingAction = (inputFile, result) -> {}; - JDTParser config = spy((JDTParser) JParser.Mode.BATCH - .create(MAXIMUM_SUPPORTED_JAVA_VERSION, List.of(), false)); + BiConsumer doNothingAction = (inputFile, result) -> { + }; + JDTParser config = spy((JDTParser) JParser.Mode.BATCH.create(MAXIMUM_SUPPORTED_JAVA_VERSION, List.of(), false, true)); // Return a lazy ASTParser that do nothing to ensure that we have not analyzed files ASTParser astParser = mock(ASTParser.class); doReturn(astParser).when(config).jdtAstParser(); @@ -208,7 +216,7 @@ void failing_batch_mode_should_stop_file_by_file_when_cancelled() { logTester.clear(); try { JavaTree.CompilationUnitTreeImpl tree = result.get(); - trace.add("[action] analyze class " + ((ClassTree)tree.types().get(0)).simpleName().name() + " in " + inputFile.filename()); + trace.add("[action] analyze class " + ((ClassTree) tree.types().get(0)).simpleName().name() + " in " + inputFile.filename()); // cancel analysis after first file isCanceled.set(true); } catch (Exception e) { @@ -217,7 +225,7 @@ void failing_batch_mode_should_stop_file_by_file_when_cancelled() { }; JParser config = BATCH - .create(MAXIMUM_SUPPORTED_JAVA_VERSION, List.of(), false); + .create(MAXIMUM_SUPPORTED_JAVA_VERSION, List.of(), false, true); AnalysisProgress analysisProgress = new AnalysisProgress(inputFiles.size()); assertThatThrownBy(() -> config.parse(inputFiles, isCanceled::get, analysisProgress, action)) .isInstanceOf(OperationCanceledException.class); @@ -286,7 +294,7 @@ static class BatchWithException extends JDTParser.Batch { Deque exceptions = new LinkedList<>(); public BatchWithException() { - super(MAXIMUM_SUPPORTED_JAVA_VERSION, DEFAULT_CLASSPATH, false); + super(MAXIMUM_SUPPORTED_JAVA_VERSION, DEFAULT_CLASSPATH, false, true); } @Override @@ -298,4 +306,88 @@ public ASTParser jdtAstParser() { } } + + @Test + void runtime_image_of_a_modular_jdk_is_replaced_by_the_java_home_of_that_jdk() throws IOException { + Path jdkHome = Files.createDirectories(temp.resolve("jdk21")); + File runtimeImage = runtimeImageOf(jdkHome); + File library = new File("lib.jar"); + Map options = new HashMap<>(); + + List environment = getFileByFileParser(List.of(library, runtimeImage)).removeJdkLibsAndProvideJdtWithJavaHome(options); + + assertThat(environment).containsExactly(library); + assertThat(options).containsExactly(Map.entry(SystemReleaseClasspath.OPTION_JAVA_HOME, jdkHome.toString())); + } + + @Test + void the_other_entries_of_the_classpath_are_kept_in_order() throws IOException { + File runtimeImage = runtimeImageOf(Files.createDirectories(temp.resolve("jdk21"))); + List classpath = List.of(new File("a.jar"), runtimeImage, new File("b.jar"), new File("target/classes")); + + List environment = getFileByFileParser(classpath).removeJdkLibsAndProvideJdtWithJavaHome(new HashMap<>()); + + assertThat(environment).containsExactly(new File("a.jar"), new File("b.jar"), new File("target/classes")); + } + + @Test + void only_the_first_runtime_image_is_replaced() throws IOException { + File first = runtimeImageOf(Files.createDirectories(temp.resolve("jdk17"))); + File second = runtimeImageOf(Files.createDirectories(temp.resolve("jdk21"))); + Map options = new HashMap<>(); + + List environment = getFileByFileParser(List.of(first, second)).removeJdkLibsAndProvideJdtWithJavaHome(options); + + assertThat(environment).containsExactly(second); + assertThat(options).containsEntry(SystemReleaseClasspath.OPTION_JAVA_HOME, temp.resolve("jdk17").toString()); + } + + @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(List.of(home.resolve("jrt-fs.jar").toFile())); + } + + @Test + void classpath_without_runtime_image_is_not_modified() { + assertKept(List.of(new File("a.jar"), new File("b.jar"))); + } + + @Test + void rt_jar_is_not_considered_as_a_runtime_image() { + assertKept(List.of(new File("jdk8/jre/lib/rt.jar"))); + } + + @Test + void android_jar_is_not_considered_as_a_runtime_image() { + assertKept(List.of(new File("sdk/platforms/android-30/android.jar"))); + } + + @Test + void empty_classpath_is_not_modified() { + assertKept(List.of()); + } + + private static void assertKept(List classpath) { + Map options = new HashMap<>(); + + List environment = getFileByFileParser(classpath).removeJdkLibsAndProvideJdtWithJavaHome(options); + + assertThat(environment).isSameAs(classpath); + assertThat(options).isEmpty(); + } + + private static JDTParser getFileByFileParser(List classpath) { + return (JDTParser) JParser.Mode.FILE_BY_FILE.create(new JavaVersionImpl(11), classpath, false, true); + } + + private static File runtimeImageOf(Path jdkHome) throws IOException { + Path image = jdkHome.resolve("lib/jrt-fs.jar"); + Files.createDirectories(image.getParent()); + Files.createFile(image); + return image.toFile(); + } + } diff --git a/java-frontend/src/test/java/org/sonar/java/model/JParserModeTest.java b/java-frontend/src/test/java/org/sonar/java/model/JParserModeTest.java index c592ae4f5d5..f1081663cde 100644 --- a/java-frontend/src/test/java/org/sonar/java/model/JParserModeTest.java +++ b/java-frontend/src/test/java/org/sonar/java/model/JParserModeTest.java @@ -17,6 +17,7 @@ package org.sonar.java.model; import java.util.Collections; + import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.slf4j.event.Level; @@ -32,9 +33,9 @@ class JParserModeTest { void a_debug_message_is_logged_when_shouldIgnoreUnnamedModuleForSplitPackage_is_set() { JParser.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList()); assertThat(logTester.logs()).isEmpty(); - JParser.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList(), false); + JParser.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList(), false, true); assertThat(logTester.logs()).isEmpty(); - JParser.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList(), true); + JParser.Mode.BATCH.create(new JavaVersionImpl(17), Collections.emptyList(), true, true); assertThat(logTester.logs()).containsExactly("The Java analyzer will ignore the unnamed module for split packages."); } } 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 e6363afff83..cad4c86a4cf 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 @@ -18,6 +18,7 @@ import com.sonar.sslr.api.RecognitionException; import com.sonarsource.scanner.engine.sensor.test.fixtures.TestInputFileBuilder; + import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; @@ -28,6 +29,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.BiConsumer; @@ -36,6 +38,8 @@ 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.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -79,6 +83,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; @@ -94,9 +99,111 @@ class JParserTest { + private static final String JDK_API_SOURCE = """ + class Example { + java.util.jar.Pack200 removedInJdk14; + java.lang.Record addedInJdk16; + } + """; + + @TempDir + private static Path tempDir; + @RegisterExtension public ThreadLocalLogTester logTester = new ThreadLocalLogTester().setLevel(Level.DEBUG); + @Test + void should_only_see_the_jdk_api_of_the_requested_release() throws IOException { + assumeRunningJdkCanServeOlderReleases(); + Set undefinedAt11 = undefinedTypes("11", JDK_API_SOURCE); + assertThat(undefinedAt11).containsExactly("java.lang.Record cannot be resolved to a type"); + assertThat(undefinedTypes("17", inputFile("Example24.java", JDK_API_SOURCE), List.of(runningJdkRuntimeImage()))).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() throws IOException { + assumeRunningJdkCanServeOlderReleases(); + var useReleaseOption = false; + var undefinedTypes = undefinedTypes("11", inputFile("Example42.java", JDK_API_SOURCE), List.of(runningJdkRuntimeImage()), useReleaseOption); + 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() throws IOException { + File runtimeImage = new File(System.getProperty("java.home"), "lib/jrt-fs.jar"); + assumeRunningJdkCanServeOlderReleases(); + List classpath = List.of(runtimeImage); + int jdkVersion = Runtime.version().feature(); + + assertThat(undefinedTypes("11", inputFile("Example1.java", JDK_API_SOURCE), classpath)) + .containsExactly("java.lang.Record cannot be resolved to a type"); + assertThat(undefinedTypes(Integer.toString(jdkVersion), inputFile("Example2.java", JDK_API_SOURCE), classpath)) + .containsExactly("java.util.jar.Pack200 cannot be resolved to a type"); + assertThat(undefinedTypes(Integer.toString(jdkVersion + 1), inputFile("Example3.java", JDK_API_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"), JDK_API_SOURCE); + List> undefinedTypes = new ArrayList<>(); + + BATCH + .create(JavaVersionImpl.fromString("11"), List.of(runningJdkRuntimeImage()), 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) throws IOException { + return undefinedTypes(release, source, List.of(runningJdkRuntimeImage())); + } + + private static File runningJdkRuntimeImage() { + return new File(System.getProperty("java.home"), "lib/jrt-fs.jar"); + } + + private static Set undefinedTypes(String release, String source, List classpath) throws IOException { + var inputFile = inputFile("Example.java", source); + return undefinedTypes(release, inputFile, classpath); + } + + private static InputFile inputFile(String fileName, String source) throws IOException { + var file = Files.createFile(tempDir.resolve(fileName)); + Files.writeString(file, source); + return TestUtils.inputFile(file.toString()); + } + + private static Set undefinedTypes(String release, InputFile inputFile, List classpath) { + return undefinedTypes(release, inputFile, classpath, true); + } + + private static Set undefinedTypes(String release, InputFile inputFile, List classpath, boolean useReleaseOpt) { + JParser parser = FILE_BY_FILE.create(JavaVersionImpl.fromString(release), classpath, false, useReleaseOpt); + Set undefinedTypes = new HashSet<>(); + parser.parse(Set.of(inputFile), () -> false, new AnalysisProgress(1), + (f, result) -> { + try { + undefinedTypes.addAll(result.get().semanticProblems().stream().map(Problem::message).collect(Collectors.toSet())); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + return undefinedTypes; + } + @Test void should_throw_RecognitionException_in_case_of_syntax_error() { // Note that without check for syntax errors will cause IndexOutOfBoundsException @@ -246,8 +353,7 @@ void declaration_enum() { EnumConstantTree c = (EnumConstantTree) t.members().get(0); assertSame( c.simpleName(), - c.initializer().identifier() - ); + c.initializer().identifier()); } @Test @@ -680,7 +786,7 @@ void for_statement_should_support_array_types_from_variable_declaration_fragment ForStatementTree forStatement = (ForStatementTree) ((MethodTree) ((ClassTree) unit.types().get(0)).members().get(0)).block().body().get(0); VariableTree variableTree = (VariableTree) forStatement.initializer().get(0); assertThat(variableTree.type().kind()).isEqualTo(Tree.Kind.ARRAY_TYPE); - assertThat(( (ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); + assertThat(((ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); } @Test @@ -689,7 +795,7 @@ void for_statement_should_support_array_types_from_variable_declaration_fragment ForStatementTree forStatement = (ForStatementTree) ((MethodTree) ((ClassTree) unit.types().get(0)).members().get(0)).block().body().get(0); VariableTree variableTree = (VariableTree) forStatement.initializer().get(0); assertThat(variableTree.type().kind()).isEqualTo(Tree.Kind.ARRAY_TYPE); - assertThat(( (ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); + assertThat(((ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); } @Test @@ -698,7 +804,7 @@ void try_statement_should_support_array_types_from_variable_declaration_fragment TryStatementTree tryStatementTree = (TryStatementTree) ((MethodTree) ((ClassTree) unit.types().get(0)).members().get(0)).block().body().get(0); VariableTree variableTree = (VariableTree) tryStatementTree.resourceList().get(0); assertThat(variableTree.type().kind()).isEqualTo(Tree.Kind.ARRAY_TYPE); - assertThat(( (ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); + assertThat(((ArrayTypeTree) variableTree.type()).openBracketToken()).isNotNull(); } private Path createFakeJrtFs(Path tempFolder) throws IOException { 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..9cc7c8114e4 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 @@ -100,7 +100,7 @@ public void define(Context context) { .name("Enable JDK's latest preview feature") .description("Allow to enable JDK's preview features for analysis. Only the Java's latest supported version preview features are supported.") .category(JavaConstants.JAVA_CATEGORY) - .subCategory("Language") + .subCategory(JavaConstants.LANGUAGE_CATEGORY) .onConfigScopes(Set.of(PropertyDefinition.ConfigScope.PROJECT)) .type(PropertyType.BOOLEAN) .defaultValue("False") @@ -120,11 +120,32 @@ public void define(Context context) { "

" ) .category(JavaConstants.JAVA_CATEGORY) - .subCategory("Language") + .subCategory(JavaConstants.LANGUAGE_CATEGORY) .onConfigScopes(Set.of(PropertyDefinition.ConfigScope.PROJECT)) .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(JavaConstants.LANGUAGE_CATEGORY) + .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); } diff --git a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/SanityTest.java b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/SanityTest.java index 736c0bb8b2b..5e9dd5788d8 100644 --- a/sonar-java-plugin/src/test/java/org/sonar/plugins/java/SanityTest.java +++ b/sonar-java-plugin/src/test/java/org/sonar/plugins/java/SanityTest.java @@ -241,7 +241,7 @@ private static List scanFiles(File moduleBaseDir, List exceptions = new ArrayList<>(); AnalysisProgress analysisProgress = new AnalysisProgress(inputFiles.size()); JParser.Mode.BATCH - .create(javaVersion, classpath, true) + .create(javaVersion, classpath, true, true) .parse(inputFiles, () -> false, analysisProgress, (input, result) -> { try { scanner.simpleScan(input, result, ast -> {