diff --git a/.evergreen/.evg.yml b/.evergreen/.evg.yml index 66b809e38a0..5a8b5ff4ece 100644 --- a/.evergreen/.evg.yml +++ b/.evergreen/.evg.yml @@ -1875,15 +1875,15 @@ axes: - id: "2.11" display_name: "Scala 2.11" variables: - SCALA: "2.11.12" + SCALA: "2.11" - id: "2.12" display_name: "Scala 2.12" variables: - SCALA: "2.12.20" + SCALA: "2.12" - id: "2.13" display_name: "Scala 2.13" variables: - SCALA: "2.13.15" + SCALA: "2.13" # Choice of MongoDB storage engine - id: storage-engine diff --git a/.evergreen/publish.sh b/.evergreen/publish.sh index e3f9f365d42..9a3e9eb405f 100755 --- a/.evergreen/publish.sh +++ b/.evergreen/publish.sh @@ -27,5 +27,5 @@ SYSTEM_PROPERTIES="-Dorg.gradle.internal.publish.checksums.insecure=true -Dorg.g ./gradlew -version ./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info ${TASK} # Scala 2.13 is published as result of this gradle execution. -./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PdefaultScalaVersions=2.12.12 -./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PdefaultScalaVersions=2.11.12 +./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PscalaVersion=2.12 +./gradlew ${SYSTEM_PROPERTIES} --stacktrace --info :bson-scala:${TASK} :driver-scala:${TASK} -PscalaVersion=2.11 diff --git a/.github/workflows/bump-version.sh b/.github/workflows/bump-version.sh index 5f39df82d79..eaa92163bfa 100755 --- a/.github/workflows/bump-version.sh +++ b/.github/workflows/bump-version.sh @@ -9,5 +9,5 @@ fi FROM_VERSION=$1 TO_VERSION=$2 -sed --in-place "s/version = '${FROM_VERSION}'/version = '${TO_VERSION}'/g" build.gradle -git commit -m "Version: bump ${TO_VERSION}" build.gradle +sed --in-place "s/version=${FROM_VERSION}/version=${TO_VERSION}/g" gradle.properties +git commit -m "Version: bump ${TO_VERSION}" gradle.properties diff --git a/bom/build.gradle.kts b/bom/build.gradle.kts index 5d1fb81c384..20e9ee015b7 100644 --- a/bom/build.gradle.kts +++ b/bom/build.gradle.kts @@ -1,6 +1,30 @@ -group = "org.mongodb" -description = "This Bill of Materials POM simplifies dependency management when referencing multiple" + - " MongoDB Java Driver artifacts in projects using Gradle or Maven." +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureMavenPublication +import groovy.util.Node +import groovy.util.NodeList + +plugins { + id("java-platform") + id("project.base") + id("conventions.publishing") + id("conventions.spotless") +} + +base.archivesName.set("mongodb-driver-bom") dependencies { constraints { @@ -21,3 +45,109 @@ dependencies { api(project(":driver-scala")) } } + +/* + * Handle the multiple versions of Scala we support as defined in `gradle.properties` + */ +val defaultScalaVersion: String = project.findProperty("defaultScalaVersion")!!.toString() +val scalaVersions: List? = project.findProperty("supportedScalaVersions")?.toString()?.split(",") + +assert(!scalaVersions.isNullOrEmpty()) { + "Scala versions must be provided as a comma-separated list in the 'supportedScalaVersions' project property" +} + +/* + * Apply the Java Platform plugin to create the BOM + * Modify the generated POM to include all supported versions of Scala for driver-scala or bson-scala. + */ +configureMavenPublication { + components.findByName("javaPlatform")?.let { from(it) } + + pom { + name.set("bom") + description.set( + "This Bill of Materials POM simplifies dependency management when referencing multiple MongoDB Java Driver artifacts in projects using Gradle or Maven.") + + withXml { + val pomXml: Node = asNode() + + val dependencyManagementNode = pomXml.getNode("dependencyManagement") + assert(dependencyManagementNode != null) { + " node not found in the generated BOM POM" + } + val dependenciesNode = dependencyManagementNode.getNode("dependencies") + assert(dependenciesNode != null) { " node not found in the generated BOM POM" } + + val existingScalaDeps = + dependenciesNode!! + .children() + .map { it as Node } + .filter { it.getNode("artifactId")?.text()?.contains("scala") ?: false } + + existingScalaDeps.forEach { + val groupId: String = it.getNode("groupId")!!.text() + val originalArtifactId: String = it.getNode("artifactId")!!.text() + val artifactVersion: String = it.getNode("version")!!.text() + + // Add multiple versions with Scala suffixes for each Scala-related dependency. + scalaVersions!!.forEach { scalaVersion -> + if (scalaVersion != defaultScalaVersion) { + // Replace scala version suffix + val newArtifactId: String = originalArtifactId.replace(defaultScalaVersion, scalaVersion) + val dependencyNode = dependenciesNode.appendNode("dependency") + dependencyNode.appendNode("groupId", groupId) + dependencyNode.appendNode("artifactId", newArtifactId) + dependencyNode.appendNode("version", artifactVersion) + } + } + } + } + } +} + +/* + * Validate the BOM file. + */ +tasks.withType { + doLast { + pom.withXml { + val pomXml: Node = asNode() + val dependenciesNode = pomXml.getNode("dependencyManagement").getNode("dependencies") + assert(dependenciesNode!!.children().isNotEmpty()) { + "BOM must contain more then one element:\n$destination" + } + + dependenciesNode + .children() + .map { it as Node } + .forEach { + val groupId: String = it.getNode("groupId")!!.text() + assert(groupId.startsWith("org.mongodb")) { + "BOM must contain only 'org.mongodb' dependencies, but found '$groupId':\n$destination" + } + + /* + * The and tags should be omitted in BOM dependencies. + * This ensures that consuming projects have the flexibility to decide whether a dependency is optional in their context. + * + * The BOM's role is to provide version information, not to dictate inclusion or exclusion of dependencies. + */ + assert(it.getNode("scope") == null) { + "BOM must not contain elements in dependency:\n$destination" + } + assert(it.getNode("optional") == null) { + "BOM must not contain elements in dependency:\n$destination" + } + } + } + } +} + +/** A node lookup helper. */ +private fun Node?.getNode(nodeName: String): Node? { + val found = this?.get(nodeName) + if (found is NodeList && found.isNotEmpty()) { + return found[0] as Node + } + return null +} diff --git a/bson-kotlin/build.gradle.kts b/bson-kotlin/build.gradle.kts index 45e8c9c0e5d..2cfd4413637 100644 --- a/bson-kotlin/build.gradle.kts +++ b/bson-kotlin/build.gradle.kts @@ -13,133 +13,27 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import io.gitlab.arturbosch.detekt.Detekt -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication -plugins { - id("org.jetbrains.kotlin.jvm") - `java-library` - - // Test based plugins - id("com.diffplug.spotless") - id("org.jetbrains.dokka") - id("io.gitlab.arturbosch.detekt") -} - -repositories { - mavenCentral() - google() -} +plugins { id("project.kotlin") } base.archivesName.set("bson-kotlin") -description = "Bson Kotlin Codecs" - -ext.set("pomName", "Bson Kotlin") - dependencies { - // Align versions of all Kotlin components - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - api(project(path = ":bson", configuration = "default")) - implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation(libs.kotlin.reflect) - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") + // Test case checks MongoClientSettings.getDefaultCodecRegistry() support testImplementation(project(path = ":driver-core", configuration = "default")) } -kotlin { explicitApi() } - -tasks.withType { kotlinOptions.jvmTarget = "1.8" } - -// =========================== -// Code Quality checks -// =========================== -spotless { - kotlinGradle { - ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") - } - - kotlin { - target("**/*.kt") - ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license")) - } - - format("extraneous") { - target("*.xml", "*.yml", "*.md") - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() +configureMavenPublication { + pom { + name.set("BSON Kotlin") + description.set("The BSON Codec for Kotlin") + url.set("https://bsonspec.org") } } -tasks.named("check") { dependsOn("spotlessApply") } - -detekt { - allRules = true // fail build on any finding - buildUponDefaultConfig = true // preconfigure defaults - config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, - // overwriting default behavior - baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt - source = - files( - file("src/main/kotlin"), - file("src/test/kotlin"), - file("src/integrationTest/kotlin"), - ) -} - -tasks.withType().configureEach { - reports { - html.required.set(true) // observe findings in your browser with structure and code snippets - xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins - txt.required.set(false) // similar to the console output, contains issue signature to manually edit - } -} - -spotbugs { showProgress.set(true) } - -// =========================== -// Test Configuration -// =========================== - -tasks.test { useJUnitPlatform() } - -// =========================== -// Dokka Configuration -// =========================== -val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}" - -tasks.dokkaHtml.configure { - outputDirectory.set(file(dokkaOutputDir)) - moduleName.set(base.archivesName.get()) -} - -val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } - -project.parent?.tasks?.named("docs") { - dependsOn(tasks.dokkaHtml) - mustRunAfter(cleanDokka) -} - -tasks.javadocJar.configure { - dependsOn(cleanDokka, tasks.dokkaHtml) - archiveClassifier.set("javadoc") - from(dokkaOutputDir) -} - -// =========================== -// Sources publishing configuration -// =========================== -tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) } - -afterEvaluate { tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlin" } } } +configureJarManifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlin" } diff --git a/bson-kotlinx/build.gradle.kts b/bson-kotlinx/build.gradle.kts index ac0b07f18eb..1671a876edf 100644 --- a/bson-kotlinx/build.gradle.kts +++ b/bson-kotlinx/build.gradle.kts @@ -13,150 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import io.gitlab.arturbosch.detekt.Detekt -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication plugins { - id("org.jetbrains.kotlin.jvm") - kotlin("plugin.serialization") - `java-library` - - // Test based plugins - id("com.diffplug.spotless") - id("org.jetbrains.dokka") - id("io.gitlab.arturbosch.detekt") -} - -repositories { - mavenCentral() - google() + id("project.kotlin") + alias(libs.plugins.kotlin.serialization) } base.archivesName.set("bson-kotlinx") -description = "Bson Kotlinx Codecs" - -ext.set("pomName", "Bson Kotlinx") - -ext.set("kotlinxDatetimeVersion", "0.4.0") - -val kotlinxDatetimeVersion: String by ext - -java { - registerFeature("dateTimeSupport") { usingSourceSet(sourceSets["main"]) } - registerFeature("jsonSupport") { usingSourceSet(sourceSets["main"]) } -} - dependencies { - // Align versions of all Kotlin components - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - - implementation(platform("org.jetbrains.kotlinx:kotlinx-serialization-bom:1.5.0")) - implementation("org.jetbrains.kotlinx:kotlinx-serialization-core") - "dateTimeSupportImplementation"("org.jetbrains.kotlinx:kotlinx-datetime:$kotlinxDatetimeVersion") - "jsonSupportImplementation"("org.jetbrains.kotlinx:kotlinx-serialization-json") - api(project(path = ":bson", configuration = "default")) - implementation("org.jetbrains.kotlin:kotlin-reflect") - - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation(project(path = ":driver-core", configuration = "default")) - testImplementation("org.jetbrains.kotlinx:kotlinx-datetime:$kotlinxDatetimeVersion") - testImplementation("org.jetbrains.kotlinx:kotlinx-serialization-json") -} - -kotlin { explicitApi() } - -tasks.withType { kotlinOptions.jvmTarget = "1.8" } - -// =========================== -// Code Quality checks -// =========================== -spotless { - kotlinGradle { - ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") - } + implementation(platform(libs.kotlinx.serialization)) + implementation(libs.kotlinx.serialization.core) + implementation(libs.kotlin.reflect) - kotlin { - target("**/*.kt") - ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license")) - } - - format("extraneous") { - target("*.xml", "*.yml", "*.md") - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - } -} - -tasks.named("check") { dependsOn("spotlessApply") } + optionalApi(libs.kotlinx.serialization.datetime) + optionalApi(libs.kotlinx.serialization.json) -detekt { - allRules = true // fail build on any finding - buildUponDefaultConfig = true // preconfigure defaults - config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, - // overwriting default behavior - baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt - source = - files( - file("src/main/kotlin"), - file("src/test/kotlin"), - file("src/integrationTest/kotlin"), - ) + // Test case checks MongoClientSettings.getDefaultCodecRegistry() support + testImplementation(project(path = ":driver-core", configuration = "default")) } -tasks.withType().configureEach { - reports { - html.required.set(true) // observe findings in your browser with structure and code snippets - xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins - txt.required.set(false) // similar to the console output, contains issue signature to manually edit +configureMavenPublication { + pom { + name.set("BSON Kotlinx") + description.set("The BSON Codec for Kotlinx serialization") + url.set("https://bsonspec.org") } } -spotbugs { showProgress.set(true) } - -// =========================== -// Test Configuration -// =========================== - -tasks.test { useJUnitPlatform() } - -// =========================== -// Dokka Configuration -// =========================== -val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}" - -tasks.dokkaHtml.configure { - outputDirectory.set(file(dokkaOutputDir)) - moduleName.set(base.archivesName.get()) -} - -val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } - -project.parent?.tasks?.named("docs") { - dependsOn(tasks.dokkaHtml) - mustRunAfter(cleanDokka) -} - -tasks.javadocJar.configure { - dependsOn(cleanDokka, tasks.dokkaHtml) - archiveClassifier.set("javadoc") - from(dokkaOutputDir) -} - -// =========================== -// Sources publishing configuration -// =========================== -tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) } - -afterEvaluate { tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlinx" } } } +configureJarManifest { attributes["Automatic-Module-Name"] = "org.mongodb.bson.kotlinx" } diff --git a/bson-record-codec/build.gradle b/bson-record-codec/build.gradle deleted file mode 100644 index 5a880461a77..00000000000 --- a/bson-record-codec/build.gradle +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -archivesBaseName = 'bson-record-codec' -description = 'The BSON Codec for Java records' - -ext { - pomName = 'BSON Record Codec' -} - -dependencies { - api project(path: ':bson', configuration: 'default') - testImplementation project(':bson').sourceSets.test.output - testImplementation project(':driver-core') -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.bson.record.codec' - jar.manifest.attributes['Bundle-SymbolicName'] = 'org.mongodb.bson-record-codec' -} - -tasks.withType(Test) { - test.onlyIf { javaVersion.isCompatibleWith(javaVersion.VERSION_17) } -} - -tasks.withType(Javadoc) { - dependsOn(project(':bson').tasks.withType(Javadoc), project(':driver-core').tasks.withType(Javadoc)) -} diff --git a/bson-record-codec/build.gradle.kts b/bson-record-codec/build.gradle.kts new file mode 100644 index 00000000000..5165679c06b --- /dev/null +++ b/bson-record-codec/build.gradle.kts @@ -0,0 +1,53 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.test-artifacts") +} + +base.archivesName.set("bson-record-codec") + +dependencies { + api(project(path = ":bson", configuration = "default")) + + // Test case checks MongoClientSettings.getDefaultCodecRegistry() support + testImplementation(project(path = ":driver-core", configuration = "default")) +} + +configureMavenPublication { + pom { + name.set("BSON Record Codec") + description.set("The BSON Codec for Java records") + url.set("https://bsonspec.org") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.bson.record.codec" + attributes["Bundle-SymbolicName"] = "org.mongodb.bson-record-codec" +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +tasks.withType { options.release.set(17) } + +tasks.withType().configureEach { onlyIf { javaVersion.isCompatibleWith(JavaVersion.VERSION_17) } } diff --git a/bson-scala/build.gradle b/bson-scala/build.gradle deleted file mode 100644 index 5d21ed521b5..00000000000 --- a/bson-scala/build.gradle +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -description = "A Scala wrapper / extension to the bson library" -archivesBaseName = 'mongo-scala-bson' - -dependencies { - api project(path: ':bson', configuration: 'default') -} - -sourceSets { - main { - scala { - if(scalaVersion.startsWith("2.13")) { - srcDirs = ["src/main/scala", "src/main/scala-2.13+"] - } else { - srcDirs = ["src/main/scala", "src/main/scala-2.13-"] - } - } - } -} - -tasks.withType(Test) { - doFirst { - println("Running Test task using scala version: $scalaVersion") - } -} - -// =================== -// Scala checks -// =================== -tasks.register("scalaCheck") { - description = "Runs all the Scala checks" - group = "verification" - - dependsOn("clean", "compileTestScala", "check") - tasks.findByName("check").mustRunAfter("clean") -} - -ext { - pomName = 'Mongo Scala Bson Library' -} - -test { - maxParallelForks = 1 -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.bson.scala' - jar.manifest.attributes['Import-Package'] = [ - '!scala.*', - '*' - ].join(',') -} diff --git a/bson-scala/build.gradle.kts b/bson-scala/build.gradle.kts new file mode 100644 index 00000000000..e23087ae314 --- /dev/null +++ b/bson-scala/build.gradle.kts @@ -0,0 +1,37 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { id("project.scala") } + +base.archivesName.set("mongo-scala-bson") + +dependencies { api(project(path = ":bson", configuration = "default")) } + +configureMavenPublication { + pom { + name.set("Mongo Scala BSON Library") + description.set("A Scala wrapper / extension to the BSON library") + url.set("https://bsonspec.org") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.bson.scala" + attributes["Bundle-SymbolicName"] = "org.mongodb.scala.mongo-scala-bson" + attributes["Import-Package"] = "!scala.*,*" +} diff --git a/bson-scala/src/test/scala/org/mongodb/scala/bson/BaseSpec.scala b/bson-scala/src/test/scala/org/mongodb/scala/bson/BaseSpec.scala index ad6cab0069a..4ac18c5b31c 100644 --- a/bson-scala/src/test/scala/org/mongodb/scala/bson/BaseSpec.scala +++ b/bson-scala/src/test/scala/org/mongodb/scala/bson/BaseSpec.scala @@ -15,10 +15,7 @@ */ package org.mongodb.scala.bson -import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import org.scalatestplus.junit.JUnitRunner -@RunWith(classOf[JUnitRunner]) abstract class BaseSpec extends AnyFlatSpec with Matchers {} diff --git a/bson-scala/src/test/scala/org/mongodb/scala/bson/codecs/MacrosSpec.scala b/bson-scala/src/test/scala/org/mongodb/scala/bson/codecs/MacrosSpec.scala index c16215a16e8..e3c8ded2d89 100644 --- a/bson-scala/src/test/scala/org/mongodb/scala/bson/codecs/MacrosSpec.scala +++ b/bson-scala/src/test/scala/org/mongodb/scala/bson/codecs/MacrosSpec.scala @@ -531,6 +531,7 @@ class MacrosSpec extends BaseSpec { } it should "support tagged types in case classes" in { + assume(!scala.util.Properties.versionNumberString.startsWith("2.11")) val a = 1.asInstanceOf[Int with Tag] val b = "b".asInstanceOf[String with Tag] val c = Map("c" -> 0).asInstanceOf[Map[String with Tag, Int with Tag] with Tag] diff --git a/bson/build.gradle.kts b/bson/build.gradle.kts new file mode 100644 index 00000000000..fab3cdaacb5 --- /dev/null +++ b/bson/build.gradle.kts @@ -0,0 +1,39 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.testing-junit") + id("conventions.testing-spock") + id("conventions.test-artifacts") +} + +base.archivesName.set("bson") + +configureMavenPublication { + pom { + name.set("BSON") + description.set("The BSON library") + url.set("https://bsonspec.org") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.bson" + attributes["Import-Package"] = "org.slf4j.*;resolution:=optional" +} diff --git a/bson/src/test/unit/org/bson/GenericBsonTest.java b/bson/src/test/unit/org/bson/GenericBsonTest.java index 6ba2c6ae382..582ec5d83dc 100644 --- a/bson/src/test/unit/org/bson/GenericBsonTest.java +++ b/bson/src/test/unit/org/bson/GenericBsonTest.java @@ -25,11 +25,9 @@ import org.junit.jupiter.params.provider.MethodSource; import util.JsonPoweredTestHelper; -import java.io.File; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; -import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; @@ -283,10 +281,9 @@ private void throwIfValueIsStringContainingReplacementCharacter(final BsonDocume } - private static Stream data() throws URISyntaxException, IOException { + private static Stream data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/bson")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/bson")) { for (BsonValue curValue : testDocument.getArray("valid", new BsonArray())) { BsonDocument testCaseDocument = curValue.asDocument(); data.add(Arguments.of( diff --git a/bson/src/test/unit/org/bson/vector/BinaryVectorGenericBsonTest.java b/bson/src/test/unit/org/bson/vector/BinaryVectorGenericBsonTest.java index 858174d7cd9..35326281c66 100644 --- a/bson/src/test/unit/org/bson/vector/BinaryVectorGenericBsonTest.java +++ b/bson/src/test/unit/org/bson/vector/BinaryVectorGenericBsonTest.java @@ -16,6 +16,7 @@ package org.bson.vector; +import org.bson.BinaryVector; import org.bson.BsonArray; import org.bson.BsonBinary; import org.bson.BsonDocument; @@ -23,16 +24,12 @@ import org.bson.BsonValue; import org.bson.Float32BinaryVector; import org.bson.PackedBitBinaryVector; -import org.bson.BinaryVector; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -73,7 +70,7 @@ class BinaryVectorGenericBsonTest { @ParameterizedTest(name = "{0}") - @MethodSource("provideTestCases") + @MethodSource("data") void shouldPassAllOutcomes(@SuppressWarnings("unused") final String description, final BsonDocument testDefinition, final BsonDocument testCase) { assumeFalse(TEST_NAMES_TO_IGNORE.contains(testCase.get("description").asString().getValue())); @@ -254,10 +251,9 @@ private static float parseFloat(final BsonString bsonValue) { } } - private static Stream provideTestCases() throws URISyntaxException, IOException { + private static Stream data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/bson-binary-vector")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/bson-binary-vector")) { for (BsonValue curValue : testDocument.getArray("tests", new BsonArray())) { BsonDocument testCaseDocument = curValue.asDocument(); data.add(Arguments.of(createTestCaseDescription(testDocument, testCaseDocument), testDocument, testCaseDocument)); diff --git a/bson/src/test/unit/util/JsonPoweredTestHelper.java b/bson/src/test/unit/util/JsonPoweredTestHelper.java index 4507e64301b..a94e3c5cb80 100644 --- a/bson/src/test/unit/util/JsonPoweredTestHelper.java +++ b/bson/src/test/unit/util/JsonPoweredTestHelper.java @@ -17,105 +17,107 @@ package util; import org.bson.BsonDocument; +import org.bson.BsonString; +import org.bson.BsonValue; import org.bson.codecs.BsonDocumentCodec; import org.bson.codecs.DecoderContext; import org.bson.json.JsonReader; import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; -import java.net.URISyntaxException; -import java.net.URL; +import java.net.URI; import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystem; import java.nio.file.FileSystems; +import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.PathMatcher; import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.function.Function; -import static java.nio.file.Files.isDirectory; -import static java.util.stream.Collectors.toMap; +import static org.bson.assertions.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; public final class JsonPoweredTestHelper { - public static BsonDocument getTestDocument(final File file) throws IOException { - return new BsonDocumentCodec().decode(new JsonReader(getFileAsString(file)), DecoderContext.builder().build()); + public static BsonDocument getTestDocument(final String resourcePath) { + BsonDocument testDocument = getTestDocumentWithMetaData(resourcePath); + testDocument.remove("resourcePath"); + testDocument.remove("fileName"); + return testDocument; } - public static BsonDocument getTestDocument(final String resourcePath) throws IOException, URISyntaxException { - return getTestDocument(new File(JsonPoweredTestHelper.class.getResource(resourcePath).toURI())); - } - - public static Path testDir(final String resourceName) { - URL res = JsonPoweredTestHelper.class.getResource(resourceName); - if (res == null) { - throw new AssertionError("Did not find " + resourceName); - } - try { - Path dir = Paths.get(res.toURI()); - if (!isDirectory(dir)) { - throw new AssertionError(dir + " is not a directory"); + public static Collection getTestData(final String resourcePath) { + List data = new ArrayList<>(); + for (BsonDocument document : getTestDocuments(resourcePath)) { + for (BsonValue test : document.getArray("tests")) { + BsonDocument testDocument = test.asDocument(); + data.add(new Object[]{document.getString("fileName").getValue(), + testDocument.getString("description").getValue(), + testDocument.getString("uri", new BsonString("")).getValue(), + testDocument}); } - return dir; - } catch (URISyntaxException e) { - throw new RuntimeException(e); } + return data; } - public static Map testDocs(final Path dir) { - PathMatcher jsonMatcher = FileSystems.getDefault().getPathMatcher("glob:**.json"); + public static List getTestDocuments(final String resourcePath) { + List files = new ArrayList<>(); try { - return Files.list(dir) - .filter(jsonMatcher::matches) - .collect(toMap(Function.identity(), path -> { - try { - return getTestDocument(path.toFile()); - } catch (IOException e) { - throw new RuntimeException(e); + URI resource = assertNotNull(JsonPoweredTestHelper.class.getResource(resourcePath)).toURI(); + try (FileSystem fileSystem = (resource.getScheme().equals("jar") ? FileSystems.newFileSystem(resource, Collections.emptyMap()) : null)) { + Path myPath = Paths.get(resource); + Files.walkFileTree(myPath, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(final Path filePath, final BasicFileAttributes attrs) throws IOException { + if (filePath.toString().endsWith(".json")) { + if (fileSystem == null) { + files.add(getTestDocumentWithMetaData(filePath.toString().substring(filePath.toString().lastIndexOf(resourcePath)))); + } else { + files.add(getTestDocumentWithMetaData(filePath.toString())); + } } - })); - } catch (IOException e) { - throw new RuntimeException(e); + return super.visitFile(filePath, attrs); + } + }); + } + } catch (Exception e) { + fail("Unable to load resource", e); } + return files; } - public static List getTestFiles(final String resourcePath) throws URISyntaxException { - List files = new ArrayList<>(); - addFilesFromDirectory(new File(JsonPoweredTestHelper.class.getResource(resourcePath).toURI()), files); - return files; + private static BsonDocument getTestDocumentWithMetaData(final String resourcePath) { + JsonReader jsonReader = new JsonReader(resourcePathToString(resourcePath)); + BsonDocument testDocument = new BsonDocumentCodec().decode(jsonReader, DecoderContext.builder().build()); + testDocument.append("resourcePath", new BsonString(resourcePath)) + .append("fileName", new BsonString(resourcePath.substring(resourcePath.lastIndexOf('/') + 1))); + return testDocument; } - private static String getFileAsString(final File file) throws IOException { + private static String resourcePathToString(final String resourcePath) { StringBuilder stringBuilder = new StringBuilder(); String line; - String ls = System.getProperty("line.separator"); - try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { - while ((line = reader.readLine()) != null) { - stringBuilder.append(line); - stringBuilder.append(ls); - } - } - return stringBuilder.toString(); - } - - private static void addFilesFromDirectory(final File directory, final List files) { - String[] fileNames = directory.list(); - if (fileNames != null) { - for (String fileName : fileNames) { - File file = new File(directory, fileName); - if (file.isDirectory()) { - addFilesFromDirectory(file, files); - } else if (file.getName().endsWith(".json")) { - files.add(file); + String ls = System.lineSeparator(); + try (InputStream inputStream = JsonPoweredTestHelper.class.getResourceAsStream(resourcePath)) { + assertNotNull(inputStream); + try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { + while ((line = reader.readLine()) != null) { + stringBuilder.append(line); + stringBuilder.append(ls); } } + } catch (Exception e) { + fail("Unable to load resource", e); } + return stringBuilder.toString(); } private JsonPoweredTestHelper() { diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 2b2a2906c8d..00000000000 --- a/build.gradle +++ /dev/null @@ -1,380 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -apply plugin: 'eclipse' -apply plugin: 'idea' - -buildscript { - repositories { - mavenLocal() - mavenCentral() - maven { url "https://plugins.gradle.org/m2/" } - } - dependencies { - classpath 'com.netflix.nebula:gradle-extra-configurations-plugin:7.0.0' - classpath "com.github.spotbugs.snom:spotbugs-gradle-plugin:6.0.15" - classpath 'biz.aQute.bnd:biz.aQute.bnd.gradle:5.1.2' - - // Scala plugins - classpath "com.adtran:scala-multiversion-plugin:2.0.4" - classpath "com.diffplug.spotless:spotless-plugin-gradle:6.14.0" - - // kotlin plugins - classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10" - classpath "org.jetbrains.kotlin:kotlin-serialization:1.8.10" - classpath "org.jetbrains.dokka:dokka-gradle-plugin:1.8.10" - classpath "io.gitlab.arturbosch.detekt:detekt-gradle-plugin:1.21.0" - - // Test logging plugin - classpath 'com.adarshr:gradle-test-logger-plugin:2.1.0' - } -} - -////////////////////////////////////////// -// Common behavior // -////////////////////////////////////////// - -ext { - configDir = new File(rootDir, 'config') - jnrUnixsocketVersion = '0.38.17' - nettyVersion = '4.1.87.Final' - snappyVersion = '1.1.10.3' - zstdVersion = '1.5.5-3' - awsSdkV2Version = '2.30.31' - awsSdkV1Version = '1.12.782' - projectReactorVersion = '2022.0.0' - junitBomVersion = '5.10.2' - logbackVersion = '1.3.14' - graalSdkVersion = '24.0.0' - reflectionsVersion = '0.9.10' - gitVersion = getGitVersion() -} - -def configDir = ext.configDir -def utilProjects = project(":util").allprojects -def bomProjects = project(":bom") -def coreProjects = subprojects - utilProjects -def scalaProjects = subprojects.findAll { it.name.contains('scala') } - bomProjects -def javaProjects = subprojects - scalaProjects - bomProjects -def javaMainProjects = javaProjects - utilProjects -def javaCodeCheckedProjects = javaMainProjects.findAll { !['driver-benchmarks', 'driver-workload-executor', 'driver-lambda'].contains(it.name) } -def javaAndScalaTestedProjects = javaCodeCheckedProjects + scalaProjects - -configure(coreProjects) { - apply plugin: 'idea' - - group = 'org.mongodb' - version = '5.5.0-SNAPSHOT' - - repositories { - mavenLocal() - google() - mavenCentral() - - // Uncomment this to test with a snapshot build of mongodb-crypt - maven { - url 'https://oss.sonatype.org/content/repositories/snapshots' - content { - includeGroup "org.mongodb" - } - } - } -} - -configure(javaProjects) { - apply plugin: 'java-library' - - sourceSets { - main { - java.srcDirs = ['src/main'] - } - } - - tasks.withType(GenerateModuleMetadata) { - enabled = false - } - -} - -configure(scalaProjects) { - apply plugin: 'scala' - apply plugin: 'java-library' - apply plugin: 'idea' - apply plugin: "com.adtran.scala-multiversion-plugin" - apply plugin: "com.diffplug.spotless" - - group = 'org.mongodb.scala' - - dependencies { - api ('org.scala-lang:scala-library:%scala-version%') - api ('org.scala-lang:scala-reflect:%scala-version%') - - testImplementation(platform("org.junit:junit-bom:$junitBomVersion")) - testImplementation("org.junit.vintage:junit-vintage-engine") - - testImplementation('org.scalatest:scalatest-flatspec_%%:3.2.9') - testImplementation('org.scalatest:scalatest-shouldmatchers_%%:3.2.9') - testImplementation('org.scalatestplus:junit-4-13_%%:3.2.9.0') - testImplementation('org.scalatestplus:mockito-3-12_%%:3.2.10.0') - testImplementation("ch.qos.logback:logback-classic:$logbackVersion") - testImplementation("org.reflections:reflections:$reflectionsVersion") - } - - test{ - useJUnitPlatform { - includeEngines('junit-jupiter', 'junit-vintage') - } - } - - spotless { - scala { - scalafmt().configFile("$configDir/scala/scalafmt.conf") - } - } - compileScala.dependsOn('spotlessApply') - compileTestScala.dependsOn('spotlessApply') - - tasks.withType(ScalaCompile) { - scalaCompileOptions.deprecation = false - if(scalaVersion.startsWith("2.11")) { - scalaCompileOptions.additionalParameters = [ - // support static methods in interfaces - "-target:jvm-1.8" - ] - } - if(scalaVersion.startsWith("2.13")) { - scalaCompileOptions.additionalParameters = [ - "-feature", - "-unchecked", - "-language:reflectiveCalls", - "-Wconf:cat=deprecation:ws", - "-Wconf:msg=While parsing annotations in:silent", - "-Xlint:strict-unsealed-patmat" - ] - } - - } - - tasks.withType(GenerateModuleMetadata) { - enabled = false - } -} - -configure(javaMainProjects) { - apply plugin: 'nebula.optional-base' - apply plugin: 'java-library' - - dependencies { - compileOnly 'com.google.code.findbugs:jsr305:1.3.9' - api 'org.slf4j:slf4j-api:1.7.6', optional - testImplementation 'com.google.code.findbugs:jsr305:1.3.9' - - // https://issues.apache.org/jira/browse/GROOVY-10194 - testImplementation 'org.codehaus.groovy:groovy-all:3.0.9' - } - - /* Compiling */ - tasks.withType(AbstractCompile) { - options.encoding = 'ISO-8859-1' - options.fork = true - options.debug = true - options.compilerArgs = ['-Xlint:all'] - } -} - -configure(javaAndScalaTestedProjects) { - /* Testing */ - tasks.withType(Test) { - systemProperties(System.getProperties().findAll { it.key.toString().startsWith("org.mongodb.") }) - systemProperty('jna.library.path', System.getProperty('jna.library.path')) - - project.ext.buildingWith = { propertyName -> - project.hasProperty(propertyName) && project.property(propertyName).toBoolean() - } - - if (project.buildingWith('ssl.enabled')) { - if (project.hasProperty('ssl.keyStoreType')) { - systemProperties( - 'javax.net.ssl.keyStoreType': project.property('ssl.keyStoreType'), - 'javax.net.ssl.keyStore': project.property('ssl.keyStore'), - 'javax.net.ssl.keyStorePassword': project.property('ssl.keyStorePassword') - ) - } - if (project.hasProperty('ssl.trustStoreType')) { - systemProperties( - 'javax.net.ssl.trustStoreType': project.property('ssl.trustStoreType'), - 'javax.net.ssl.trustStore': project.property('ssl.trustStore'), - 'javax.net.ssl.trustStorePassword': project.property('ssl.trustStorePassword') - ) - } - if (project.hasProperty('ocsp.property')) { - systemProperties( - 'org.mongodb.test.ocsp.tls.should.succeed': project.property('ocsp.tls.should.succeed'), - 'java.security.properties': file(project.property('ocsp.property')), - 'com.sun.net.ssl.checkRevocation': project.property('ssl.checkRevocation'), - 'jdk.tls.client.enableStatusRequestExtension': project.property('client.enableStatusRequestExtension'), - 'jdk.tls.client.protocols': project.property('client.protocols') - ) - } - } - - if (project.buildingWith('gssapi.enabled')) { - systemProperties( - 'sun.security.krb5.debug': project.getProperty('sun.security.krb5.debug'), - 'javax.security.auth.useSubjectCredsOnly': "false", - 'java.security.krb5.kdc': project.getProperty('krb5.kdc'), - 'java.security.krb5.realm': project.getProperty('krb5.realm'), - 'java.security.auth.login.config': project.getProperty('auth.login.config'), - ) - } - } -} - -configure(javaCodeCheckedProjects) { - apply plugin: 'checkstyle' - apply plugin: "com.github.spotbugs" - apply plugin: 'jacoco' - apply plugin: 'groovy' - apply plugin: 'codenarc' - apply plugin: 'com.adarshr.test-logger' - - dependencies { - testImplementation(platform("org.junit:junit-bom:$junitBomVersion")) - testImplementation('org.junit.jupiter:junit-jupiter') - testImplementation('org.junit.jupiter:junit-jupiter-params') - testImplementation('org.junit.jupiter:junit-jupiter-engine') - testImplementation('org.junit.vintage:junit-vintage-engine') - - testImplementation platform('org.spockframework:spock-bom:2.1-groovy-3.0') - testImplementation 'org.spockframework:spock-core' - testImplementation 'org.spockframework:spock-junit4' - if ('8'.equals(findProperty("javaVersion"))) { - testImplementation("org.mockito:mockito-core:4.6.1") - testImplementation("org.mockito:mockito-inline:4.6.1") - } else { - testImplementation("org.mockito:mockito-core:5.11.0") - } - testImplementation 'cglib:cglib-nodep:2.2.2' - testImplementation 'org.objenesis:objenesis:1.3' - testImplementation 'org.hamcrest:hamcrest-all:1.3' - testImplementation "ch.qos.logback:logback-classic:$logbackVersion" - testImplementation project(':util:spock') //Adding categories to classpath - } - - sourceSets { - test { - groovy.srcDirs = ['src/test/functional', 'src/test/unit'] - } - } - - /* Testing */ - tasks.withType(Test) { - maxHeapSize = "4g" - maxParallelForks = 1 - - useJUnitPlatform { - includeEngines('junit-jupiter', 'junit-vintage', 'spock') - excludeTags('Slow') - } - systemProperty('spock.configuration', "${configDir}/spock/ExcludeSlow.groovy") - - jacoco { enabled = false } - - testLogging { - exceptionFormat = 'full' - events("passed", "skipped", "failed") - } - - testlogger { - theme 'standard' - showExceptions false - showStackTraces false - showFullStackTraces false - } - } - - task testSlowOnly(type: Test) { - dependsOn('testSlowGroovy') - useJUnitPlatform { - includeEngines('junit-jupiter', 'junit-vintage') - includeTags('Slow') - } - } - - task testSlowGroovy(type: Test) { - useJUnitPlatform { - includeEngines( 'spock') - } - systemProperty('spock.configuration', "${configDir}/spock/OnlySlow.groovy") - } - - gradle.taskGraph.whenReady { taskGraph -> - if (taskGraph.hasTask(testCoverage)) { - tasks.withType(Test) { jacoco { enabled = true } } - } - } - - task testCoverage(dependsOn: test) - - /* Code quality */ - tasks.withType(Checkstyle) { - reports { - xml.required = true - html.required = true - } - } - - checkstyle { - toolVersion = "9.1" - } - - spotbugs { - if (!project.buildingWith('ssdlcReport.enabled')) { - excludeFilter = new File(configDir, 'spotbugs/exclude.xml') - } - } - - codenarc { - toolVersion = '1.6.1' - reportFormat = project.buildingWith('xmlReports.enabled') ? 'xml' : 'html' - } - - spotbugsMain { - reports { - xml.enabled = project.buildingWith('xmlReports.enabled') - html.enabled = !project.buildingWith('xmlReports.enabled') - sarif.enabled = project.buildingWith('ssdlcReport.enabled') - } - } - - spotbugsTest { - enabled = false - } -} - -def getGitVersion() { - def describeStdOut = new ByteArrayOutputStream() - exec { - commandLine 'git', 'describe', '--tags', '--always', '--dirty' - standardOutput = describeStdOut - } - describeStdOut.toString().substring(1).trim() -} - -apply from: 'gradle/javaToolchain.gradle' -apply from: 'gradle/publish.gradle' -apply from: 'gradle/deploy.gradle' -apply from: 'gradle/javadoc.gradle' diff --git a/util/spock/build.gradle b/build.gradle.kts similarity index 93% rename from util/spock/build.gradle rename to build.gradle.kts index 4498034e07a..287017f0ed4 100644 --- a/util/spock/build.gradle +++ b/build.gradle.kts @@ -14,3 +14,7 @@ * limitations under the License. */ +plugins { + id("eclipse") + id("idea") +} diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts new file mode 100644 index 00000000000..23095a6700b --- /dev/null +++ b/buildSrc/build.gradle.kts @@ -0,0 +1,83 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import dev.panuszewski.gradle.pluginMarker + +plugins { + id("java-library") + `kotlin-dsl` + alias(libs.plugins.spotless) + alias(libs.plugins.detekt) apply false +} + +repositories { + gradlePluginPortal() + mavenCentral() + google() +} + +// Dependencies needed for the configuration of the plugins +// Uses `pluginMarker` from the `typesafe-conventions` plugin, see `settings.gradle.kts` +dependencies { + implementation(pluginMarker(libs.plugins.bnd)) + implementation(pluginMarker(libs.plugins.detekt)) + implementation(pluginMarker(libs.plugins.dokka)) + implementation(pluginMarker(libs.plugins.kotlin.gradle)) + implementation(pluginMarker(libs.plugins.spotbugs)) + implementation(pluginMarker(libs.plugins.spotless)) + implementation(pluginMarker(libs.plugins.test.logger)) +} + +// Spotless configuration for `buildSrc` code. +spotless { + kotlinGradle { + target("**/*.gradle.kts") + ktfmt("0.39").dropboxStyle().configure { + it.setMaxWidth(120) + it.setRemoveUnusedImport(true) + } + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + licenseHeaderFile( + "../config/mongodb.license", "(package|group|plugins|import|buildscript|rootProject|@Suppress)") + } + + kotlin { + target("**/*.kt") + ktfmt().dropboxStyle().configure { + it.setMaxWidth(120) + it.setRemoveUnusedImport(true) + } + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + licenseHeaderFile(rootProject.file("../config/mongodb.license")) + } + + java { + palantirJavaFormat() + target("src/*/java/**/*.java") + removeUnusedImports() + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + licenseHeaderFile(rootProject.file("../config/mongodb.license")) + } +} + +java { toolchain { languageVersion.set(JavaLanguageVersion.of("17")) } } + +tasks.findByName("check")?.dependsOn("spotlessCheck") diff --git a/buildSrc/settings.gradle.kts b/buildSrc/settings.gradle.kts new file mode 100644 index 00000000000..ae51c27d8ae --- /dev/null +++ b/buildSrc/settings.gradle.kts @@ -0,0 +1,21 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +plugins { + // Add support for `libs.versions.toml` within `buildSrc` + // https://github.com/radoslaw-panuszewski/typesafe-conventions-gradle-plugin + // https://github.com/gradle/gradle/issues/15383 + id("dev.panuszewski.typesafe-conventions") version "0.4.1" +} diff --git a/util/taglets/src/main/AtlasManualTaglet.java b/buildSrc/src/main/java/com/mongodb/doclet/AtlasManualTaglet.java similarity index 97% rename from util/taglets/src/main/AtlasManualTaglet.java rename to buildSrc/src/main/java/com/mongodb/doclet/AtlasManualTaglet.java index 004ce1b64c1..673b55a6bf6 100644 --- a/util/taglets/src/main/AtlasManualTaglet.java +++ b/buildSrc/src/main/java/com/mongodb/doclet/AtlasManualTaglet.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.mongodb.doclet; public final class AtlasManualTaglet extends DocTaglet { @Override diff --git a/util/taglets/src/main/DocTaglet.java b/buildSrc/src/main/java/com/mongodb/doclet/DocTaglet.java similarity index 93% rename from util/taglets/src/main/DocTaglet.java rename to buildSrc/src/main/java/com/mongodb/doclet/DocTaglet.java index c63265e40a4..0f51f45f197 100644 --- a/util/taglets/src/main/DocTaglet.java +++ b/buildSrc/src/main/java/com/mongodb/doclet/DocTaglet.java @@ -13,15 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import com.sun.source.doctree.DocTree; -import com.sun.source.doctree.UnknownBlockTagTree; -import jdk.javadoc.doclet.Taglet; - -import javax.lang.model.element.Element; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +package com.mongodb.doclet; import static java.util.Arrays.asList; import static jdk.javadoc.doclet.Taglet.Location.CONSTRUCTOR; @@ -31,6 +23,14 @@ import static jdk.javadoc.doclet.Taglet.Location.PACKAGE; import static jdk.javadoc.doclet.Taglet.Location.TYPE; +import com.sun.source.doctree.DocTree; +import com.sun.source.doctree.UnknownBlockTagTree; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import javax.lang.model.element.Element; +import jdk.javadoc.doclet.Taglet; + public abstract class DocTaglet implements Taglet { @Override @@ -49,7 +49,8 @@ public String toString(List tags, Element element) { return null; } - StringBuilder buf = new StringBuilder(String.format("
%s
", getHeader())); + StringBuilder buf = + new StringBuilder(String.format("
%s
", getHeader())); for (DocTree tag : tags) { String text = ((UnknownBlockTagTree) tag).getContent().get(0).toString(); buf.append("
").append(genLink(text)).append("
"); diff --git a/util/taglets/src/main/DochubTaglet.java b/buildSrc/src/main/java/com/mongodb/doclet/DochubTaglet.java similarity index 97% rename from util/taglets/src/main/DochubTaglet.java rename to buildSrc/src/main/java/com/mongodb/doclet/DochubTaglet.java index 2092e8ffa5c..a6b960eaa27 100644 --- a/util/taglets/src/main/DochubTaglet.java +++ b/buildSrc/src/main/java/com/mongodb/doclet/DochubTaglet.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.mongodb.doclet; public class DochubTaglet extends DocTaglet { @@ -30,5 +31,4 @@ protected String getHeader() { protected String getBaseDocURI() { return "https://dochub.mongodb.org/"; } - } diff --git a/util/taglets/src/main/ManualTaglet.java b/buildSrc/src/main/java/com/mongodb/doclet/ManualTaglet.java similarity index 97% rename from util/taglets/src/main/ManualTaglet.java rename to buildSrc/src/main/java/com/mongodb/doclet/ManualTaglet.java index 8ccbc2b9f62..ff49c9ab37c 100644 --- a/util/taglets/src/main/ManualTaglet.java +++ b/buildSrc/src/main/java/com/mongodb/doclet/ManualTaglet.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.mongodb.doclet; public class ManualTaglet extends DocTaglet { @@ -30,5 +31,4 @@ protected String getHeader() { protected String getBaseDocURI() { return "https://www.mongodb.com/docs/manual/"; } - } diff --git a/util/taglets/src/main/ServerReleaseTaglet.java b/buildSrc/src/main/java/com/mongodb/doclet/ServerReleaseTaglet.java similarity index 97% rename from util/taglets/src/main/ServerReleaseTaglet.java rename to buildSrc/src/main/java/com/mongodb/doclet/ServerReleaseTaglet.java index 6508ceab712..9b4f88fbf92 100644 --- a/util/taglets/src/main/ServerReleaseTaglet.java +++ b/buildSrc/src/main/java/com/mongodb/doclet/ServerReleaseTaglet.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package com.mongodb.doclet; public class ServerReleaseTaglet extends DocTaglet { @@ -30,5 +31,4 @@ protected String getHeader() { protected String getBaseDocURI() { return "https://www.mongodb.com/docs/manual/release-notes/"; } - } diff --git a/buildSrc/src/main/kotlin/ProjectExtensions.kt b/buildSrc/src/main/kotlin/ProjectExtensions.kt new file mode 100644 index 00000000000..a369aefc9d2 --- /dev/null +++ b/buildSrc/src/main/kotlin/ProjectExtensions.kt @@ -0,0 +1,56 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import org.gradle.api.Project +import org.gradle.api.java.archives.Manifest +import org.gradle.api.publish.maven.MavenPublication +import org.gradle.api.tasks.bundling.Jar +import org.gradle.kotlin.dsl.named +import org.gradle.kotlin.dsl.withType + +object ProjectExtensions { + + /** + * Extension function to get and validate the current scala version + * + * See: gradle.properties for `supportedScalaVersions` and `defaultScalaVersion` + */ + fun Project.scalaVersion(): String { + val supportedScalaVersions = (project.property("supportedScalaVersions") as String).split(",") + val scalaVersion: String = + (project.findProperty("scalaVersion") ?: project.property("defaultScalaVersion")) as String + + if (!supportedScalaVersions.contains(scalaVersion)) { + throw UnsupportedOperationException( + """Scala version: $scalaVersion is not a supported scala version. + |Supported versions: $supportedScalaVersions + """ + .trimMargin()) + } + + return scalaVersion + } + + /** Extension function to configure the maven publication */ + fun Project.configureMavenPublication(configure: MavenPublication.() -> Unit = {}) { + val publishing = extensions.getByName("publishing") as org.gradle.api.publish.PublishingExtension + publishing.publications.named("maven") { configure() } + } + + /** Extension function to configure the jars manifest */ + fun Project.configureJarManifest(configure: Manifest.() -> Unit = {}) { + tasks.withType { manifest { afterEvaluate { configure() } } } + } +} diff --git a/buildSrc/src/main/kotlin/conventions/Companion.kt b/buildSrc/src/main/kotlin/conventions/Companion.kt new file mode 100644 index 00000000000..c28eef2a080 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/Companion.kt @@ -0,0 +1,29 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import org.gradle.accessors.dm.LibrariesForLibs +import org.gradle.api.Project +import org.gradle.kotlin.dsl.getByType + +// Adds the `libs` value for use in conventions +internal val Project.libs: LibrariesForLibs + get() = extensions.getByType() + +/** Extension function to determine if a project property has been set. */ +fun Project.buildingWith(name: String): Boolean { + return this.findProperty(name)?.toString()?.toBoolean() ?: false +} diff --git a/util/build.gradle b/buildSrc/src/main/kotlin/conventions/bnd.gradle.kts similarity index 77% rename from util/build.gradle rename to buildSrc/src/main/kotlin/conventions/bnd.gradle.kts index 6a2444433a7..39a4513b41d 100644 --- a/util/build.gradle +++ b/buildSrc/src/main/kotlin/conventions/bnd.gradle.kts @@ -13,3 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package conventions + +// Gradle Plugin for developing OSGi bundles with Bnd. +// https://plugins.gradle.org/plugin/biz.aQute.bnd.builder + +plugins { id("biz.aQute.bnd.builder") } diff --git a/buildSrc/src/main/kotlin/conventions/codenarc.gradle.kts b/buildSrc/src/main/kotlin/conventions/codenarc.gradle.kts new file mode 100644 index 00000000000..25cd5c00cc8 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/codenarc.gradle.kts @@ -0,0 +1,25 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// The CodeNarc plugin performs quality checks on your project’s Groovy source files +// https://docs.gradle.org/current/userguide/codenarc_plugin.html +plugins { id("codenarc") } + +codenarc { + toolVersion = "1.6.1" + reportFormat = if (project.buildingWith("xmlReports.enabled")) "xml" else "html" +} diff --git a/buildSrc/src/main/kotlin/conventions/detekt.gradle.kts b/buildSrc/src/main/kotlin/conventions/detekt.gradle.kts new file mode 100644 index 00000000000..3ca88eac418 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/detekt.gradle.kts @@ -0,0 +1,44 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import io.gitlab.arturbosch.detekt.Detekt + +// Static code analysis for Kotlin +// https://plugins.gradle.org/plugin/io.gitlab.arturbosch.detekt +plugins { id("io.gitlab.arturbosch.detekt") } + +detekt { + allRules = true // fail build on any finding + buildUponDefaultConfig = true // preconfigure defaults + config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, + // overwriting default behavior + baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt + source = + files( + file("src/main/kotlin"), + file("src/test/kotlin"), + file("src/integrationTest/kotlin"), + ) +} + +tasks.withType().configureEach { + reports { + html.required.set(true) // observe findings in your browser with structure and code snippets + xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins + txt.required.set(false) // similar to the console output, contains issue signature to manually edit + } +} diff --git a/buildSrc/src/main/kotlin/conventions/dokka.gradle.kts b/buildSrc/src/main/kotlin/conventions/dokka.gradle.kts new file mode 100644 index 00000000000..8ad68409662 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/dokka.gradle.kts @@ -0,0 +1,47 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Dokka, the documentation engine for Kotlin +// https://plugins.gradle.org/plugin/org.jetbrains.dokka +plugins { + id("org.jetbrains.dokka") + id("conventions.publishing") +} + +// Create a generic `docs` task +tasks.register("docs") { + group = "documentation" + dependsOn("dokkaHtml") +} + +val dokkaOutputDir: Provider = rootProject.layout.buildDirectory.dir("docs/${base.archivesName.get()}") + +tasks.dokkaHtml.configure { + outputDirectory.set(dokkaOutputDir.get().asFile) + moduleName.set(base.archivesName.get()) +} + +val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } + +// Ensure dokka is used for the javadoc +afterEvaluate { + tasks.named("javadocJar").configure { + dependsOn("cleanDokka", "dokkaHtml") + archiveClassifier.set("javadoc") + from(dokkaOutputDir) + } +} diff --git a/buildSrc/src/main/kotlin/conventions/git-version.gradle.kts b/buildSrc/src/main/kotlin/conventions/git-version.gradle.kts new file mode 100644 index 00000000000..5370f59cea9 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/git-version.gradle.kts @@ -0,0 +1,31 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Provides the current git version for the build + +val gitVersion: Provider = + providers + .exec { commandLine("git", "describe", "--tags", "--always", "--dirty") } + .standardOutput + .asText + .map { it.trim().removePrefix("r") } + +// Allows access to gitVersion extension to other conventions +extensions.add("gitVersion", gitVersion) + +// Debug task that outputs the gitVersion. +tasks.register("gitVersion") { doLast { println("Git version: ${gitVersion.get()}") } } diff --git a/buildSrc/src/main/kotlin/conventions/javadoc.gradle.kts b/buildSrc/src/main/kotlin/conventions/javadoc.gradle.kts new file mode 100644 index 00000000000..8ab2ef5bb5b --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/javadoc.gradle.kts @@ -0,0 +1,125 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Provides the Javadoc configuration for the build +plugins { + id("java-library") + id("maven-publish") +} + +// Create a generic `docs` task +tasks.register("docs") { + group = "documentation" + dependsOn("javadoc") +} + +tasks.withType { + exclude("**/com/mongodb/**/assertions/**") + exclude("**/com/mongodb/**/internal/**") + exclude("**/org/bson/**/internal/**") + + setDestinationDir(rootProject.file("build/docs/${project.base.archivesName.get()}")) + + val standardDocletOptions = options as StandardJavadocDocletOptions + standardDocletOptions.apply { + author(true) + version(true) + links = + listOf( + "https://docs.oracle.com/en/java/javase/11/docs/api/", + "https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/") + tagletPath(rootProject.projectDir.resolve("buildSrc/build/classes/java/main")) + taglets("com.mongodb.doclet.AtlasManualTaglet") + taglets("com.mongodb.doclet.ManualTaglet") + taglets("com.mongodb.doclet.DochubTaglet") + taglets("com.mongodb.doclet.ServerReleaseTaglet") + encoding = "UTF-8" + charSet("UTF-8") + docEncoding("UTF-8") + addBooleanOption("html5", true) + addBooleanOption("-allow-script-in-comments", true) + header( + """ + + """.trimIndent()) + } + + // Customizations for specific projects + afterEvaluate { + val docVersion = docVersion(project.version as String) + if (project.name != "bson") linksOfflineHelper(docVersion, "bson", standardDocletOptions) + if (!project.name.contains("bson") && project.name != "mongodb-driver-core") + linksOfflineHelper(docVersion, "mongodb-driver-core", standardDocletOptions) + if (!project.name.contains("bson") && project.name != "mongodb-driver-sync") + linksOfflineHelper(docVersion, "mongodb-driver-sync", standardDocletOptions) + } +} + +// Helper functions +internal fun docVersion(version: String): String { + val (major, minor, patch) = version.split("-").first().split(".").map { it.toInt() } + var docVersion = "${major}.${minor}" + if (version.contains("-SNAPSHOT") && patch == 0 && minor > 0) { + docVersion = "${major}.${minor - 1}" + } + return docVersion +} + +internal fun linksOfflineHelper(docVersion: String, packageName: String, options: StandardJavadocDocletOptions): Unit { + val docsPath = rootProject.file("build/docs/${packageName}") + if (docsPath.exists()) { + options.apply { + linksOffline( + "http://mongodb.github.io/mongo-java-driver/${docVersion}/apidocs/${packageName}/", docsPath.path) + } + } +} diff --git a/buildSrc/src/main/kotlin/conventions/optional.gradle.kts b/buildSrc/src/main/kotlin/conventions/optional.gradle.kts new file mode 100644 index 00000000000..1bf10321971 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/optional.gradle.kts @@ -0,0 +1,33 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Provides the optional dependencies support eg: optionalApi, optionalImplementation +plugins { + id("java-library") + id("maven-publish") +} + +java { registerFeature("optional") { usingSourceSet(sourceSets["main"]) } } + +// Suppress POM warnings for the optional features (eg: optionalApi, optionalImplementation) +afterEvaluate { + configurations + .filter { it.name.startsWith("optional") } + .forEach { optional -> + publishing.publications.named("maven") { suppressPomMetadataWarningsFor(optional.name) } + } +} diff --git a/buildSrc/src/main/kotlin/conventions/publishing.gradle.kts b/buildSrc/src/main/kotlin/conventions/publishing.gradle.kts new file mode 100644 index 00000000000..bd27acfabb5 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/publishing.gradle.kts @@ -0,0 +1,174 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Provides the publishing configuration for the build +// +// Note: Further configuration can be achieved using the `project.configureMavenPublication` and +// `project.configureJarManifest` helpers. +// See: `ProjectExtensions.kt` for more information +plugins { + id("conventions.git-version") + id("maven-publish") + id("signing") +} + +val signingKey: Provider = providers.gradleProperty("signingKey") +val signingPassword: Provider = providers.gradleProperty("signingPassword") +val nexusUsername: Provider = providers.gradleProperty("nexusUsername") +val nexusPassword: Provider = providers.gradleProperty("nexusPassword") +@Suppress("UNCHECKED_CAST") val gitVersion: Provider = project.findProperty("gitVersion") as Provider + +tasks.withType().configureEach { + // Gradle warns about some signing tasks using publishing task outputs without explicit + // dependencies. Here's a quick fix. + dependsOn(tasks.withType()) + mustRunAfter(tasks.withType()) + + doLast { + logger.lifecycle("[task: ${name}] ${publication.groupId}:${publication.artifactId}:${publication.version}") + } +} + +val localBuildRepo: Provider = rootProject.layout.buildDirectory.dir("repo") + +val sonatypeRepositoryReleaseUrl: Provider = provider { + if (version.toString().endsWith("SNAPSHOT")) { + "https://oss.sonatype.org/content/repositories/snapshots/" + } else { + "https://oss.sonatype.org/service/local/staging/deploy/maven2/" + } +} + +publishing { + repositories { + maven { + url = uri(sonatypeRepositoryReleaseUrl) + if (nexusUsername.isPresent && nexusPassword.isPresent) { + credentials { + username = nexusUsername.get() + password = nexusPassword.get() + } + } + } + + // publish to local dir, for artifact tracking and testing + // `./gradlew publishMavenPublicationToLocalBuildRepository` + maven { + url = uri(localBuildRepo.get()) + name = "LocalBuild" + } + } + + publications.create("maven") { + components.findByName("java")?.let { from(it) } + + pom { + url.set("https://www.mongodb.com/") + scm { + url.set("https://github.com/mongodb/mongo-java-driver") + connection.set("scm:https://github.com/mongodb/mongo-java-driver.git") + developerConnection.set("scm:https://github.com/mongodb/mongo-java-driver.git") + } + + developers { + developer { + name.set("Various") + organization.set("MongoDB") + } + } + + licenses { + license { + name.set("The Apache License, Version 2.0") + url.set("https://www.apache.org/licenses/LICENSE-2.0.txt") + } + } + } + + // Ensure get the final set `base.archivesName` not the default one (project name). + afterEvaluate { artifactId = base.archivesName.get() } + } +} + +tasks.withType { + manifest { attributes["-exportcontents"] = "*;-noimport:=true" } + + afterEvaluate { + manifest { + if (attributes.containsKey("-nomanifest")) { + attributes.remove("-exportcontents") + } else { + attributes["Bundle-Version"] = project.version + attributes["Bundle-SymbolicName"] = + "${project.findProperty("group")}.${project.findProperty("archivesBaseName")}" + attributes["Build-Version"] = gitVersion.get() + attributes["Bundle-Name"] = base.archivesName.get() + } + } + } +} + +signing { + if (signingKey.isPresent && signingPassword.isPresent) { + logger.debug("[${project.displayName}] Signing is enabled") + useInMemoryPgpKeys(signingKey.get(), signingPassword.get()) + } +} + +tasks.named("clean") { delete.add(localBuildRepo) } + +tasks.withType { enabled = false } + +tasks.register("publishSnapshots") { + group = "publishing" + description = "Publishes snapshots to Sonatype" + + if (version.toString().endsWith("-SNAPSHOT")) { + dependsOn(tasks.withType()) + } +} + +tasks.register("publishArchives") { + group = "publishing" + description = "Publishes a release and uploads to Sonatype / Maven Central" + + val currentGitVersion = gitVersion.get() + val gitVersionMatch = currentGitVersion == version + doFirst { + if (!gitVersionMatch) { + val cause = + """ + Version mismatch: + ================= + + $version != $currentGitVersion + + The project version does not match the git tag. + """.trimMargin() + throw GradleException(cause) + } else { + println("Publishing: ${project.name} : $currentGitVersion") + } + } + if (gitVersionMatch) { + dependsOn(tasks.withType()) + } +} + +// workaround for https://github.com/gradle/gradle/issues/16543 +inline fun TaskContainer.provider(taskName: String): Provider = + providers.provider { taskName }.flatMap { named(it) } diff --git a/buildSrc/src/main/kotlin/conventions/scaladoc.gradle.kts b/buildSrc/src/main/kotlin/conventions/scaladoc.gradle.kts new file mode 100644 index 00000000000..b14d9573e72 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/scaladoc.gradle.kts @@ -0,0 +1,34 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Provides the scaladoc configuration for the build +plugins { + id("scala") + id("conventions.publishing") +} + +// Create a generic `docs` task +tasks.register("docs") { + group = "documentation" + dependsOn("scaladoc") +} + +tasks.withType { + group = "documentation" + + destinationDir = rootProject.file("build/docs/${project.base.archivesName.get()}") +} diff --git a/buildSrc/src/main/kotlin/conventions/spotbugs.gradle.kts b/buildSrc/src/main/kotlin/conventions/spotbugs.gradle.kts new file mode 100644 index 00000000000..d675fd27139 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/spotbugs.gradle.kts @@ -0,0 +1,53 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import com.github.spotbugs.snom.SpotBugsTask +import org.gradle.kotlin.dsl.dependencies +import project.libs + +// Performs quality checks on your project's Java source files using SpotBug +// https://plugins.gradle.org/plugin/com.github.spotbugs +plugins { + id("java-library") + id("com.github.spotbugs") +} + +dependencies { + compileOnly(libs.findbugs.jsr) + + testImplementation(libs.findbugs.jsr) +} + +spotbugs { + if (!project.buildingWith("ssdlcReport.enabled")) { + excludeFilter.set(rootProject.file("config/spotbugs/exclude.xml")) + } +} + +tasks.withType().configureEach { + if (name == "spotbugsMain") { + reports { + register("xml") { required.set(project.buildingWith("xmlReports.enabled")) } + register("html") { required.set(!project.buildingWith("xmlReports.enabled")) } + register("sarif") { required.set(project.buildingWith("ssdlcReport.enabled")) } + } + } else if (name == "spotbugsTest") { + enabled = false + } else if (name == "spotbugsIntegrationTest") { + enabled = false + } +} diff --git a/buildSrc/src/main/kotlin/conventions/spotless.gradle.kts b/buildSrc/src/main/kotlin/conventions/spotless.gradle.kts new file mode 100644 index 00000000000..f4175ec0c6a --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/spotless.gradle.kts @@ -0,0 +1,69 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import com.diffplug.gradle.spotless.SpotlessApply +import com.diffplug.gradle.spotless.SpotlessCheck + +// Spotless - keep your code spotless +// https://plugins.gradle.org/plugin/com.diffplug.spotless +plugins { id("com.diffplug.spotless") } + +val doesNotHaveACustomLicenseHeader = "/^(?s)(?!.*@custom-license-header).*/" + +spotless { + kotlinGradle { + ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") + } + + scala { + target("**/*.scala") + scalafmt().configFile(rootProject.file("config/scala/scalafmt.conf")) + } + + kotlin { + target("**/*.kt") + ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + licenseHeaderFile(rootProject.file("config/mongodb.license")) + .named("standard") + .onlyIfContentMatches(doesNotHaveACustomLicenseHeader) + } + + format("extraneous") { + target("*.xml", "*.yml", "*.md") + trimTrailingWhitespace() + indentWithSpaces() + endWithNewline() + } +} + +tasks.named("check") { dependsOn("spotlessApply") } + +tasks { + withType().configureEach { + notCompatibleWithConfigurationCache("https://github.com/diffplug/spotless/issues/644") + } + withType().configureEach { + notCompatibleWithConfigurationCache("https://github.com/diffplug/spotless/issues/644") + } +} diff --git a/buildSrc/src/main/kotlin/conventions/test-artifacts-runtime-dependencies.gradle.kts b/buildSrc/src/main/kotlin/conventions/test-artifacts-runtime-dependencies.gradle.kts new file mode 100644 index 00000000000..73b2b891faa --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/test-artifacts-runtime-dependencies.gradle.kts @@ -0,0 +1,27 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +plugins { id("java-library") } + +// Also include test runtime dependencies +dependencies { + testRuntimeClasspath(platform(libs.netty.bom)) + testRuntimeClasspath(libs.netty.tcnative.boringssl.static) + listOf("linux-x86_64", "linux-aarch_64", "osx-x86_64", "osx-aarch_64", "windows-x86_64").forEach { arch -> + testRuntimeClasspath(variantOf(libs.netty.tcnative.boringssl.static) { classifier(arch) }) + } +} diff --git a/buildSrc/src/main/kotlin/conventions/test-artifacts.gradle.kts b/buildSrc/src/main/kotlin/conventions/test-artifacts.gradle.kts new file mode 100644 index 00000000000..f82a88c7df9 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/test-artifacts.gradle.kts @@ -0,0 +1,43 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import project.DEFAULT_JAVA_VERSION + +// Allows test artifacts (resources and code) to be shared between projects +plugins { id("java-library") } + +/** Create a test artifact configuration so that test resources can be consumed by other projects. */ +val testArtifacts by configurations.creating +val testJar by + tasks.registering(Jar::class) { + archiveBaseName.set("${project.name}-test") + from(sourceSets.test.get().output) + setDuplicatesStrategy(DuplicatesStrategy.EXCLUDE) + } + +val testJavaVersion: Int = findProperty("javaVersion")?.toString()?.toInt() ?: DEFAULT_JAVA_VERSION + +tasks.withType() { + mustRunAfter(testJar) + + // Needed for OidcAuthenticationProseTests calls `field.setAccessible(true)` + if (testJavaVersion >= DEFAULT_JAVA_VERSION) { + jvmArgs("--add-opens=java.base/java.lang=ALL-UNNAMED") + } +} + +artifacts { add("testArtifacts", testJar) } diff --git a/driver-legacy/build.gradle b/buildSrc/src/main/kotlin/conventions/test-include-optionals.gradle.kts similarity index 50% rename from driver-legacy/build.gradle rename to buildSrc/src/main/kotlin/conventions/test-include-optionals.gradle.kts index 7266e724f7d..e7fde0b4c0f 100644 --- a/driver-legacy/build.gradle +++ b/buildSrc/src/main/kotlin/conventions/test-include-optionals.gradle.kts @@ -13,30 +13,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package conventions +import org.gradle.kotlin.dsl.dependencies +import org.gradle.kotlin.dsl.project -archivesBaseName = 'mongodb-driver-legacy' -description = 'The MongoDB Legacy Driver' -ext { - pomName = 'The Legacy MongoDB Driver' -} - -sourceSets { - test.groovy.srcDirs += ['src/examples'] -} +// Adds common optional dependencies to the testImplementations +dependencies { -test { - exclude 'tour/**' -} + // Encryption testing + "testImplementation"(project(path = ":mongodb-crypt", configuration = "default")) -dependencies { - api project(':bson') - api project(':driver-core') - api project(':driver-sync') + // Netty stream type testing + "testImplementation"(platform(libs.netty.bom)) + "testImplementation"(libs.bundles.netty) - testImplementation project(':bson').sourceSets.test.output - testImplementation project(':driver-core').sourceSets.test.output - testImplementation project(':driver-sync').sourceSets.test.output + // Snappy / zstd testing + "testImplementation"(libs.snappy.java) + "testImplementation"(libs.zstd.jni) - testRuntimeOnly project(path: ':driver-core', configuration: 'consumableTestRuntimeOnly') + // Socket testing + "testImplementation"(libs.jnr.unixsocket) } diff --git a/buildSrc/src/main/kotlin/conventions/testing-base.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-base.gradle.kts new file mode 100644 index 00000000000..8aa6d25a5fd --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-base.gradle.kts @@ -0,0 +1,107 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import com.adarshr.gradle.testlogger.theme.ThemeType +import project.DEFAULT_JAVA_VERSION + +// Default test configuration for projects +// +// Utilizes the test-logger plugin: +// https://plugins.gradle.org/plugin/com.adarshr.test-logger +plugins { + id("java-library") + id("com.adarshr.test-logger") +} + +tasks.withType { + maxHeapSize = "4g" + maxParallelForks = 1 + + useJUnitPlatform() + + // Pass any `org.mongodb.*` system settings + systemProperties = + System.getProperties() + .map { (key, value) -> Pair(key.toString(), value) } + .filter { it.first.startsWith("org.mongodb.") } + .toMap() + + // Convert any ssl based properties + if (project.buildingWith("ssl.enabled")) { + if (project.hasProperty("ssl.keyStoreType")) { + systemProperties( + mapOf( + "javax.net.ssl.keyStoreType" to project.property("ssl.keyStoreType"), + "javax.net.ssl.keyStore" to project.property("ssl.keyStore"), + "javax.net.ssl.keyStorePassword" to project.property("ssl.keyStorePassword"))) + } + if (project.hasProperty("ssl.trustStoreType")) { + systemProperties( + mapOf( + "javax.net.ssl.trustStoreType" to project.property("ssl.trustStoreType"), + "javax.net.ssl.trustStore" to project.property("ssl.trustStore"), + "javax.net.ssl.trustStorePassword" to project.property("ssl.trustStorePassword"))) + } + if (project.hasProperty("ocsp.property")) { + systemProperties( + mapOf( + "org.mongodb.test.ocsp.tls.should.succeed" to project.property("ocsp.tls.should.succeed"), + "java.security.properties" to file(project.property("ocsp.property").toString()), + "com.sun.net.ssl.checkRevocation" to project.property("ssl.checkRevocation"), + "jdk.tls.client.enableStatusRequestExtension" to + project.property("client.enableStatusRequestExtension"), + "jdk.tls.client.protocols" to project.property("client.protocols"))) + } + } + + // Convert gssapi properties + if (project.buildingWith("gssapi.enabled")) { + systemProperties( + mapOf( + "sun.security.krb5.debug" to project.property("sun.security.krb5.debug"), + "javax.security.auth.useSubjectCredsOnly" to "false", + "java.security.krb5.kdc" to project.property("krb5.kdc"), + "java.security.krb5.realm" to project.property("krb5.realm"), + "java.security.auth.login.config" to project.property("auth.login.config"), + )) + } + + // Allow testing with an alternative JDK version + val testJavaVersion: Int = findProperty("javaVersion")?.toString()?.toInt() ?: DEFAULT_JAVA_VERSION + javaLauncher.set(javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(testJavaVersion) }) +} + +// Pretty test output +testlogger { + theme = ThemeType.STANDARD + showExceptions = true + showStackTraces = true + showFullStackTraces = false + showCauses = true + slowThreshold = 2000 + showSummary = true + showSimpleNames = false + showPassed = true + showSkipped = true + showFailed = true + showOnlySlow = false + showStandardStreams = false + showPassedStandardStreams = true + showSkippedStandardStreams = true + showFailedStandardStreams = true + logLevel = LogLevel.LIFECYCLE +} diff --git a/buildSrc/src/main/kotlin/conventions/testing-integration.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-integration.gradle.kts new file mode 100644 index 00000000000..bdd30028b18 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-integration.gradle.kts @@ -0,0 +1,50 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Adds separate `integrationTest` configuration to a project +// Allows unit and integrations tests to be separate tasks +// +// See: +// https://docs.gradle.org/current/samples/sample_jvm_multi_project_with_additional_test_types.html +plugins { id("java-library") } + +val integrationTest by sourceSets.creating + +configurations[integrationTest.implementationConfigurationName].extendsFrom(configurations.testImplementation.get()) + +configurations[integrationTest.runtimeOnlyConfigurationName].extendsFrom(configurations.testRuntimeOnly.get()) + +val integrationTestTask = + tasks.register("integrationTest") { + description = "Runs integration tests." + group = "verification" + useJUnitPlatform() + + testClassesDirs = integrationTest.output.classesDirs + classpath = configurations[integrationTest.runtimeClasspathConfigurationName] + integrationTest.output + shouldRunAfter(tasks.test) + } + +tasks.findByName("check")?.dependsOn(integrationTestTask) + +dependencies { + "integrationTestImplementation"(project) + "integrationTestImplementation"(platform(libs.junit.bom)) + "integrationTestImplementation"(libs.bundles.junit.vintage) +} + +sourceSets["integrationTest"].java.srcDirs("src/integrationTest", "src/integrationTest/java") diff --git a/buildSrc/src/main/kotlin/conventions/testing-junit-vintage.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-junit-vintage.gradle.kts new file mode 100644 index 00000000000..48f6eee92eb --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-junit-vintage.gradle.kts @@ -0,0 +1,26 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Default junit vintage (aka junit4) test configuration for projects +plugins { id("conventions.testing-base") } + +dependencies { + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.bundles.junit.vintage) +} + +sourceSets["test"].java { srcDirs("src/test", "src/test/unit", "src/test/functional") } diff --git a/buildSrc/src/main/kotlin/conventions/testing-junit.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-junit.gradle.kts new file mode 100644 index 00000000000..7e72c5101bf --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-junit.gradle.kts @@ -0,0 +1,26 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +// Default junit test configuration for projects +plugins { id("conventions.testing-base") } + +dependencies { + testImplementation(platform(libs.junit.bom)) + testImplementation(libs.bundles.junit) +} + +sourceSets["test"].java { srcDirs("src/test", "src/test/unit", "src/test/functional") } diff --git a/bson/build.gradle b/buildSrc/src/main/kotlin/conventions/testing-mockito.gradle.kts similarity index 67% rename from bson/build.gradle rename to buildSrc/src/main/kotlin/conventions/testing-mockito.gradle.kts index d2b2ed3ba0e..08c33262e9e 100644 --- a/bson/build.gradle +++ b/buildSrc/src/main/kotlin/conventions/testing-mockito.gradle.kts @@ -13,16 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package conventions -archivesBaseName = 'bson' -description = 'The BSON library' +// Adds mockito support to a project +plugins { id("java-library") } -ext { - pomName = 'BSON' - pomURL = 'https://bsonspec.org' -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.bson' - jar.manifest.attributes['Import-Package'] = 'org.slf4j.*;resolution:=optional' +dependencies { + if (project.findProperty("javaVersion")?.toString().equals("8")) { + testImplementation(libs.bundles.mockito.java8) + } else { + testImplementation(libs.bundles.mockito) + } } diff --git a/buildSrc/src/main/kotlin/conventions/testing-spock-exclude-slow.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-spock-exclude-slow.gradle.kts new file mode 100644 index 00000000000..706bca27e8c --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-spock-exclude-slow.gradle.kts @@ -0,0 +1,36 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import org.gradle.api.tasks.testing.Test +import org.gradle.kotlin.dsl.withType + +// Adds groovy spock testing framework support +// See: https://spockframework.org/ +plugins { id("conventions.testing-spock") } + +tasks.withType().configureEach { + exclude("examples/**") + useJUnitPlatform { excludeTags("Slow") } + + systemProperty("spock.configuration", "${rootProject.file("config/spock/ExcludeSlow.groovy")}") +} + +tasks.register("testSlowOnly", Test::class.java) { + useJUnitPlatform { includeTags("Slow") } + + systemProperty("spock.configuration", "${rootProject.file("config/spock/OnlySlow.groovy")}") +} diff --git a/buildSrc/src/main/kotlin/conventions/testing-spock.gradle.kts b/buildSrc/src/main/kotlin/conventions/testing-spock.gradle.kts new file mode 100644 index 00000000000..e4d46007856 --- /dev/null +++ b/buildSrc/src/main/kotlin/conventions/testing-spock.gradle.kts @@ -0,0 +1,42 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package conventions + +import org.gradle.kotlin.dsl.dependencies +import project.libs + +// Adds groovy spock testing framework support +// See: https://spockframework.org/ +plugins { + id("groovy") + id("conventions.codenarc") + id("conventions.testing-base") + id("conventions.testing-junit-vintage") +} + +dependencies { + testImplementation(platform(libs.spock.bom)) + testImplementation(libs.bundles.spock) +} + +sourceSets { + test { + groovy { srcDirs("src/test", "src/test/unit", "src/test/functional", "src/examples") } + + // Disable java src directories - groovy will compile the mixed java and groovy test code + java { setSrcDirs(emptyList()) } + } +} diff --git a/buildSrc/src/main/kotlin/project/Companion.kt b/buildSrc/src/main/kotlin/project/Companion.kt new file mode 100644 index 00000000000..b4b9650031a --- /dev/null +++ b/buildSrc/src/main/kotlin/project/Companion.kt @@ -0,0 +1,26 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package project + +import org.gradle.accessors.dm.LibrariesForLibs +import org.gradle.api.Project +import org.gradle.kotlin.dsl.getByType + +// Adds the `libs` value for use in project +internal val Project.libs: LibrariesForLibs + get() = extensions.getByType() + +internal const val DEFAULT_JAVA_VERSION = 17 diff --git a/util/taglets/build.gradle b/buildSrc/src/main/kotlin/project/base.gradle.kts similarity index 80% rename from util/taglets/build.gradle rename to buildSrc/src/main/kotlin/project/base.gradle.kts index 4498034e07a..ed13c40cb76 100644 --- a/util/taglets/build.gradle +++ b/buildSrc/src/main/kotlin/project/base.gradle.kts @@ -13,4 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +package project +plugins { id("conventions.git-version") } + +group = "org.mongodb" + +repositories { + mavenLocal() + google() + mavenCentral() +} diff --git a/buildSrc/src/main/kotlin/project/java.gradle.kts b/buildSrc/src/main/kotlin/project/java.gradle.kts new file mode 100644 index 00000000000..60861167f17 --- /dev/null +++ b/buildSrc/src/main/kotlin/project/java.gradle.kts @@ -0,0 +1,50 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package project + +plugins { + id("java-library") + id("checkstyle") + id("project.base") + id("conventions.bnd") + id("conventions.javadoc") + id("conventions.optional") + id("conventions.publishing") + id("conventions.spotbugs") + id("conventions.spotless") + id("conventions.testing-junit") +} + +dependencies { "optionalApi"(libs.slf4j) } + +logger.info("Compiling ${project.name} using JDK${DEFAULT_JAVA_VERSION}") + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + toolchain { languageVersion = JavaLanguageVersion.of(DEFAULT_JAVA_VERSION) } + + withSourcesJar() + withJavadocJar() +} + +tasks.withType { + options.encoding = "UTF-8" + options.release.set(8) +} + +sourceSets["main"].java { srcDir("src/main") } diff --git a/buildSrc/src/main/kotlin/project/kotlin.gradle.kts b/buildSrc/src/main/kotlin/project/kotlin.gradle.kts new file mode 100644 index 00000000000..f6bad54d696 --- /dev/null +++ b/buildSrc/src/main/kotlin/project/kotlin.gradle.kts @@ -0,0 +1,67 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package project + +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile + +plugins { + kotlin("jvm") + id("project.base") + id("conventions.bnd") + id("conventions.detekt") + id("conventions.dokka") + id("conventions.optional") + id("conventions.publishing") + id("conventions.spotbugs") + id("conventions.spotless") + id("conventions.testing-integration") + id("conventions.testing-junit") +} + +/* Compiling */ +logger.info("Compiling ${project.name} using JDK${DEFAULT_JAVA_VERSION}") + +kotlin { + explicitApi() + jvmToolchain(DEFAULT_JAVA_VERSION) +} + +tasks.withType { compilerOptions { jvmTarget = JvmTarget.JVM_1_8 } } + +java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + withSourcesJar() + withJavadocJar() +} + +dependencies { + "optionalApi"(libs.slf4j) + + // Align versions of all Kotlin components + implementation(platform(libs.kotlin.bom)) + implementation(libs.kotlin.stdlib.jdk8) + + testImplementation(libs.kotlin.reflect) + testImplementation(libs.junit.kotlin) + testImplementation(libs.bundles.mockito.kotlin) + testImplementation(libs.assertj) + testImplementation(libs.classgraph) + + "integrationTestImplementation"(libs.junit.kotlin) +} diff --git a/buildSrc/src/main/kotlin/project/scala.gradle.kts b/buildSrc/src/main/kotlin/project/scala.gradle.kts new file mode 100644 index 00000000000..9e3d36b957b --- /dev/null +++ b/buildSrc/src/main/kotlin/project/scala.gradle.kts @@ -0,0 +1,105 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package project + +import ProjectExtensions.configureMavenPublication +import ProjectExtensions.scalaVersion + +plugins { + id("scala") + id("project.base") + id("conventions.bnd") + id("conventions.optional") + id("conventions.publishing") + id("conventions.scaladoc") + id("conventions.spotless") + id("conventions.testing-junit") + id("conventions.testing-integration") +} + +group = "org.mongodb.scala" + +val scalaVersion: String by lazy { project.scalaVersion() } + +sourceSets["integrationTest"].scala.srcDir("src/integrationTest/scala") + +tasks.register("scalaCheck") { + description = "Runs all the Scala checks" + group = "verification" + + dependsOn("clean", "compileTestScala", "check") + tasks.findByName("check")?.mustRunAfter("clean") +} + +tasks.withType { + doFirst { println("Running Test task using scala version: $scalaVersion") } + useJUnitPlatform() +} + +tasks.named("clean") { delete.add(rootProject.file("build/docs/")) } + +afterEvaluate { + configureMavenPublication { artifactId = "${base.archivesName.get()}_${scalaVersion}" } + + // ============================================ + // Scala version specific configuration + // ============================================ + val compileOptions = mutableListOf("-target:jvm-1.8") + when (scalaVersion) { + "2.13" -> { + dependencies { + api(libs.bundles.scala.v2.v13) + + testImplementation(libs.bundles.scala.test.v2.v13) + } + sourceSets { main { scala { setSrcDirs(listOf("src/main/scala", "src/main/scala-2.13+")) } } } + + compileOptions.addAll( + listOf( + "-feature", + "-unchecked", + "-language:reflectiveCalls", + "-Wconf:cat=deprecation:ws", + "-Xlint:strict-unsealed-patmat")) + } + "2.12" -> { + dependencies { + api(libs.bundles.scala.v2.v12) + + testImplementation(libs.bundles.scala.test.v2.v12) + } + sourceSets { main { scala { setSrcDirs(listOf("src/main/scala", "src/main/scala-2.13-")) } } } + } + "2.11" -> { + dependencies { + api(libs.bundles.scala.v2.v11) + + testImplementation(libs.bundles.scala.test.v2.v11) + } + // Reuse the scala-2.12 source as its compatible. + sourceSets { main { scala { setSrcDirs(listOf("src/main/scala", "src/main/scala-2.13-")) } } } + + compileOptions.add("-Xexperimental") + } + } + + tasks.withType { + doFirst { println("Compiling using scala version: $scalaVersion") } + + scalaCompileOptions.isDeprecation = false + scalaCompileOptions.additionalParameters = compileOptions + } +} diff --git a/config/detekt/baseline.xml b/config/detekt/baseline.xml index 718bfeabbf1..d462c314e9c 100644 --- a/config/detekt/baseline.xml +++ b/config/detekt/baseline.xml @@ -2,22 +2,35 @@ + EmptyDefaultConstructor:UnifiedCrudTest.kt$UnifiedCrudTest$() + EmptyDefaultConstructor:UnifiedTest.kt$UnifiedTest$() + EmptyFunctionBlock:SyncMongoCursor.kt$SyncMongoCursor${} IteratorNotThrowingNoSuchElementException:MongoCursor.kt$MongoCursor<T : Any> : IteratorCloseable LargeClass:MongoCollectionTest.kt$MongoCollectionTest LongMethod:FindFlowTest.kt$FindFlowTest$@Test fun shouldCallTheUnderlyingMethods() LongMethod:FindIterableTest.kt$FindIterableTest$@Test fun shouldCallTheUnderlyingMethods() LongMethod:KotlinSerializerCodecTest.kt$KotlinSerializerCodecTest$@Test fun testDataClassOptionalBsonValues() - MaxLineLength:MapReduceFlow.kt$MapReduceFlow$* - MaxLineLength:MapReduceIterable.kt$MapReduceIterable$* + MaxLineLength:ListCollectionNamesFlow.kt$ListCollectionNamesFlow$* + MaxLineLength:ListCollectionNamesIterable.kt$ListCollectionNamesIterable$* MaxLineLength:ListCollectionsFlow.kt$ListCollectionsFlow$* MaxLineLength:ListCollectionsIterable.kt$ListCollectionsIterable$* - MaxLineLength:ListCollectionNamesIterable.kt$ListCollectionNamesIterable$* - MaxLineLength:ListCollectionNamesFlow.kt$ListCollectionNamesFlow$* + MaxLineLength:MapReduceFlow.kt$MapReduceFlow$* + MaxLineLength:MapReduceIterable.kt$MapReduceIterable$* SwallowedException:MockitoHelper.kt$MockitoHelper.DeepReflectionEqMatcher$e: Throwable TooManyFunctions:ClientSession.kt$ClientSession : jClientSession TooManyFunctions:FindFlow.kt$FindFlow<T : Any> : Flow TooManyFunctions:FindIterable.kt$FindIterable<T : Any> : MongoIterable TooManyFunctions:MongoCollection.kt$MongoCollection<T : Any> TooManyFunctions:MongoDatabase.kt$MongoDatabase + TooManyFunctions:SyncClientSession.kt$SyncClientSession : JClientSession + TooManyFunctions:SyncFindIterable.kt$SyncFindIterable<T : Any> : JFindIterableSyncMongoIterable + TooManyFunctions:SyncMongoCluster.kt$SyncMongoCluster : JMongoCluster + TooManyFunctions:SyncMongoCollection.kt$SyncMongoCollection<T : Any> : JMongoCollection + TooManyFunctions:SyncMongoDatabase.kt$SyncMongoDatabase : JMongoDatabase + UnnecessaryAbstractClass:UnifiedTest.kt$UnifiedTest$UnifiedTest + UnsafeCallOnNullableType:SmokeTests.kt$SmokeTests$collection!! + UnusedPrivateMember:SyncMongoIterable.kt$SyncMongoIterable$private var timeoutMode: TimeoutMode? = null + VarCouldBeVal:SyncMongoIterable.kt$SyncMongoIterable$private var timeoutMode: TimeoutMode? = null + WildcardImport:SyncMongoDatabase.kt$import com.mongodb.client.* diff --git a/config/spock/ExcludeSlow.groovy b/config/spock/ExcludeSlow.groovy index db9671d4261..033fbdb2a7d 100644 --- a/config/spock/ExcludeSlow.groovy +++ b/config/spock/ExcludeSlow.groovy @@ -2,5 +2,5 @@ package spock runner { println "Excluding Slow Spock tests" - exclude util.spock.annotations.Slow + exclude com.mongodb.spock.Slow } diff --git a/config/spock/OnlySlow.groovy b/config/spock/OnlySlow.groovy index f333feaa94b..d98c04bd826 100644 --- a/config/spock/OnlySlow.groovy +++ b/config/spock/OnlySlow.groovy @@ -2,5 +2,5 @@ package spock runner { println "Only including Slow Spock tests" - include util.spock.annotations.Slow + include com.mongodb.spock.Slow } diff --git a/driver-benchmarks/build.gradle b/driver-benchmarks/build.gradle deleted file mode 100644 index 84e32c42e52..00000000000 --- a/driver-benchmarks/build.gradle +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2016-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -apply plugin: 'application' - -mainClassName = "com.mongodb.benchmark.benchmarks.BenchmarkSuite" - -sourceSets { - main { - java { - srcDir 'src/main' - } - resources { - srcDir 'src/resources' - } - } -} - -dependencies { - api project(':driver-sync') - api project(':mongodb-crypt') - implementation "ch.qos.logback:logback-classic:$logbackVersion" - - implementation 'org.openjdk.jmh:jmh-core:1.37' - annotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess:1.37' -} - -tasks.register("jmh", JavaExec) { - group = 'benchmark' - description = 'Run JMH benchmarks.' - mainClass = 'org.openjdk.jmh.Main' - classpath = sourceSets.main.runtimeClasspath -} - -javadoc { - enabled = false -} - -applicationDefaultJvmArgs = ["-Dorg.mongodb.benchmarks.data=" + System.getProperty('org.mongodb.benchmarks.data'), - "-Dorg.mongodb.benchmarks.output=" + System.getProperty('org.mongodb.benchmarks.output')] - diff --git a/driver-benchmarks/build.gradle.kts b/driver-benchmarks/build.gradle.kts new file mode 100644 index 00000000000..eac033920e3 --- /dev/null +++ b/driver-benchmarks/build.gradle.kts @@ -0,0 +1,54 @@ +/* + * Copyright 2016-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +plugins { + id("application") + id("java-library") + id("project.base") +} + +application { + mainClass = "com.mongodb.benchmark.benchmarks.BenchmarkSuite" + applicationDefaultJvmArgs = listOf( + "-Dorg.mongodb.benchmarks.data=${System.getProperty("org.mongodb.benchmarks.data")}", + "-Dorg.mongodb.benchmarks.output=${System.getProperty("org.mongodb.benchmarks.output")}") +} + +sourceSets { + main { + java { setSrcDirs(listOf("src/main")) } + resources { setSrcDirs(listOf("src/resources")) } + } +} + +dependencies { + api(project(":driver-sync")) + api(project(":mongodb-crypt")) + implementation(libs.logback.classic) + implementation(libs.jmh.core) + annotationProcessor(libs.jmh.generator.annprocess) +} + +tasks.register("jmh") { + group = "benchmark" + description = "Run JMH benchmarks." + mainClass = "org.openjdk.jmh.Main" + classpath = sourceSets.main.get().runtimeClasspath +} + +tasks.withType().configureEach { + enabled = false +} diff --git a/driver-core/build.gradle b/driver-core/build.gradle deleted file mode 100644 index a44f65bbc1b..00000000000 --- a/driver-core/build.gradle +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -plugins { - id 'com.github.gmazzo.buildconfig' version '3.0.3' -} - -archivesBaseName = 'mongodb-driver-core' -description = 'Shared components for the Synchronous and Reactive Streams implementations of the MongoDB Java Driver.' - -ext { - pomName = 'MongoDB Java Driver Core' -} - -configurations { - consumableTestRuntimeOnly { - extendsFrom testRuntimeOnly - canBeConsumed = true - } -} - -def classifiers = ["linux-x86_64", "linux-aarch_64", "osx-x86_64", "osx-aarch_64", "windows-x86_64"] -dependencies { - api project(path: ':bson', configuration: 'default') - implementation project(path: ':bson-record-codec', configuration: 'default') - implementation project(path: ':bson-kotlin', configuration: 'default'), optional - implementation project(path: ':bson-kotlinx', configuration: 'default'), optional - implementation project(path: ':mongodb-crypt', configuration: 'default'), optional - - implementation "com.github.jnr:jnr-unixsocket:$jnrUnixsocketVersion", optional - api platform("io.netty:netty-bom:$nettyVersion") - api "io.netty:netty-buffer", optional - api "io.netty:netty-transport", optional - api "io.netty:netty-handler", optional - compileOnly "org.graalvm.sdk:graal-sdk:$graalSdkVersion" - - // Optionally depend on both AWS SDK v2 and v1. The driver will use v2 is present, v1 if present, or built-in functionality if - // neither are present - implementation "software.amazon.awssdk:auth:$awsSdkV2Version", optional - implementation "software.amazon.awssdk:sts:$awsSdkV2Version", optional - implementation "com.amazonaws:aws-java-sdk-core:$awsSdkV1Version", optional - implementation "com.amazonaws:aws-java-sdk-sts:$awsSdkV1Version", optional - - implementation "org.xerial.snappy:snappy-java:$snappyVersion", optional - implementation "com.github.luben:zstd-jni:$zstdVersion", optional - - testImplementation project(':bson').sourceSets.test.output - testImplementation('org.junit.jupiter:junit-jupiter-api') - testImplementation("org.reflections:reflections:$reflectionsVersion") - testRuntimeOnly "io.netty:netty-tcnative-boringssl-static" - - classifiers.forEach { - testRuntimeOnly "io.netty:netty-tcnative-boringssl-static::$it" - } -} - -buildConfig { - className('MongoDriverVersion') - packageName('com.mongodb.internal.build') - useJavaOutput() - buildConfigField('String', 'NAME', '"mongo-java-driver"') - buildConfigField('String', 'VERSION', "\"${gitVersion}\"") -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.driver.core' - jar.manifest.attributes['Bundle-SymbolicName'] = 'org.mongodb.driver-core' - jar.manifest.attributes['Import-Package'] = [ - '!sun.misc.*', // Used by DirectBufferDeallocator only for java 8 - '!sun.nio.ch.*', // Used by DirectBufferDeallocator only for java 8 - '!javax.annotation.*', // Brought in by com.google.code.findbugs:annotations - '!com.oracle.svm.core.annotate.*', // this dependency is provided by the GraalVM runtime - 'io.netty.*;resolution:=optional', - 'com.amazonaws.*;resolution:=optional', - 'software.amazon.awssdk.*;resolution:=optional', - 'org.xerial.snappy.*;resolution:=optional', - 'com.github.luben.zstd.*;resolution:=optional', - 'org.slf4j.*;resolution:=optional', - 'jnr.unixsocket.*;resolution:=optional', - 'com.mongodb.internal.crypt.capi.*;resolution:=optional', - 'jdk.net.*;resolution:=optional', // Used by SocketStreamHelper & depends on JDK version - 'org.bson.codecs.record.*;resolution:=optional', // Depends on JDK version - 'org.bson.codecs.kotlin.*;resolution:=optional', - 'org.bson.codecs.kotlinx.*;resolution:=optional', - '*' // import all that is not excluded or modified before - ].join(',') -} diff --git a/driver-core/build.gradle.kts b/driver-core/build.gradle.kts new file mode 100644 index 00000000000..4f06805a6ea --- /dev/null +++ b/driver-core/build.gradle.kts @@ -0,0 +1,100 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.test-artifacts") + id("conventions.testing-mockito") + id("conventions.testing-junit") + id("conventions.testing-spock-exclude-slow") + alias(libs.plugins.build.config) +} + +base.archivesName.set("mongodb-driver-core") + +buildConfig { + className("MongoDriverVersion") + packageName("com.mongodb.internal.build") + useJavaOutput() + buildConfigField("String", "NAME", "\"mongo-java-driver\"") + buildConfigField("String", "VERSION", "\"${(project.findProperty("gitVersion") as Provider<*>?)?.get()}\"") +} + +dependencies { + api(project(path = ":bson", configuration = "default")) + implementation(project(path = ":bson-record-codec", configuration = "default")) + compileOnly(libs.graal.sdk) + + optionalImplementation(project(path = ":bson-kotlin", configuration = "default")) + optionalImplementation(project(path = ":bson-kotlinx", configuration = "default")) + optionalImplementation(project(path = ":mongodb-crypt", configuration = "default")) + optionalImplementation(libs.jnr.unixsocket) + optionalApi(platform(libs.netty.bom)) + optionalApi(libs.bundles.netty) + + // Optionally depend on both AWS SDK v2 and v1. + // The driver will choose: v2 or v1 or fallback to built-in functionality + optionalImplementation(libs.bundles.aws.java.sdk.v1) + optionalImplementation(libs.bundles.aws.java.sdk.v2) + + optionalImplementation(libs.snappy.java) + optionalImplementation(libs.zstd.jni) + + testImplementation(project(path = ":bson", configuration = "testArtifacts")) + testImplementation(libs.reflections) + testImplementation(libs.netty.tcnative.boringssl.static) + listOf("linux-x86_64", "linux-aarch_64", "osx-x86_64", "osx-aarch_64", "windows-x86_64").forEach { arch -> + testImplementation("${libs.netty.tcnative.boringssl.static.get()}::$arch") + } +} + +configureMavenPublication { + pom { + name.set("MongoDB Java Driver Core") + description.set( + "Shared components for the Synchronous and Reactive Streams implementations of the MongoDB Java Driver.") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.core" + attributes["Bundle-SymbolicName"] = "org.mongodb.driver-core" + attributes["Import-Package"] = + listOf( + "!sun.misc.*", // Used by DirectBufferDeallocator only for java 8 + "!sun.nio.ch.*", // Used by DirectBufferDeallocator only for java 8 + "!javax.annotation.*", // Brought in by com.google.code.findbugs:annotations + "!com.oracle.svm.core.annotate.*", // this dependency is provided by the GraalVM + // runtime + "io.netty.*;resolution:=optional", + "com.amazonaws.*;resolution:=optional", + "software.amazon.awssdk.*;resolution:=optional", + "org.xerial.snappy.*;resolution:=optional", + "com.github.luben.zstd.*;resolution:=optional", + "org.slf4j.*;resolution:=optional", + "jnr.unixsocket.*;resolution:=optional", + "com.mongodb.internal.crypt.capi.*;resolution:=optional", + "jdk.net.*;resolution:=optional", // Used by SocketStreamHelper & depends on JDK + // version + "org.bson.codecs.record.*;resolution:=optional", // Depends on JDK version + "org.bson.codecs.kotlin.*;resolution:=optional", + "org.bson.codecs.kotlinx.*;resolution:=optional", + "*" // import all that is not excluded or modified before + ) + .joinToString(",") +} diff --git a/driver-core/src/test/functional/com/mongodb/client/model/AggregatesFunctionalSpecification.groovy b/driver-core/src/test/functional/com/mongodb/client/model/AggregatesFunctionalSpecification.groovy index 82c63393e7e..388736a9a82 100644 --- a/driver-core/src/test/functional/com/mongodb/client/model/AggregatesFunctionalSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/client/model/AggregatesFunctionalSpecification.groovy @@ -1336,7 +1336,8 @@ class AggregatesFunctionalSpecification extends OperationFunctionalSpecification [1, 2, 3, 4, 1, 2, 3, 4, 4.1] 'num' | 'partitionId' | densify(field, partitionRangeWithStep(1), densifyOptions().partitionByFields([partitionByField])) | [1, 2, 3, 4.1] - 'date' | null | densify(field, rangeWithStep(Instant.EPOCH, Instant.ofEpochMilli(BigInteger.TWO.pow(32).longValueExact()) + 1, + 'date' | null | densify(field, rangeWithStep(Instant.EPOCH, Instant.ofEpochMilli(BigInteger.TWO.pow(32).longValueExact()) + .plusMillis(1), // there is a server bug that prevents using `step` larger than 2^31 - 1 in versions before 6.1 BigInteger.TWO.pow(31).longValueExact() - 1, MongoTimeUnit.MILLISECOND)) | [Instant.EPOCH, diff --git a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy index 012ba23e339..e582e0fc398 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy @@ -13,7 +13,7 @@ import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.nio.NioSocketChannel import spock.lang.IgnoreIf import spock.lang.Specification -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy index 0ac6b8fd9df..85f23350984 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy @@ -9,7 +9,7 @@ import com.mongodb.connection.SslSettings import com.mongodb.spi.dns.InetAddressResolver import spock.lang.IgnoreIf import spock.lang.Specification -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.CountDownLatch diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy index 6efe88806e8..3589362b8ac 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy @@ -26,7 +26,7 @@ import com.mongodb.connection.ServerId import com.mongodb.connection.SocketSettings import com.mongodb.internal.connection.netty.NettyStreamFactory import spock.lang.IgnoreIf -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.TimeUnit diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy index 42886648a2c..0283ce44f7b 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy @@ -8,7 +8,7 @@ import com.mongodb.spi.dns.InetAddressResolver import spock.lang.Ignore import spock.lang.IgnoreIf import spock.lang.Specification -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import javax.net.SocketFactory import java.util.concurrent.TimeUnit diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CommandOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CommandOperationSpecification.groovy index a9f74ca50b3..57aee534fd0 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CommandOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CommandOperationSpecification.groovy @@ -23,7 +23,7 @@ import org.bson.BsonDocument import org.bson.BsonInt32 import org.bson.BsonString import org.bson.codecs.BsonDocumentCodec -import util.spock.annotations.Slow +import com.mongodb.spock.Slow class CommandOperationSpecification extends OperationFunctionalSpecification { diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/MixedBulkWriteOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/MixedBulkWriteOperationSpecification.groovy index 9363f6a1812..6bdedf2ff60 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/MixedBulkWriteOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/MixedBulkWriteOperationSpecification.groovy @@ -46,7 +46,7 @@ import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.DocumentCodec import org.bson.types.ObjectId import spock.lang.IgnoreIf -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import static com.mongodb.ClusterFixture.configureFailPoint import static com.mongodb.ClusterFixture.disableFailPoint diff --git a/driver-core/src/test/unit/com/mongodb/AuthConnectionStringTest.java b/driver-core/src/test/unit/com/mongodb/AuthConnectionStringTest.java index cab5b0e0365..8e8a78008e7 100644 --- a/driver-core/src/test/unit/com/mongodb/AuthConnectionStringTest.java +++ b/driver-core/src/test/unit/com/mongodb/AuthConnectionStringTest.java @@ -29,12 +29,7 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import static com.mongodb.AuthenticationMechanism.MONGODB_OIDC; import static com.mongodb.MongoCredential.OIDC_CALLBACK_KEY; @@ -61,16 +56,8 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/auth/legacy")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{file.getName(), test.asDocument().getString("description").getValue(), - test.asDocument().getString("uri").getValue(), test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/auth/legacy"); } private void testInvalidUris() { diff --git a/driver-core/src/test/unit/com/mongodb/ConnectionStringTest.java b/driver-core/src/test/unit/com/mongodb/ConnectionStringTest.java index 80cc9f65e83..312c3698d8b 100644 --- a/driver-core/src/test/unit/com/mongodb/ConnectionStringTest.java +++ b/driver-core/src/test/unit/com/mongodb/ConnectionStringTest.java @@ -17,17 +17,11 @@ package com.mongodb; import org.bson.BsonDocument; -import org.bson.BsonValue; import org.junit.Test; import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import static org.junit.Assume.assumeFalse; @@ -70,15 +64,7 @@ public void shouldPassAllOutcomes() { @Parameterized.Parameters(name = "{1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/connection-string")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{file.getName(), test.asDocument().getString("description").getValue(), - test.asDocument().getString("uri").getValue(), test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/connection-string"); } } diff --git a/driver-core/src/test/unit/com/mongodb/ReadConcernConnectionStringTest.java b/driver-core/src/test/unit/com/mongodb/ReadConcernConnectionStringTest.java index 7d228604460..f45a620bfdf 100644 --- a/driver-core/src/test/unit/com/mongodb/ReadConcernConnectionStringTest.java +++ b/driver-core/src/test/unit/com/mongodb/ReadConcernConnectionStringTest.java @@ -19,18 +19,12 @@ import junit.framework.TestCase; import org.bson.BsonBoolean; import org.bson.BsonDocument; -import org.bson.BsonValue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; // See https://github.com/mongodb/specifications/tree/master/source/read-write-concern/tests/ @RunWith(Parameterized.class) @@ -39,7 +33,8 @@ public class ReadConcernConnectionStringTest extends TestCase { private final String input; private final BsonDocument definition; - public ReadConcernConnectionStringTest(final String description, final String input, final BsonDocument definition) { + public ReadConcernConnectionStringTest(@SuppressWarnings("unused") final String fileName, final String description, + final String input, final BsonDocument definition) { this.description = description; this.input = input; this.definition = definition; @@ -59,16 +54,7 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/read-concern/connection-string")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{test.asDocument().getString("description").getValue(), - test.asDocument().getString("uri").getValue(), - test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/read-concern/connection-string"); } } diff --git a/driver-core/src/test/unit/com/mongodb/ReadConcernDocumentTest.java b/driver-core/src/test/unit/com/mongodb/ReadConcernDocumentTest.java index 0555d368b91..9b49ec3a6d8 100644 --- a/driver-core/src/test/unit/com/mongodb/ReadConcernDocumentTest.java +++ b/driver-core/src/test/unit/com/mongodb/ReadConcernDocumentTest.java @@ -19,18 +19,12 @@ import junit.framework.TestCase; import org.bson.BsonBoolean; import org.bson.BsonDocument; -import org.bson.BsonValue; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; // See https://github.com/mongodb/specifications/tree/master/source/read-write-concern/tests/connection-string @RunWith(Parameterized.class) @@ -38,7 +32,8 @@ public class ReadConcernDocumentTest extends TestCase { private final String description; private final BsonDocument definition; - public ReadConcernDocumentTest(final String description, final BsonDocument definition) { + public ReadConcernDocumentTest(@SuppressWarnings("unused") final String fileName, final String description, + @SuppressWarnings("unused") final String uri, final BsonDocument definition) { this.description = description; this.definition = definition; } @@ -71,15 +66,7 @@ private ReadConcern getReadConcern(final BsonDocument readConcernDocument) { } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/read-concern/document")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{test.asDocument().getString("description").getValue(), - test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/read-concern/document"); } } diff --git a/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java b/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java index 3ca5ce0aa76..03915c27258 100644 --- a/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java +++ b/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java @@ -18,17 +18,11 @@ import org.bson.BsonBoolean; import org.bson.BsonDocument; -import org.bson.BsonValue; import org.junit.Test; import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import static org.junit.Assume.assumeFalse; @@ -54,15 +48,7 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/uri-options")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{file.getName(), test.asDocument().getString("description").getValue(), - test.asDocument().getString("uri").getValue(), test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/uri-options"); } } diff --git a/driver-core/src/test/unit/com/mongodb/WriteConcernConnectionStringTest.java b/driver-core/src/test/unit/com/mongodb/WriteConcernConnectionStringTest.java index ec5815abfc9..1ddfd4cbb2b 100644 --- a/driver-core/src/test/unit/com/mongodb/WriteConcernConnectionStringTest.java +++ b/driver-core/src/test/unit/com/mongodb/WriteConcernConnectionStringTest.java @@ -28,12 +28,7 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.concurrent.TimeUnit; // See https://github.com/mongodb/specifications/tree/master/source/read-write-concern/tests/connection-string @@ -43,7 +38,8 @@ public class WriteConcernConnectionStringTest extends TestCase { private final String input; private final BsonDocument definition; - public WriteConcernConnectionStringTest(final String description, final String input, final BsonDocument definition) { + public WriteConcernConnectionStringTest(@SuppressWarnings("unused") final String fileName, final String description, + final String input, final BsonDocument definition) { this.description = description; this.input = input; this.definition = definition; @@ -89,16 +85,7 @@ private WriteConcern getExpectedWriteConcern() { } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/write-concern/connection-string")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{test.asDocument().getString("description").getValue(), - test.asDocument().getString("uri").getValue(), - test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/write-concern/connection-string"); } } diff --git a/driver-core/src/test/unit/com/mongodb/WriteConcernDocumentTest.java b/driver-core/src/test/unit/com/mongodb/WriteConcernDocumentTest.java index 1c828a42f15..e4a9b579268 100644 --- a/driver-core/src/test/unit/com/mongodb/WriteConcernDocumentTest.java +++ b/driver-core/src/test/unit/com/mongodb/WriteConcernDocumentTest.java @@ -28,12 +28,7 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.ArrayList; import java.util.Collection; -import java.util.List; import java.util.concurrent.TimeUnit; // See https://github.com/mongodb/specifications/tree/master/source/read-write-concern/tests/connection-string @@ -43,9 +38,10 @@ public class WriteConcernDocumentTest extends TestCase { private final BsonDocument writeConcernDocument; private final BsonDocument definition; - public WriteConcernDocumentTest(final String description, final BsonDocument writeConcernDocument, final BsonDocument definition) { + public WriteConcernDocumentTest(@SuppressWarnings("unused") final String fileName, final String description, + @SuppressWarnings("unused") final String uri, final BsonDocument definition) { this.description = description; - this.writeConcernDocument = writeConcernDocument; + this.writeConcernDocument = definition.getDocument("writeConcern"); this.definition = definition; } @@ -86,16 +82,7 @@ private WriteConcern getWriteConcern(final BsonDocument writeConcernDocument) { } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { - List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/write-concern/document")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - for (BsonValue test : testDocument.getArray("tests")) { - data.add(new Object[]{test.asDocument().getString("description").getValue(), - test.asDocument().getDocument("writeConcern"), - test.asDocument()}); - } - } - return data; + public static Collection data() { + return JsonPoweredTestHelper.getTestData("/write-concern/document"); } } diff --git a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java index 9e1326f6d54..65d26722bf2 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -39,9 +39,6 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; @@ -75,7 +72,7 @@ public ServerSelectionSelectionTest(final String description, final BsonDocument @Test public void shouldPassAllOutcomes() { // skip this test because the driver prohibits maxStaleness or tagSets with mode of primary at a much lower level - assumeTrue(!description.equals("max-staleness/ReplicaSetWithPrimary/MaxStalenessWithModePrimary.json")); + assumeTrue(!description.equals("/max-staleness/server_selection/ReplicaSetWithPrimary/MaxStalenessWithModePrimary.json")); ServerSelector serverSelector = null; List suitableServers = buildServerDescriptions(definition.getArray("suitable_servers", new BsonArray())); @@ -102,26 +99,17 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/server-selection/server_selection")) { - data.add(new Object[]{getServerSelectionTestDescription(file), JsonPoweredTestHelper.getTestDocument(file)}); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/server-selection/server_selection")) { + data.add(new Object[]{testDocument.getString("resourcePath").getValue(), testDocument}); } - for (File file : JsonPoweredTestHelper.getTestFiles("/max-staleness/server_selection")) { - data.add(new Object[]{getMaxStalenessTestDescription(file), JsonPoweredTestHelper.getTestDocument(file)}); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/max-staleness/server_selection")) { + data.add(new Object[]{testDocument.getString("resourcePath").getValue(), testDocument}); } return data; } - private static String getServerSelectionTestDescription(final File file) { - return "server-selection" + "/" + file.getParentFile().getParentFile().getName() + "/" + file.getParentFile().getName() + "/" - + file.getName(); - } - - private static String getMaxStalenessTestDescription(final File file) { - return "max-staleness" + "/" + file.getParentFile().getName() + "/" + file.getName(); - } - public static ClusterDescription buildClusterDescription(final BsonDocument topologyDescription, @Nullable final ServerSettings serverSettings) { ClusterType clusterType = getClusterType(topologyDescription.getString("type").getValue()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java index 5b2cb1ab5f6..6a54fcce406 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java @@ -60,9 +60,6 @@ import org.mockito.Mockito; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -85,8 +82,8 @@ import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.Arrays.asList; +import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; @@ -566,16 +563,12 @@ protected ConnectionPool getPool() { } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/connection-monitoring-and-pooling/cmap-format")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - data.add(new Object[]{ - file.getName(), + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/connection-monitoring-and-pooling/cmap-format")) { + data.add(new Object[]{testDocument.getString("fileName").getValue(), testDocument.getString("description").getValue(), - testDocument, - JsonTestServerVersionChecker.skipTest(testDocument, BsonDocument.parse("{}")) - }); + testDocument, JsonTestServerVersionChecker.skipTest(testDocument, BsonDocument.parse("{}"))}); } return data; } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java index 6fe76d0198a..50c78c0ffae 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java @@ -35,9 +35,7 @@ import org.bson.BsonInt32; import util.JsonPoweredTestHelper; -import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -60,11 +58,11 @@ public AbstractServerDiscoveryAndMonitoringTest(final BsonDocument definition) { this.definition = definition; } - public static Collection data(final String root) throws URISyntaxException, IOException { + public static Collection data(final String resourcePath) { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles(root)) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); - data.add(new Object[]{file.getName() + ": " + testDocument.getString("description").getValue(), testDocument}); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments(resourcePath)) { + data.add(new Object[]{testDocument.getString("fileName").getValue() + + ": " + testDocument.getString("description").getValue(), testDocument}); } return data; } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy index 50f78639168..a509779d09f 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy @@ -37,7 +37,7 @@ import com.mongodb.internal.selector.ServerAddressSelector import com.mongodb.internal.selector.WritableServerSelector import com.mongodb.internal.time.Timeout import spock.lang.Specification -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.CountDownLatch diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy index fe251d34311..b3e78d2dc54 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy @@ -34,7 +34,7 @@ import com.mongodb.logging.TestLoggingInterceptor import org.bson.types.ObjectId import spock.lang.Specification import spock.lang.Subject -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.CompletableFuture import java.util.concurrent.CountDownLatch diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringMonitoringTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringMonitoringTest.java index c542fb29b1f..1aac97daaa9 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringMonitoringTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringMonitoringTest.java @@ -34,8 +34,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -78,7 +76,7 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { return data("/server-discovery-and-monitoring-monitoring"); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java index 4a2e94c19a5..701e28d3664 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java @@ -27,8 +27,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; @@ -78,7 +76,7 @@ private void assertTopology(final BsonDocument outcome) { } @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { return data("/server-discovery-and-monitoring"); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionRttTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionRttTest.java index 9a7a8492563..11d91cfb327 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionRttTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionRttTest.java @@ -23,9 +23,6 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -57,10 +54,10 @@ public void shouldPassAllOutcomes() { } @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/server-selection/rtt")) { - data.add(new Object[]{file.getName(), JsonPoweredTestHelper.getTestDocument(file)}); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/server-selection/rtt")) { + data.add(new Object[]{testDocument.getString("fileName").getValue(), testDocument}); } return data; } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionWithinLatencyWindowTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionWithinLatencyWindowTest.java index 878876d74bd..31086a699b9 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionWithinLatencyWindowTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerSelectionWithinLatencyWindowTest.java @@ -31,10 +31,11 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.mockito.Mockito; +import util.JsonPoweredTestHelper; import java.math.BigDecimal; import java.math.RoundingMode; -import java.nio.file.Path; +import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; @@ -44,12 +45,9 @@ import static com.mongodb.ClusterFixture.createOperationContext; import static com.mongodb.connection.ServerSelectionSelectionTest.buildClusterDescription; import static java.util.stream.Collectors.groupingBy; -import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; -import static util.JsonPoweredTestHelper.testDir; -import static util.JsonPoweredTestHelper.testDocs; /** * A runner for @@ -64,7 +62,7 @@ public class ServerSelectionWithinLatencyWindowTest { private final Outcome outcome; public ServerSelectionWithinLatencyWindowTest( - @SuppressWarnings("unused") final Path fileName, + @SuppressWarnings("unused") final String fileName, @SuppressWarnings("unused") final String description, final BsonDocument definition) { clusterDescription = buildClusterDescription(definition.getDocument("topology_description"), null); @@ -93,14 +91,13 @@ public void shouldPassAllOutcomes() { @Parameterized.Parameters(name = "{0}: {1}") public static Collection data() { - return testDocs(testDir("/server-selection/in_window")) - .entrySet() - .stream() - .map(entry -> new Object[] { - entry.getKey().getFileName(), - entry.getValue().getString("description").getValue(), - entry.getValue()}) - .collect(toList()); + List data = new ArrayList<>(); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/server-selection/in_window")) { + data.add(new Object[]{testDocument.getString("fileName").getValue(), + testDocument.getString("description").getValue(), + testDocument}); + } + return data; } private static Cluster.ServersSnapshot serverCatalog(final BsonArray mockedTopologyState) { diff --git a/driver-core/src/test/unit/com/mongodb/spock/Slow.java b/driver-core/src/test/unit/com/mongodb/spock/Slow.java new file mode 100644 index 00000000000..fba0029931d --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/spock/Slow.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.mongodb.spock; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.METHOD, ElementType.TYPE}) +public @interface Slow { +} diff --git a/driver-kotlin-coroutine/build.gradle.kts b/driver-kotlin-coroutine/build.gradle.kts index 96ac4cc31eb..02a2bf047aa 100644 --- a/driver-kotlin-coroutine/build.gradle.kts +++ b/driver-kotlin-coroutine/build.gradle.kts @@ -13,177 +13,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import io.gitlab.arturbosch.detekt.Detekt -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication plugins { - id("org.jetbrains.kotlin.jvm") - `java-library` - - // Test based plugins - id("com.diffplug.spotless") - id("org.jetbrains.dokka") - id("io.gitlab.arturbosch.detekt") -} - -repositories { - mavenCentral() - google() + id("project.kotlin") + id("conventions.test-artifacts") + id("conventions.test-artifacts-runtime-dependencies") } base.archivesName.set("mongodb-driver-kotlin-coroutine") -description = "The MongoDB Kotlin Coroutine Driver" - -ext.set("pomName", "MongoDB Kotlin Coroutine Driver") - -sourceSets { - create("integrationTest") { - kotlin.srcDir("$projectDir/src/integration/kotlin") - compileClasspath += sourceSets.main.get().output - runtimeClasspath += sourceSets.main.get().output - compileClasspath += project(":driver-sync").sourceSets.test.get().output - runtimeClasspath += project(":driver-sync").sourceSets.test.get().output - compileClasspath += project(":driver-core").sourceSets.test.get().output - runtimeClasspath += project(":driver-core").sourceSets.test.get().output - compileClasspath += project(":bson").sourceSets.test.get().output - runtimeClasspath += project(":bson").sourceSets.test.get().output - } -} - -val integrationTestImplementation: Configuration by - configurations.getting { extendsFrom(configurations.testImplementation.get()) } - dependencies { - // Align versions of all Kotlin components - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - - implementation(platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.6.4")) - api("org.jetbrains.kotlinx:kotlinx-coroutines-core") - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactive") - api(project(path = ":bson", configuration = "default")) api(project(path = ":driver-reactive-streams", configuration = "default")) - implementation(project(path = ":bson-kotlin", configuration = "default")) - - testImplementation("org.jetbrains.kotlin:kotlin-reflect") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") - testImplementation("org.mockito:mockito-junit-jupiter:4.11.0") - testImplementation("org.assertj:assertj-core:3.24.2") - testImplementation("io.github.classgraph:classgraph:4.8.154") - - integrationTestImplementation("org.jetbrains.kotlin:kotlin-test-junit") - integrationTestImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test") - integrationTestImplementation(project(path = ":driver-sync")) - integrationTestImplementation(project(path = ":driver-core")) - integrationTestImplementation(project(path = ":bson")) -} - -kotlin { explicitApi() } - -tasks.withType { kotlinOptions.jvmTarget = "1.8" } - -// =========================== -// Code Quality checks -// =========================== -spotless { - kotlinGradle { - ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") - } - - kotlin { - target("**/*.kt") - ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license")) - } - - format("extraneous") { - target("*.xml", "*.yml", "*.md") - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - } -} - -tasks.named("check") { dependsOn("spotlessApply") } - -detekt { - allRules = true // fail build on any finding - buildUponDefaultConfig = true // preconfigure defaults - config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, - // overwriting default behavior - baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt - source = - files( - file("src/main/kotlin"), - file("src/test/kotlin"), - file("src/integrationTest/kotlin"), - ) -} - -tasks.withType().configureEach { - reports { - html.required.set(true) // observe findings in your browser with structure and code snippets - xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins - txt.required.set(false) // similar to the console output, contains issue signature to manually edit - } -} -spotbugs { - showProgress.set(true) + implementation(platform(libs.kotlinx.coroutines.bom)) + api(libs.kotlinx.coroutines.core) + implementation(libs.kotlinx.coroutines.reactive) + implementation(project(path = ":bson-kotlin", configuration = "default")) - tasks.getByName("spotbugsIntegrationTest") { enabled = false } + integrationTestImplementation(libs.kotlinx.coroutines.test) + integrationTestImplementation(project(path = ":driver-sync", configuration = "default")) + integrationTestImplementation(project(path = ":bson", configuration = "testArtifacts")) + integrationTestImplementation(project(path = ":driver-sync", configuration = "testArtifacts")) + integrationTestImplementation(project(path = ":driver-core", configuration = "testArtifacts")) } -// =========================== -// Test Configuration -// =========================== -val integrationTest = - tasks.create("integrationTest", Test::class) { - description = "Runs the integration tests." - group = "verification" - - testClassesDirs = sourceSets["integrationTest"].output.classesDirs - classpath = sourceSets["integrationTest"].runtimeClasspath +configureMavenPublication { + pom { + name.set("MongoDB Kotlin Coroutine Driver") + description.set("The MongoDB Kotlin Coroutine Driver") } - -tasks.test { useJUnitPlatform() } - -// =========================== -// Dokka Configuration -// =========================== -val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}" - -tasks.dokkaHtml.configure { - outputDirectory.set(file(dokkaOutputDir)) - moduleName.set(base.archivesName.get()) } -val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } - -project.parent?.tasks?.named("docs") { - dependsOn(tasks.dokkaHtml) - mustRunAfter(cleanDokka) -} - -tasks.javadocJar.configure { - dependsOn(cleanDokka, tasks.dokkaHtml) - archiveClassifier.set("javadoc") - from(dokkaOutputDir) +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.coroutine" + attributes["Bundle-SymbolicName"] = "org.mongodb.mongodb-driver-kotlin-coroutine" } - -// =========================== -// Sources publishing configuration -// =========================== -tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) } - -afterEvaluate { tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.coroutine" } } } diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/SmokeTests.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/SmokeTests.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/SmokeTests.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/SmokeTests.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedCrudTest.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedCrudTest.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedCrudTest.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedCrudTest.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedTest.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedTest.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedTest.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/UnifiedTest.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncClientSession.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncClientSession.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncClientSession.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncClientSession.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionNamesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionNamesIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionNamesIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionNamesIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoChangeStreamCursor.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoChangeStreamCursor.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoChangeStreamCursor.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoChangeStreamCursor.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoClient.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoClient.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoClient.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoClient.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCursor.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCursor.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCursor.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCursor.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt diff --git a/driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt similarity index 100% rename from driver-kotlin-coroutine/src/integration/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt rename to driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt diff --git a/driver-kotlin-extensions/build.gradle.kts b/driver-kotlin-extensions/build.gradle.kts index 76f36ca33b2..0bd9405f27e 100644 --- a/driver-kotlin-extensions/build.gradle.kts +++ b/driver-kotlin-extensions/build.gradle.kts @@ -13,56 +13,40 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import io.gitlab.arturbosch.detekt.Detekt +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication import org.jetbrains.kotlin.gradle.tasks.KotlinCompile -plugins { - id("org.jetbrains.kotlin.jvm") - `java-library` - - // Test based plugins - id("com.diffplug.spotless") - id("org.jetbrains.dokka") - id("io.gitlab.arturbosch.detekt") -} - -repositories { - mavenCentral() - google() -} +plugins { id("project.kotlin") } base.archivesName.set("mongodb-driver-kotlin-extensions") -description = "The MongoDB Kotlin Driver Extensions" - -ext.set("pomName", "MongoDB Kotlin Driver Extensions") - -java { registerFeature("kotlinDrivers") { usingSourceSet(sourceSets["main"]) } } - dependencies { - // Align versions of all Kotlin components - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - api(project(path = ":driver-core", configuration = "default")) // Some extensions require higher API like MongoCollection which are defined in the sync & // coroutine Kotlin driver - "kotlinDriversImplementation"(project(path = ":driver-kotlin-sync", configuration = "default")) - "kotlinDriversImplementation"(project(path = ":driver-kotlin-coroutine", configuration = "default")) + optionalImplementation(project(path = ":driver-kotlin-sync", configuration = "default")) + optionalImplementation(project(path = ":driver-kotlin-coroutine", configuration = "default")) - testImplementation("org.jetbrains.kotlin:kotlin-reflect") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation("org.assertj:assertj-core:3.24.2") - testImplementation("io.github.classgraph:classgraph:4.8.154") - testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") + testImplementation(platform(libs.kotlinx.serialization)) + testImplementation(libs.kotlinx.serialization.core) +} + +configureMavenPublication { + pom { + name.set("MongoDB Kotlin Driver Extensions") + description.set("The MongoDB Kotlin Driver Extensions") + } } -kotlin { explicitApi() } +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.extensions" + attributes["Bundle-SymbolicName"] = "org.mongodb.mongodb-driver-kotlin-extensions" +} tasks.withType { kotlinOptions { - jvmTarget = "1.8" freeCompilerArgs = listOf( // Adds OnlyInputTypes support @@ -70,101 +54,3 @@ tasks.withType { ) } } - -// =========================== -// Code Quality checks -// =========================== -val customLicenseHeader = "/^(?s)(?!.*@custom-license-header).*/" - -spotless { - kotlinGradle { - ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") - } - - kotlin { - target("**/*.kt") - ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - - licenseHeaderFile(rootProject.file("config/mongodb.license")) - .named("standard") - .onlyIfContentMatches(customLicenseHeader) - } - - format("extraneous") { - target("*.xml", "*.yml", "*.md") - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - } -} - -tasks.named("check") { dependsOn("spotlessApply") } - -detekt { - allRules = true // fail build on any finding - buildUponDefaultConfig = true // preconfigure defaults - config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, - // overwriting default behavior - baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt - source = files(file("src/main/kotlin"), file("src/test/kotlin")) -} - -tasks.withType().configureEach { - reports { - html.required.set(true) // observe findings in your browser with structure and code snippets - xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins - txt.required.set(false) // similar to the console output, contains issue signature to manually edit - } -} - -spotbugs { showProgress.set(true) } - -tasks.spotbugsMain { - // we need the xml report to find out the "rank" (see config/spotbugs/exclude.xml) - reports.getByName("xml") { required.set(true) } -} - -// =========================== -// Test Configuration -// =========================== - -tasks.test { useJUnitPlatform() } - -// =========================== -// Dokka Configuration -// =========================== -val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}" - -tasks.dokkaHtml.configure { - outputDirectory.set(file(dokkaOutputDir)) - moduleName.set(base.archivesName.get()) -} - -val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } - -project.parent?.tasks?.named("docs") { - dependsOn(tasks.dokkaHtml) - mustRunAfter(cleanDokka) -} - -tasks.javadocJar.configure { - dependsOn(cleanDokka, tasks.dokkaHtml) - archiveClassifier.set("javadoc") - from(dokkaOutputDir) -} - -// =========================== -// Sources publishing configuration -// =========================== -tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) } - -afterEvaluate { - tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.extensions" } } -} diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt index 50f369e50ec..f0fd6d7a1a4 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt @@ -61,11 +61,11 @@ import com.mongodb.kotlin.client.model.Aggregates.unwind import com.mongodb.kotlin.client.model.Projections.excludeId import com.mongodb.kotlin.client.model.Projections.projection import com.mongodb.kotlin.client.model.Sorts.ascending +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.conversions.Bson import org.junit.jupiter.api.BeforeAll -import org.junit.jupiter.api.Test import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.kotlin.doReturn diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ExtensionsApiTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ExtensionsApiTest.kt index e4455f9cfc6..5bad9104408 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ExtensionsApiTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ExtensionsApiTest.kt @@ -16,8 +16,8 @@ package com.mongodb.kotlin.client.model import io.github.classgraph.ClassGraph +import kotlin.test.Test import kotlin.test.assertTrue -import org.junit.jupiter.api.Test class ExtensionsApiTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/FiltersTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/FiltersTest.kt index da15d6ee5af..0ab3d83936a 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/FiltersTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/FiltersTest.kt @@ -58,11 +58,11 @@ import com.mongodb.kotlin.client.model.Filters.size import com.mongodb.kotlin.client.model.Filters.text import com.mongodb.kotlin.client.model.Filters.type import com.mongodb.kotlin.client.model.Filters.where +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.BsonType import org.bson.conversions.Bson -import org.junit.Test class FiltersTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/IndexesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/IndexesTest.kt index 00a819810fe..6c4646dd7f6 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/IndexesTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/IndexesTest.kt @@ -26,10 +26,10 @@ import com.mongodb.kotlin.client.model.Indexes.geo2d import com.mongodb.kotlin.client.model.Indexes.geo2dsphere import com.mongodb.kotlin.client.model.Indexes.hashed import com.mongodb.kotlin.client.model.Indexes.text +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.conversions.Bson -import org.junit.Test class IndexesTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/KPropertiesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/KPropertiesTest.kt index 9d27b86c7ef..0007c6251ea 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/KPropertiesTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/KPropertiesTest.kt @@ -17,11 +17,11 @@ package com.mongodb.kotlin.client.model import java.util.Locale +import kotlin.test.Test import kotlin.test.assertEquals import kotlinx.serialization.SerialName import org.bson.codecs.pojo.annotations.BsonId import org.bson.codecs.pojo.annotations.BsonProperty -import org.junit.Test import org.junit.jupiter.api.assertThrows class KPropertiesTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ProjectionTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ProjectionTest.kt index b4e49ee7dda..2033713d4dc 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ProjectionTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/ProjectionTest.kt @@ -37,10 +37,10 @@ import com.mongodb.kotlin.client.model.Projections.metaVectorSearchScore import com.mongodb.kotlin.client.model.Projections.projection import com.mongodb.kotlin.client.model.Projections.projectionWith import com.mongodb.kotlin.client.model.Projections.slice +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.conversions.Bson -import org.junit.Test class ProjectionTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/SortsTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/SortsTest.kt index f3740ede352..2a8ec84530f 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/SortsTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/SortsTest.kt @@ -22,10 +22,10 @@ import com.mongodb.client.model.Sorts.orderBy import com.mongodb.kotlin.client.model.Sorts.ascending import com.mongodb.kotlin.client.model.Sorts.descending import com.mongodb.kotlin.client.model.Sorts.metaTextScore +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.conversions.Bson -import org.junit.Test class SortsTest { diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/UpdatesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/UpdatesTest.kt index aa51bc98921..9b07d6b8345 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/UpdatesTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/UpdatesTest.kt @@ -45,6 +45,7 @@ import com.mongodb.kotlin.client.model.Updates.setOnInsert import com.mongodb.kotlin.client.model.Updates.unset import java.time.Instant import java.util.Date +import kotlin.test.Test import kotlin.test.assertEquals import org.bson.BsonDocument import org.bson.Document @@ -53,7 +54,6 @@ import org.bson.codecs.configuration.CodecRegistries.fromProviders import org.bson.codecs.configuration.CodecRegistry import org.bson.codecs.pojo.PojoCodecProvider import org.bson.conversions.Bson -import org.junit.Test class UpdatesTest { @Test diff --git a/driver-kotlin-sync/build.gradle.kts b/driver-kotlin-sync/build.gradle.kts index e7fb132cb36..5da1a5eec26 100644 --- a/driver-kotlin-sync/build.gradle.kts +++ b/driver-kotlin-sync/build.gradle.kts @@ -13,171 +13,35 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import io.gitlab.arturbosch.detekt.Detekt -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication plugins { - id("org.jetbrains.kotlin.jvm") - `java-library` - - // Test based plugins - id("com.diffplug.spotless") - id("org.jetbrains.dokka") - id("io.gitlab.arturbosch.detekt") -} - -repositories { - mavenCentral() - google() + id("project.kotlin") + id("conventions.test-artifacts") + id("conventions.test-artifacts-runtime-dependencies") } base.archivesName.set("mongodb-driver-kotlin-sync") -description = "The MongoDB Kotlin Driver" - -ext.set("pomName", "MongoDB Kotlin Driver") - -sourceSets { - create("integrationTest") { - kotlin.srcDir("$projectDir/src/integration/kotlin") - compileClasspath += sourceSets.main.get().output - runtimeClasspath += sourceSets.main.get().output - compileClasspath += project(":driver-sync").sourceSets.test.get().output - runtimeClasspath += project(":driver-sync").sourceSets.test.get().output - compileClasspath += project(":driver-core").sourceSets.test.get().output - runtimeClasspath += project(":driver-core").sourceSets.test.get().output - compileClasspath += project(":bson").sourceSets.test.get().output - runtimeClasspath += project(":bson").sourceSets.test.get().output - } -} - -val integrationTestImplementation: Configuration by - configurations.getting { extendsFrom(configurations.testImplementation.get()) } - dependencies { - // Align versions of all Kotlin components - implementation(platform("org.jetbrains.kotlin:kotlin-bom")) - implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") - api(project(path = ":bson", configuration = "default")) api(project(path = ":driver-sync", configuration = "default")) implementation(project(path = ":bson-kotlin", configuration = "default")) - testImplementation("org.jetbrains.kotlin:kotlin-reflect") - testImplementation("org.jetbrains.kotlin:kotlin-test-junit") - testImplementation("org.mockito.kotlin:mockito-kotlin:4.1.0") - testImplementation("org.mockito:mockito-junit-jupiter:4.11.0") - testImplementation("org.assertj:assertj-core:3.24.2") - testImplementation("io.github.classgraph:classgraph:4.8.154") - - integrationTestImplementation("org.jetbrains.kotlin:kotlin-test-junit") - integrationTestImplementation(project(path = ":driver-sync")) - integrationTestImplementation(project(path = ":driver-core")) -} - -kotlin { explicitApi() } - -tasks.withType { kotlinOptions.jvmTarget = "1.8" } - -// =========================== -// Code Quality checks -// =========================== -spotless { - kotlinGradle { - ktfmt("0.39").dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license"), "(group|plugins|import|buildscript|rootProject)") - } - - kotlin { - target("**/*.kt") - ktfmt().dropboxStyle().configure { it.setMaxWidth(120) } - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - licenseHeaderFile(rootProject.file("config/mongodb.license")) - } - - format("extraneous") { - target("*.xml", "*.yml", "*.md") - trimTrailingWhitespace() - indentWithSpaces() - endWithNewline() - } + integrationTestImplementation(project(path = ":bson", configuration = "testArtifacts")) + integrationTestImplementation(project(path = ":driver-sync", configuration = "testArtifacts")) + integrationTestImplementation(project(path = ":driver-core", configuration = "testArtifacts")) } -tasks.named("check") { dependsOn("spotlessApply") } - -detekt { - allRules = true // fail build on any finding - buildUponDefaultConfig = true // preconfigure defaults - config = rootProject.files("config/detekt/detekt.yml") // point to your custom config defining rules to run, - // overwriting default behavior - baseline = rootProject.file("config/detekt/baseline.xml") // a way of suppressing issues before introducing detekt - source = - files( - file("src/main/kotlin"), - file("src/test/kotlin"), - file("src/integrationTest/kotlin"), - ) -} - -tasks.withType().configureEach { - reports { - html.required.set(true) // observe findings in your browser with structure and code snippets - xml.required.set(true) // checkstyle like format mainly for integrations like Jenkins - txt.required.set(false) // similar to the console output, contains issue signature to manually edit +configureMavenPublication { + pom { + name.set("MongoDB Kotlin Driver") + description.set("The MongoDB Kotlin Driver") } } -spotbugs { - showProgress.set(true) - - tasks.getByName("spotbugsIntegrationTest") { enabled = false } +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.sync" + attributes["Bundle-SymbolicName"] = "org.mongodb.mongodb-driver-kotlin-sync" } - -// =========================== -// Test Configuration -// =========================== -val integrationTest = - tasks.create("integrationTest", Test::class) { - description = "Runs the integration tests." - group = "verification" - - testClassesDirs = sourceSets["integrationTest"].output.classesDirs - classpath = sourceSets["integrationTest"].runtimeClasspath - } - -tasks.test { useJUnitPlatform() } - -// =========================== -// Dokka Configuration -// =========================== -val dokkaOutputDir = "${rootProject.buildDir}/docs/${base.archivesName.get()}" - -tasks.dokkaHtml.configure { - outputDirectory.set(file(dokkaOutputDir)) - moduleName.set(base.archivesName.get()) -} - -val cleanDokka by tasks.register("cleanDokka") { delete(dokkaOutputDir) } - -project.parent?.tasks?.named("docs") { - dependsOn(tasks.dokkaHtml) - mustRunAfter(cleanDokka) -} - -tasks.javadocJar.configure { - dependsOn(cleanDokka, tasks.dokkaHtml) - archiveClassifier.set("javadoc") - from(dokkaOutputDir) -} - -// =========================== -// Sources publishing configuration -// =========================== -tasks.sourcesJar { from(project.sourceSets.main.map { it.kotlin }) } - -afterEvaluate { tasks.jar { manifest { attributes["Automatic-Module-Name"] = "org.mongodb.driver.kotlin.sync" } } } diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/SmokeTests.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/SmokeTests.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/SmokeTests.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/SmokeTests.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/UnifiedCrudTest.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/UnifiedCrudTest.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/UnifiedCrudTest.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/UnifiedCrudTest.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/UnifiedTest.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/UnifiedTest.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/UnifiedTest.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/UnifiedTest.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncClientSession.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncClientSession.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncClientSession.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncClientSession.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionNamesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionNamesIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionNamesIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionNamesIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoChangeStreamCursor.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoChangeStreamCursor.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoChangeStreamCursor.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoChangeStreamCursor.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoClient.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoClient.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoClient.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoClient.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCursor.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCursor.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCursor.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCursor.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt diff --git a/driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoIterable.kt similarity index 100% rename from driver-kotlin-sync/src/integration/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoIterable.kt rename to driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoIterable.kt diff --git a/driver-lambda/build.gradle b/driver-lambda/build.gradle deleted file mode 100644 index d7b9928e8f7..00000000000 --- a/driver-lambda/build.gradle +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -buildscript { - repositories { - maven { url "https://plugins.gradle.org/m2/" } - } - dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:6.1.0' - } -} - -plugins { - id("application") -} - -apply plugin: 'application' -apply plugin: 'com.github.johnrengelman.shadow' -apply plugin: 'java' - -compileJava { - sourceCompatibility = JavaVersion.VERSION_11 - targetCompatibility = JavaVersion.VERSION_11 -} - -mainClassName = "com.mongodb.workload.WorkloadExecutor" - -sourceSets { - main { - java { - srcDir 'src/main' - } - resources { - srcDir 'src/resources' - } - } -} - -dependencies { - implementation project(':driver-sync') - implementation project(':bson') - - implementation('com.amazonaws:aws-lambda-java-core:1.2.2') - implementation('com.amazonaws:aws-lambda-java-events:3.11.1') - implementation(platform("org.junit:junit-bom:$junitBomVersion")) - implementation('org.junit.jupiter:junit-jupiter-api') -} - - -javadoc { - enabled = false -} - -jar { - manifest { - attributes "Main-Class": "com.mongodb.lambdatest.LambdaTestApp" - } -} - -shadowJar { - archiveBaseName.set('lambdatest') - archiveVersion.set('') -} diff --git a/driver-lambda/build.gradle.kts b/driver-lambda/build.gradle.kts new file mode 100644 index 00000000000..d5cd57cfaa9 --- /dev/null +++ b/driver-lambda/build.gradle.kts @@ -0,0 +1,64 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +plugins { + id("application") + id("java-library") + id("project.base") + alias(libs.plugins.shadow) +} + +application { + mainClass = "com.mongodb.lambdatest.LambdaTestApp" +} + +sourceSets { + main { + java { setSrcDirs(listOf("src/main")) } + resources { setSrcDirs(listOf("src/resources")) } + } +} + +dependencies { + implementation(project(":driver-sync")) + implementation(project(":bson")) + + implementation(libs.aws.lambda.core) + implementation(libs.aws.lambda.events) + implementation(platform(libs.junit.bom)) + implementation(libs.bundles.junit) +} + +tasks.withType().configureEach { + enabled = false +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + +tasks.withType { + manifest { + attributes["Main-Class"] = "com.mongodb.lambdatest.LambdaTestApp" + } +} +tasks.withType { + archiveBaseName.set("lambdatest") + archiveVersion.set("") +} diff --git a/driver-legacy/build.gradle.kts b/driver-legacy/build.gradle.kts new file mode 100644 index 00000000000..2855bce4cdf --- /dev/null +++ b/driver-legacy/build.gradle.kts @@ -0,0 +1,48 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.test-artifacts") + id("conventions.test-artifacts-runtime-dependencies") + id("conventions.test-include-optionals") + id("conventions.testing-junit") + id("conventions.testing-spock-exclude-slow") +} + +base.archivesName.set("mongodb-driver-legacy") + +dependencies { + api(project(path = ":bson", configuration = "default")) + api(project(path = ":driver-core", configuration = "default")) + api(project(path = ":driver-sync", configuration = "default")) + + testImplementation(project(path = ":bson", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-core", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-sync", configuration = "testArtifacts")) +} + +configureMavenPublication { + pom { + name.set("The Legacy MongoDB Driver") + description.set("The Legacy MongoDB Driver") + } +} + +// Disable the manifest for driver-legacy as its not a valid OSGI package +configureJarManifest { attributes["-nomanifest"] = true } diff --git a/driver-legacy/src/test/functional/com/mongodb/MongoClientSessionSpecification.groovy b/driver-legacy/src/test/functional/com/mongodb/MongoClientSessionSpecification.groovy index e6929fa4020..b76872c3d81 100644 --- a/driver-legacy/src/test/functional/com/mongodb/MongoClientSessionSpecification.groovy +++ b/driver-legacy/src/test/functional/com/mongodb/MongoClientSessionSpecification.groovy @@ -28,7 +28,7 @@ import org.bson.Document import org.bson.types.ObjectId import org.junit.Assert import spock.lang.IgnoreIf -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.TimeUnit diff --git a/driver-reactive-streams/build.gradle b/driver-reactive-streams/build.gradle deleted file mode 100644 index 7b86f010484..00000000000 --- a/driver-reactive-streams/build.gradle +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -description = "A Reactive Streams implementation of the MongoDB Java driver" -archivesBaseName = 'mongodb-driver-reactivestreams' - -dependencies { - api project(path: ':bson', configuration: 'default') - api project(path: ':driver-core', configuration: 'default') - - api 'org.reactivestreams:reactive-streams:1.0.4' - implementation platform("io.projectreactor:reactor-bom:$projectReactorVersion") - implementation 'io.projectreactor:reactor-core' - - testImplementation project(':bson').sourceSets.test.output - testImplementation project(':driver-sync') - testImplementation project(':driver-sync').sourceSets.test.output - testImplementation project(':driver-core').sourceSets.test.output - testImplementation 'org.reactivestreams:reactive-streams-tck:1.0.4' - testImplementation 'io.projectreactor:reactor-test' - if ('8'.equals(findProperty("javaVersion"))) { - testImplementation 'org.mockito:mockito-junit-jupiter:4.6.1' - } else { - testImplementation 'org.mockito:mockito-junit-jupiter:5.11.0' - } - - testRuntimeOnly project(path: ':driver-core', configuration: 'consumableTestRuntimeOnly') -} - -sourceSets { - test.groovy.srcDirs += ['src/examples'] - test.java.srcDirs += ['src/test/tck'] -} - -test { - exclude 'tour/**' -} - -// Reactive Streams TCK uses TestNG, and Gradle can't run TestNG and JUnit in the same run. -task tckTest(type: Test) { - useTestNG() - scanForTestClasses = false - - classpath = sourceSets.test.runtimeClasspath - testClassesDirs = sourceSets.test.output.classesDirs - - binaryResultsDirectory.set(file("$buildDir/$name-results/binary")) - reports { - html.destination = file("$buildDir/reports/$name") - junitXml.destination = file("$buildDir/$name-results") - } - - maxParallelForks = 1 -} - -ext { - pomName = 'The MongoDB Reactive Streams Driver' -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.driver.reactivestreams' - jar.manifest.attributes['Bundle-SymbolicName'] = 'org.mongodb.driver-reactivestreams' - jar.manifest.attributes['Import-Package'] = [ - 'com.mongodb.crypt.capi.*;resolution:=optional', - 'com.mongodb.internal.crypt.capi.*;resolution:=optional', - '*', - ].join(',') -} diff --git a/driver-reactive-streams/build.gradle.kts b/driver-reactive-streams/build.gradle.kts new file mode 100644 index 00000000000..f1c758b31da --- /dev/null +++ b/driver-reactive-streams/build.gradle.kts @@ -0,0 +1,79 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.test-artifacts") + id("conventions.test-artifacts-runtime-dependencies") + id("conventions.test-include-optionals") + id("conventions.testing-mockito") + id("conventions.testing-junit") + id("conventions.testing-spock-exclude-slow") +} + +base.archivesName.set("mongodb-driver-reactivestreams") + +dependencies { + api(project(path = ":bson", configuration = "default")) + api(project(path = ":driver-core", configuration = "default")) + api(libs.reactive.streams) + implementation(platform(libs.project.reactor.bom)) + implementation(libs.project.reactor.core) + compileOnly(project(path = ":mongodb-crypt", configuration = "default")) + + testImplementation(libs.project.reactor.test) + testImplementation(project(path = ":driver-sync", configuration = "default")) + testImplementation(project(path = ":bson", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-core", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-sync", configuration = "testArtifacts")) + + // Reactive Streams TCK testing + testImplementation(libs.reactive.streams.tck) +} + +configureMavenPublication { + pom { + name.set("The MongoDB Reactive Streams Driver") + description.set("A Reactive Streams implementation of the MongoDB Java driver") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.reactivestreams" + attributes["Bundle-SymbolicName"] = "org.mongodb.driver-reactivestreams" + attributes["Import-Package"] = + listOf( + "com.mongodb.crypt.capi.*;resolution:=optional", + "com.mongodb.internal.crypt.capi.*;resolution:=optional", + "*" // import all that is not excluded or modified before + ) + .joinToString(",") +} + +sourceSets { test { java { setSrcDirs(listOf("src/test/tck")) } } } + +// Reactive Streams TCK uses TestNG +tasks.register("tckTest", Test::class) { + useTestNG() + maxParallelForks = 1 + isScanForTestClasses = false + + binaryResultsDirectory.set(layout.buildDirectory.dir("$name-results/binary")) + reports.html.outputLocation.set(layout.buildDirectory.dir("reports/$name")) + reports.junitXml.outputLocation.set(layout.buildDirectory.dir("reports/$name-results")) +} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionCorpusTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionCorpusTest.java index 9a44252b938..d36942c212a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionCorpusTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionCorpusTest.java @@ -38,7 +38,6 @@ import org.junit.runners.Parameterized; import reactor.core.publisher.Mono; -import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; @@ -283,9 +282,8 @@ public void testCorpus() throws IOException, URISyntaxException { } } - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionCorpusTest.class - .getResource("/client-side-encryption-corpus/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-corpus/" + path); } @Parameterized.Parameters(name = "useLocalSchema: {0}") diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionExternalKeyVaultTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionExternalKeyVaultTest.java index bc43222239f..f3c10a87f07 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionExternalKeyVaultTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionExternalKeyVaultTest.java @@ -36,9 +36,6 @@ import org.junit.runners.Parameterized; import reactor.core.publisher.Mono; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Arrays; import java.util.Base64; import java.util.Collection; @@ -146,9 +143,8 @@ public void testExternal() { assertEquals(authExceptionThrown, withExternalKeyVault); } - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionExternalKeyVaultTest.class - .getResource("/client-side-encryption-external/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-external/" + path); } @Parameterized.Parameters(name = "withExternalKeyVault: {0}") diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionSessionTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionSessionTest.java index f6814013779..ec7c8ccf648 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionSessionTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideEncryptionSessionTest.java @@ -31,9 +31,6 @@ import org.junit.runners.Parameterized; import reactor.core.publisher.Mono; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Arrays; import java.util.Base64; import java.util.Collection; @@ -152,8 +149,7 @@ public void testWithExplicitSession() throws Throwable { assertEquals(6, encryptedDocument.getBinary("encrypted").getType()); } - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionSessionTest.class - .getResource("/client-side-encryption-external/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-external/" + path); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MongoClientSessionSpecification.groovy b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MongoClientSessionSpecification.groovy index 64c1386e0e7..5fda2f76319 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MongoClientSessionSpecification.groovy +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/MongoClientSessionSpecification.groovy @@ -32,7 +32,7 @@ import org.bson.Document import org.junit.Assert import reactor.core.publisher.Mono import spock.lang.IgnoreIf -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.TimeUnit diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ReactiveInitialDnsSeedlistDiscoveryTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ReactiveInitialDnsSeedlistDiscoveryTest.java index cdc30a80cdc..834bf6ddf35 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ReactiveInitialDnsSeedlistDiscoveryTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ReactiveInitialDnsSeedlistDiscoveryTest.java @@ -24,14 +24,13 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.nio.file.Path; import java.util.List; // See https://github.com/mongodb/specifications/tree/master/source/initial-dns-seedlist-discovery/tests @RunWith(Parameterized.class) public class ReactiveInitialDnsSeedlistDiscoveryTest extends InitialDnsSeedlistDiscoveryTest { - public ReactiveInitialDnsSeedlistDiscoveryTest(final String filename, final Path parentDirectory, final String uri, + public ReactiveInitialDnsSeedlistDiscoveryTest(final String filename, final String parentDirectory, final String uri, final List seeds, final Integer numSeeds, final List hosts, final Integer numHosts, final BsonDocument options, final BsonDocument parsedOptions, final boolean isError, final boolean executePingCommand) { diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ChangeStreamsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ChangeStreamsTest.java index 6775cc8570e..5d59779076e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ChangeStreamsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ChangeStreamsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ChangeStreamsTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/change-streams"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideEncryptionTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideEncryptionTest.java index 8169a300e0e..431664d224d 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideEncryptionTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideEncryptionTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ClientSideEncryptionTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/client-side-encryption"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java index a1063f05362..bb0c39e1489 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java @@ -31,8 +31,6 @@ import org.junit.jupiter.params.provider.MethodSource; import reactor.core.publisher.Hooks; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; import java.util.List; import java.util.concurrent.atomic.AtomicReference; @@ -50,7 +48,7 @@ public class ClientSideOperationTimeoutTest extends UnifiedReactiveStreamsTest { private final AtomicReference atomicReferenceThrowable = new AtomicReference<>(); - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/client-side-operation-timeout"); } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CollectionManagementTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CollectionManagementTest.java index 5e3038a06c8..f187cb360e2 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CollectionManagementTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CollectionManagementTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class CollectionManagementTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/collection-management"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandLoggingTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandLoggingTest.java index 10d563cb928..d75fceb5081 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandLoggingTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class CommandLoggingTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/command-logging"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandMonitoringTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandMonitoringTest.java index c30ca720b46..ad5dd230175 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandMonitoringTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/CommandMonitoringTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class CommandMonitoringTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/command-monitoring"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ConnectionPoolLoggingTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ConnectionPoolLoggingTest.java index 12db392686f..26d314b0f82 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ConnectionPoolLoggingTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ConnectionPoolLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ConnectionPoolLoggingTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/connection-monitoring-and-pooling/logging"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/IndexManagmentTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/IndexManagmentTest.java index 931a53dba40..346b3adfce3 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/IndexManagmentTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/IndexManagmentTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class IndexManagmentTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/index-management"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/LoadBalancerTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/LoadBalancerTest.java index f60f42139b4..317c718a45b 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/LoadBalancerTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/LoadBalancerTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class LoadBalancerTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/load-balancers"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ServerSelectionLoggingTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ServerSelectionLoggingTest.java index d78522fb75c..c89329e3940 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ServerSelectionLoggingTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ServerSelectionLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ServerSelectionLoggingTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/server-selection/logging"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/SessionsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/SessionsTest.java index 81cd47637a0..c68d847f839 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/SessionsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/SessionsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class SessionsTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/sessions"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedCrudTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedCrudTest.java index b8fd81ac7c7..f69c4a55c68 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedCrudTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedCrudTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedCrudTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/crud"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedGridFSTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedGridFSTest.java index eefc6839d17..4fe8015421f 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedGridFSTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedGridFSTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedGridFSTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/gridfs"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedReactiveStreamsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedReactiveStreamsTest.java index 28c8a27f8fa..716d04a2890 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedReactiveStreamsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedReactiveStreamsTest.java @@ -34,8 +34,6 @@ import com.mongodb.reactivestreams.client.syncadapter.SyncMongoDatabase; import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; import static com.mongodb.client.unified.UnifiedTestModifications.Modifier; @@ -102,7 +100,7 @@ protected void postCleanUp(final TestDef testDef) { } @NonNull - protected static Collection getTestData(final String directory) throws URISyntaxException, IOException { + protected static Collection getTestData(final String directory) { return getTestData(directory, true); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableReadsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableReadsTest.java index 4f2336f4173..ac2c986e88a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableReadsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableReadsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedRetryableReadsTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/retryable-reads"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableWritesTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableWritesTest.java index 8fbfb43d92d..8cc66ea813b 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableWritesTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedRetryableWritesTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedRetryableWritesTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/retryable-writes"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java index e4fb6da3627..e016fc7ecdc 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedServerDiscoveryAndMonitoringTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/server-discovery-and-monitoring"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedTransactionsTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedTransactionsTest.java index c1990e5d830..43bb0fd8229 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedTransactionsTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedTransactionsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedTransactionsTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/transactions"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedWriteConcernTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedWriteConcernTest.java index 3b7fa4afb00..08a7bccabf3 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedWriteConcernTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/UnifiedWriteConcernTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedWriteConcernTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/write-concern"); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/VersionedApiTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/VersionedApiTest.java index 5a0d4b69dcd..8378fb00482 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/VersionedApiTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/VersionedApiTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class VersionedApiTest extends UnifiedReactiveStreamsTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("versioned-api"); } } diff --git a/driver-scala/build.gradle b/driver-scala/build.gradle deleted file mode 100644 index e9e9e15040e..00000000000 --- a/driver-scala/build.gradle +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -description = "A Scala wrapper of the MongoDB Reactive Streams Java driver" -archivesBaseName = 'mongo-scala-driver' - - -dependencies { - api project(path: ':bson-scala', configuration: 'default') - api project(path: ':driver-reactive-streams', configuration: 'default') - compileOnly 'com.google.code.findbugs:jsr305:1.3.9' - - testImplementation project(':driver-sync') - testImplementation project(':bson').sourceSets.test.output - testImplementation project(':driver-sync').sourceSets.test.output - testImplementation project(':driver-core').sourceSets.test.output - testImplementation project(':driver-reactive-streams').sourceSets.test.output - testRuntimeOnly project(path: ':driver-core', configuration: 'consumableTestRuntimeOnly') -} - -sourceSets { - integrationTest { - scala.srcDir file('src/integration/scala') - scala { - compileClasspath += main.output - runtimeClasspath += main.output - } - } -} - -test { - maxParallelForks = 1 -} - -tasks.withType(Test) { - doFirst { - println("Running Test task using scala version: $scalaVersion") - } -} - -tasks.withType(ScalaCompile) { - if(scalaVersion.startsWith("2.11")) { - // Better support SAM style closures in scala 2.11 - scalaCompileOptions.additionalParameters.addAll([ - // Better support SAM style closures in scala 2.11 - "-Xexperimental" - ]) - } -} - -task integrationTest(type: Test) { - delete 'build/test-integration' - testClassesDirs = sourceSets.integrationTest.output.classesDirs - classpath = sourceSets.integrationTest.runtimeClasspath - mustRunAfter test -} - -check.dependsOn integrationTest - -// =================== -// Scala checks -// =================== -tasks.register("scalaCheck") { - description = "Runs all the Scala checks" - group = "verification" - - dependsOn("clean", "compileTestScala", "compileIntegrationTestScala", "check") - tasks.findByName("check").mustRunAfter("clean") -} - - -task aggregatedScalaDoc(type: ScalaDoc) { - description('Unified Scaladoc for bson-scala and driver-scala') - group('documentation') - ext.fromProjects = [ - project(':bson-scala'), - project(':driver-scala') - ] - destinationDir = file("${rootProject.buildDir.path}/docs/${project.archivesBaseName}") - classpath = project.sourceSets.main.compileClasspath - source = fromProjects.collect { it.sourceSets.main.allSource } - - scalaDocOptions.additionalParameters = ["-doc-root-content", "${project.rootDir}/driver-scala/rootdoc.txt" as String] -} -project.parent.tasks.named("docs"){ it.dependsOn(aggregatedScalaDoc) } - -configurations { - integrationTestImplementation { - extendsFrom testImplementation - canBeResolved = true - } -} - -idea { - module { - testSourceDirs += sourceSets.integrationTest.scala.srcDirs - testResourceDirs += sourceSets.integrationTest.resources.srcDirs - scopes.TEST.plus += [ configurations.integrationTestImplementation ] - } -} - - -ext { - pomName = 'Mongo Scala Driver' -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.driver.scala' - jar.manifest.attributes['Import-Package'] = [ - '!scala.*', - '*' - ].join(',') -} diff --git a/driver-scala/build.gradle.kts b/driver-scala/build.gradle.kts new file mode 100644 index 00000000000..96828175d29 --- /dev/null +++ b/driver-scala/build.gradle.kts @@ -0,0 +1,60 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication +import ProjectExtensions.scalaVersion + +plugins { id("project.scala") } + +base.archivesName.set("mongo-scala-driver") + +val scalaVersion: String = project.scalaVersion() + +dependencies { + api(project(path = ":bson-scala", configuration = "default")) + api(project(path = ":driver-reactive-streams", configuration = "default")) + + testImplementation(project(path = ":driver-sync", configuration = "default")) + testImplementation(project(path = ":bson", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-core", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-sync", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-reactive-streams", configuration = "testArtifacts")) + + // Encryption testing + integrationTestImplementation(project(path = ":mongodb-crypt", configuration = "default")) +} + +configureMavenPublication { + pom { + name.set("Mongo Scala Driver") + description.set("A Scala wrapper of the MongoDB Reactive Streams Java driver") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.scala" + attributes["Bundle-SymbolicName"] = "org.mongodb.scala.mongo-scala-driver" + attributes["Import-Package"] = "!scala.*,*" +} + +// =================== +// Scala docs +// =================== +tasks.withType().forEach { + // Include bson-scala source for main scaladoc + project(":bson-scala").tasks.withType().forEach { bsonScala -> it.source += bsonScala.source } + it.scalaDocOptions.additionalParameters = listOf("-doc-root-content", "${project.rootDir}/driver-scala/rootdoc.txt") +} diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/BaseSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/BaseSpec.scala similarity index 88% rename from driver-scala/src/integration/scala/org/mongodb/scala/BaseSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/BaseSpec.scala index 98ce89a88fe..9d59b8f55e6 100644 --- a/driver-scala/src/integration/scala/org/mongodb/scala/BaseSpec.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/BaseSpec.scala @@ -15,10 +15,7 @@ */ package org.mongodb.scala -import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import org.scalatestplus.junit.JUnitRunner -@RunWith(classOf[JUnitRunner]) abstract class BaseSpec extends AnyFlatSpec with Matchers {} diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/ClientSideEncryptionBypassAutoEncryptionSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/ClientSideEncryptionBypassAutoEncryptionSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/ClientSideEncryptionBypassAutoEncryptionSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/ClientSideEncryptionBypassAutoEncryptionSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/ClientSideEncryptionTest.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/ClientSideEncryptionTest.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/ClientSideEncryptionTest.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/ClientSideEncryptionTest.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/FuturesSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/FuturesSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/FuturesSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/FuturesSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/MongoCollectionCaseClassSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/MongoCollectionCaseClassSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/MongoCollectionCaseClassSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/MongoCollectionCaseClassSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/RequiresMongoDBISpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/RequiresMongoDBISpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/RequiresMongoDBISpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/RequiresMongoDBISpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/TestMongoClientHelper.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/TestMongoClientHelper.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/TestMongoClientHelper.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/TestMongoClientHelper.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationChangeStreamExampleSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationChangeStreamExampleSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationChangeStreamExampleSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationChangeStreamExampleSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationExampleSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationExampleSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationExampleSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationExampleSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationTransactionsExampleSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationTransactionsExampleSpec.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/documentation/DocumentationTransactionsExampleSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/documentation/DocumentationTransactionsExampleSpec.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala similarity index 98% rename from driver-scala/src/integration/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala index 55f943a9402..e6ca96183e6 100644 --- a/driver-scala/src/integration/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/gridfs/GridFSObservableSpec.scala @@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream import java.nio.ByteBuffer import java.nio.channels.Channels import java.util.UUID - import org.bson.UuidRepresentation import org.bson.codecs.UuidCodec import org.bson.codecs.configuration.CodecRegistries @@ -31,6 +30,7 @@ import org.scalatest.BeforeAndAfterEach import org.scalatest.exceptions.TestFailedException import scala.annotation.tailrec +import scala.concurrent.Await class GridFSObservableSpec extends RequiresMongoDBISpec with FuturesSpec with BeforeAndAfterEach { private val filesCollectionName = "fs.files" @@ -45,13 +45,13 @@ class GridFSObservableSpec extends RequiresMongoDBISpec with FuturesSpec with Be val mongoDatabase = mongoClient().getDatabase(databaseName) _filesCollection = Some(mongoDatabase.getCollection[GridFSFile](filesCollectionName)) _chunksCollection = Some(mongoDatabase.getCollection(chunksCollectionName)) - _filesCollection.map(_.drop()) - _chunksCollection.map(_.drop()) + _filesCollection.foreach(coll => Await.result(coll.drop().toFuture(), WAIT_DURATION)) + _chunksCollection.foreach(coll => Await.result(coll.drop().toFuture(), WAIT_DURATION)) _gridFSBucket = Some(GridFSBucket(mongoDatabase)) } override def afterEach(): Unit = { - withDatabase(db => db.drop()) + withDatabase(db => Await.result(db.drop().toFuture(), WAIT_DURATION)) } private def gridFSBucket = _gridFSBucket.get diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncClientSession.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncClientSession.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncClientSession.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncClientSession.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoClient.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoClient.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoClient.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoClient.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCursor.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCursor.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoCursor.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCursor.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoIterable.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/SyncMongoIterable.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoIterable.scala diff --git a/driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/package.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/package.scala similarity index 100% rename from driver-scala/src/integration/scala/org/mongodb/scala/syncadapter/package.scala rename to driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/package.scala diff --git a/driver-scala/src/integration/scala/tour/ClientSideEncryptionAutoEncryptionSettingsTour.scala b/driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionAutoEncryptionSettingsTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/ClientSideEncryptionAutoEncryptionSettingsTour.scala rename to driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionAutoEncryptionSettingsTour.scala diff --git a/driver-scala/src/integration/scala/tour/ClientSideEncryptionExplicitEncryptionAndDecryptionTour.scala b/driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionExplicitEncryptionAndDecryptionTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/ClientSideEncryptionExplicitEncryptionAndDecryptionTour.scala rename to driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionExplicitEncryptionAndDecryptionTour.scala diff --git a/driver-scala/src/integration/scala/tour/ClientSideEncryptionExplicitEncryptionOnlyTour.scala b/driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionExplicitEncryptionOnlyTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/ClientSideEncryptionExplicitEncryptionOnlyTour.scala rename to driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionExplicitEncryptionOnlyTour.scala diff --git a/driver-scala/src/integration/scala/tour/ClientSideEncryptionSimpleTour.scala b/driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionSimpleTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/ClientSideEncryptionSimpleTour.scala rename to driver-scala/src/integrationTest/scala/tour/ClientSideEncryptionSimpleTour.scala diff --git a/driver-scala/src/integration/scala/tour/GridFSTour.scala b/driver-scala/src/integrationTest/scala/tour/GridFSTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/GridFSTour.scala rename to driver-scala/src/integrationTest/scala/tour/GridFSTour.scala diff --git a/driver-scala/src/integration/scala/tour/Helpers.scala b/driver-scala/src/integrationTest/scala/tour/Helpers.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/Helpers.scala rename to driver-scala/src/integrationTest/scala/tour/Helpers.scala diff --git a/driver-scala/src/integration/scala/tour/QuickTour.scala b/driver-scala/src/integrationTest/scala/tour/QuickTour.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/QuickTour.scala rename to driver-scala/src/integrationTest/scala/tour/QuickTour.scala diff --git a/driver-scala/src/integration/scala/tour/QuickTourCaseClass.scala b/driver-scala/src/integrationTest/scala/tour/QuickTourCaseClass.scala similarity index 100% rename from driver-scala/src/integration/scala/tour/QuickTourCaseClass.scala rename to driver-scala/src/integrationTest/scala/tour/QuickTourCaseClass.scala diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala index 2e21d30526a..a5b76965651 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ApiAliasAndCompanionSpec.scala @@ -73,6 +73,7 @@ class ApiAliasAndCompanionSpec extends BaseSpec { "ServerSession", "SessionContext", "SingleResultCallback", + "Slow", "SubjectProvider", "TransactionExample", "UnixServerAddress", diff --git a/driver-scala/src/test/scala/org/mongodb/scala/BaseSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/BaseSpec.scala index 98ce89a88fe..9d59b8f55e6 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/BaseSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/BaseSpec.scala @@ -15,10 +15,7 @@ */ package org.mongodb.scala -import org.junit.runner.RunWith import org.scalatest.flatspec.AnyFlatSpec import org.scalatest.matchers.should.Matchers -import org.scalatestplus.junit.JUnitRunner -@RunWith(classOf[JUnitRunner]) abstract class BaseSpec extends AnyFlatSpec with Matchers {} diff --git a/driver-sync/build.gradle b/driver-sync/build.gradle deleted file mode 100644 index 1c2f3ac6c59..00000000000 --- a/driver-sync/build.gradle +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -archivesBaseName = 'mongodb-driver-sync' -description = 'The MongoDB Synchronous Driver' -ext { - pomName = 'MongoDB Driver' -} - -dependencies { - api project(path: ':bson', configuration: 'default') - api project(path: ':driver-core', configuration: 'default') - - testImplementation project(':bson').sourceSets.test.output - testImplementation project(':driver-core').sourceSets.test.output - testRuntimeOnly project(path: ':driver-core', configuration: 'consumableTestRuntimeOnly') - - testImplementation('com.amazonaws:aws-lambda-java-core:1.2.1') -} - -sourceSets { - test.groovy.srcDirs += ['src/examples'] -} - -test { - exclude 'tour/**' -} - -tasks.withType(Checkstyle) { - // needed so the Javadoc checks can find the code in other modules - classpath = files(project(':driver-core').sourceSets.main.output, sourceSets.main.output) -} - -afterEvaluate { - jar.manifest.attributes['Automatic-Module-Name'] = 'org.mongodb.driver.sync.client' - jar.manifest.attributes['Bundle-SymbolicName'] = 'org.mongodb.driver-sync' - jar.manifest.attributes['Import-Package'] = [ - 'com.mongodb.crypt.capi.*;resolution:=optional', - 'com.mongodb.internal.crypt.capi.*;resolution:=optional', - '*', - ].join(',') -} diff --git a/driver-sync/build.gradle.kts b/driver-sync/build.gradle.kts new file mode 100644 index 00000000000..95cd0979973 --- /dev/null +++ b/driver-sync/build.gradle.kts @@ -0,0 +1,60 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication + +plugins { + id("project.java") + id("conventions.test-artifacts") + id("conventions.test-artifacts-runtime-dependencies") + id("conventions.test-include-optionals") + id("conventions.testing-mockito") + id("conventions.testing-junit") + id("conventions.testing-spock-exclude-slow") +} + +base.archivesName.set("mongodb-driver-sync") + +dependencies { + api(project(path = ":bson", configuration = "default")) + api(project(path = ":driver-core", configuration = "default")) + compileOnly(project(path = ":mongodb-crypt", configuration = "default")) + + testImplementation(project(path = ":bson", configuration = "testArtifacts")) + testImplementation(project(path = ":driver-core", configuration = "testArtifacts")) + + // lambda testing + testImplementation(libs.aws.lambda.core) +} + +configureMavenPublication { + pom { + name.set("MongoDB Driver") + description.set("The MongoDB Synchronous Driver") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "org.mongodb.driver.sync.client" + attributes["Bundle-SymbolicName"] = "org.mongodb.driver-sync" + attributes["Import-Package"] = + listOf( + "com.mongodb.crypt.capi.*;resolution:=optional", + "com.mongodb.internal.crypt.capi.*;resolution:=optional", + "*", + ) + .joinToString(",") +} diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionDeadlockTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionDeadlockTest.java index 2a83b328298..c7a8893ada0 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionDeadlockTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionDeadlockTest.java @@ -44,7 +44,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.HashSet; @@ -225,9 +224,8 @@ private static MongoClientSettings getClientSettings(final int maxPoolSize, .build(); } - private static BsonDocument bsonDocumentFromPath(final String path) throws URISyntaxException, IOException { - return getTestDocument(new File(ClientSideEncryptionExternalKeyVaultTest.class - .getResource("/client-side-encryption-external/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-external/" + path); } private static final class ExpectedEvent { diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionExplicitEncryptionTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionExplicitEncryptionTest.java index 068a9079dad..3979f63cf93 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionExplicitEncryptionTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionExplicitEncryptionTest.java @@ -37,7 +37,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -54,7 +53,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static util.JsonPoweredTestHelper.getTestDocument; @@ -207,12 +205,6 @@ public void canRoundtripEncryptedUnindexed() { } private static BsonDocument bsonDocumentFromPath(final String path) { - try { - return getTestDocument(new File(AbstractClientSideEncryptionExplicitEncryptionTest.class - .getResource("/client-side-encryption-data/" + path).toURI())); - } catch (Exception e) { - fail("Unable to load resource", e); - return null; - } + return getTestDocument("/client-side-encryption-data/" + path); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionNotSpawnMongocryptdTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionNotSpawnMongocryptdTest.java index 3ec814ba704..13acc41cf2e 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionNotSpawnMongocryptdTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionNotSpawnMongocryptdTest.java @@ -23,7 +23,6 @@ import com.mongodb.MongoTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.WriteConcern; -import com.mongodb.assertions.Assertions; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import org.bson.Document; @@ -31,7 +30,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.io.File; import java.net.InetAddress; import java.net.InetSocketAddress; import java.time.Duration; @@ -43,6 +41,7 @@ import java.util.function.BiConsumer; import java.util.stream.Collectors; import java.util.stream.Stream; + import static com.mongodb.ClusterFixture.serverVersionAtLeast; import static com.mongodb.client.AbstractClientSideEncryptionNotCreateMongocryptdClientTest.findAvailableMongocryptdLoopbackPort; import static com.mongodb.client.AbstractClientSideEncryptionTest.cryptSharedLibPathSysPropValue; @@ -216,21 +215,11 @@ private void assertMongocryptdNotSpawned() { } private static BsonDocument externalSchema() { - try { - return getTestDocument(new File(Assertions.assertNotNull(AbstractClientSideEncryptionNotSpawnMongocryptdTest.class - .getResource("/client-side-encryption-external/external-schema.json")).toURI())); - } catch (Exception e) { - throw new RuntimeException(e); - } + return getTestDocument("/client-side-encryption-external/external-schema.json"); } private static BsonDocument externalKey() { - try { - return getTestDocument(new File(Assertions.assertNotNull(AbstractClientSideEncryptionNotSpawnMongocryptdTest.class - .getResource("/client-side-encryption-external/external-key.json")).toURI())); - } catch (Exception e) { - throw new RuntimeException(e); - } + return getTestDocument("/client-side-encryption-external/external-key.json"); } @SafeVarargs diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionRangeExplicitEncryptionTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionRangeExplicitEncryptionTest.java index be667c9b64c..df3affc9df0 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionRangeExplicitEncryptionTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionRangeExplicitEncryptionTest.java @@ -51,7 +51,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; -import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -70,7 +69,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertIterableEquals; import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static util.JsonPoweredTestHelper.getTestDocument; @@ -96,8 +94,8 @@ public void setUp(final Type type) { assumeFalse(isServerlessTest()); MongoNamespace dataKeysNamespace = new MongoNamespace("keyvault.datakeys"); - BsonDocument encryptedFields = bsonDocumentFromPath("range-encryptedFields-" + type.value + ".json"); - BsonDocument key1Document = bsonDocumentFromPath("keys/key1-document.json"); + BsonDocument encryptedFields = getTestDocument("/client-side-encryption-data/range-encryptedFields-" + type.value + ".json"); + BsonDocument key1Document = getTestDocument("/client-side-encryption-data/keys/key1-document.json"); key1Id = key1Document.getBinary("_id"); MongoDatabase explicitEncryptionDatabase = getDefaultDatabase(); @@ -354,15 +352,4 @@ BsonValue convertNumber(final int number) { } } } - - private static BsonDocument bsonDocumentFromPath(final String path) { - try { - return getTestDocument(new File(AbstractClientSideEncryptionRangeExplicitEncryptionTest.class - .getResource("/client-side-encryption-data/" + path).toURI())); - } catch (Exception e) { - fail("Unable to load resource", e); - return null; - } - } - } diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionTest.java index dca25078b7c..f130e004cca 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideEncryptionTest.java @@ -44,9 +44,6 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -403,14 +400,15 @@ private void assertBsonValue(final String message, final BsonValue expectedResul } @Parameterized.Parameters(name = "{0}: {1}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/client-side-encryption/legacy")) { - BsonDocument specDocument = JsonPoweredTestHelper.getTestDocument(file); + for (BsonDocument specDocument : JsonPoweredTestHelper.getTestDocuments("/client-side-encryption/legacy")) { for (BsonValue test : specDocument.getArray("tests")) { - data.add(new Object[]{file.getName(), test.asDocument().getString("description").getValue(), specDocument, - specDocument.getArray("data", new BsonArray()), test.asDocument(), - skipTest(specDocument, test.asDocument())}); + BsonDocument testDocument = test.asDocument(); + data.add(new Object[]{specDocument.getString("fileName").getValue(), + testDocument.getString("description").getValue(), specDocument, + specDocument.getArray("data", new BsonArray()), testDocument, + skipTest(specDocument, testDocument)}); } } return data; diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryption25LookupProseTests.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryption25LookupProseTests.java index f7c672b289b..a6da323e715 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryption25LookupProseTests.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryption25LookupProseTests.java @@ -37,7 +37,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; -import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -52,7 +51,6 @@ import static com.mongodb.testing.MongoAssertions.assertCause; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; import static util.JsonPoweredTestHelper.getTestDocument; @@ -244,12 +242,6 @@ void testCase9() { } public static BsonDocument bsonDocumentFromPath(final String path) { - try { - return getTestDocument(new File(ClientSideEncryption25LookupProseTests.class - .getResource("/client-side-encryption-data/lookup/" + path).toURI())); - } catch (Exception e) { - fail("Unable to load resource", e); - return null; - } + return getTestDocument("/client-side-encryption-data/lookup/" + path); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionCorpusTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionCorpusTest.java index a812e174047..94e527544e5 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionCorpusTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionCorpusTest.java @@ -38,7 +38,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Base64; @@ -261,9 +260,8 @@ public void testCorpus() throws IOException, URISyntaxException { } } - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionTest.class - .getResource("/client-side-encryption-corpus/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-corpus/" + path); } @Parameterized.Parameters(name = "useLocalSchema: {0}") diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionExternalKeyVaultTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionExternalKeyVaultTest.java index da513bb2a9e..4e056b93209 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionExternalKeyVaultTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionExternalKeyVaultTest.java @@ -37,7 +37,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; @@ -146,9 +145,8 @@ public void testExternal() { assertEquals(authExceptionThrown, withExternalKeyVault); } - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionExternalKeyVaultTest.class - .getResource("/client-side-encryption-external/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-external/" + path); } @Parameterized.Parameters(name = "withExternalKeyVault: {0}") diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionSessionTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionSessionTest.java index f2c51988bd7..7d8cc943d22 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionSessionTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ClientSideEncryptionSessionTest.java @@ -30,7 +30,6 @@ import org.junit.runner.RunWith; import org.junit.runners.Parameterized; -import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.Arrays; @@ -143,9 +142,7 @@ public void testWithExplicitSession() { assertEquals(6, encryptedDocument.getBinary("encrypted").getType()); } - - private static BsonDocument bsonDocumentFromPath(final String path) throws IOException, URISyntaxException { - return getTestDocument(new File(ClientSideEncryptionSessionTest.class - .getResource("/client-side-encryption-external/" + path).toURI())); + private static BsonDocument bsonDocumentFromPath(final String path) { + return getTestDocument("/client-side-encryption-external/" + path); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java index c4068375f9f..b39920682cc 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java @@ -20,8 +20,6 @@ import com.mongodb.client.unified.UnifiedSyncTest; import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; import static org.junit.jupiter.api.Assumptions.assumeFalse; @@ -30,7 +28,7 @@ // See https://github.com/mongodb/specifications/tree/master/source/client-side-operation-timeout/tests public class ClientSideOperationTimeoutTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/client-side-operation-timeout"); } diff --git a/driver-sync/src/test/functional/com/mongodb/client/InitialDnsSeedlistDiscoveryTest.java b/driver-sync/src/test/functional/com/mongodb/client/InitialDnsSeedlistDiscoveryTest.java index a51f6e3624d..091d876201c 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/InitialDnsSeedlistDiscoveryTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/InitialDnsSeedlistDiscoveryTest.java @@ -41,10 +41,6 @@ import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.List; @@ -69,7 +65,7 @@ // See https://github.com/mongodb/specifications/tree/master/source/initial-dns-seedlist-discovery/tests @RunWith(Parameterized.class) public abstract class InitialDnsSeedlistDiscoveryTest { - private final Path parentDirectory; + private final String parentDirectory; private final String uri; @Nullable private final List seeds; @@ -84,7 +80,7 @@ public abstract class InitialDnsSeedlistDiscoveryTest { private final boolean isError; private final boolean executePingCommand; - public InitialDnsSeedlistDiscoveryTest(@SuppressWarnings("unused") final String filename, final Path parentDirectory, final String uri, + public InitialDnsSeedlistDiscoveryTest(@SuppressWarnings("unused") final String filename, final String parentDirectory, final String uri, @Nullable final List seeds, @Nullable final Integer numSeeds, @Nullable final List hosts, @Nullable final Integer numHosts, final BsonDocument options, final BsonDocument parsedOptions, @@ -306,13 +302,13 @@ private void assertParsedOptions(final ConnectionString connectionString) { @Parameterized.Parameters(name = "{0}") - public static Collection data() throws URISyntaxException, IOException { + public static Collection data() { List data = new ArrayList<>(); - for (File file : JsonPoweredTestHelper.getTestFiles("/initial-dns-seedlist-discovery")) { - BsonDocument testDocument = JsonPoweredTestHelper.getTestDocument(file); + for (BsonDocument testDocument : JsonPoweredTestHelper.getTestDocuments("/initial-dns-seedlist-discovery")) { + String resourcePath = testDocument.getString("resourcePath").getValue(); data.add(new Object[]{ - file.getName(), - file.toPath().getParent(), + testDocument.getString("fileName").getValue(), + resourcePath.substring(0, resourcePath.lastIndexOf("/")), testDocument.getString("uri").getValue(), toStringList(testDocument.getArray("seeds", null)), toInteger(testDocument.getNumber("numSeeds", null)), @@ -323,7 +319,6 @@ public static Collection data() throws URISyntaxException, IOException testDocument.getBoolean("error", BsonBoolean.FALSE).getValue(), testDocument.getBoolean("ping", BsonBoolean.TRUE).getValue() }); - } return data; } diff --git a/driver-sync/src/test/functional/com/mongodb/client/MongoClientSessionSpecification.groovy b/driver-sync/src/test/functional/com/mongodb/client/MongoClientSessionSpecification.groovy index fc688fec5df..a8596536e8e 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/MongoClientSessionSpecification.groovy +++ b/driver-sync/src/test/functional/com/mongodb/client/MongoClientSessionSpecification.groovy @@ -35,7 +35,7 @@ import org.bson.Document import org.bson.types.ObjectId import org.junit.Assert import spock.lang.IgnoreIf -import util.spock.annotations.Slow +import com.mongodb.spock.Slow import java.util.concurrent.TimeUnit diff --git a/driver-sync/src/test/functional/com/mongodb/client/SyncInitialDnsSeedlistDiscoveryTest.java b/driver-sync/src/test/functional/com/mongodb/client/SyncInitialDnsSeedlistDiscoveryTest.java index d3750434ea6..afe31d41d27 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/SyncInitialDnsSeedlistDiscoveryTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/SyncInitialDnsSeedlistDiscoveryTest.java @@ -19,11 +19,10 @@ import com.mongodb.MongoClientSettings; import org.bson.BsonDocument; -import java.nio.file.Path; import java.util.List; public class SyncInitialDnsSeedlistDiscoveryTest extends InitialDnsSeedlistDiscoveryTest { - public SyncInitialDnsSeedlistDiscoveryTest(final String filename, final Path parentDirectory, final String uri, + public SyncInitialDnsSeedlistDiscoveryTest(final String filename, final String parentDirectory, final String uri, final List seeds, final Integer numSeeds, final List hosts, final Integer numHosts, final BsonDocument options, final BsonDocument parsedOptions, final boolean isError, final boolean executePingCommand) { diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ChangeStreamsTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ChangeStreamsTest.java index d07429fa479..db719bca0d7 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ChangeStreamsTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ChangeStreamsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ChangeStreamsTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/change-streams"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ClientSideEncryptionTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ClientSideEncryptionTest.java index bbb232386dd..151f237afec 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ClientSideEncryptionTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ClientSideEncryptionTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ClientSideEncryptionTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/client-side-encryption"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/CollectionManagementTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/CollectionManagementTest.java index 1830fa24c9d..74df339951c 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/CollectionManagementTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/CollectionManagementTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class CollectionManagementTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/collection-management"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/CommandLoggingTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/CommandLoggingTest.java index 23302ebdd52..cbcab69f1c6 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/CommandLoggingTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/CommandLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class CommandLoggingTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/command-logging"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/CommandMonitoringTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/CommandMonitoringTest.java index c6148aaaef4..0d93cb47b7f 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/CommandMonitoringTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/CommandMonitoringTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public final class CommandMonitoringTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/command-monitoring"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ConnectionPoolLoggingTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ConnectionPoolLoggingTest.java index 6079f1931b7..b6ec522106d 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ConnectionPoolLoggingTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ConnectionPoolLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ConnectionPoolLoggingTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/connection-monitoring-and-pooling/logging"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/IndexManagmentTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/IndexManagmentTest.java index 382c5edb3a4..a8bcd07b782 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/IndexManagmentTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/IndexManagmentTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class IndexManagmentTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/index-management"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/LoadBalancerTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/LoadBalancerTest.java index eb70f5da4cf..4c00290e8b2 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/LoadBalancerTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/LoadBalancerTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class LoadBalancerTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/load-balancers"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ServerSelectionLoggingTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ServerSelectionLoggingTest.java index 2e932ba975f..7ef28e20609 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ServerSelectionLoggingTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ServerSelectionLoggingTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class ServerSelectionLoggingTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/server-selection/logging"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/SessionsTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/SessionsTest.java index 33d851a38c9..49884fcf3fb 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/SessionsTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/SessionsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class SessionsTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/sessions"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAtlasDataLakeTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAtlasDataLakeTest.java index 009a78d3d3f..82df14c7a62 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAtlasDataLakeTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAtlasDataLakeTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedAtlasDataLakeTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/atlas-data-lake-testing"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAuthTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAuthTest.java index 0471a9600c6..5f31133cc1b 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAuthTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedAuthTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedAuthTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/auth"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudTest.java index eaf7546bece..b6a250ed00c 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public final class UnifiedCrudTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/crud"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSTest.java index baac34f4959..c35223c0dc1 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedGridFSTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/gridfs"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableReadsTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableReadsTest.java index 9859bcc782e..a8b4ea08b19 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableReadsTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableReadsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public final class UnifiedRetryableReadsTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/retryable-reads"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableWritesTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableWritesTest.java index 2397aeb8b0d..017f58f0b68 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableWritesTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedRetryableWritesTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public final class UnifiedRetryableWritesTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/retryable-writes"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java index a88fe334525..e6ddac1266b 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedServerDiscoveryAndMonitoringTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public final class UnifiedServerDiscoveryAndMonitoringTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/server-discovery-and-monitoring"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedSyncTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedSyncTest.java index afcc8e4f1a3..e206dcc138a 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedSyncTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedSyncTest.java @@ -28,8 +28,6 @@ import com.mongodb.lang.NonNull; import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; public abstract class UnifiedSyncTest extends UnifiedTest { @@ -52,7 +50,7 @@ protected ClientEncryption createClientEncryption(final MongoClient keyVaultClie } @NonNull - protected static Collection getTestData(final String directory) throws URISyntaxException, IOException { + protected static Collection getTestData(final String directory) { return getTestData(directory, false); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java index a437084ac1d..6f20c0b22a8 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTest.java @@ -59,9 +59,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.opentest4j.TestAbortedException; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; @@ -98,8 +95,7 @@ import static org.junit.jupiter.api.Assumptions.abort; import static org.junit.jupiter.api.Assumptions.assumeFalse; import static org.junit.jupiter.api.Assumptions.assumeTrue; -import static util.JsonPoweredTestHelper.getTestDocument; -import static util.JsonPoweredTestHelper.getTestFiles; +import static util.JsonPoweredTestHelper.getTestDocuments; @ExtendWith(AfterBeforeParameterResolver.class) public abstract class UnifiedTest { @@ -165,11 +161,9 @@ public Entities getEntities() { } @NonNull - protected static Collection getTestData(final String directory, final boolean isReactive) - throws URISyntaxException, IOException { + protected static Collection getTestData(final String directory, final boolean isReactive) { List data = new ArrayList<>(); - for (File file : getTestFiles("/" + directory + "/")) { - BsonDocument fileDocument = getTestDocument(file); + for (BsonDocument fileDocument : getTestDocuments("/" + directory + "/")) { for (BsonValue cur : fileDocument.getArray("tests")) { final BsonDocument testDocument = cur.asDocument(); diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestFailureValidator.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestFailureValidator.java index 0472ef8e6ce..9a6e307cfa3 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestFailureValidator.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestFailureValidator.java @@ -24,8 +24,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -101,7 +99,7 @@ public void shouldPassAllOutcomes( assertNotNull(exception, "Expected exception but not was thrown"); } - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/valid-fail"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestValidator.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestValidator.java index 414d161677d..13822b7a57f 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestValidator.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestValidator.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedTestValidator extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/valid-pass"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTransactionsTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTransactionsTest.java index cf95ba9795a..5fd5fe6c8c2 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTransactionsTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTransactionsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedTransactionsTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/transactions"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedWriteConcernTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedWriteConcernTest.java index 4d1a5a2f854..124958b23d8 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedWriteConcernTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedWriteConcernTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class UnifiedWriteConcernTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/write-concern"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/VersionedApiTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/VersionedApiTest.java index e9ccd4d1cd4..95b23da9ce7 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/VersionedApiTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/VersionedApiTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class VersionedApiTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("versioned-api"); } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/WithTransactionHelperTransactionsTest.java b/driver-sync/src/test/functional/com/mongodb/client/unified/WithTransactionHelperTransactionsTest.java index d9fb4c9b4df..012e935d333 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/WithTransactionHelperTransactionsTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/WithTransactionHelperTransactionsTest.java @@ -18,12 +18,10 @@ import org.junit.jupiter.params.provider.Arguments; -import java.io.IOException; -import java.net.URISyntaxException; import java.util.Collection; final class WithTransactionHelperTransactionsTest extends UnifiedSyncTest { - private static Collection data() throws URISyntaxException, IOException { + private static Collection data() { return getTestData("unified-test-format/transactions-convenient-api"); } } diff --git a/driver-workload-executor/build.gradle b/driver-workload-executor/build.gradle deleted file mode 100644 index 7c48e444dc2..00000000000 --- a/driver-workload-executor/build.gradle +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -buildscript { - repositories { - maven { url "https://plugins.gradle.org/m2/" } - } - dependencies { - classpath 'com.github.jengelman.gradle.plugins:shadow:6.1.0' - } -} - -apply plugin: 'application' -apply plugin: 'com.github.johnrengelman.shadow' - -mainClassName = "com.mongodb.workload.WorkloadExecutor" - -sourceSets { - main { - java { - srcDir 'src/main' - } - resources { - srcDir 'src/resources' - } - } -} - -dependencies { - implementation project(':driver-sync') - implementation project(':driver-core').sourceSets.test.output - implementation project(':driver-sync').sourceSets.test.output - implementation "ch.qos.logback:logback-classic:$logbackVersion" - implementation(platform("org.junit:junit-bom:$junitBomVersion")) - implementation('org.junit.jupiter:junit-jupiter') - implementation('org.junit.vintage:junit-vintage-engine') -} - -javadoc { - enabled = false -} - -jar { - manifest { - attributes "Main-Class": "com.mongodb.workload.WorkloadExecutor" - } -} diff --git a/driver-workload-executor/build.gradle.kts b/driver-workload-executor/build.gradle.kts new file mode 100644 index 00000000000..2cb5f2e1073 --- /dev/null +++ b/driver-workload-executor/build.gradle.kts @@ -0,0 +1,57 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +plugins { + id("application") + id("java-library") + id("project.base") + id("conventions.test-artifacts") +} + +application { + mainClass = "com.mongodb.workload.WorkloadExecutor" +} + +sourceSets { + main { + java { setSrcDirs(listOf("src/main")) } + resources { setSrcDirs(listOf("src/resources")) } + } +} + +dependencies { + implementation(project(":driver-sync")) + implementation(project(path = ":driver-core", configuration = "testArtifacts")) + implementation(project(path = ":driver-sync", configuration = "testArtifacts")) + implementation(platform(libs.junit.bom)) + implementation(libs.bundles.junit.vintage) +} + +tasks.withType().configureEach { + enabled = false +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + + +tasks.withType { + manifest { + attributes["Main-Class"] = "com.mongodb.workload.WorkloadExecutor" + } +} diff --git a/graalvm-native-image-app/build.gradle b/graalvm-native-image-app/build.gradle deleted file mode 100644 index b3d7335f9d9..00000000000 --- a/graalvm-native-image-app/build.gradle +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// Note requires a Gradle project flag `-PincludeGraalvm` (see settings.gradle). - -plugins { - id 'application' - id 'org.graalvm.buildtools.native' version '0.9.23' -} - -application { - mainClass = 'com.mongodb.internal.graalvm.NativeImageApp' -} - -def systemPropertiesForRunningNativeApp = System.getProperties().findAll { it.key.toString().startsWith("org.mongodb.") } -tasks.matching { it.name == 'run' }.configureEach { - systemProperties(systemPropertiesForRunningNativeApp) -} - -// see https://graalvm.github.io/native-build-tools/latest/gradle-plugin.html -graalvmNative { - metadataRepository { - enabled = false - } - agent { - // Executing the `run` Gradle task with the tracing agent - // https://www.graalvm.org/latest/reference-manual/native-image/metadata/AutomaticMetadataCollection/ - // requires running Gradle with GraalVM despite the toolchain for the task already being GraalVM. - // The same is true about executing the `metadataCopy` Gradle task. - // This may be a manifestation of an issue with the `org.graalvm.buildtools.native` plugin. - enabled = false - defaultMode = 'direct' - def taskExecutedWithAgentAttached = 'run' - modes { - direct { - // see https://www.graalvm.org/latest/reference-manual/native-image/metadata/ExperimentalAgentOptions - options.add("config-output-dir=$buildDir/native/agent-output/$taskExecutedWithAgentAttached") - // `experimental-configuration-with-origins` produces - // `graalvm-native-image-app/build/native/agent-output/run/reflect-origins.txt` - // and similar files that explain the origin of each of the reachability metadata piece. - // However, for some reason, the actual reachability metadata is not generated when this option is enabled, - // so enable it manually if you need an explanation for a specific reachability metadata entry, - // and expect the build to fail. - // options.add('experimental-configuration-with-origins') - - // `experimental-class-define-support` does not seem to do what it is supposed to do. - // We need this option to work if we want to support `UnixServerAddress` in native image. - // Unfortunately, the tracing agent neither generates the metadata in - // `graalvm-native-image-app/src/main/resources/META-INF/native-image/proxy-config.json`, - // nor does it extract the bytecode of the generated classes to - // `graalvm-native-image-app/src/main/resources/META-INF/native-image/agent-extracted-predefined-classes`. - options.add('experimental-class-define-support') - } - } - metadataCopy { - inputTaskNames.add(taskExecutedWithAgentAttached) - outputDirectories.add('src/main/resources/META-INF/native-image') - mergeWithExisting = false - } - } - binaries { - configureEach { - buildArgs.add('--strict-image-heap') - buildArgs.add('-H:+UnlockExperimentalVMOptions') - // see class initialization and other reports in `graalvm/build/native/nativeCompile/reports` - buildArgs.add('--diagnostics-mode') - // see the "registerResource" entries in the `native-image` built-time output, - // informing us on the resources included in the native image being built - buildArgs.add('-H:Log=registerResource:5') - } - main { - sharedLibrary = false - def mainClassName = application.mainClass.get() - imageName = mainClassName.substring(mainClassName.lastIndexOf('.') + 1, mainClassName.length()) - runtimeArgs.addAll(systemPropertiesForRunningNativeApp.entrySet() - .stream() - .map {"-D${it.getKey()}=${it.getValue()}" } - .toList()) - quickBuild = true - // See the "Apply" entries in the `native-image` built-time output, informing us on - // the build configuration files (https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/) - // and the reachability metadata files (https://www.graalvm.org/latest/reference-manual/native-image/metadata/) - // which are applied at build time. - verbose = true - } - } -} - -dependencies { - // we intentionally depend here on the driver artifacts instead of depending on compiled classes - implementation project(path:':bson', configuration:'archives') - implementation project(path:':driver-core', configuration:'archives') - implementation project(path:':driver-sync', configuration:'archives') - implementation project(path:':driver-reactive-streams', configuration:'archives') - implementation project(path:':driver-legacy', configuration:'archives') - implementation project(path: ':mongodb-crypt', configuration: 'archives') - implementation project(path: ':mongodb-crypt', configuration: 'runtimeElements') - // note that as a result of these `sourceSets` dependencies, `driver-sync/src/test/resources/logback-test.xml` is used - implementation project(':driver-core').sourceSets.test.output - implementation project(':driver-sync').sourceSets.test.output - implementation project(':driver-legacy').sourceSets.test.output - implementation project(':driver-reactive-streams').sourceSets.test.output - implementation 'org.slf4j:slf4j-api:2.0.12' - implementation "ch.qos.logback:logback-classic:$logbackVersion" - implementation platform("io.projectreactor:reactor-bom:$projectReactorVersion") - implementation 'io.projectreactor:reactor-core' - implementation "org.graalvm.sdk:nativeimage:$graalSdkVersion" -} diff --git a/graalvm-native-image-app/build.gradle.kts b/graalvm-native-image-app/build.gradle.kts new file mode 100644 index 00000000000..464c7711f20 --- /dev/null +++ b/graalvm-native-image-app/build.gradle.kts @@ -0,0 +1,185 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Note requires a Gradle project flag `-PincludeGraalvm` (see settings.gradle.kts). + +plugins { + id("application") + id("java-library") + id("project.base") + id("conventions.test-artifacts") + alias(libs.plugins.graalvm.buildtools) +} + +application { + mainClass = "com.mongodb.internal.graalvm.NativeImageApp" +} + +sourceSets { + main { + java { setSrcDirs(listOf("src/main")) } + resources { setSrcDirs(listOf("src/main/resources")) } + } +} + +dependencies { + // we intentionally depend here on the driver artifacts instead of depending on compiled classes + implementation(project(path = ":bson", configuration = "archives")) + implementation(project(path = ":driver-core", configuration = "archives")) + implementation(project(path = ":driver-sync", configuration = "archives")) + implementation(project(path = ":driver-legacy", configuration = "archives")) + implementation(project(path = ":driver-reactive-streams", configuration = "archives")) + implementation(project(path = ":mongodb-crypt", configuration = "archives")) + implementation(project(path = ":mongodb-crypt", configuration = "runtimeElements")) + + implementation(project(path = ":driver-core", configuration = "testArtifacts")) + implementation(project(path = ":driver-sync", configuration = "testArtifacts")) + implementation(project(path = ":driver-legacy", configuration = "testArtifacts")) + implementation(project(path = ":driver-reactive-streams", configuration = "testArtifacts")) + + implementation(libs.slf4j) + implementation(libs.jna) + implementation(libs.graal.sdk.nativeimage) + implementation(libs.jetbrains.annotations) + implementation(libs.logback.classic) + implementation(platform(libs.project.reactor.bom)) + implementation(libs.project.reactor.core) +} + +tasks.withType().configureEach { + enabled = false +} + + +@Suppress("UNCHECKED_CAST") +val systemPropertiesForRunningNativeApp: Map = (System.getProperties().toMap() as Map) + .filterKeys { it.startsWith("org.mongodb.") } +tasks.named("run") { systemProperties = systemPropertiesForRunningNativeApp } + +// see https://graalvm.github.io/native-build-tools/latest/gradle-plugin.html +graalvmNative { + metadataRepository { + enabled.set(false) + } + agent { + // Executing the `run` Gradle task with the tracing agent + // https://www.graalvm.org/latest/reference-manual/native-image/metadata/AutomaticMetadataCollection/ + // requires running Gradle with GraalVM despite the toolchain for the task already being GraalVM. + // The same is true about executing the `metadataCopy` Gradle task. + // This may be a manifestation of an issue with the `org.graalvm.buildtools.native` plugin. + enabled.set(false) + defaultMode.set("direct") + val taskExecutedWithAgentAttached = "run" + modes { + direct { + // see https://www.graalvm.org/latest/reference-manual/native-image/metadata/ExperimentalAgentOptions + options.add("config-output-dir=${rootProject.file("build/native/agent-output/$taskExecutedWithAgentAttached").path}") + // `experimental-configuration-with-origins` produces + // `graalvm-native-image-app/build/native/agent-output/run/reflect-origins.txt` + // and similar files that explain the origin of each of the reachability metadata piece. + // However, for some reason, the actual reachability metadata is not generated when this option is enabled, + // so enable it manually if you need an explanation for a specific reachability metadata entry, + // and expect the build to fail. + // options.add("experimental-configuration-with-origins") + + // `experimental-class-define-support` does not seem to do what it is supposed to do. + // We need this option to work if we want to support `UnixServerAddress` in native image. + // Unfortunately, the tracing agent neither generates the metadata in + // `graalvm-native-image-app/src/main/resources/META-INF/native-image/proxy-config.json`, + // nor does it extract the bytecode of the generated classes to + // `graalvm-native-image-app/src/main/resources/META-INF/native-image/agent-extracted-predefined-classes`. + options.add("experimental-class-define-support") + } + } + metadataCopy { + inputTaskNames.add(taskExecutedWithAgentAttached) + outputDirectories.add("src/main/resources/META-INF/native-image") + mergeWithExisting.set(false) + } + } + binaries { + configureEach { + buildArgs.add("--strict-image-heap") + buildArgs.add("-H:+UnlockExperimentalVMOptions") + // see class initialization and other reports in `graalvm/build/native/nativeCompile/reports` + buildArgs.add("--diagnostics-mode") + // see the "registerResource" entries in the `native-image` built-time output, + // informing us on the resources included in the native image being built + buildArgs.add("-H:Log=registerResource:5") + } + named("main") { + val mainClassName = application.mainClass.get() + imageName = mainClassName.substring(mainClassName.lastIndexOf('.') + 1) + sharedLibrary.set(false) + runtimeArgs.addAll(systemPropertiesForRunningNativeApp.entries + .stream() + .map {"-D${it.key}=${it.value}" } + .toList()) + quickBuild.set(true) + // See the "Apply" entries in the `native-image` built-time output, informing us on + // the build configuration files (https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/) + // and the reachability metadata files (https://www.graalvm.org/latest/reference-manual/native-image/metadata/) + // which are applied at build time. + verbose.set(true) + } + } +} + +// By configuring the toolchains for the `org.graalvm.buildtools.native` plugin +// conditionally, we avoid Gradle errors caused by it failing to locate an installed GraalVM +// for Java SE older than 21. One situation when this is relevant is building from an IDE, +// where the `DEFAULT_JDK_VERSION` is likely used. +val minRequiredGraalVMJavaVersion = 21 +val graalJavaVersion: Int = findProperty("javaVersion")?.toString()?.toInt() ?: minRequiredGraalVMJavaVersion +val javaLanguageVersion: JavaLanguageVersion = JavaLanguageVersion.of(graalJavaVersion) + +if (graalJavaVersion >= minRequiredGraalVMJavaVersion) { + // `JvmVendorSpec.GRAAL_VM` matches only GraalVM Community (https://github.com/graalvm/graalvm-ce-builds/releases), + // and does not match any other GraalVM distribution. + // That is, Gradle fails to locate any other installed distribution of GraalVM. + // Furthermore, there is no other way to express via the Gradle toolchain functionality + // that GraalVM must be used. The documentation of the `org.graalvm.buildtools.native` plugin + // says the following about this limitation: + // "be aware that the toolchain detection cannot distinguish between GraalVM JDKs + // and standard JDKs without Native Image support: + // if you have both installed on the machine, Gradle may randomly pick one or the other". + // Fortunately, `JvmVendorSpec.GRAAL_VM` makes things less hideous than that. + // + // The documentation of the `org.graalvm.buildtools.native` plugin mentions + // the environment variable `GRAALVM_HOME` as an alternative to Gradle toolchain functionality. + // I was unable to find a way to stop relying on the toolchain specification requiring `JvmVendorSpec.GRAAL_VM` + // even with `GRAALVM_HOME`. + val graalVendor = JvmVendorSpec.GRAAL_VM + graalvmNative { + agent { + java { + toolchain { + // TODO - errors saying its immutable. + // languageVersion.set(javaLanguageVersion) + // vendor.set(graalVendor) + } + } + } + binaries { + configureEach { + javaLauncher.set(javaToolchains.launcherFor { + languageVersion.set(javaLanguageVersion) + vendor.set(graalVendor) + }) + } + } + } +} diff --git a/graalvm-native-image-app/src/main/com/mongodb/internal/graalvm/NativeImageApp.java b/graalvm-native-image-app/src/main/com/mongodb/internal/graalvm/NativeImageApp.java index 59778d7686f..400a1131108 100644 --- a/graalvm-native-image-app/src/main/com/mongodb/internal/graalvm/NativeImageApp.java +++ b/graalvm-native-image-app/src/main/com/mongodb/internal/graalvm/NativeImageApp.java @@ -18,7 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.annotation.Nullable; +import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Objects; diff --git a/graalvm-native-image-app/src/main/resources/META-INF/native-image/resource-config.json b/graalvm-native-image-app/src/main/resources/META-INF/native-image/resource-config.json index d4bf7ea12ff..3727b46aaff 100644 --- a/graalvm-native-image-app/src/main/resources/META-INF/native-image/resource-config.json +++ b/graalvm-native-image-app/src/main/resources/META-INF/native-image/resource-config.json @@ -44,12 +44,6 @@ "pattern":"\\QMETA-INF/services/javax.xml.parsers.SAXParserFactory\\E" }, { "pattern":"\\QMETA-INF/services/org.slf4j.spi.SLF4JServiceProvider\\E" - }, { - "pattern":"\\Qlogback-test.scmo\\E" - }, { - "pattern":"\\Qlogback-test.xml\\E" - }, { - "pattern":"\\Qlogback.scmo\\E" }, { "pattern":"java.base:\\Qjdk/internal/icu/impl/data/icudt72b/nfc.nrm\\E" }]}, diff --git a/gradle.properties b/gradle.properties index d3514e32f68..7da38a9cbc6 100644 --- a/gradle.properties +++ b/gradle.properties @@ -14,11 +14,13 @@ # limitations under the License. # +version=5.5.0-SNAPSHOT + org.gradle.daemon=true -org.gradle.jvmargs=-Duser.country=US -Duser.language=en +org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en ## NOTE: This property is also used to generate scala compile versions in BOM. -scalaVersions=2.11.12,2.12.20,2.13.15 -defaultScalaVersions=2.13.15 +supportedScalaVersions=2.13,2.12,2.11 +defaultScalaVersion=2.13 runOnceTasks=clean,release org.gradle.java.installations.auto-download=false org.gradle.java.installations.fromEnv=JDK8,JDK11,JDK17,JDK21,JDK21_GRAALVM diff --git a/gradle/deploy.gradle b/gradle/deploy.gradle deleted file mode 100644 index c34f7bf9b71..00000000000 --- a/gradle/deploy.gradle +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -def utilProjects = project(":util").allprojects -def deployedProjects = subprojects - utilProjects - -configure(deployedProjects) { - - def isScala = project.name.contains('scala') - def hasAllScalaVersions = project.hasProperty('allScalaVersions') - def isInvalidScalaProject = false // isScala && !hasAllScalaVersions // TODO JAVA-3564 - - task publishSnapshots { - group = 'publishing' - description = 'Publishes snapshots to Sonatype' - - if ( version.endsWith('-SNAPSHOT')) { - if (isInvalidScalaProject) { - doFirst { - def cause = """ - | Not publishing all Scala versions: - | ================================= - | - | You must set the -PallScalaVersions flag when publishing - |""".stripMargin() - throw new GradleException(cause) - } - } else { - dependsOn tasks.withType(PublishToMavenRepository) - } - } - } - - task publishArchives { - group = 'publishing' - description = 'Publishes a release and uploads to Sonatype / Maven Central' - - def gitVersionMatch = project.gitVersion == version - - doFirst { - if (!gitVersionMatch) { - def cause = """ - | Version mismatch: - | ================= - | - | $version != $gitVersion - | - | The project version does not match the git tag. - |""".stripMargin() - throw new GradleException(cause) - } else if (isInvalidScalaProject) { - def cause = """ - | Not publishing all Scala versions: - | ================================= - | - | You must set the -PallScalaVersions flag when publishing - |""".stripMargin() - throw new GradleException(cause) - } else { - println("Publishing: ${project.name} : ${project.gitVersion}") - } - } - if (gitVersionMatch && !isInvalidScalaProject) { - dependsOn tasks.withType(PublishToMavenRepository) - } - } -} diff --git a/gradle/javaToolchain.gradle b/gradle/javaToolchain.gradle deleted file mode 100644 index f1c779dab33..00000000000 --- a/gradle/javaToolchain.gradle +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -final Integer DEFAULT_JDK_VERSION = 17 - -def javaMainProjects = subprojects - project(":util:taglets") - -allprojects { - - def javaVersion = (findProperty("javaVersion") ?: DEFAULT_JDK_VERSION.toString()).toInteger() - project.pluginManager.withPlugin("java") { - if (!project.pluginManager.hasPlugin("scala")) { - logger.info("Compiling ${project.name} using JDK${DEFAULT_JDK_VERSION}") - java { - toolchain { - languageVersion = JavaLanguageVersion.of(DEFAULT_JDK_VERSION) - } - } - } - } - project.pluginManager.withPlugin('org.graalvm.buildtools.native') { - def minRequiredGraalVMJavaVersion = 21 - // By configuring the toolchains for the `org.graalvm.buildtools.native` plugin - // conditionally, we avoid Gradle errors caused by it failing to locate an installed GraalVM - // for Java SE older than 21. One situation when this is relevant is building from an IDE, - // where the `DEFAULT_JDK_VERSION` is likely used. - if (javaVersion >= minRequiredGraalVMJavaVersion) { - def javaLanguageVersion = JavaLanguageVersion.of(javaVersion) - // `JvmVendorSpec.GRAAL_VM` matches only GraalVM Community (https://github.com/graalvm/graalvm-ce-builds/releases), - // and does not match any other GraalVM distribution. - // That is, Gradle fails to locate any other installed distribution of GraalVM. - // Furthermore, there is no other way to express via the Gradle toolchain functionality - // that GraalVM must be used. The documentation of the `org.graalvm.buildtools.native` plugin - // says the following about this limitation: - // "be aware that the toolchain detection cannot distinguish between GraalVM JDKs - // and standard JDKs without Native Image support: - // if you have both installed on the machine, Gradle may randomly pick one or the other". - // Fortunately, `JvmVendorSpec.GRAAL_VM` makes things less hideous than that. - // - // The documentation of the `org.graalvm.buildtools.native` plugin mentions - // the environment variable `GRAALVM_HOME` as an alternative to Gradle toolchain functionality. - // I was unable to find a way to stop relying on the toolchain specification requiring `JvmVendorSpec.GRAAL_VM` - // even with `GRAALVM_HOME`. - def graalVendor = JvmVendorSpec.GRAAL_VM - graalvmNative { - agent { - java { - toolchain { - languageVersion = javaLanguageVersion - vendor = graalVendor - } - } - } - binaries { - configureEach { - javaLauncher = javaToolchains.launcherFor { - languageVersion = javaLanguageVersion - vendor = graalVendor - } - } - } - } - } - } - - if (project == project(":bson-record-codec")) { - tasks.withType(JavaCompile) { - options.encoding = "UTF-8" - options.release.set(17) - } - } else if (project.name == 'graalvm-native-image-app') { - tasks.withType(JavaCompile) { - options.encoding = 'UTF-8' - options.release.set(DEFAULT_JDK_VERSION) - } - } else if (project in javaMainProjects) { - tasks.withType(JavaCompile) { - options.encoding = "UTF-8" - options.release.set(8) - } - - // Work around for: https://github.com/gradle/gradle/issues/15703 - tasks.withType(GroovyCompile) { - sourceCompatibility = 1.8 - targetCompatibility = 1.8 - } - } - - tasks.withType(Test) { - javaLauncher.set(javaToolchains.launcherFor { - languageVersion = JavaLanguageVersion.of(javaVersion) - }) - } - -} diff --git a/gradle/javadoc.gradle b/gradle/javadoc.gradle deleted file mode 100644 index b986747c647..00000000000 --- a/gradle/javadoc.gradle +++ /dev/null @@ -1,120 +0,0 @@ -import static org.gradle.util.CollectionUtils.single - -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -def projectNamesThatDoNotPublishJavaDocs =["driver-benchmarks", "driver-lambda", "driver-workload-executor", "graalvm-native-image-app", "util", - "spock", "taglets"] -def javaMainProjects = subprojects.findAll { !projectNamesThatDoNotPublishJavaDocs.contains(it.name) } - -task docs { - dependsOn javaMainProjects.collect { it.tasks.withType(Javadoc) + it.tasks.withType(ScalaDoc) } -} - -def buildDocsUrl(String version, String packageName) { - def docVersion = version.split('-').head() - def (major, minor, patch) = docVersion.split('\\.') - - docVersion = "${major}.${minor}" - if (version.contains("-SNAPSHOT") && patch == 0) { - // If a snapshot of the next minor version, set the version to the previous released version - docVersion = minor > 0 ? "${major}.${minor - 1}" : '4.0' - } - - ["http://mongodb.github.io/mongo-java-driver/${docVersion}/apidocs/${packageName}/", "${rootProject.buildDir.path}/docs/${packageName}"] -} - -def tagletsProject = project(':util:taglets') -subprojects { project -> - if (project in javaMainProjects) { - - tasks.withType(Javadoc) { - dependsOn tagletsProject.compileJava //We need taglets to be compiled - exclude "**/com/mongodb/**/benchmark/**" - exclude "**/com/mongodb/**/assertions/**" - exclude "**/com/mongodb/**/internal/**" - exclude "**/org/bson/**/internal/**" - options { - author = true - version = true - links = ['https://docs.oracle.com/en/java/javase/11/docs/api/', - 'https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/'] - tagletPath tagletsProject.sourceSets.main.output.classesDirs.head() - taglets 'AtlasManualTaglet' - taglets 'ManualTaglet' - taglets 'DochubTaglet' - taglets 'ServerReleaseTaglet' - encoding = 'UTF-8' - charSet 'UTF-8' - docEncoding 'UTF-8' - addBooleanOption("html5", true) - addBooleanOption("-allow-script-in-comments", true) - header = ''' - | '''.stripMargin() - } - - afterEvaluate { - destinationDir = new File(rootDir, "build/docs/${project.archivesBaseName}") - def version = project.version as String - if (project.name != 'bson') { - options.linksOffline(*buildDocsUrl(version, 'bson')) - if (project.name != 'driver-core') options.linksOffline(*buildDocsUrl(version, 'mongodb-driver-core')) - if (project.name == 'driver-legacy') { - dependsOn javaMainProjects.find({ it.name == 'driver-sync' }).javadoc - options.linksOffline(*buildDocsUrl(version, 'mongodb-driver-sync')) - } - } - } - } - } -} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 00000000000..eab637a8b41 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,214 @@ +# Copyright 2008-present MongoDB, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +[versions] +aws-sdk-v1 = "1.12.782" +aws-sdk-v2 = "2.30.31" +graal-sdk = "24.0.0" +jna = "5.11.0" +jnr-unixsocket = "0.38.17" +netty-bom = "4.1.87.Final" +project-reactor-bom = "2022.0.0" +reactive-streams = "1.0.4" +snappy = "1.1.10.3" +zstd = "1.5.5-3" +jetbrains-annotations = "26.0.2" + +kotlin = "1.8.10" +kotlinx-coroutines-bom = "1.6.4" +kotlinx-datetime = "0.4.0" +kotlinx-serialization = "1.5.0" + +scala-v2-v13 = "2.13.16" +scala-v2-v12 = "2.12.20" +scala-v2-v11 = "2.11.12" + +# Test +assertj = "3.24.2" +aws-lambda-core = "1.2.2" +aws-lambda-events = "3.11.1" +cglib = "2.2.2" +classgraph = "4.8.154" +findbugs-jsr = "1.3.9" +groovy = "3.0.9" +hamcrest = "1.3" +jmh = "1.37" +junit-bom = "5.10.2" +logback = "1.3.14" +mockito = "5.11.0" +mockito-java8 = "4.6.1" +mockito-kotlin = "4.1.0" +objenesis = "1.3" +reflections = "0.9.10" +slf4j = "1.7.6" +spock-bom = "2.1-groovy-3.0" +scala-test = "3.2.18" +scala-test-plus = "3.2.18.0" + +# Plugins +plugin-bnd = "5.1.2" +plugin-build-config = "3.0.3" +plugin-detekt = "1.21.0" +plugin-dokka = "1.8.10" +plugin-download = "5.6.0" +plugin-graalvm = "0.9.23" +plugin-optional-base = "7.0.0" +plugin-shadow = "8.3.6" +plugin-spotbugs = "6.0.15" +plugin-spotless = "6.14.0" +plugin-test-logger = "4.0.0" + +[libraries] +aws-java-sdk-v1-core = { module = "com.amazonaws:aws-java-sdk-core", version.ref = "aws-sdk-v1" } +aws-java-sdk-v1-sts = { module = "com.amazonaws:aws-java-sdk-sts", version.ref = "aws-sdk-v1" } +aws-java-sdk-v2-auth = { module = "software.amazon.awssdk:auth", version.ref = "aws-sdk-v2" } +aws-java-sdk-v2-sts = { module = "software.amazon.awssdk:sts", version.ref = "aws-sdk-v2" } + +jna = { module = "net.java.dev.jna:jna", version.ref = "jna" } +jna-platform = { module = "net.java.dev.jna:jna-platform", version.ref = "jna" } +jnr-unixsocket = { module = "com.github.jnr:jnr-unixsocket", version.ref = "jnr-unixsocket" } +jetbrains-annotations = {module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } + +netty-bom = { module = "io.netty:netty-bom", version.ref = "netty-bom" } +netty-buffer = { module = "io.netty:netty-buffer" } +netty-handler = { module = "io.netty:netty-handler" } +netty-transport = { module = "io.netty:netty-transport" } + +project-reactor-bom = { module = "io.projectreactor:reactor-bom", version.ref = "project-reactor-bom" } +project-reactor-core = { module = "io.projectreactor:reactor-core" } +reactive-streams = { module = " org.reactivestreams:reactive-streams", version.ref = "reactive-streams" } + +slf4j = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +snappy-java = { module = "org.xerial.snappy:snappy-java", version.ref = "snappy" } +zstd-jni = { module = "com.github.luben:zstd-jni", version.ref = "zstd" } + +graal-sdk = { module = "org.graalvm.sdk:graal-sdk", version.ref = "graal-sdk" } +graal-sdk-nativeimage = { module = "org.graalvm.sdk:nativeimage", version.ref = "graal-sdk" } + +kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom" } +kotlin-stdlib-jdk8 = { module = "org.jetbrains.kotlin:kotlin-stdlib-jdk8" } +kotlinx-coroutines-bom = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-bom", version.ref = "kotlinx-coroutines-bom" } +kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core" } +kotlinx-coroutines-reactive = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-reactive" } +kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect" } +kotlinx-serialization = { module = "org.jetbrains.kotlinx:kotlinx-serialization-bom", version.ref = "kotlinx-serialization" } +kotlinx-serialization-core = { module = "org.jetbrains.kotlinx:kotlinx-serialization-core" } +kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json" } +kotlinx-serialization-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinx-datetime" } + +scala-library-v2-v13 = { module = "org.scala-lang:scala-library", version.ref = "scala-v2-v13" } +scala-reflect-v2-v13 = { module = "org.scala-lang:scala-reflect", version.ref = "scala-v2-v13" } + +scala-library-v2-v12 = { module = "org.scala-lang:scala-library", version.ref = "scala-v2-v12" } +scala-reflect-v2-v12 = { module = "org.scala-lang:scala-reflect", version.ref = "scala-v2-v12" } + +scala-library-v2-v11 = { module = "org.scala-lang:scala-library", version.ref = "scala-v2-v11" } +scala-reflect-v2-v11 = { module = "org.scala-lang:scala-reflect", version.ref = "scala-v2-v11" } + +# Test +jmh-core = { module = "org.openjdk.jmh:jmh-core", version.ref = "jmh"} +jmh-generator-annprocess = { module = "org.openjdk.jmh:jmh-generator-annprocess", version.ref = "jmh"} + +junit-bom = { module = "org.junit:junit-bom", version.ref = "junit-bom" } +junit-jupiter = { module = "org.junit.jupiter:junit-jupiter" } +junit-jupiter-params = { module = "org.junit.jupiter:junit-jupiter-params" } +junit-jupiter-engine = { module = "org.junit.jupiter:junit-jupiter-engine" } +junit-vintage-engine = { module = "org.junit.vintage:junit-vintage-engine" } +junit-kotlin = { module = "org.jetbrains.kotlin:kotlin-test-junit5" } + +spock-bom = { module = "org.spockframework:spock-bom", version.ref = "spock-bom" } +spock-core = { module = "org.spockframework:spock-core" } +spock-junit4 = { module = "org.spockframework:spock-junit4" } + +mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockito" } +mockito-junit-jupiter = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockito" } +mockito-junit-jupiter-java8 = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockito-java8" } +mockito-core-java8 = { module = "org.mockito:mockito-core", version.ref = "mockito-java8" } +mockito-inline-java8 = { module = "org.mockito:mockito-inline", version.ref = "mockito-java8" } +mockito-kotlin = { module = "org.mockito.kotlin:mockito-kotlin", version.ref = "mockito-kotlin" } + + +scala-test-flatspec-v2-v13 = { module = "org.scalatest:scalatest-flatspec_2.13", version.ref = "scala-test" } +scala-test-shouldmatchers-v2-v13 = { module = "org.scalatest:scalatest-shouldmatchers_2.13", version.ref = "scala-test" } +scala-test-mockito-v2-v13 = { module = "org.scalatestplus:mockito-4-11_2.13", version.ref = "scala-test-plus" } +scala-test-junit-runner-v2-v13 = { module = "org.scalatestplus:junit-5-10_2.13", version.ref = "scala-test-plus" } + +scala-test-flatspec-v2-v12 = { module = "org.scalatest:scalatest-flatspec_2.12", version.ref = "scala-test" } +scala-test-shouldmatchers-v2-v12 = { module = "org.scalatest:scalatest-shouldmatchers_2.12", version.ref = "scala-test" } +scala-test-mockito-v2-v12 = { module = "org.scalatestplus:mockito-4-11_2.12", version.ref = "scala-test-plus" } +scala-test-junit-runner-v2-v12 = { module = "org.scalatestplus:junit-5-10_2.12", version.ref = "scala-test-plus" } + +scala-test-flatspec-v2-v11 = { module = "org.scalatest:scalatest-flatspec_2.11", version.ref = "scala-test" } +scala-test-shouldmatchers-v2-v11 = { module = "org.scalatest:scalatest-shouldmatchers_2.11", version.ref = "scala-test" } +scala-test-mockito-v2-v11 = { module = "org.scalatestplus:mockito-4-11_2.11", version.ref = "scala-test-plus" } +scala-test-junit-runner-v2-v11 = { module = "org.scalatestplus:junit-5-10_2.11", version.ref = "scala-test-plus" } + +kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test" } + +assertj = { module = "org.assertj:assertj-core", version.ref = "assertj" } +aws-lambda-core = { module = " com.amazonaws:aws-lambda-java-core", version.ref = "aws-lambda-core" } +aws-lambda-events = { module = " com.amazonaws:aws-lambda-java-events", version.ref = "aws-lambda-events" } +cglib = { module = "cglib:cglib-nodep", version.ref = "cglib" } +classgraph = { module = "io.github.classgraph:classgraph", version.ref = "classgraph" } +findbugs-jsr = { module = "com.google.code.findbugs:jsr305", version.ref = "findbugs-jsr" } +groovy = { module = "org.codehaus.groovy:groovy-all", version.ref = "groovy" } +hamcrest-all = { module = "org.hamcrest:hamcrest-all", version.ref = "hamcrest" } +logback-classic = { module = "ch.qos.logback:logback-classic", version.ref = "logback" } +netty-tcnative-boringssl-static = { module = "io.netty:netty-tcnative-boringssl-static" } +objenesis = { module = "org.objenesis:objenesis", version.ref = "objenesis" } +project-reactor-test = { module = "io.projectreactor:reactor-test" } +reactive-streams-tck = { module = " org.reactivestreams:reactive-streams-tck", version.ref = "reactive-streams" } +reflections = { module = "org.reflections:reflections", version.ref = "reflections" } + + +[bundles] +aws-java-sdk-v1 = ["aws-java-sdk-v1-core", "aws-java-sdk-v1-sts"] +aws-java-sdk-v2 = ["aws-java-sdk-v2-auth", "aws-java-sdk-v2-sts"] +netty = ["netty-buffer", "netty-handler", "netty-transport"] + +scala-v2-v13 = ["scala-library-v2-v13", "scala-reflect-v2-v13"] +scala-v2-v12 = ["scala-library-v2-v12", "scala-reflect-v2-v12"] +scala-v2-v11 = ["scala-library-v2-v11", "scala-reflect-v2-v11"] + +# Test +junit = ["junit-jupiter", "junit-jupiter-params", "junit-jupiter-engine", "logback-classic", "hamcrest-all"] +junit-vintage = ["junit-vintage-engine", "junit-jupiter-params", "junit-jupiter-engine", "logback-classic", "hamcrest-all"] +spock = ["spock-core", "spock-junit4"] + +mockito = ["mockito-junit-jupiter", "mockito-core"] +mockito-java8 = ["mockito-junit-jupiter-java8", "mockito-core-java8", "mockito-inline-java8"] +mockito-kotlin = ["mockito-kotlin", "mockito-junit-jupiter-java8"] + +scala-test-v2-v13 = ["scala-test-flatspec-v2-v13", "scala-test-shouldmatchers-v2-v13", "scala-test-mockito-v2-v13", + "scala-test-junit-runner-v2-v13", "reflections"] +scala-test-v2-v12 = ["scala-test-flatspec-v2-v12", "scala-test-shouldmatchers-v2-v12", "scala-test-mockito-v2-v12", + "scala-test-junit-runner-v2-v12", "reflections"] +scala-test-v2-v11 = ["scala-test-flatspec-v2-v11", "scala-test-shouldmatchers-v2-v11", "scala-test-mockito-v2-v11", + "scala-test-junit-runner-v2-v11", "reflections"] + +[plugins] +kotlin-gradle = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +bnd = { id = "biz.aQute.bnd", version.ref = "plugin-bnd" } +build-config = { id = "com.github.gmazzo.buildconfig", version.ref = "plugin-build-config" } +detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "plugin-detekt" } +dokka = { id = "org.jetbrains.dokka", version.ref = "plugin-dokka" } +download = { id = "de.undercouch.download", version.ref = "plugin-download" } +graalvm-buildtools = { id = "org.graalvm.buildtools.native", version.ref = "plugin-graalvm" } +kotlin = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +optional = { id = "nebula.optional-base", version.ref = "plugin-optional-base" } +shadow = { id = "com.gradleup.shadow", version.ref = "plugin-shadow" } +spotbugs = { id = "com.github.spotbugs", version.ref = "plugin-spotbugs" } +spotless = { id = "com.diffplug.spotless", version.ref = "plugin-spotless" } +test-logger = { id = "com.adarshr.test-logger", version.ref = "plugin-test-logger" } diff --git a/gradle/publish.gradle b/gradle/publish.gradle deleted file mode 100644 index fa56f09f138..00000000000 --- a/gradle/publish.gradle +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Configures publishing of the main java projects - */ - -// Publishing helpers -ext { - configurePom = { project -> - { -> - name = project.hasProperty('pomName') ? project.getProperty('pomName') : project.name - description = project.description - url = project.hasProperty('pomURL') ? project.getProperty('pomURL') : 'https://www.mongodb.com/' - licenses { - license { - name = 'The Apache License, Version 2.0' - url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' - } - } - scm { - url = 'https://github.com/mongodb/mongo-java-driver' - connection = 'scm:https://github.com/mongodb/mongo-java-driver.git' - developerConnection = 'scm:git@github.com:mongodb/mongo-java-driver.git' - } - developers { - developer { - name = 'Various' - organization = 'MongoDB' - } - } - } - } - configureMavenRepositories = { project -> - { -> - def snapshotsRepoUrl = 'https://oss.sonatype.org/content/repositories/snapshots/' - def releasesRepoUrl = 'https://oss.sonatype.org/service/local/staging/deploy/maven2/' - maven { - url = project.version.endsWith('SNAPSHOT') ? snapshotsRepoUrl : releasesRepoUrl - credentials { - username project.hasProperty('nexusUsername') ? project.getProperty('nexusUsername') : '' - password project.hasProperty('nexusPassword') ? project.getProperty('nexusPassword') : '' - } - } - - maven { - url = "$rootDir/build/repo" - } - } - } - configureJarManifestAttributes = { project -> - { -> - manifest.attributes['-exportcontents'] = "*;-noimport:=true" - manifest.attributes['Build-Version'] = project.gitVersion - manifest.attributes['Bundle-Version'] = project.version - manifest.attributes['Bundle-Name'] = project.archivesBaseName - manifest.attributes['Bundle-SymbolicName'] = project.group + '.' + project.archivesBaseName - } - } -} - - -def projectNamesNotToBePublished = ["driver-benchmarks", "driver-lambda", "driver-workload-executor", "graalvm-native-image-app", "util", - "spock", "taglets"] -def publishedProjects = subprojects.findAll { !projectNamesNotToBePublished.contains(it.name) } -def bomProjects = project(":bom") -def scalaProjects = publishedProjects.findAll { it.name.contains('scala') } - bomProjects -def javaProjects = publishedProjects - scalaProjects - bomProjects -def projectsWithManifest = publishedProjects.findAll {it.name != 'driver-legacy' } - bomProjects - -configure(javaProjects) { project -> - apply plugin: 'maven-publish' - apply plugin: 'signing' - - task sourcesJar(type: Jar) { - from project.sourceSets.main.allJava - classifier = 'sources' - } - - task javadocJar(type: Jar) { - from javadoc - classifier = 'javadoc' - } - - publishing { - publications { - mavenJava(MavenPublication) { - artifactId = project.archivesBaseName - from project.components.java - artifact sourcesJar - artifact javadocJar - - suppressPomMetadataWarningsFor("dateTimeSupportApiElements") - suppressPomMetadataWarningsFor("dateTimeSupportRuntimeElements") - - suppressPomMetadataWarningsFor("jsonSupportApiElements") - suppressPomMetadataWarningsFor("jsonSupportRuntimeElements") - - suppressPomMetadataWarningsFor("mongoCryptSupportApiElements") - suppressPomMetadataWarningsFor("mongoCryptSupportRuntimeElements") - } - } - - repositories configureMavenRepositories(project) - } - - afterEvaluate { - publishing.publications.mavenJava.artifactId = project.archivesBaseName - publishing.publications.mavenJava.pom configurePom(project) - signing { - useInMemoryPgpKeys(findProperty("signingKey"), findProperty("signingPassword")) - sign publishing.publications.mavenJava - } - } -} - -configure(scalaProjects) { project -> - apply plugin: 'maven-publish' - apply plugin: 'signing' - - task sourcesJar(type: Jar) { - from project.sourceSets.main.allScala - classifier = 'sources' - } - - task scaladocJar(type: Jar) { - from scaladoc - classifier = 'javadoc' - } - - publishing { - publications { - mavenJava(MavenPublication) { - artifactId = project.archivesBaseName.contains('bson') ? 'mongo-scala-bson' : 'mongo-scala-driver' - from project.components.java - artifact sourcesJar - artifact scaladocJar - } - } - - repositories configureMavenRepositories(project) - } - - afterEvaluate { - publishing.publications.mavenJava.pom configurePom(project) - signing { - useInMemoryPgpKeys(findProperty("signingKey"), findProperty("signingPassword")) - sign publishing.publications.mavenJava - } - } -} - - -configure(projectsWithManifest) { project -> - apply plugin: 'biz.aQute.bnd.builder' - afterEvaluate { - jar configureJarManifestAttributes(project) - } -} - -configure(bomProjects) { project -> - apply plugin: 'maven-publish' - apply plugin: 'signing' - apply plugin: 'java-platform' - - // Get the Scala versions from the project property. Only major.minor versions. - def scalaVersions = project.findProperty("scalaVersions")?.split(",") - ?.collect { it.split("\\.")[0] + "." + it.split("\\.")[1] } - - assert scalaVersions != null && !scalaVersions.isEmpty() : "Scala versions must be provided as a comma-separated list" + - " in the 'scalaVersions' project property" - - publishing { - publications { - mavenJava(MavenPublication) { - artifactId = "bom".equals(project.archivesBaseName) ? "mongodb-driver-bom" : project.archivesBaseName - from components.javaPlatform - - // Modify the generated POM to add multiple compile versions of driver-scala or bson-scala. - // Scala multi-version support generates only one for BOM. - pom.withXml { - def pomXml = asNode() - - def dependencyManagementNode = pomXml.get("dependencyManagement")?.getAt(0) - assert dependencyManagementNode : " node not found in the generated BOM POM" - - def dependenciesNode = dependencyManagementNode.get("dependencies")?.getAt(0) - assert dependenciesNode : " node not found inside " - - // Check if scala dependencies are present in the BOM. - def existingScalaDeps = dependenciesNode.children().findAll { - it.artifactId.text().contains("scala") - } - - existingScalaDeps.each { existingDep -> - String groupId = existingDep.groupId.text() - String originalArtifactId = existingDep.artifactId.text() - String artifactVersion = existingDep.version.text() - - // Add multiple versions with Scala suffixes for each Scala-related dependency. - scalaVersions.each { scalaVersion -> - // Remove existing Scala version suffix (_2.12, _2.13, etc.) - String baseArtifactId = originalArtifactId.replaceAll("_\\d+\\.\\d+(\\.\\d+)?\$", "") - String newArtifactId = "${baseArtifactId}_${scalaVersion}" - - // Skip if Scala dependency with this scalaVersion already exists in BOM. - if(newArtifactId != originalArtifactId) { - def dependencyNode = dependenciesNode.appendNode("dependency") - dependencyNode.appendNode("groupId", groupId) - dependencyNode.appendNode("artifactId", newArtifactId) - dependencyNode.appendNode("version", artifactVersion) - } - } - } - } - } - } - - repositories configureMavenRepositories(project) - } - - afterEvaluate { - publishing.publications.mavenJava.pom configurePom(project) - signing { - useInMemoryPgpKeys(findProperty("signingKey"), findProperty("signingPassword")) - sign publishing.publications.mavenJava - } - } - - tasks.withType(GenerateModuleMetadata) { - enabled = false - } - - tasks.withType(GenerateMavenPom).configureEach { - doLast { - def xml = file(destination).text - def root = new groovy.xml.XmlSlurper().parseText(xml) - - def dependencies = root.dependencyManagement.dependencies.children() - assert dependencies.children().size() > 1 : "BOM must contain more then one element:\n$destination" - - dependencies.each { dependency -> - def groupId = dependency.groupId.text() - assert groupId.startsWith('org.mongodb') : "BOM must contain only 'org.mongodb' dependencies, but found '$groupId':\n$destination" - /* The and tags should be omitted in BOM dependencies. - This ensures that consuming projects have the flexibility to decide whether a - dependency is optional in their context. The BOM's role is to provide version information, - not to dictate inclusion or exclusion of dependencies. */ - assert dependency.scope.size() == 0 : "BOM must not contain elements in dependency:\n$destination" - assert dependency.optional.size() == 0 : "BOM must not contain elements in dependency:\n$destination" - } - } - } -} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index e708b1c023e..afba109285a 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e750102e092..9bf7bd33972 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip +networkTimeout=10000 zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 4f906e0c811..65dcd68d65c 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME @@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the @@ -106,80 +140,105 @@ location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index 107acd32c4e..93e3f59f135 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/mongodb-crypt/build.gradle.kts b/mongodb-crypt/build.gradle.kts index 72d7fd47292..464c32c16a8 100644 --- a/mongodb-crypt/build.gradle.kts +++ b/mongodb-crypt/build.gradle.kts @@ -12,50 +12,44 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - * */ - +import ProjectExtensions.configureJarManifest +import ProjectExtensions.configureMavenPublication import de.undercouch.gradle.tasks.download.Download -buildscript { - repositories { - mavenCentral() - google() - } - dependencies { - "classpath"(group = "net.java.dev.jna", name = "jna", version = "5.11.0") - } -} - plugins { - // Needed to download libmongocrypt from s3. - id("de.undercouch.download") version "5.6.0" -} - -group = "org.mongodb" -base.archivesName.set("mongodb-crypt") -description = "MongoDB client-side crypto support" -ext.set("pomName", "MongoCrypt") - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + id("project.java") + alias(libs.plugins.download) } dependencies { api(project(path = ":bson", configuration = "default")) - api("net.java.dev.jna:jna:5.11.0") + api(libs.jna) +} - // Tests - testImplementation("org.junit.jupiter:junit-jupiter") +configureMavenPublication { + pom { + name.set("MongoCrypt") + description.set("MongoDB client-side crypto support") + } +} + +configureJarManifest { + attributes["Automatic-Module-Name"] = "com.mongodb.crypt.capi" + attributes["Bundle-Name"] = "MongoCrypt" + attributes["Bundle-SymbolicName"] = "com.mongodb.crypt.capi" + attributes["Import-Package"] = "org.slf4j.*;resolution:=optional,org.bson.*" + attributes["-exportcontents"] = "com.mongodb.*;-noimport:=true" + attributes["Private-Package"] = "" } /* * Jna copy or download resources */ -val jnaDownloadsDir = "$buildDir/jnaLibs/downloads/" -val jnaResourcesDir = "$buildDir/jnaLibs/resources/" -val jnaLibPlatform: String = if (com.sun.jna.Platform.RESOURCE_PREFIX.startsWith("darwin")) "darwin" else com.sun.jna.Platform.RESOURCE_PREFIX +val jnaDownloadsDir = rootProject.file("build/jnaLibs/downloads/").path +val jnaResourcesDir = rootProject.file("build/jnaLibs/resources/").path +val jnaLibPlatform: String = + if (com.sun.jna.Platform.RESOURCE_PREFIX.startsWith("darwin")) "darwin" else com.sun.jna.Platform.RESOURCE_PREFIX val jnaLibsPath: String = System.getProperty("jnaLibsPath", "${jnaResourcesDir}${jnaLibPlatform}") val jnaResources: String = System.getProperty("jna.library.path", jnaLibsPath) @@ -70,26 +64,19 @@ val binariesArchiveName = "libmongocrypt-java.tar.gz" */ val localBinariesArchiveName = "libmongocrypt-java-$downloadRevision.tar.gz" -val downloadUrl: String = "https://mciuploads.s3.amazonaws.com/libmongocrypt/java/$downloadRevision/$binariesArchiveName" - -val jnaMapping: Map = mapOf( - "rhel-62-64-bit" to "linux-x86-64", - "rhel72-zseries-test" to "linux-s390x", - "rhel-71-ppc64el" to "linux-ppc64le", - "ubuntu1604-arm64" to "linux-aarch64", - "windows-test" to "win32-x86-64", - "macos" to "darwin" -) - -sourceSets { - main { - java { - resources { - srcDirs(jnaResourcesDir) - } - } - } -} +val downloadUrl: String = + "https://mciuploads.s3.amazonaws.com/libmongocrypt/java/$downloadRevision/$binariesArchiveName" + +val jnaMapping: Map = + mapOf( + "rhel-62-64-bit" to "linux-x86-64", + "rhel72-zseries-test" to "linux-s390x", + "rhel-71-ppc64el" to "linux-ppc64le", + "ubuntu1604-arm64" to "linux-aarch64", + "windows-test" to "win32-x86-64", + "macos" to "darwin") + +sourceSets { main { java { resources { srcDirs(jnaResourcesDir) } } } } tasks.register("downloadJava") { src(downloadUrl) @@ -101,57 +88,49 @@ tasks.register("downloadJava") { tasks.register("unzipJava") { /* - Clean up the directory first if the task is not UP-TO-DATE. - This can happen if the download revision has been changed and the archive is downloaded again. - */ + Clean up the directory first if the task is not UP-TO-DATE. + This can happen if the download revision has been changed and the archive is downloaded again. + */ doFirst { println("Cleaning up $jnaResourcesDir") delete(jnaResourcesDir) } from(tarTree(resources.gzip("${jnaDownloadsDir}/$localBinariesArchiveName"))) - include(jnaMapping.keys.flatMap { - listOf("${it}/nocrypto/**/libmongocrypt.so", "${it}/lib/**/libmongocrypt.dylib", "${it}/bin/**/mongocrypt.dll" ) - }) - eachFile { - path = "${jnaMapping[path.substringBefore("/")]}/${name}" - } + include( + jnaMapping.keys.flatMap { + listOf( + "${it}/nocrypto/**/libmongocrypt.so", "${it}/lib/**/libmongocrypt.dylib", "${it}/bin/**/mongocrypt.dll") + }) + eachFile { path = "${jnaMapping[path.substringBefore("/")]}/${name}" } into(jnaResourcesDir) dependsOn("downloadJava") - doLast { - println("jna.library.path contents: \n ${fileTree(jnaResourcesDir).files.joinToString(",\n ")}") - } + doLast { println("jna.library.path contents: \n ${fileTree(jnaResourcesDir).files.joinToString(",\n ")}") } } -// The `processResources` task (defined by the `java-library` plug-in) consumes files in the main source set. +// The `processResources` task (defined by the `java-library` plug-in) consumes files in the main +// source set. // Add a dependency on `unzipJava`. `unzipJava` adds libmongocrypt libraries to the main source set. -tasks.processResources { - mustRunAfter(tasks.named("unzipJava")) -} +tasks.processResources { mustRunAfter(tasks.named("unzipJava")) } -tasks.register("downloadJnaLibs") { - dependsOn("downloadJava", "unzipJava") -} +tasks.register("downloadJnaLibs") { dependsOn("downloadJava", "unzipJava") } tasks.test { systemProperty("jna.debug_load", "true") systemProperty("jna.library.path", jnaResources) useJUnitPlatform() - testLogging { - events("passed", "skipped", "failed") - } + testLogging { events("passed", "skipped", "failed") } doFirst { println("jna.library.path contents:") - println(fileTree(jnaResources) { - this.setIncludes(listOf("*.*")) - }.files.joinToString(",\n ", " ")) + println(fileTree(jnaResources) { this.setIncludes(listOf("*.*")) }.files.joinToString(",\n ", " ")) } dependsOn("downloadJnaLibs", "downloadJava", "unzipJava") } tasks.withType { - description = """$description + description = + """$description | System properties: | ================= | @@ -160,28 +139,7 @@ tasks.withType { """.trimMargin() } -tasks.jar { - //NOTE this enables depending on the mongocrypt from driver-core - dependsOn("downloadJnaLibs") -} - -tasks.javadoc { - if (JavaVersion.current().isJava9Compatible) { - (options as StandardJavadocDocletOptions).addBooleanOption("html5", true) - } -} - -afterEvaluate { - tasks.jar { - manifest { - attributes( - "-exportcontents" to "com.mongodb.*;-noimport:=true", - "Automatic-Module-Name" to "com.mongodb.crypt.capi", - "Import-Package" to "org.slf4j.*;resolution:=optional,org.bson.*", - "Bundle-Name" to "MongoCrypt", - "Bundle-SymbolicName" to "com.mongodb.crypt.capi", - "Private-Package" to "" - ) - } - } +tasks.withType { + // NOTE this enables depending on the mongocrypt from driver-core + dependsOn("downloadJnaLibs") } diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index e390791d5d5..00000000000 --- a/settings.gradle +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -include ':bson' -include ':bson-record-codec' -include ':driver-benchmarks' -include ':driver-workload-executor' -include ':driver-lambda' -include ':driver-core' -include ':driver-legacy' -include ':driver-sync' -include ':driver-reactive-streams' -include ':bson-kotlin' -include ':bson-kotlinx' -include ':driver-kotlin-extensions' -include ':driver-kotlin-sync' -include ':driver-kotlin-coroutine' -include ':bson-scala' -include ':driver-scala' -include ':mongodb-crypt' -include 'util:spock' -include 'util:taglets' -include ':bom' - -if(hasProperty("includeGraalvm")) { - include ':graalvm-native-image-app' -} diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 00000000000..019d3b8290d --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,49 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +pluginManagement { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } +} + +include(":bom") + +include(":bson") +include(":bson-kotlin") +include(":bson-kotlinx") +include(":bson-record-codec") +include(":bson-scala") + +include(":driver-core") +include(":driver-sync") +include(":driver-legacy") +include(":driver-reactive-streams") +include(":mongodb-crypt") + +include(":driver-kotlin-coroutine") +include(":driver-kotlin-extensions") +include(":driver-kotlin-sync") +include(":driver-scala") + +include(":driver-benchmarks") +include(":driver-lambda") +include(":driver-workload-executor") +if (providers.gradleProperty("includeGraalvm").isPresent) { + include(":graalvm-native-image-app") +} diff --git a/util/spock/src/main/util/spock/annotations/Slow.java b/util/spock/src/main/util/spock/annotations/Slow.java deleted file mode 100644 index c3611cbb22b..00000000000 --- a/util/spock/src/main/util/spock/annotations/Slow.java +++ /dev/null @@ -1,11 +0,0 @@ -package util.spock.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD, ElementType.TYPE}) -public @interface Slow { -}