From f9553e6b485dd27f219ac44808fc954a31845765 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 14:03:02 +0200 Subject: [PATCH 01/27] Bump the version. --- version.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.gradle.kts b/version.gradle.kts index a29cf4cf19..06c4d3396c 100644 --- a/version.gradle.kts +++ b/version.gradle.kts @@ -38,7 +38,7 @@ */ /** The version of this library. */ -val base = "2.0.0-SNAPSHOT.77" +val base = "2.0.0-SNAPSHOT.78" val spineVersion: String by extra(base) val spineBaseVersion: String by extra(base) // Used by `filter-internal-javadoc.gradle`. From 140914ef2556b0515af05217205a688ee016abd3 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 14:03:43 +0200 Subject: [PATCH 02/27] Update to the latest `config`. --- buildSrc/build.gradle.kts | 21 ++ .../src/main/groovy/js/build-tasks.gradle | 2 + .../src/main/groovy/js/configure-proto.gradle | 2 + buildSrc/src/main/groovy/js/js.gradle | 2 + buildSrc/src/main/groovy/js/npm-cli.gradle | 1 + .../main/groovy/js/npm-publish-tasks.gradle | 3 + .../groovy/js/update-package-version.gradle | 3 + .../spine/internal/dependency/CheckStyle.kt | 2 +- .../io/spine/internal/dependency/Kotlin.kt | 2 +- .../io/spine/internal/dependency/Protobuf.kt | 6 + .../io/spine/internal/gradle/TaskName.kt | 59 ++++ .../io/spine/internal/gradle/base/Tasks.kt | 87 ++++++ .../io/spine/internal/gradle/java/Tasks.kt | 45 ++++ .../internal/gradle/java/publish/Tasks.kt | 45 ++++ .../io/spine/internal/gradle/javac/Javac.kt | 5 +- .../internal/gradle/javascript/JsContext.kt | 61 +++++ .../gradle/javascript/JsEnvironment.kt | 255 ++++++++++++++++++ .../internal/gradle/javascript/JsExtension.kt | 194 +++++++++++++ .../internal/gradle/javascript/plugin/Idea.kt | 64 +++++ .../gradle/javascript/plugin/JsPlugins.kt | 92 +++++++ .../internal/gradle/javascript/plugin/McJs.kt | 63 +++++ .../gradle/javascript/plugin/Protobuf.kt | 90 +++++++ .../gradle/javascript/task/Assemble.kt | 205 ++++++++++++++ .../internal/gradle/javascript/task/Check.kt | 197 ++++++++++++++ .../internal/gradle/javascript/task/Clean.kt | 124 +++++++++ .../gradle/javascript/task/IntegrationTest.kt | 127 +++++++++ .../gradle/javascript/task/JsTasks.kt | 118 ++++++++ .../gradle/javascript/task/LicenseReport.kt | 88 ++++++ .../gradle/javascript/task/Publish.kt | 194 +++++++++++++ .../gradle/javascript/task/Webpack.kt | 106 ++++++++ .../internal/gradle/kotlin/KotlinConfig.kt | 56 ++++ .../report/license/MarkdownReportRenderer.kt | 2 +- .../internal/gradle/report/license/Tasks.kt | 40 +++ .../spine/internal/markup/MarkdownDocument.kt | 10 +- config | 2 +- 35 files changed, 2362 insertions(+), 11 deletions(-) create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/TaskName.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/base/Tasks.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/java/Tasks.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/java/publish/Tasks.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsContext.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsExtension.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Idea.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/McJs.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Protobuf.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Assemble.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Check.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Clean.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/IntegrationTest.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/JsTasks.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/LicenseReport.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Publish.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Webpack.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/kotlin/KotlinConfig.kt create mode 100644 buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/Tasks.kt diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index 0686127bf0..7176b88cd1 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -60,6 +60,14 @@ val googleAuthToolVersion = "2.1.2" val licenseReportVersion = "2.0" val grGitVersion = "3.1.1" +/** + * The version of the Kotlin Gradle plugin. + * + * Please check that this value matches one defined in + * `io.spine.internal.dependency.Kotlin.version`. + */ +val kotlinVersion = "1.6.0" + /** * The version of Guava used in `buildSrc`. * @@ -78,7 +86,18 @@ val guavaVersion = "30.1.1-jre" */ val errorProneVersion = "2.0.2" +/** + * The version of Protobuf Gradle Plugin. + * + * Please keep in sync. with `io.spine.internal.dependency.Protobuf.GradlePlugin.version`. + * + * @see + * Protobuf Gradle Plugins Releases + */ +val protobufPluginVersion = "0.8.17" + dependencies { + implementation("com.fasterxml.jackson.core:jackson-databind:$jacksonVersion") implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml:$jacksonVersion") implementation("com.google.cloud.artifactregistry:artifactregistry-auth-common:$googleAuthToolVersion") { exclude(group = "com.google.guava") @@ -87,4 +106,6 @@ dependencies { api("com.github.jk1:gradle-license-report:$licenseReportVersion") implementation("org.ajoberstar.grgit:grgit-core:${grGitVersion}") implementation("net.ltgt.gradle:gradle-errorprone-plugin:${errorProneVersion}") + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}") + implementation("gradle.plugin.com.google.protobuf:protobuf-gradle-plugin:$protobufPluginVersion") } diff --git a/buildSrc/src/main/groovy/js/build-tasks.gradle b/buildSrc/src/main/groovy/js/build-tasks.gradle index 0f6c359481..dafd8b478f 100644 --- a/buildSrc/src/main/groovy/js/build-tasks.gradle +++ b/buildSrc/src/main/groovy/js/build-tasks.gradle @@ -33,6 +33,8 @@ *

This script doesn't configure Protobuf plugin and Spine's Protobuf JS plugin. */ +println("`build-tasks.gradle` script is deprecated. Please use `javascript` extension instead.") + ext { JAVA_SCRIPT_TASK_GROUP = 'JavaScript' diff --git a/buildSrc/src/main/groovy/js/configure-proto.gradle b/buildSrc/src/main/groovy/js/configure-proto.gradle index 32ee112cff..75d2950e77 100644 --- a/buildSrc/src/main/groovy/js/configure-proto.gradle +++ b/buildSrc/src/main/groovy/js/configure-proto.gradle @@ -43,6 +43,8 @@ import io.spine.internal.gradle.Scripts * the NPM packages should be published. */ +println("`configure-proto.gradle` script is deprecated. Please use `javascript` extension instead.") + ext { genProtoBaseDir = "$projectDir/generated" genProtoMain = "$genProtoBaseDir/main/js" diff --git a/buildSrc/src/main/groovy/js/js.gradle b/buildSrc/src/main/groovy/js/js.gradle index 1499346302..836bb729c0 100644 --- a/buildSrc/src/main/groovy/js/js.gradle +++ b/buildSrc/src/main/groovy/js/js.gradle @@ -39,6 +39,8 @@ *

The script is based on other scripts from `config` submodule. */ +println("`js.gradle` script is deprecated. Please use `javascript` extension instead.") + ext { srcDir = "$projectDir/main" testSrcDir = "$projectDir/test" diff --git a/buildSrc/src/main/groovy/js/npm-cli.gradle b/buildSrc/src/main/groovy/js/npm-cli.gradle index f8b1836389..c222844974 100644 --- a/buildSrc/src/main/groovy/js/npm-cli.gradle +++ b/buildSrc/src/main/groovy/js/npm-cli.gradle @@ -30,6 +30,7 @@ import org.apache.tools.ant.taskdefs.condition.Os * The script allowing to run NPM commands from Gradle. */ +println("`npm-cli.gradle` script is deprecated. Please use `javascript` extension instead.") /** * The name of an environmental variable which contains the NPM auth token. diff --git a/buildSrc/src/main/groovy/js/npm-publish-tasks.gradle b/buildSrc/src/main/groovy/js/npm-publish-tasks.gradle index 0dc7a4e367..70421e2784 100644 --- a/buildSrc/src/main/groovy/js/npm-publish-tasks.gradle +++ b/buildSrc/src/main/groovy/js/npm-publish-tasks.gradle @@ -32,6 +32,9 @@ * the NPM execution process, which is sufficient for the local development. */ +println("`npm-publish-tasks.gradle` script is deprecated. " + + "Please use `javascript` extension instead.") + apply from: "$rootDir" + io.spine.internal.gradle.Scripts.commonPath + "js/build-tasks.gradle" ext { diff --git a/buildSrc/src/main/groovy/js/update-package-version.gradle b/buildSrc/src/main/groovy/js/update-package-version.gradle index ee503e7c15..ddbd665da9 100644 --- a/buildSrc/src/main/groovy/js/update-package-version.gradle +++ b/buildSrc/src/main/groovy/js/update-package-version.gradle @@ -31,6 +31,9 @@ import groovy.json.JsonSlurper * This script declares a task to update the version in in a package.json file. */ +println("`update-package-version.gradle` script is deprecated. " + + "Please use `javascript` extension instead.") + /** * Updates the package.json version to the specified one. * diff --git a/buildSrc/src/main/kotlin/io/spine/internal/dependency/CheckStyle.kt b/buildSrc/src/main/kotlin/io/spine/internal/dependency/CheckStyle.kt index 342fecf918..c3d5156b7c 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/dependency/CheckStyle.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/dependency/CheckStyle.kt @@ -30,5 +30,5 @@ package io.spine.internal.dependency // See `io.spine.internal.gradle.checkstyle.CheckStyleConfig`. @Suppress("unused") object CheckStyle { - const val version = "8.29" + const val version = "9.1" } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/dependency/Kotlin.kt b/buildSrc/src/main/kotlin/io/spine/internal/dependency/Kotlin.kt index c4de182522..e1d2b2035a 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/dependency/Kotlin.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/dependency/Kotlin.kt @@ -30,7 +30,7 @@ package io.spine.internal.dependency // https://github.com/Kotlin object Kotlin { @Suppress("MemberVisibilityCanBePrivate") // used directly from outside - const val version = "1.5.31" + const val version = "1.6.0" const val reflect = "org.jetbrains.kotlin:kotlin-reflect:${version}" const val stdLib = "org.jetbrains.kotlin:kotlin-stdlib:${version}" const val stdLibCommon = "org.jetbrains.kotlin:kotlin-stdlib-common:${version}" diff --git a/buildSrc/src/main/kotlin/io/spine/internal/dependency/Protobuf.kt b/buildSrc/src/main/kotlin/io/spine/internal/dependency/Protobuf.kt index cccfb73c5a..aa2c6783a1 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/dependency/Protobuf.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/dependency/Protobuf.kt @@ -38,6 +38,12 @@ object Protobuf { // https://github.com/google/protobuf-gradle-plugin/releases object GradlePlugin { + /** + * The version of this plugin is already specified in `buildSrc/build.gradle.kts` file. + * Thus, when applying the plugin in projects build files, only the [id] should be used. + * + * When changing the version, also change the version used in the `build.gradle.kts`. + */ const val version = "0.8.17" const val id = "com.google.protobuf" const val lib = "com.google.protobuf:protobuf-gradle-plugin:${version}" diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/TaskName.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/TaskName.kt new file mode 100644 index 0000000000..4956a35d66 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/TaskName.kt @@ -0,0 +1,59 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle + +import kotlin.reflect.KClass +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.kotlin.dsl.named +import org.gradle.kotlin.dsl.register + +/** + * A name and a type of a Gradle task. + */ +internal class TaskName( + val value: String, + val clazz: KClass, +) { + companion object { + + fun of(name: String) = TaskName(name, Task::class) + + fun of(name: String, clazz: KClass) = TaskName(name, clazz) + } +} + +/** + * Locates [the task][TaskName] in this [TaskContainer]. + */ +internal fun TaskContainer.named(name: TaskName) = named(name.value, name.clazz) + +/** + * Registers [the task][TaskName] in this [TaskContainer]. + */ +internal fun TaskContainer.register(name: TaskName, init: T.() -> Unit) = + register(name.value, name.clazz, init) diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/base/Tasks.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/base/Tasks.kt new file mode 100644 index 0000000000..59d108430a --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/base/Tasks.kt @@ -0,0 +1,87 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.base + +import org.gradle.api.Task +import org.gradle.api.tasks.Delete +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider +import org.gradle.kotlin.dsl.named + +/** + * Locates `clean` task in this [TaskContainer]. + * + * The task deletes the build directory and everything in it, + * i.e. the path specified by the `Project.getBuildDir()` project property. + * + * @see + * Tasks | The Base Plugin + */ +val TaskContainer.clean: TaskProvider + get() = named("clean") + +/** + * Locates `check` task in this [TaskContainer]. + * + * This is a lifecycle task that performs no action itself. + * + * Plugins and build authors should attach their verification tasks, + * such as ones that run tests, to this lifecycle task using `check.dependsOn(myTask)`. + * + * @see + * Tasks | The Base Plugin + */ +val TaskContainer.check: TaskProvider + get() = named("check") + +/** + * Locates `assemble` task in this [TaskContainer]. + * + * This is a lifecycle task that performs no action itself. + * + * Plugins and build authors should attach their assembling tasks that produce distributions and + * other consumable artifacts to this lifecycle task using `assemble.dependsOn(myTask)`. + * + * @see + * Tasks | The Base Plugin + */ +val TaskContainer.assemble: TaskProvider + get() = named("assemble") + +/** + * Locates `build` task in this [TaskContainer]. + * + * Intended to build everything, including running all tests, producing the production artifacts + * and generating documentation. One will probably rarely attach concrete tasks directly + * to `build` as [assemble][io.spine.internal.gradle.base.assemble] and + * [check][io.spine.internal.gradle.base.check] are typically more appropriate. + * + * @see + * Tasks | The Base Plugin + */ +val TaskContainer.build: TaskProvider + get() = named("build") diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/Tasks.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/Tasks.kt new file mode 100644 index 0000000000..9d1b49a550 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/Tasks.kt @@ -0,0 +1,45 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.java + +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider +import org.gradle.api.tasks.testing.Test +import org.gradle.kotlin.dsl.named + +/** + * Locates `test` task in this [TaskContainer]. + * + * Runs the unit tests using JUnit or TestNG. + * + * Depends on `testClasses`, and all tasks which produce the test runtime classpath. + * + * @see + * Tasks | The Java Plugin + */ +val TaskContainer.test: TaskProvider + get() = named("test") diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/publish/Tasks.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/publish/Tasks.kt new file mode 100644 index 0000000000..46f339dca6 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/java/publish/Tasks.kt @@ -0,0 +1,45 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.java.publish + +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Locates `publish` task in this [TaskContainer]. + * + * This task publishes all defined publications to all defined repositories. To achieve that, + * the task depends on all `publish`*PubName*`PublicationTo`*RepoName*`Repository` tasks. + * + * Please note, task execution would not copy publications to the local Maven cache. + * + * @see + * Tasks | Maven Publish Plugin + */ +internal val TaskContainer.publish: TaskProvider + get() = named("publish") diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javac/Javac.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javac/Javac.kt index 2c4094097d..210010ed27 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javac/Javac.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javac/Javac.kt @@ -51,10 +51,11 @@ import org.gradle.process.CommandLineArgumentProvider * } *``` */ +@Suppress("unused") fun JavaCompile.configureJavac() { with(options) { encoding = JavacConfig.SOURCE_FILES_ENCODING - compilerArgumentProviders.add(JavacConfig.ARGUMENTS) + compilerArgumentProviders.add(JavacConfig.COMMAND_LINE) } } @@ -63,7 +64,7 @@ fun JavaCompile.configureJavac() { */ private object JavacConfig { const val SOURCE_FILES_ENCODING = "UTF-8" - val ARGUMENTS = CommandLineArgumentProvider { + val COMMAND_LINE = CommandLineArgumentProvider { listOf( // Protobuf Compiler generates the code, which uses the deprecated `PARSER` field. diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsContext.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsContext.kt new file mode 100644 index 0000000000..84fc2ddd8e --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsContext.kt @@ -0,0 +1,61 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript + +import java.io.File +import org.gradle.api.Project + +/** + * Provides access to the current [JsEnvironment] and shortcuts for running `npm` tool. + */ +open class JsContext(jsEnv: JsEnvironment, internal val project: Project) + : JsEnvironment by jsEnv +{ + /** + * Executes `npm` command in a separate process. + * + * [JsEnvironment.projectDir] is used as a working directory. + */ + fun npm(vararg args: String) = projectDir.npm(*args) + + /** + * Executes `npm` command in a separate process. + * + * This [File] is used as a working directory. + */ + fun File.npm(vararg args: String) = project.exec { + + workingDir(this@npm) + commandLine(npmExecutable) + args(*args) + + // Using private packages in a CI/CD workflow | npm Docs + // https://docs.npmjs.com/using-private-packages-in-a-ci-cd-workflow + + environment["NPM_TOKEN"] = npmAuthToken + } +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt new file mode 100644 index 0000000000..79b2259b4b --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsEnvironment.kt @@ -0,0 +1,255 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript + +import java.io.File +import org.apache.tools.ant.taskdefs.condition.Os + +/** + * Describes the environment in which JavaScript code is assembled and processed during the build. + * + * Consists of three parts describing: + * + * 1. A module itself. + * 2. Tools and their input/output files. + * 3. Code generation. + */ +interface JsEnvironment { + + /* + * A module itself + ******************/ + + /** + * Module's root catalog. + */ + val projectDir: File + + /** + * Module's version. + */ + val moduleVersion: String + + /** + * Module's production sources directory. + * + * Default value: "$projectDir/main". + */ + val srcDir: File + get() = projectDir.resolve("main") + + /** + * Module's test sources directory. + * + * Default value: "$projectDir/test". + */ + val testSrcDir: File + get() = projectDir.resolve("test") + + /** + * A directory which all artifacts are generated into. + * + * Default value: "$projectDir/build". + */ + val buildDir: File + get() = projectDir.resolve("build") + + /** + * A directory where artifacts for further publishing would be prepared. + * + * Default value: "$buildDir/npm-publication". + */ + val publicationDir: File + get() = buildDir.resolve("npm-publication") + + /* + * Tools and their input/output files + *************************************/ + + /** + * Name of an executable for running `npm`. + * + * Default value: + * + * 1. "nmp.cmd" for Windows. + * 2. "npm" for other OSs. + */ + val npmExecutable: String + get() = if (isWindows()) "npm.cmd" else "npm" + + /** + * An access token that allows installation and/or publishing modules. + * + * During installation a token is required only if dependencies from private + * repositories are used. + * + * Default value is read from the environmental variable - `NPM_TOKEN`. + * "PUBLISHING_FORBIDDEN" stub value would be assigned in case `NPM_TOKEN` variable is not set. + * + * See [Creating and viewing access tokens | npm Docs](https://docs.npmjs.com/creating-and-viewing-access-tokens). + */ + val npmAuthToken: String + get() = System.getenv("NPM_TOKEN") ?: "PUBLISHING_FORBIDDEN" + + /** + * A directory where `npm` puts downloaded module's dependencies. + * + * Default value: "$projectDir/node_modules". + */ + val nodeModules: File + get() = projectDir.resolve("node_modules") + + /** + * Module's descriptor used by `npm`. + * + * Default value: "$projectDir/package.json". + */ + val packageJson: File + get() = projectDir.resolve("package.json") + + /** + * `npm` gets its configuration settings from the command line, environment variables, + * and `npmrc` file. + * + * Default value: "$projectDir/.npmrc". + * + * See [npmrc | npm Docs](https://docs.npmjs.com/cli/v8/configuring-npm/npmrc). + */ + val npmrc: File + get() = projectDir.resolve(".npmrc") + + /** + * A cache directory in which `nyc` tool outputs raw coverage report. + * + * Default value: "$projectDir/.nyc_output". + * + * See [istanbuljs/nyc](https://github.com/istanbuljs/nyc). + */ + val nycOutput: File + get() = projectDir.resolve(".nyc_output") + + /** + * A directory in which `webpack` would put a ready-to-use bundle. + * + * Default value: "$projectDir/dist" + * + * See [webpack - npm](https://www.npmjs.com/package/webpack). + */ + val webpackOutput: File + get() = projectDir.resolve("dist") + + /** + * A directory where bundled artifacts for further publishing would be prepared. + * + * Default value: "$publicationDir/dist". + */ + val webpackPublicationDir: File + get() = publicationDir.resolve("dist") + + /* + * Code generation + ******************/ + + /** + * Name of a directory that contains generated code. + * + * Default value: "proto". + */ + val genProtoDirName: String + get() = "proto" + + /** + * Directory with production Protobuf messages compiled into JavaScript. + * + * Default value: "$srcDir/$genProtoDirName". + */ + val genProtoMain: File + get() = srcDir.resolve(genProtoDirName) + + /** + * Directory with test Protobuf messages compiled into JavaScript. + * + * Default value: "$testSrcDir/$genProtoDirName". + */ + val genProtoTest: File + get() = testSrcDir.resolve(genProtoDirName) +} + +/** + * Allows overriding [JsEnvironment]'s defaults. + * + * All of declared properties can be split into two groups: + * + * 1. The ones that *define* something - can be overridden. + * 2. The ones that *describe* something - can NOT be overridden. + * + * Overriding a "defining" property affects the way `npm` tool works. + * In contrary, overriding a "describing" property does not affect the tool. + * Such properties just describe how the used tool works. + * + * Therefore, overriding of "describing" properties leads to inconsistency with expectations. + * + * The next properties could not be overridden: + * + * 1. [JsEnvironment.nodeModules]. + * 2. [JsEnvironment.packageJson]. + * 3. [JsEnvironment.npmrc]. + * 4. [JsEnvironment.nycOutput]. + */ +class ConfigurableJsEnvironment(initialEnvironment: JsEnvironment) + : JsEnvironment by initialEnvironment +{ + /* + * A module itself + ******************/ + + override var projectDir = initialEnvironment.projectDir + override var moduleVersion = initialEnvironment.moduleVersion + override var srcDir = initialEnvironment.srcDir + override var testSrcDir = initialEnvironment.testSrcDir + override var buildDir = initialEnvironment.buildDir + override var publicationDir = initialEnvironment.publicationDir + + /* + * Tools and their input/output files + *************************************/ + + override var npmExecutable = initialEnvironment.npmExecutable + override var npmAuthToken = initialEnvironment.npmAuthToken + override var webpackOutput = initialEnvironment.webpackOutput + override var webpackPublicationDir = initialEnvironment.webpackPublicationDir + + /* + * Code generation + ******************/ + + override var genProtoDirName = initialEnvironment.genProtoDirName + override var genProtoMain = initialEnvironment.genProtoMain + override var genProtoTest = initialEnvironment.genProtoTest +} + +internal fun isWindows(): Boolean = Os.isFamily(Os.FAMILY_WINDOWS) diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsExtension.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsExtension.kt new file mode 100644 index 0000000000..de5aec18e9 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/JsExtension.kt @@ -0,0 +1,194 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript + +import io.spine.internal.gradle.javascript.task.JsTasks +import io.spine.internal.gradle.javascript.plugin.JsPlugins +import org.gradle.api.Project +import org.gradle.kotlin.dsl.create +import org.gradle.kotlin.dsl.extra +import org.gradle.kotlin.dsl.findByType + +/** + * Configures [JsExtension] that facilitates configuration of Gradle tasks and plugins + * to build JavaScripts projects. + * + * The whole structure of the extension looks as follows: + * + * ``` + * javascript { + * environment { + * // ... + * } + * tasks { + * // ... + * } + * plugins { + * // ... + * } + * } + * ``` + * + * ### Environment + * + * One of the main features of this extension is [JsEnvironment]. Environment describes a module + * itself, used tools with their input/output files, code generation. + * + * The extension is shipped with a pre-configured environment. So, no pre-configuration is required. + * Most properties in [JsEnvironment] have calculated defaults right in the interface. + * Only two properties need explicit override. + * + * The extension defines them as follows: + * + * 1. [JsEnvironment.projectDir] –> `project.projectDir`. + * 2. [JsEnvironment.moduleVersion] —> `project.extra["versionToPublishJs"]`. + * + * There are two ways to modify the environment: + * + * 1. Update [JsEnvironment] directly. Go with this option when it is a global change + * that should affect all projects which use this extension. + * 2. Use [JsExtension.environment] scope — for temporary and custom overridings. + * + * An example of a property overriding: + * + * ``` + * javascript { + * environment { + * moduleVersion = "$moduleVersion-SPECIAL_EDITION" + * } + * } + * ``` + * + * Please note, environment should be set up firstly to have the effect on the parts + * of the extension that use it. + * + * ### Tasks and Plugins + * + * The spirit of tasks configuration in this extension is extracting the code that defines and + * registers tasks into extension functions upon `JsTasks` in `buildSrc`. Those extensions should be + * named after a task it registers or a task group if several tasks are registered at once. + * Then this extension is called in a project's `build.gradle.kts`. + * + * `JsTasks` and `JsPlugins` scopes extend [JsContext] which provides access + * to the current [JsEnvironment] and shortcuts for running `npm` tool. + * + * Below is the simplest example of how to create a primitive `printNpmVersion` task. + * + * Firstly, a corresponding extension function should be defined in `buildSrc`: + * + * ``` + * fun JsTasks.printNpmVersion() = + * register("printNpmVersion") { + * doLast { + * npm("--version") + * } + * } + * ``` + * + * Secondly, in a project's `build.gradle.kts` this extension is called: + * + * ``` + * javascript { + * tasks { + * printNpmVersion() + * } + * } + * ``` + * + * An extension function is not restricted to register exactly one task. If several tasks can + * be grouped into a logical bunch, they should be registered together: + * + * ``` + * fun JsTasks.build() { + * assembleJs() + * testJs() + * generateCoverageReport() + * } + * + * private fun JsTasks.assembleJs() = ... + * + * private fun JsTasks.testJs() = ... + * + * private fun JsTasks.generateCoverageReport() = ... + * ``` + * + * This section is mostly dedicated to tasks. But tasks and plugins are configured + * in a very similar way. So, everything above is also applicable to plugins. More detailed + * guides can be found in docs to `JsTasks` and `JsPlugins`. + * + * @see [ConfigurableJsEnvironment] + * @see [JsTasks] + * @see [JsPlugins] + */ +fun Project.javascript(configuration: JsExtension.() -> Unit) { + extensions.run { + configuration.invoke( + findByType() ?: create("jsExtension", project) + ) + } +} + +/** + * Scope for performing JavaScript-related configuration. + * + * @see [javascript] + */ +open class JsExtension(internal val project: Project) { + + private val configurableEnvironment = ConfigurableJsEnvironment( + object : JsEnvironment { + override val projectDir = project.projectDir + override val moduleVersion = project.extra["versionToPublishJs"].toString() + } + ) + + val environment: JsEnvironment = configurableEnvironment + val tasks: JsTasks = JsTasks(environment, project) + val plugins: JsPlugins = JsPlugins(environment, project) + + /** + * Overrides default values of [JsEnvironment]. + * + * Please note, environment should be set up firstly to have the effect on the parts + * of the extension that use it. + */ + fun environment(overridings: ConfigurableJsEnvironment.() -> Unit) = + configurableEnvironment.run(overridings) + + /** + * Configures [JavaScript-related tasks][JsTasks]. + */ + fun tasks(configurations: JsTasks.() -> Unit) = + tasks.run(configurations) + + /** + * Configures [JavaScript-related plugins][JsPlugins]. + */ + fun plugins(configurations: JsPlugins.() -> Unit) = + plugins.run(configurations) + +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Idea.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Idea.kt new file mode 100644 index 0000000000..155bdebabe --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Idea.kt @@ -0,0 +1,64 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.plugin + +import org.gradle.kotlin.dsl.configure +import org.gradle.plugins.ide.idea.model.IdeaModel + +/** + * Applies and configures `idea` plugin to work with a JavaScript module. + * + * In particular, this method: + * + * 1. Specifies directories for production and test sources. + * 2. Excludes directories with generated code and build artifacts. + * + * @see JsPlugins + */ +fun JsPlugins.idea() { + + plugins { + apply("org.gradle.idea") + } + + extensions.configure { + + module { + sourceDirs.add(srcDir) + testSourceDirs.add(testSrcDir) + + excludeDirs.addAll( + listOf( + nodeModules, + nycOutput, + genProtoMain, + genProtoTest + ) + ) + } + } +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt new file mode 100644 index 0000000000..3a472cfccd --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt @@ -0,0 +1,92 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.plugin + +import io.spine.internal.gradle.javascript.JsContext +import io.spine.internal.gradle.javascript.JsEnvironment +import org.gradle.api.Project +import org.gradle.api.plugins.ExtensionContainer +import org.gradle.api.plugins.PluginContainer +import org.gradle.api.tasks.TaskContainer + +/** + * A scope for applying and configuring JavaScript-related plugins. + * + * The scope extends [JsContext] and provides shortcuts for key project's containers: + * + * 1. [plugins]. + * 2. [extensions]. + * 3. [tasks]. + * + * Let's imagine one wants to apply and configure `FooBar` plugin. To do that, several steps + * should be completed: + * + * 1. Declare the corresponding extension function upon [JsPlugins] named after the plugin. + * 2. Apply and configure the plugin inside that function. + * 3. Call the resulted extension in your `build.gradle.kts` file. + * + * Here's an example of `javascript/plugin/FooBar.kt`: + * + * ``` + * fun JsPlugins.fooBar() { + * plugins.apply("com.fooBar") + * extensions.configure { + * // ... + * } + * } + * ``` + * + * And here's how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.plugins.fooBar + * + * // ... + * + * javascript { + * plugins { + * fooBar() + * } + * } + * ``` + */ +class JsPlugins(jsEnv: JsEnvironment, project: Project) : JsContext(jsEnv, project) { + + internal val plugins = project.plugins + internal val extensions = project.extensions + internal val tasks = project.tasks + + internal fun plugins(configurations: PluginContainer.() -> Unit) = + plugins.run(configurations) + + internal fun extensions(configurations: ExtensionContainer.() -> Unit) = + extensions.run(configurations) + + internal fun tasks(configurations: TaskContainer.() -> Unit) = + tasks.run(configurations) +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/McJs.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/McJs.kt new file mode 100644 index 0000000000..845d7633d4 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/McJs.kt @@ -0,0 +1,63 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.plugin + +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider +import org.gradle.kotlin.dsl.withGroovyBuilder + +/** + * Applies `mc-js` plugin and specifies directories for generated code. + * + * @see JsPlugins + */ +fun JsPlugins.mcJs() { + + plugins { + apply("io.spine.mc-js") + } + + // Temporarily use GroovyInterop. + // Currently, it is not possible to obtain `McJsPlugin` on the classpath of `buildSrc`. + // See issue: https://github.com/SpineEventEngine/config/issues/298 + + project.withGroovyBuilder { + "protoJs" { + setProperty("generatedMainDir", genProtoMain) + setProperty("generatedTestDir", genProtoTest) + } + } +} + +/** + * Locates `generateJsonParsers` in this [TaskContainer]. + * + * The task generates JSON-parsing code for JavaScript messages compiled from Protobuf. + */ +val TaskContainer.generateJsonParsers: TaskProvider + get() = named("generateJsonParsers") diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Protobuf.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Protobuf.kt new file mode 100644 index 0000000000..8c71e0ff1f --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/Protobuf.kt @@ -0,0 +1,90 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.plugin + +import com.google.protobuf.gradle.builtins +import com.google.protobuf.gradle.generateProtoTasks +import com.google.protobuf.gradle.id +import com.google.protobuf.gradle.protobuf +import com.google.protobuf.gradle.protoc +import com.google.protobuf.gradle.remove +import io.spine.internal.dependency.Protobuf + +/** + * Applies and configures `protobuf` plugin to work with a JavaScript module. + * + * In particular, this method: + * + * 1. Specifies an executable for `protoc` compiler. + * 2. Configures `GenerateProtoTask`. + * + * @see JsPlugins + */ +fun JsPlugins.protobuf() { + + plugins { + apply(Protobuf.GradlePlugin.id) + } + + project.protobuf { + + generatedFilesBaseDir = projectDir.path + + protoc { + artifact = Protobuf.compiler + } + + generateProtoTasks { + all().forEach { task -> + + task.builtins { + + // Do not use java builtin output in this project. + + remove("java") + + // For information on JavaScript code generation please see + // https://github.com/google/protobuf/blob/master/js/README.md + + id("js") { + option("import_style=commonjs") + outputSubDir = genProtoDirName + } + } + + val sourceSet = task.sourceSet.name + val testClassifier = if (sourceSet == "test") "_test" else "" + val artifact = "${project.group}_${project.name}_${moduleVersion}" + val descriptor = "$artifact$testClassifier.desc" + + task.generateDescriptorSet = true + task.descriptorSetOptions.path = + "${projectDir}/build/descriptors/${sourceSet}/${descriptor}" + } + } + } +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Assemble.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Assemble.kt new file mode 100644 index 0000000000..5ae6b1bf9e --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Assemble.kt @@ -0,0 +1,205 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.node.ObjectNode +import com.google.protobuf.gradle.GenerateProtoTask +import io.spine.internal.gradle.base.assemble +import io.spine.internal.gradle.javascript.plugin.generateJsonParsers +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider +import org.gradle.kotlin.dsl.withType + +/** + * Registers tasks for assembling JavaScript artifacts. + * + * Please note, this task group depends on [mc-js][io.spine.internal.gradle.javascript.plugin.mcJs] + * and [protobuf][io.spine.internal.gradle.javascript.plugin.protobuf]` plugins. Therefore, + * these plugins should be applied in the first place. + * + * List of tasks to be created: + * + * 1. [TaskContainer.assembleJs]. + * 2. [TaskContainer.compileProtoToJs]. + * 3. [TaskContainer.installNodePackages]. + * 4. [TaskContainer.updatePackageVersion]. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.assemble + * + * // ... + * + * javascript { + * tasks { + * assemble() + * } + * } + * ``` + * + * @param configuration any additional configuration related to the module's assembling. + */ +fun JsTasks.assemble(configuration: JsTasks.() -> Unit = {}) { + + installNodePackages() + + compileProtoToJs().also { + generateJsonParsers.configure { + dependsOn(it) + } + } + + updatePackageVersion() + + assembleJs().also { + assemble.configure { + dependsOn(it) + } + } + + configuration() +} + +private val assembleJsName = TaskName.of("assembleJs") + +/** + * Locates `assembleJs` task in this [TaskContainer]. + * + * It is a lifecycle task that produces consumable JavaScript artifacts. + */ +val TaskContainer.assembleJs: TaskProvider + get() = named(assembleJsName) + +private fun JsTasks.assembleJs() = + register(assembleJsName) { + + description = "Assembles JavaScript sources into consumable artifacts." + group = JsTasks.Group.assemble + + dependsOn( + installNodePackages, + compileProtoToJs, + updatePackageVersion, + generateJsonParsers + ) + } + +private val compileProtoToJsName = TaskName.of("compileProtoToJs") + +/** + * Locates `compileProtoToJs` task in this [TaskContainer]. + * + * The task is responsible for compiling Protobuf messages into JavaScript. It aggregates the tasks + * provided by `protobuf` plugin that perform actual compilation. + */ +val TaskContainer.compileProtoToJs: TaskProvider + get() = named(compileProtoToJsName) + +private fun JsTasks.compileProtoToJs() = + register(compileProtoToJsName) { + + description = "Compiles Protobuf messages into JavaScript." + group = JsTasks.Group.assemble + + withType() + .forEach { dependsOn(it) } + } + +private val installNodePackagesName = TaskName.of("installNodePackages") + +/** + * Locates `installNodePackages` task in this [TaskContainer]. + * + * The task installs Node packages which this module depends on using `npm install` command. + * + * The `npm install` command is executed with the vulnerability check disabled since + * it cannot fail the task execution despite on vulnerabilities found. + * + * To check installed Node packages for vulnerabilities execute + * [TaskContainer.auditNodePackages] task. + * + * See [npm-install | npm Docs](https://docs.npmjs.com/cli/v8/commands/npm-install). + */ +val TaskContainer.installNodePackages: TaskProvider + get() = named(installNodePackagesName) + +private fun JsTasks.installNodePackages() = + register(installNodePackagesName) { + + description = "Installs module`s Node dependencies." + group = JsTasks.Group.assemble + + inputs.file(packageJson) + outputs.dir(nodeModules) + + doLast { + npm("set", "audit", "false") + npm("install") + } + } + +private val updatePackageVersionName = TaskName.of("updatePackageVersion") + +/** + * Locates `updatePackageVersion` task in this [TaskContainer]. + * + * The task sets the module's version in `package.json` to the value of + * [moduleVersion][io.spine.internal.gradle.javascript.JsEnvironment.moduleVersion] + * specified in the current `JsEnvironment`. + */ +val TaskContainer.updatePackageVersion: TaskProvider + get() = named(updatePackageVersionName) + +private fun JsTasks.updatePackageVersion() = + register(updatePackageVersionName) { + + description = "Sets a module's version in `package.json`." + group = JsTasks.Group.assemble + + doLast { + val objectNode = ObjectMapper() + .readValue(packageJson, ObjectNode::class.java) + .put("version", moduleVersion) + + packageJson.writeText( + + // We are going to stick to JSON formatting used by `npm` itself. + // So that modifying the line with the version would ONLY affect a single line + // when comparing two files i.e. in Git. + + (objectNode.toPrettyString() + '\n') + .replace("\" : ", "\": ") + ) + } + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Check.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Check.kt new file mode 100644 index 0000000000..bbb38c4746 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Check.kt @@ -0,0 +1,197 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.base.check +import io.spine.internal.gradle.java.test +import io.spine.internal.gradle.javascript.isWindows +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Registers tasks for verifying a JavaScript module. + * + * Please note, this task group depends on [assemble] tasks. Therefore, assembling tasks should + * be applied in the first place. + * + * List of tasks to be created: + * + * 1. [TaskContainer.checkJs]. + * 2. [TaskContainer.auditNodePackages]. + * 3. [TaskContainer.testJs]. + * 4. [TaskContainer.coverageJs]. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.assemble + * import io.spine.internal.gradle.javascript.task.check + * + * // ... + * + * javascript { + * tasks { + * assemble() + * check() + * } + * } + * ``` + * + * @param configuration any additional configuration related to the module's verification. + */ +fun JsTasks.check(configuration: JsTasks.() -> Unit = {}) { + + auditNodePackages() + coverageJs() + testJs() + + checkJs().also { + check.configure { + dependsOn(it) + } + } + + configuration() +} + +private val checkJsName = TaskName.of("checkJs") + +/** + * Locates `checkJs` task in this [TaskContainer]. + * + * The task runs tests, audits NPM modules and creates a test-coverage report. + */ +val TaskContainer.checkJs: TaskProvider + get() = named(checkJsName) + +private fun JsTasks.checkJs() = + register(checkJsName) { + + description = "Runs tests, audits NPM modules and creates a test-coverage report." + group = JsTasks.Group.check + + dependsOn( + auditNodePackages, + coverageJs, + testJs, + ) + } + +private val auditNodePackagesName = TaskName.of("auditNodePackages") + +/** + * Locates `auditNodePackages` task in this [TaskContainer]. + * + * The task audits the module dependencies using the `npm audit` command. + * + * The `audit` command submits a description of the dependencies configured in the module + * to a public registry and asks for a report of known vulnerabilities. If any are found, + * then the impact and appropriate remediation will be calculated. + * + * @see npm-audit | npm Docs + */ +val TaskContainer.auditNodePackages: TaskProvider + get() = named(auditNodePackagesName) + +private fun JsTasks.auditNodePackages() = + register(auditNodePackagesName) { + + description = "Audits the module's Node dependencies." + group = JsTasks.Group.check + + inputs.dir(nodeModules) + + doLast { + + // `critical` level is set as the minimum level of vulnerability for `npm audit` + // to exit with a non-zero code. + + npm("set", "audit-level", "critical") + + try { + npm("audit") + } catch (ignored: Exception) { + npm("audit", "--registry", "https://registry.npmjs.eu") + } + } + + dependsOn(installNodePackages) + } + +private val coverageJsName = TaskName.of("coverageJs") + +/** + * Locates `coverageJs` task in this [TaskContainer]. + * + * The task runs the JavaScript tests and collects the code coverage. + */ +val TaskContainer.coverageJs: TaskProvider + get() = named(coverageJsName) + +private fun JsTasks.coverageJs() = + register(coverageJsName) { + + description = "Runs the JavaScript tests and collects the code coverage." + group = JsTasks.Group.check + + outputs.dir(nycOutput) + + doLast { + npm("run", if (isWindows()) "coverage:win" else "coverage:unix") + } + + dependsOn(assembleJs) + } + +private val testJsName = TaskName.of("testJs") + +/** + * Locates `testJs` task in this [TaskContainer]. + * + * The task runs JavaScript tests. + */ +val TaskContainer.testJs: TaskProvider + get() = named(testJsName) + +private fun JsTasks.testJs() = + register(testJsName) { + + description = "Runs JavaScript tests." + group = JsTasks.Group.check + + doLast { + npm("run", "test") + } + + dependsOn(assembleJs) + mustRunAfter(test) + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Clean.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Clean.kt new file mode 100644 index 0000000000..a927757d16 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Clean.kt @@ -0,0 +1,124 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.base.clean +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.tasks.Delete +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Registers tasks for deleting output of JavaScript builds. + * + * Please note, this task group depends on [assemble] tasks. Therefore, assembling tasks should + * be applied in the first place. + * + * List of tasks to be created: + * + * 1. [TaskContainer.cleanJs]. + * 2. [TaskContainer.cleanGenerated]. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.assemble + * import io.spine.internal.gradle.javascript.task.clean + * + * // ... + * + * javascript { + * tasks { + * assemble() + * clean() + * } + * } + * ``` + */ +fun JsTasks.clean() { + + cleanGenerated() + + cleanJs().also { + clean.configure { + dependsOn(it) + } + } +} + +private val cleanJsName = TaskName.of("cleanJs", Delete::class) + +/** + * Locates `cleanJs` task in this [TaskContainer]. + * + * The task deletes output of `assembleJs` task and output of its dependants. + */ +val TaskContainer.cleanJs: TaskProvider + get() = named(cleanJsName) + +private fun JsTasks.cleanJs() = + register(cleanJsName) { + + description = "Cleans output of `assembleJs` task and output of its dependants." + group = JsTasks.Group.clean + + delete( + assembleJs.map { it.outputs }, + compileProtoToJs.map { it.outputs }, + installNodePackages.map { it.outputs }, + ) + + dependsOn( + cleanGenerated + ) + } + +private val cleanGeneratedName = TaskName.of("cleanGenerated", Delete::class) + +/** + * Locates `cleanGenerated` task in this [TaskContainer]. + * + * The task deletes directories with generated code and reports. + */ +val TaskContainer.cleanGenerated: TaskProvider + get() = named(cleanGeneratedName) + +private fun JsTasks.cleanGenerated() = + register(cleanGeneratedName) { + + description = "Cleans generated code and reports." + group = JsTasks.Group.clean + + delete( + genProtoMain, + genProtoTest, + nycOutput, + ) + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/IntegrationTest.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/IntegrationTest.kt new file mode 100644 index 0000000000..f1455e1649 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/IntegrationTest.kt @@ -0,0 +1,127 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.base.build +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +private val integrationTestName = TaskName.of("integrationTest") + +/** + * Locates `integrationTest` task in this [TaskContainer]. + * + * The task runs integration tests of the `spine-web` library against + * a sample Spine-based application. + * + * A sample Spine-based application is run from the `test-app` module before integration + * tests and is stopped as the tests complete. + * + * See also: `./integration-tests/README.MD` + */ +val TaskContainer.integrationTest: TaskProvider + get() = named(integrationTestName) + +/** + * Registers [TaskContainer.integrationTest] task. + * + * The task runs integration tests of the `spine-web` library against + * a sample Spine-based application. + * + * Please note, this task depends on [assemble] and `client-js:publishJsLocally` tasks. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.integrationTest + * + * // ... + * + * javascript { + * tasks { + * assemble() + * integrationTest() + * } + * } + * ``` + */ +fun JsTasks.integrationTest() { + + linkSpineWebModule() + + register(integrationTestName) { + + // Find a way to run the same tests against `spine-web` in `client-js` module + // to recover coverage. + // See issue: https://github.com/SpineEventEngine/web/issues/96 + + description = "Runs integration tests of the `spine-web` library " + + "against the sample application." + group = JsTasks.Group.check + + dependsOn(build, linkSpineWebModule, ":test-app:appBeforeIntegrationTest") + + doLast { + npm("run", "test") + } + + finalizedBy(":test-app:appAfterIntegrationTest") + } +} + +private val linkSpineWebModuleName = TaskName.of("linkSpineWebModule") + +/** + * Locates `linkSpineWebModule` task in this [TaskContainer]. + * + * The task installs unpublished artifact of `spine-web` library as a module dependency. + * + * Creates a symbolic link from globally-installed `spine-web` library to `node_modules` of + * the current project. + * + * See also: [npm-link | npm Docs](https://docs.npmjs.com/cli/v8/commands/npm-link) + */ +val TaskContainer.linkSpineWebModule: TaskProvider + get() = named(linkSpineWebModuleName) + +private fun JsTasks.linkSpineWebModule() = + register(linkSpineWebModuleName) { + + description = "Install unpublished artifact of `spine-web` library as a module dependency." + group = JsTasks.Group.assemble + + dependsOn(":client-js:publishJsLocally") + + doLast { + npm("run", "installLinkedLib") + } + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/JsTasks.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/JsTasks.kt new file mode 100644 index 0000000000..98ca8b7000 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/JsTasks.kt @@ -0,0 +1,118 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.javascript.JsEnvironment +import io.spine.internal.gradle.javascript.JsContext +import org.gradle.api.Project +import org.gradle.api.tasks.TaskContainer + +/** + * A scope for registering and configuring JavaScript-related tasks. + * + * The scope provides: + * + * 1. Access to the current [JsContext]. + * 2. Project's [TaskContainer]. + * 3. Default task groups. + * + * Supposing, one needs to create a new task that would participate in building. Let the task name + * be `bundleJs`. To do that, several steps should be completed: + * + * 1. Define the task name and type using [TaskName][io.spine.internal.gradle.TaskName]. + * 2. Create a public typed reference for the task upon [TaskContainer]. It would facilitate + * referencing to the new task, so that external tasks could depend on it. This reference + * should be documented. + * 3. Implement an extension upon [JsTasks] to register the task. + * 4. Call the resulted extension from `build.gradle.kts`. + * + * Here's an example of `bundleJs()` extension: + * + * ``` + * import io.spine.internal.gradle.named + * import io.spine.internal.gradle.register + * import io.spine.internal.gradle.TaskName + * import org.gradle.api.Task + * import org.gradle.api.tasks.TaskContainer + * import org.gradle.api.tasks.Exec + * + * // ... + * + * private val bundleJsName = TaskName.of("bundleJs", Exec::class) + * + * /** + * * Locates `bundleJs` task in this [TaskContainer]. + * * + * * The task bundles JS sources using `webpack` tool. + * */ + * val TaskContainer.bundleJs: TaskProvider + * get() = named(bundleJsName) + * + * fun JsTasks.bundleJs() = + * register(bundleJsName) { + * + * description = "Bundles JS sources using `webpack` tool." + * group = JsTasks.Group.build + * + * // ... + * } + * ``` + * + * And here's how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.bundleJs + * + * // ... + * + * javascript { + * tasks { + * bundleJs() + * } + * } + * ``` + * + * Declaring typed references upon [TaskContainer] is optional. But it is highly encouraged + * to reference other tasks by such extensions instead of hard-typed string values. + */ +class JsTasks(jsEnv: JsEnvironment, project: Project) + : JsContext(jsEnv, project), TaskContainer by project.tasks +{ + /** + * Default task groups for tasks that participate in building a JavaScript module. + * + * @see [org.gradle.api.Task.getGroup] + */ + internal object Group { + const val assemble = "JavaScript/Assemble" + const val check = "JavaScript/Check" + const val clean = "JavaScript/Clean" + const val build = "JavaScript/Build" + const val publish = "JavaScript/Publish" + } +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/LicenseReport.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/LicenseReport.kt new file mode 100644 index 0000000000..cc1fa43809 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/LicenseReport.kt @@ -0,0 +1,88 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.report.license.generateLicenseReport +import io.spine.internal.gradle.TaskName +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Registers [npmLicenseReport] task for including NPM dependencies into license reports. + * + * The task depends on [generateLicenseReport]. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.clean + * + * // ... + * + * javascript { + * tasks { + * licenseReport() + * } + * } + * ``` + */ +fun JsTasks.licenseReport() { + npmLicenseReport().also { + generateLicenseReport.configure { + finalizedBy(it) + } + } +} + +private val npmLicenseReportName = TaskName.of("npmLicenseReport") + +/** + * Locates `npmLicenseReport` task in this [TaskContainer]. + * + * The task generates the report on NPM dependencies and their licenses. + */ +val TaskContainer.npmLicenseReport: TaskProvider + get() = named(npmLicenseReportName) + +private fun JsTasks.npmLicenseReport() = + register(npmLicenseReportName) { + + description = "Generates the report on NPM dependencies and their licenses." + group = JsTasks.Group.build + + doLast { + + // The script below generates license report for NPM dependencies and appends it + // to the report for Java dependencies generated by `generateLicenseReport` task. + + npm("run", "license-report") + } + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Publish.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Publish.kt new file mode 100644 index 0000000000..16b1df74bc --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Publish.kt @@ -0,0 +1,194 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.java.publish.publish +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Registers tasks for publishing a JavaScript module. + * + * Please note, this task group depends on [assemble] tasks. Therefore, assembling tasks should + * be applied in the first place. + * + * List of tasks to be created: + * + * 1. [TaskContainer.publishJs]. + * 2. [TaskContainer.publishJsLocally]. + * 3. [TaskContainer.prepareJsPublication]. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.assemble + * import io.spine.internal.gradle.javascript.task.publish + * + * // ... + * + * javascript { + * tasks { + * assemble() + * publish() + * } + * } + * ``` + */ +fun JsTasks.publish() { + + transpileSources() + prepareJsPublication() + publishJsLocally() + + publishJs().also { + publish.configure { + dependsOn(it) + } + } +} + +private val transpileSourcesName = TaskName.of("transpileSources") + +/** + * Locates `transpileSources` task in this [TaskContainer]. + * + * The task transpiles JavaScript sources using Babel before their publishing. + */ +val TaskContainer.transpileSources: TaskProvider + get() = named(transpileSourcesName) + +private fun JsTasks.transpileSources() = + register(transpileSourcesName) { + + description = "Transpiles JavaScript sources using Babel before their publishing." + group = JsTasks.Group.publish + + doLast { + npm("run", "transpile-before-publish") + } + } + +private val prepareJsPublicationName = TaskName.of("prepareJsPublication") + +/** + * Locates `prepareJsPublication` task in this [TaskContainer]. + * + * This is a lifecycle task that prepares the NPM package in + * [publicationDirectory][io.spine.internal.gradle.javascript.JsEnvironment.publicationDir] + * of the current `JsEnvironment`. + */ +val TaskContainer.prepareJsPublication: TaskProvider + get() = named(prepareJsPublicationName) + +private fun JsTasks.prepareJsPublication() = + register(prepareJsPublicationName) { + + description = "Prepares the NPM package for publishing." + group = JsTasks.Group.publish + + // We need to copy two files into a destination directory without overwriting its content. + // Default `Copy` task is not used since it overwrites the content of a destination + // when copying there. + // See issue: https://github.com/gradle/gradle/issues/1012 + + doLast { + project.copy { + from( + packageJson, + npmrc + ) + + into(publicationDir) + } + } + + dependsOn( + assembleJs, + transpileSources + ) + } + +private val publishJsLocallyName = TaskName.of("publishJsLocally") + +/** + * Locates `publishJsLocally` task in this [TaskContainer]. + * + * The task publishes the prepared NPM package locally using `npm link`. + * + * @see npm-link | npm Docs + */ +val TaskContainer.publishJsLocally: TaskProvider + get() = named(publishJsLocallyName) + +private fun JsTasks.publishJsLocally() = + register(publishJsLocallyName) { + + description = "Publishes the NPM package locally with `npm link`." + group = JsTasks.Group.publish + + doLast { + publicationDir.npm("link") + } + + dependsOn(prepareJsPublication) + } + +private val publishJsName = TaskName.of("publishJs") + +/** + * Locates `publishJs` task in this [TaskContainer]. + * + * The task publishes the prepared NPM package from + * [publicationDirectory][io.spine.internal.gradle.javascript.JsEnvironment.publicationDir] + * using `npm publish`. + * + * Please note, in order to publish an NMP package, a valid + * [npmAuthToken][io.spine.internal.gradle.javascript.JsEnvironment.npmAuthToken] should be + * set. If no token is set, a default dummy value is quite enough for the local development. + * + * @see npm-publish | npm Docs + */ +val TaskContainer.publishJs: TaskProvider + get() = named(publishJsName) + +private fun JsTasks.publishJs() = + register(publishJsName) { + + description = "Publishes the NPM package with `npm publish`." + group = JsTasks.Group.publish + + doLast { + publicationDir.npm("publish") + } + + dependsOn(prepareJsPublication) + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Webpack.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Webpack.kt new file mode 100644 index 0000000000..61a9c9cf79 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/task/Webpack.kt @@ -0,0 +1,106 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.javascript.task + +import io.spine.internal.gradle.named +import io.spine.internal.gradle.register +import io.spine.internal.gradle.TaskName +import org.gradle.api.tasks.Copy +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Configures `assembleJs` task and creates `copyBundledJs` task to work with `webpack` bundler. + * + * Please note, this task group depends on [assemble] and [publish] tasks. Therefore, those tasks + * should be applied in the first place. + * + * In particular, this method: + * + * 1. Extends `assembleJs` task to bundle sources during assembling. + * 2. Creates `copyBundledJs` task and binds it to `prepareJsPublication` task execution. + * + * Here's an example of how to apply it in `build.gradle.kts`: + * + * ``` + * import io.spine.internal.gradle.javascript.javascript + * import io.spine.internal.gradle.javascript.task.assemble + * import io.spine.internal.gradle.javascript.task.publish + * import io.spine.internal.gradle.javascript.task.webpack + * + * // ... + * + * javascript { + * tasks { + * assemble() + * publish() + * webpack() + * } + * } + * ``` + */ +fun JsTasks.webpack() { + + assembleJs.configure { + + outputs.dir(webpackOutput) + + doLast { + npm("run", "build") + npm("run", "build-dev") + } + } + + // Temporarily don't publish a bundle. + // See: https://github.com/SpineEventEngine/web/issues/61 + + copyBundledJs()/*.also { + prepareJsPublication.configure { + dependsOn(it) + } + }*/ +} + +private val copyBundledJsName = TaskName.of("copyBundledJs", Copy::class) + +/** + * Locates `copyBundledJs` task in this [TaskContainer]. + * + * The task copies bundled JavaScript sources to the publication directory. + */ +val TaskContainer.copyBundledJs: TaskProvider + get() = named(copyBundledJsName) + +private fun JsTasks.copyBundledJs() = + register(copyBundledJsName) { + + description = "Copies bundled JavaScript sources to the NPM publication directory." + group = JsTasks.Group.publish + + from(assembleJs.map { it.outputs }) + into(webpackPublicationDir) + } diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/kotlin/KotlinConfig.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/kotlin/KotlinConfig.kt new file mode 100644 index 0000000000..9b3ff48464 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/kotlin/KotlinConfig.kt @@ -0,0 +1,56 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.kotlin + +import org.gradle.jvm.toolchain.JavaLanguageVersion +import org.gradle.jvm.toolchain.JavaToolchainSpec +import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +/** + * Sets [Java toolchain](https://kotlinlang.org/docs/gradle.html#gradle-java-toolchains-support) + * to the specified version (e.g. "11" or "8"). + */ +fun KotlinJvmProjectExtension.applyJvmToolchain(version: Int) { + jvmToolchain { + (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(version)) + } +} + +/** + * Opts-in to experimental features that we use in our codebase. + */ +fun KotlinCompile.setFreeCompilerArgs() { + kotlinOptions { + freeCompilerArgs = listOf( + "-Xskip-prerelease-check", + "-Xjvm-default=all", + "-Xopt-in=kotlin.contracts.ExperimentalContracts", + "-Xopt-in=kotlin.ExperimentalStdlibApi" + ) + } +} diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/MarkdownReportRenderer.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/MarkdownReportRenderer.kt index d41ac25c7d..4a57964bba 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/MarkdownReportRenderer.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/MarkdownReportRenderer.kt @@ -50,7 +50,7 @@ internal class MarkdownReportRenderer( ProjectDependencies.of(data).printTo(document) template.writeFooter() - document.appendToFile(outputFile) + document.writeToFile(outputFile) } private fun outputFile(project: Project): File { diff --git a/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/Tasks.kt b/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/Tasks.kt new file mode 100644 index 0000000000..38a5b4c23f --- /dev/null +++ b/buildSrc/src/main/kotlin/io/spine/internal/gradle/report/license/Tasks.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2021, TeamDev. All rights reserved. + * + * 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 + * + * Redistribution and use in source and/or binary forms, with or without + * modification, must retain the above copyright notice and the following + * disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package io.spine.internal.gradle.report.license + +import org.gradle.api.Task +import org.gradle.api.tasks.TaskContainer +import org.gradle.api.tasks.TaskProvider + +/** + * Locates `generateLicenseReport` in this [TaskContainer]. + * + * The task generates a license report for a specific Gradle project. License report includes + * information of all dependencies and their licenses. + */ +val TaskContainer.generateLicenseReport: TaskProvider + get() = named("generateLicenseReport") diff --git a/buildSrc/src/main/kotlin/io/spine/internal/markup/MarkdownDocument.kt b/buildSrc/src/main/kotlin/io/spine/internal/markup/MarkdownDocument.kt index 506587b92b..0310792a64 100644 --- a/buildSrc/src/main/kotlin/io/spine/internal/markup/MarkdownDocument.kt +++ b/buildSrc/src/main/kotlin/io/spine/internal/markup/MarkdownDocument.kt @@ -35,7 +35,7 @@ import java.io.File /** * A virtual document written in Markdown. * - * After it's finished, end-users would typically write it to a [real file][appendToFile]. + * After it's finished, end-users would typically write it to a [real file][writeToFile]. */ @SuppressWarnings("detekt.complexity.TooManyFunctions") /* By design. */ class MarkdownDocument { @@ -113,11 +113,11 @@ class MarkdownDocument { fun ol(): MarkdownDocument = nl().text("1. ") /** - * Appends the passed [file] with the contents of this document. + * Writes the content of this document to the passed file. * - * The previous contents of the file are NOT overwritten. + * If the file exists, it becomes overwritten. */ - fun appendToFile(file: File) { - file.appendText(builder.toString()) + fun writeToFile(file: File) { + file.writeText(builder.toString()) } } diff --git a/config b/config index c504d46466..65696b1ddd 160000 --- a/config +++ b/config @@ -1 +1 @@ -Subproject commit c504d464664c4b162e496046b36d7cdc171bed42 +Subproject commit 65696b1dddd8eb2b56fe1f20ec177012f3ddbf4f From 384a1e1d3925d03cd393c34a0284980fa22fe61e Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 14:53:12 +0200 Subject: [PATCH 03/27] Switch to Java 11 in the build script. --- build.gradle.kts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index d529f5d486..aa73ddce9a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -43,6 +43,8 @@ import io.spine.internal.gradle.forceVersions import io.spine.internal.gradle.github.pages.updateGitHubPages import io.spine.internal.gradle.javac.configureErrorProne import io.spine.internal.gradle.javac.configureJavac +import io.spine.internal.gradle.kotlin.applyJvmToolchain +import io.spine.internal.gradle.kotlin.setFreeCompilerArgs import io.spine.internal.gradle.publish.PublishingRepos import io.spine.internal.gradle.publish.spinePublishing import io.spine.internal.gradle.report.coverage.JacocoConfig @@ -63,11 +65,11 @@ repositories.applyStandard() // Apply some plugins to make type-safe extension accessors available in this script file. plugins { `java-library` - kotlin("jvm") version io.spine.internal.dependency.Kotlin.version + kotlin("jvm") idea io.spine.internal.dependency.Protobuf.GradlePlugin.apply { - id(id) version version + id(id) } io.spine.internal.dependency.ErrorProne.GradlePlugin.apply { id(id) @@ -143,11 +145,15 @@ subprojects { rootFolder.set(rootDir) } - val javaVersion = JavaVersion.VERSION_1_8 + val javaVersion = 11 + kotlin { + applyJvmToolchain(javaVersion) + explicitApi() + } - the().apply { - sourceCompatibility = javaVersion - targetCompatibility = javaVersion + tasks.withType().configureEach { + kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString() + setFreeCompilerArgs() } tasks.withType { @@ -175,12 +181,10 @@ subprojects { */ dependencies { errorprone(ErrorProne.core) - errorproneJavac(ErrorProne.javacPlugin) Protobuf.libs.forEach { api(it) } api(Flogger.lib) api(Guava.lib) - api(kotlin("stdlib-jdk8")) compileOnlyApi(CheckerFramework.annotations) compileOnlyApi(JavaX.annotations) From f9dee8c522866bc6f4d8d3d2e76eea52392f572a Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 14:53:24 +0200 Subject: [PATCH 04/27] Update the report files. --- license-report.md | 154 ++++++++++++++++++++++++---------------------- pom.xml | 19 +++--- 2 files changed, 87 insertions(+), 86 deletions(-) diff --git a/license-report.md b/license-report.md index 046098c5ad..1dac07dabf 100644 --- a/license-report.md +++ b/license-report.md @@ -1,6 +1,6 @@ -# Dependencies of `io.spine:spine-base:2.0.0-SNAPSHOT.77` +# Dependencies of `io.spine:spine-base:2.0.0-SNAPSHOT.78` ## Runtime 1. **Group** : com.google.code.findbugs. **Name** : jsr305. **Version** : 3.0.2. @@ -57,31 +57,27 @@ * **Project URL:** [http://www.jetbrains.org](http://www.jetbrains.org) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) ## Compile, tests, and tooling -1. **Group** : antlr. **Name** : antlr. **Version** : 2.7.7. - * **Project URL:** [http://www.antlr.org/](http://www.antlr.org/) - * **License:** [BSD License](http://www.antlr.org/license.html) - 1. **Group** : com.beust. **Name** : jcommander. **Version** : 1.48. * **Project URL:** [http://beust.com/jcommander](http://beust.com/jcommander) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -136,10 +132,6 @@ 1. **Group** : com.google.errorprone. **Name** : error_prone_type_annotations. **Version** : 2.8.0. * **License:** [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : com.google.errorprone. **Name** : javac. **Version** : 9+181-r4173-1. - * **Project URL:** [https://github.com/google/error-prone-javac](https://github.com/google/error-prone-javac) - * **License:** [GNU General Public License, version 2, with the Classpath Exception](http://openjdk.java.net/legal/gplv2+ce.html) - 1. **Group** : com.google.flogger. **Name** : flogger. **Version** : 0.6. * **Project URL:** [https://github.com/google/flogger](https://github.com/google/flogger) * **License:** [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) @@ -191,7 +183,7 @@ 1. **Group** : com.google.truth.extensions. **Name** : truth-proto-extension. **Version** : 1.1.3. * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : com.puppycrawl.tools. **Name** : checkstyle. **Version** : 8.29. +1. **Group** : com.puppycrawl.tools. **Name** : checkstyle. **Version** : 9.1. * **Project URL:** [https://checkstyle.org/](https://checkstyle.org/) * **License:** [LGPL-2.1+](http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt) @@ -207,7 +199,7 @@ * **Project URL:** [http://commons.apache.org/proper/commons-io/](http://commons.apache.org/proper/commons-io/) * **License:** [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : info.picocli. **Name** : picocli. **Version** : 4.1.4. +1. **Group** : info.picocli. **Name** : picocli. **Version** : 4.6.1. * **Project URL:** [http://picocli.info](http://picocli.info) * **License:** [The Apache Software License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -223,7 +215,12 @@ * **Project URL:** [http://junit.org](http://junit.org) * **License:** [Eclipse Public License 1.0](http://www.eclipse.org/legal/epl-v10.html) -1. **Group** : net.sf.saxon. **Name** : Saxon-HE. **Version** : 9.9.1-6. +1. **Group** : net.java.dev.jna. **Name** : jna. **Version** : 5.6.0. + * **Project URL:** [https://github.com/java-native-access/jna](https://github.com/java-native-access/jna) + * **License:** [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) + * **License:** [LGPL, version 2.1](http://www.gnu.org/licenses/licenses.html) + +1. **Group** : net.sf.saxon. **Name** : Saxon-HE. **Version** : 10.6. * **Project URL:** [http://www.saxonica.com/](http://www.saxonica.com/) * **License:** [Mozilla Public License Version 2.0](http://www.mozilla.org/MPL/2.0/) @@ -241,7 +238,7 @@ * **Project URL:** [http://www.antlr.org](http://www.antlr.org) * **License:** [The BSD License](http://www.antlr.org/license.html) -1. **Group** : org.antlr. **Name** : antlr4-runtime. **Version** : 4.8-1. +1. **Group** : org.antlr. **Name** : antlr4-runtime. **Version** : 4.9.2. * **Project URL:** [http://www.antlr.org](http://www.antlr.org) * **License:** [The BSD License](http://www.antlr.org/license.html) @@ -284,6 +281,12 @@ 1. **Group** : org.jacoco. **Name** : org.jacoco.report. **Version** : 0.8.7. * **License:** [Eclipse Public License 2.0](https://www.eclipse.org/legal/epl-2.0/) +1. **Group** : org.javassist. **Name** : javassist. **Version** : 3.28.0-GA. + * **Project URL:** [http://www.javassist.org/](http://www.javassist.org/) + * **License:** [Apache License 2.0](http://www.apache.org/licenses/) + * **License:** [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) + * **License:** [MPL 1.1](http://www.mozilla.org/MPL/MPL-1.1.html) + 1. **Group** : org.jetbrains. **Name** : annotations. **Version** : 13.0. * **Project URL:** [http://www.jetbrains.org](http://www.jetbrains.org) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -292,63 +295,58 @@ * **Project URL:** [https://github.com/JetBrains/intellij-deps-trove4j](https://github.com/JetBrains/intellij-deps-trove4j) * **License:** [GNU LESSER GENERAL PUBLIC LICENSE 2.1](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-compiler-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-compiler-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-daemon-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-daemon-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-klib-commonizer-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-klib-commonizer-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-script-runtime. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-script-runtime. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-impl-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-impl-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-jvm. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-jvm. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlinx. **Name** : kotlinx-coroutines-core. **Version** : 1.5.0.**No license information found** -1. **Group** : org.jetbrains.kotlinx. **Name** : kotlinx-coroutines-core-jvm. **Version** : 1.5.0. - * **Project URL:** [https://github.com/Kotlin/kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines) - * **License:** [The Apache Software License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) - 1. **Group** : org.junit. **Name** : junit-bom. **Version** : 5.7.1.**No license information found** 1. **Group** : org.junit-pioneer. **Name** : junit-pioneer. **Version** : 1.3.8. * **Project URL:** [https://junit-pioneer.org/](https://junit-pioneer.org/) @@ -406,15 +404,20 @@ * **Project URL:** [http://pcollections.org](http://pcollections.org) * **License:** [The MIT License](http://www.opensource.org/licenses/mit-license.php) +1. **Group** : org.reflections. **Name** : reflections. **Version** : 0.10.2. + * **Project URL:** [http://github.com/ronmamo/reflections](http://github.com/ronmamo/reflections) + * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) + * **License:** [WTFPL](http://www.wtfpl.net/) + The dependencies distributed under several licenses, are used according their commercial-use-friendly license. -This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-License-Report plugin](https://github.com/jk1/Gradle-License-Report) by Evgeny Naumenko, licensed under [Apache 2.0 License](https://github.com/jk1/Gradle-License-Report/blob/master/LICENSE). +This report was generated on **Wed Dec 08 14:05:12 EET 2021** using [Gradle-License-Report plugin](https://github.com/jk1/Gradle-License-Report) by Evgeny Naumenko, licensed under [Apache 2.0 License](https://github.com/jk1/Gradle-License-Report/blob/master/LICENSE). -# Dependencies of `io.spine.tools:spine-testlib:2.0.0-SNAPSHOT.77` +# Dependencies of `io.spine.tools:spine-testlib:2.0.0-SNAPSHOT.78` ## Runtime 1. **Group** : com.google.auto.value. **Name** : auto-value-annotations. **Version** : 1.8. @@ -501,23 +504,23 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [http://www.jetbrains.org](http://www.jetbrains.org) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -544,10 +547,6 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) ## Compile, tests, and tooling -1. **Group** : antlr. **Name** : antlr. **Version** : 2.7.7. - * **Project URL:** [http://www.antlr.org/](http://www.antlr.org/) - * **License:** [BSD License](http://www.antlr.org/license.html) - 1. **Group** : com.beust. **Name** : jcommander. **Version** : 1.48. * **Project URL:** [http://beust.com/jcommander](http://beust.com/jcommander) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -598,10 +597,6 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice 1. **Group** : com.google.errorprone. **Name** : error_prone_type_annotations. **Version** : 2.8.0. * **License:** [Apache 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : com.google.errorprone. **Name** : javac. **Version** : 9+181-r4173-1. - * **Project URL:** [https://github.com/google/error-prone-javac](https://github.com/google/error-prone-javac) - * **License:** [GNU General Public License, version 2, with the Classpath Exception](http://openjdk.java.net/legal/gplv2+ce.html) - 1. **Group** : com.google.flogger. **Name** : flogger. **Version** : 0.6. * **Project URL:** [https://github.com/google/flogger](https://github.com/google/flogger) * **License:** [Apache 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) @@ -653,7 +648,7 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice 1. **Group** : com.google.truth.extensions. **Name** : truth-proto-extension. **Version** : 1.1.3. * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : com.puppycrawl.tools. **Name** : checkstyle. **Version** : 8.29. +1. **Group** : com.puppycrawl.tools. **Name** : checkstyle. **Version** : 9.1. * **Project URL:** [https://checkstyle.org/](https://checkstyle.org/) * **License:** [LGPL-2.1+](http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt) @@ -669,7 +664,7 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [http://commons.apache.org/proper/commons-io/](http://commons.apache.org/proper/commons-io/) * **License:** [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : info.picocli. **Name** : picocli. **Version** : 4.1.4. +1. **Group** : info.picocli. **Name** : picocli. **Version** : 4.6.1. * **Project URL:** [http://picocli.info](http://picocli.info) * **License:** [The Apache Software License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -685,7 +680,12 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [http://junit.org](http://junit.org) * **License:** [Eclipse Public License 1.0](http://www.eclipse.org/legal/epl-v10.html) -1. **Group** : net.sf.saxon. **Name** : Saxon-HE. **Version** : 9.9.1-6. +1. **Group** : net.java.dev.jna. **Name** : jna. **Version** : 5.6.0. + * **Project URL:** [https://github.com/java-native-access/jna](https://github.com/java-native-access/jna) + * **License:** [Apache License v2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) + * **License:** [LGPL, version 2.1](http://www.gnu.org/licenses/licenses.html) + +1. **Group** : net.sf.saxon. **Name** : Saxon-HE. **Version** : 10.6. * **Project URL:** [http://www.saxonica.com/](http://www.saxonica.com/) * **License:** [Mozilla Public License Version 2.0](http://www.mozilla.org/MPL/2.0/) @@ -703,7 +703,7 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [http://www.antlr.org](http://www.antlr.org) * **License:** [The BSD License](http://www.antlr.org/license.html) -1. **Group** : org.antlr. **Name** : antlr4-runtime. **Version** : 4.8-1. +1. **Group** : org.antlr. **Name** : antlr4-runtime. **Version** : 4.9.2. * **Project URL:** [http://www.antlr.org](http://www.antlr.org) * **License:** [The BSD License](http://www.antlr.org/license.html) @@ -746,6 +746,12 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice 1. **Group** : org.jacoco. **Name** : org.jacoco.report. **Version** : 0.8.7. * **License:** [Eclipse Public License 2.0](https://www.eclipse.org/legal/epl-2.0/) +1. **Group** : org.javassist. **Name** : javassist. **Version** : 3.28.0-GA. + * **Project URL:** [http://www.javassist.org/](http://www.javassist.org/) + * **License:** [Apache License 2.0](http://www.apache.org/licenses/) + * **License:** [LGPL 2.1](http://www.gnu.org/licenses/lgpl-2.1.html) + * **License:** [MPL 1.1](http://www.mozilla.org/MPL/MPL-1.1.html) + 1. **Group** : org.jetbrains. **Name** : annotations. **Version** : 13.0. * **Project URL:** [http://www.jetbrains.org](http://www.jetbrains.org) * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) @@ -754,63 +760,58 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [https://github.com/JetBrains/intellij-deps-trove4j](https://github.com/JetBrains/intellij-deps-trove4j) * **License:** [GNU LESSER GENERAL PUBLIC LICENSE 2.1](https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-compiler-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-compiler-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-daemon-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-daemon-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-klib-commonizer-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-klib-commonizer-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-reflect. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-script-runtime. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-script-runtime. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-impl-embeddable. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-compiler-impl-embeddable. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-jvm. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-scripting-jvm. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-common. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk7. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.5.31. +1. **Group** : org.jetbrains.kotlin. **Name** : kotlin-stdlib-jdk8. **Version** : 1.6.0. * **Project URL:** [https://kotlinlang.org/](https://kotlinlang.org/) * **License:** [The Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) -1. **Group** : org.jetbrains.kotlinx. **Name** : kotlinx-coroutines-core. **Version** : 1.5.0.**No license information found** -1. **Group** : org.jetbrains.kotlinx. **Name** : kotlinx-coroutines-core-jvm. **Version** : 1.5.0. - * **Project URL:** [https://github.com/Kotlin/kotlinx.coroutines](https://github.com/Kotlin/kotlinx.coroutines) - * **License:** [The Apache Software License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.txt) - 1. **Group** : org.junit. **Name** : junit-bom. **Version** : 5.7.1.**No license information found** 1. **Group** : org.junit-pioneer. **Name** : junit-pioneer. **Version** : 1.3.8. * **Project URL:** [https://junit-pioneer.org/](https://junit-pioneer.org/) @@ -868,7 +869,12 @@ This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-Lice * **Project URL:** [http://pcollections.org](http://pcollections.org) * **License:** [The MIT License](http://www.opensource.org/licenses/mit-license.php) +1. **Group** : org.reflections. **Name** : reflections. **Version** : 0.10.2. + * **Project URL:** [http://github.com/ronmamo/reflections](http://github.com/ronmamo/reflections) + * **License:** [The Apache Software License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.txt) + * **License:** [WTFPL](http://www.wtfpl.net/) + The dependencies distributed under several licenses, are used according their commercial-use-friendly license. -This report was generated on **Fri Nov 26 19:50:18 EET 2021** using [Gradle-License-Report plugin](https://github.com/jk1/Gradle-License-Report) by Evgeny Naumenko, licensed under [Apache 2.0 License](https://github.com/jk1/Gradle-License-Report/blob/master/LICENSE). \ No newline at end of file +This report was generated on **Wed Dec 08 14:05:13 EET 2021** using [Gradle-License-Report plugin](https://github.com/jk1/Gradle-License-Report) by Evgeny Naumenko, licensed under [Apache 2.0 License](https://github.com/jk1/Gradle-License-Report/blob/master/LICENSE). \ No newline at end of file diff --git a/pom.xml b/pom.xml index 546b793ecf..326a405b9c 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ all modules and does not describe the project structure per-subproject. --> io.spine spine-base -2.0.0-SNAPSHOT.77 +2.0.0-SNAPSHOT.78 2015 @@ -68,13 +68,13 @@ all modules and does not describe the project structure per-subproject. org.jetbrains.kotlin kotlin-reflect - 1.5.31 + 1.6.0 compile org.jetbrains.kotlin kotlin-stdlib-jdk8 - 1.5.31 + 1.6.0 compile @@ -148,11 +148,6 @@ all modules and does not describe the project structure per-subproject. 2.8.0 provided - - com.google.errorprone - javac - 9+181-r4173-1 - com.google.protobuf protoc @@ -161,7 +156,7 @@ all modules and does not describe the project structure per-subproject. com.puppycrawl.tools checkstyle - 8.29 + 9.1 javax.annotation @@ -193,17 +188,17 @@ all modules and does not describe the project structure per-subproject. org.jetbrains.kotlin kotlin-compiler-embeddable - 1.5.31 + 1.6.0 org.jetbrains.kotlin kotlin-klib-commonizer-embeddable - 1.5.31 + 1.6.0 org.jetbrains.kotlin kotlin-scripting-compiler-embeddable - 1.5.31 + 1.6.0 From 164174fbce00bc1df75feda3a3c4ac61d2c84100 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 14:53:43 +0200 Subject: [PATCH 05/27] Update the code style. --- .idea/codeStyles/Project.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml index 68d26ae3bf..809943cce4 100644 --- a/.idea/codeStyles/Project.xml +++ b/.idea/codeStyles/Project.xml @@ -69,7 +69,7 @@ - + From 4ce66e6914e9c573ed008c5c5942d81fa0806aa6 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 17:50:05 +0200 Subject: [PATCH 08/27] Set `VariableTypeCanBeExplicit` to `WARNING`. --- .idea/inspectionProfiles/Project_Default.xml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index 30c3b896db..edf9a1959d 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -840,6 +840,7 @@ \ No newline at end of file + From 29a119c5362efbf0b4b0f5958279ca332d9fe9d0 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 18:03:40 +0200 Subject: [PATCH 09/27] Set `RedundantExplicitVariableType` to `WARNING`. Turn off `VariableTypeCanBeExplicit`. --- .idea/inspectionProfiles/Project_Default.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml index edf9a1959d..d4e24101be 100644 --- a/.idea/inspectionProfiles/Project_Default.xml +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -635,6 +635,7 @@ + - From 830e95c4dc4670bf0eb36dbf0f9016e1f7c600ee Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 19:02:02 +0200 Subject: [PATCH 10/27] Use `var`s in `io.spine.base` package. --- base/src/main/java/io/spine/base/Errors.java | 20 +++-- base/src/main/java/io/spine/base/Field.java | 81 +++++++++---------- base/src/main/java/io/spine/base/IdType.java | 12 +-- .../main/java/io/spine/base/Identifier.java | 53 ++++++------ .../main/java/io/spine/base/MessageFile.java | 2 +- .../java/io/spine/base/MessageIdToString.java | 26 +++--- .../io/spine/base/RejectionThrowable.java | 4 +- .../java/io/spine/base/RejectionType.java | 12 +-- base/src/main/java/io/spine/base/Time.java | 13 ++- 9 files changed, 104 insertions(+), 119 deletions(-) diff --git a/base/src/main/java/io/spine/base/Errors.java b/base/src/main/java/io/spine/base/Errors.java index 17baed6fdd..8745597951 100644 --- a/base/src/main/java/io/spine/base/Errors.java +++ b/base/src/main/java/io/spine/base/Errors.java @@ -46,7 +46,7 @@ private Errors() { * Creates new instance of {@link Error} by the passed {@code Throwable}. */ public static Error fromThrowable(Throwable throwable) { - Error.Builder result = toErrorBuilder(throwable); + var result = toErrorBuilder(throwable); return result.build(); } @@ -58,7 +58,7 @@ public static Error fromThrowable(Throwable throwable) { * @return new instance of {@link Error} */ public static Error causeOf(Throwable throwable) { - Error.Builder error = toBuilderCauseOf(throwable); + var error = toBuilderCauseOf(throwable); return error.build(); } @@ -76,7 +76,7 @@ public static Error causeOf(Throwable throwable) { * @see #causeOf(Throwable) as the recommended overload */ public static Error causeOf(Throwable throwable, int errorCode) { - Error.Builder error = toBuilderCauseOf(throwable).setCode(errorCode); + var error = toBuilderCauseOf(throwable).setCode(errorCode); return error.build(); } @@ -101,20 +101,18 @@ private static Error.Builder toBuilderCauseOf(Throwable throwable) { * the {@code Throwable} to convert * @return new builder of {@link Error} */ - @SuppressWarnings("CheckReturnValue") // calling builder + @SuppressWarnings({"CheckReturnValue", "ResultOfMethodCallIgnored"}) // Calling builder. private static Error.Builder toErrorBuilder(Throwable throwable) { checkNotNull(throwable); - String type = throwable.getClass() - .getCanonicalName(); - String message = nullToEmpty(throwable.getMessage()); - String stacktrace = getStackTraceAsString(throwable); - Error.Builder result = Error - .newBuilder() + var type = throwable.getClass().getCanonicalName(); + var message = nullToEmpty(throwable.getMessage()); + var stacktrace = getStackTraceAsString(throwable); + var result = Error.newBuilder() .setType(type) .setMessage(message) .setStacktrace(stacktrace); if (throwable instanceof ValidationException) { - ValidationException validationException = (ValidationException) throwable; + var validationException = (ValidationException) throwable; result.setValidationError(validationException.asValidationError()); } return result; diff --git a/base/src/main/java/io/spine/base/Field.java b/base/src/main/java/io/spine/base/Field.java index b0c5408e95..bbb923f429 100644 --- a/base/src/main/java/io/spine/base/Field.java +++ b/base/src/main/java/io/spine/base/Field.java @@ -32,7 +32,6 @@ import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.EnumDescriptor; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; @@ -42,7 +41,6 @@ import io.spine.value.ValueHolder; import org.checkerframework.checker.nullness.qual.Nullable; -import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -100,7 +98,7 @@ public static Field withPath(FieldPath path) { */ public static Field parse(String path) { checkNotNull(path); - FieldPath fp = doParse(path); + var fp = doParse(path); return create(fp); } @@ -112,8 +110,8 @@ public static Field parse(String path) { */ public static Field named(String fieldName) { checkName(fieldName); - FieldPath path = create(ImmutableList.of(fieldName)); - Field result = create(path); + var path = create(ImmutableList.of(fieldName)); + var result = create(path); return result; } @@ -129,8 +127,8 @@ public static Field named(String fieldName) { * if there is no field with the passed number in this message type */ public static Field withNumberIn(int number, Descriptor message) { - String name = nameOf(number, message); - Field result = named(name); + var name = nameOf(number, message); + var result = named(name); return result; } @@ -149,9 +147,7 @@ public static Field withNumberIn(int number, Descriptor message) { public static String nameOf(int fieldNumber, Descriptor message) { checkNotNull(message); checkArgument(fieldNumber > 0); - String result = message - .getFields() - .stream() + var result = message.getFields().stream() .filter(f -> f.getNumber() == fieldNumber) .findFirst() .map(FieldDescriptor::getName) @@ -168,9 +164,9 @@ public static String nameOf(int fieldNumber, Descriptor message) { */ public Field nested(String fieldName) { checkName(fieldName); - FieldPath newPath = path().toBuilder() - .addFieldName(fieldName) - .build(); + var newPath = path().toBuilder() + .addFieldName(fieldName) + .build(); return create(newPath); } @@ -181,9 +177,9 @@ public Field nested(Field other) { checkNotNull(other); List fieldNames = other.path() .getFieldNameList(); - FieldPath newPath = path().toBuilder() - .addAllFieldName(fieldNames) - .build(); + var newPath = path().toBuilder() + .addAllFieldName(fieldNames) + .build(); return create(newPath); } @@ -201,7 +197,7 @@ public FieldPath path() { * in this type of messages */ public Optional findValue(Message holder) { - Object value = doGetValue(path(), holder, false); + var value = doGetValue(path(), holder, false); return Optional.ofNullable(value); } @@ -211,7 +207,7 @@ public Optional findValue(Message holder) { * @throws IllegalStateException if the type of the passed message does not declare this field */ public Object valueIn(Message holder) { - Object result = findValue(holder).orElseThrow( + var result = findValue(holder).orElseThrow( () -> newIllegalStateException("Unable to get the field `%s` from `%s`.", this, shortDebugString(holder)) ); @@ -222,8 +218,8 @@ this, shortDebugString(holder)) * Checks if the field is present (as top-level or nested) in the given message type. */ public boolean presentIn(Descriptor message) { - Optional descriptor = findDescriptor(message); - boolean result = descriptor.isPresent(); + var descriptor = findDescriptor(message); + var result = descriptor.isPresent(); return result; } @@ -241,12 +237,12 @@ public Optional findDescriptor(Descriptor message) { * Obtains the type of the referenced field in the passed message class. */ public Optional> findType(Class holderType) { - Descriptor message = TypeName.of(holderType).messageDescriptor(); + var message = TypeName.of(holderType).messageDescriptor(); @Nullable FieldDescriptor field = fieldIn(path(), message); if (field == null) { return Optional.empty(); } - Class result = classOf(field); + var result = classOf(field); return Optional.of(result); } @@ -254,8 +250,8 @@ public Optional> findType(Class holderType) { * Checks if the field is a nested field. */ public boolean isNested() { - int pathComponents = path().getFieldNameCount(); - boolean result = pathComponents > 1; + var pathComponents = path().getFieldNameCount(); + var result = pathComponents > 1; return result; } @@ -273,8 +269,7 @@ public String toString() { /** Creates a new path containing the passed elements. */ private static FieldPath create(List elements) { elements.forEach(Field::checkName); - FieldPath result = FieldPath - .newBuilder() + var result = FieldPath.newBuilder() .addAllFieldName(elements) .build(); return result; @@ -284,7 +279,7 @@ private static FieldPath create(List elements) { @VisibleForTesting static FieldPath doParse(String fieldPath) { checkArgument(!fieldPath.isEmpty(), "A field path must not be empty."); - List pathElements = dotSplitter.splitToList(fieldPath); + var pathElements = dotSplitter.splitToList(fieldPath); return create(pathElements); } @@ -306,11 +301,11 @@ static FieldPath doParse(String fieldPath) { * if the call is {@code strict} and the value not found */ private static @Nullable Object doGetValue(FieldPath path, Message holder, boolean strict) { - Message message = holder; + var message = holder; Object currentValue = message; - for (Iterator iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) { - String fieldName = iterator.next(); - Descriptor type = message.getDescriptorForType(); + for (var iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) { + var fieldName = iterator.next(); + var type = message.getDescriptorForType(); @Nullable FieldDescriptor field = type.findFieldByName(fieldName); if (field == null) { if (strict) { @@ -360,11 +355,11 @@ private static Object convertIfEnum(Object currentValue) { if (!(currentValue instanceof EnumValueDescriptor)) { return currentValue; } - EnumValueDescriptor value = (EnumValueDescriptor) currentValue; - EnumDescriptor enumType = value.getType(); - TypeName typeName = TypeName.of(enumType.getFullName()); + var value = (EnumValueDescriptor) currentValue; + var enumType = value.getType(); + var typeName = TypeName.of(enumType.getFullName()); Class cls = typeName.toEnumClass(); - Enum enumValue = Enum.valueOf(cls, value.getName()); + var enumValue = Enum.valueOf(cls, value.getName()); return enumValue; } @@ -374,10 +369,10 @@ private static Object convertIfEnum(Object currentValue) { * @return the descriptor or {@code null} if the message type does not declare this field */ private static @Nullable FieldDescriptor fieldIn(FieldPath path, Descriptor message) { - Descriptor current = message; + var current = message; FieldDescriptor field = null; - for (Iterator iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) { - String fieldName = iterator.next(); + for (var iterator = path.getFieldNameList().iterator(); iterator.hasNext(); ) { + var fieldName = iterator.next(); field = current.findFieldByName(fieldName); if (field == null) { return null; @@ -402,15 +397,15 @@ private static void checkName(String fieldName) { /** Obtains the type of the values stored in the field. */ static Class classOf(FieldDescriptor field) { - FieldDescriptor.Type type = field.getType(); + var type = field.getType(); if (type == MESSAGE) { - Class cls = TypeUrl.from(field.getMessageType()).toJavaClass(); + var cls = TypeUrl.from(field.getMessageType()).toJavaClass(); return cls; } else if (type == ENUM) { - Class cls = TypeUrl.from(field.getEnumType()).toJavaClass(); + var cls = TypeUrl.from(field.getEnumType()).toJavaClass(); return cls; } else { - Class result = ScalarType.javaType(field.toProto().getType()); + var result = ScalarType.javaType(field.toProto().getType()); return result; } } @@ -424,7 +419,7 @@ private static void checkNotEmpty(FieldPath path) throws IllegalArgumentExceptio * Joins the passed path elements into the string representation of the path. */ private static String join(Iterable elements) { - String result = joiner.join(elements); + var result = joiner.join(elements); return result; } } diff --git a/base/src/main/java/io/spine/base/IdType.java b/base/src/main/java/io/spine/base/IdType.java index 267f4a6c3b..525d57370f 100644 --- a/base/src/main/java/io/spine/base/IdType.java +++ b/base/src/main/java/io/spine/base/IdType.java @@ -181,8 +181,8 @@ Message fromMessage(Message message) { @Override I defaultValue(Class idClass) { - Class msgClass = (Class) idClass; - Message result = defaultInstance(msgClass); + var msgClass = (Class) idClass; + var result = defaultInstance(msgClass); return (I) result; } @@ -205,7 +205,7 @@ boolean matchField(FieldDescriptor field) { * if the passed value is not of supported type */ static IdType of(I id) { - for (IdType type : values()) { + for (var type : values()) { if (type.matchValue(id)) { return type; } @@ -251,7 +251,7 @@ static IdType of(I id) { * Converts the passed ID object into the Protobuf implementation instance. */ Message toMessage(I id) { - Message message = TypeConverter.toMessage(id); + var message = TypeConverter.toMessage(id); return message; } @@ -260,8 +260,8 @@ Message toMessage(I id) { * then packs it into {@code Any}. */ Any pack(I id) { - Message msg = toMessage(id); - Any result = AnyPacker.pack(msg); + var msg = toMessage(id); + var result = AnyPacker.pack(msg); return result; } } diff --git a/base/src/main/java/io/spine/base/Identifier.java b/base/src/main/java/io/spine/base/Identifier.java index e5af9d0018..5a3f175184 100644 --- a/base/src/main/java/io/spine/base/Identifier.java +++ b/base/src/main/java/io/spine/base/Identifier.java @@ -72,8 +72,8 @@ private Identifier(IdType type, I value) { static Identifier from(I value) { checkNotNull(value); - IdType type = IdType.of(value); - Identifier result = create(type, value); + var type = IdType.of(value); + var result = create(type, value); return result; } @@ -83,7 +83,7 @@ private static Identifier create(IdType type, I value) { private static Identifier fromMessage(Message value) { checkNotNull(value); - Identifier result = create(IdType.MESSAGE, value); + var result = create(IdType.MESSAGE, value); return result; } @@ -92,8 +92,8 @@ private static Identifier fromMessage(Message value) { */ public static I defaultValue(Class idClass) { checkNotNull(idClass); - IdType type = toType(idClass); - I result = type.defaultValue(idClass); + var type = toType(idClass); + var result = type.defaultValue(idClass); return result; } @@ -109,7 +109,7 @@ IdType type() { * Converts the class of identifiers to {@code Identifier.Type}. */ public static IdType toType(Class idClass) { - for (IdType type : IdType.values()) { + for (var type : IdType.values()) { if (type.matchClass(idClass)) { return type; } @@ -135,13 +135,13 @@ public static IdType toType(Class idClass) { */ public static boolean isEmpty(I value) { checkNotNull(value); - Identifier id = from(value); + var id = from(value); if (id.type == IdType.INTEGER || id.type == IdType.LONG) { return false; } - String str = id.toString(); - boolean result = EMPTY_ID.equals(str); + var str = id.toString(); + var result = EMPTY_ID.equals(str); return result; } @@ -188,7 +188,7 @@ public static void checkSupported(Class idClass) { // Even through `getType()` can never return null, we use its return value here // instead of annotating the method so that the returned value can be ignored // just because of this one usage. - IdType type = toType(idClass); + var type = toType(idClass); checkNotNull(type); } @@ -215,8 +215,8 @@ public static void checkSupported(Class idClass) { */ public static Any pack(I id) { checkNotNull(id); - Identifier identifier = from(id); - Any anyId = identifier.pack(); + var identifier = from(id); + var anyId = identifier.pack(); return anyId; } @@ -237,10 +237,10 @@ public static Any pack(I id) { */ public static Object unpack(Any any) { checkNotNull(any); - Message unpacked = AnyPacker.unpack(any); - for (IdType type : IdType.values()) { + var unpacked = AnyPacker.unpack(any); + for (var type : IdType.values()) { if (type.matchMessage(unpacked)) { - Object result = type.fromMessage(unpacked); + var result = type.fromMessage(unpacked); return result; } } @@ -273,7 +273,7 @@ public static Object unpack(Any any) { */ public static I unpack(Any any, Class idClass) { checkNotNull(idClass); - Object identifier = unpack(any); + var identifier = unpack(any); return idClass.cast(identifier); } @@ -284,8 +284,8 @@ public static I unpack(Any any, Class idClass) { * @see UUID#randomUUID() */ public static String newUuid() { - String id = UUID.randomUUID() - .toString(); + var id = UUID.randomUUID() + .toString(); return id; } @@ -315,18 +315,18 @@ public static String toString(@Nullable I id) { Identifier identifier; if (id instanceof Any) { - Message unpacked = AnyPacker.unpack((Any) id); + var unpacked = AnyPacker.unpack((Any) id); identifier = fromMessage(unpacked); } else { identifier = from(id); } - String result = identifier.toString(); + var result = identifier.toString(); return result; } private Any pack() { - Any result = type.pack(value); + var result = type.pack(value); return result; } @@ -345,8 +345,8 @@ private Any pack() { public static Optional findField(Class idClass, Descriptor message) { checkNotNull(idClass); checkNotNull(message); - IdType idType = toType(idClass); - Optional found = + var idType = toType(idClass); + var found = message.getFields() .stream() .filter(idType::matchField) @@ -360,9 +360,8 @@ public static Optional findField(Class idClass, Descript */ private static boolean sameType(Class idClass, FieldDescriptor f) { @SuppressWarnings("unchecked") // safe since it's Message type. - TypeUrl messageType = TypeUrl.of( - (Class) idClass); - TypeUrl fieldType = TypeUrl.from(f.getMessageType()); + var messageType = TypeUrl.of((Class) idClass); + var fieldType = TypeUrl.from(f.getMessageType()); return fieldType.equals(messageType); } @@ -372,8 +371,6 @@ public String toString() { switch (type) { case INTEGER: case LONG: - result = value.toString(); - break; case STRING: result = value.toString(); break; diff --git a/base/src/main/java/io/spine/base/MessageFile.java b/base/src/main/java/io/spine/base/MessageFile.java index aa0801d8b3..7699f23d19 100644 --- a/base/src/main/java/io/spine/base/MessageFile.java +++ b/base/src/main/java/io/spine/base/MessageFile.java @@ -64,7 +64,7 @@ public enum MessageFile implements Predicate { */ @Override public boolean test(FileDescriptorProto file) { - String name = file.getName(); + var name = file.getName(); return name.endsWith(suffix); } diff --git a/base/src/main/java/io/spine/base/MessageIdToString.java b/base/src/main/java/io/spine/base/MessageIdToString.java index e927f655aa..968ee46ac7 100644 --- a/base/src/main/java/io/spine/base/MessageIdToString.java +++ b/base/src/main/java/io/spine/base/MessageIdToString.java @@ -29,15 +29,13 @@ import com.google.common.reflect.TypeToken; import com.google.protobuf.Message; import com.google.protobuf.MessageOrBuilder; -import io.spine.string.Stringifier; import io.spine.string.StringifierRegistry; -import java.util.Collection; -import java.util.Optional; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.protobuf.TextFormat.shortDebugString; +import static java.util.Objects.requireNonNull; /** * Utilities for converting message-based identifiers to String. @@ -53,29 +51,27 @@ private MessageIdToString() { static String toString(Message message) { checkNotNull(message); String result; - StringifierRegistry registry = StringifierRegistry.instance(); - Class msgClass = message.getClass(); - TypeToken msgToken = TypeToken.of(msgClass); - java.lang.reflect.Type msgType = msgToken.getType(); - Optional> optional = registry.find(msgType); + var registry = StringifierRegistry.instance(); + var msgClass = message.getClass(); + var msgToken = TypeToken.of(msgClass); + var msgType = msgToken.getType(); + var optional = registry.find(msgType); if (optional.isPresent()) { - Stringifier converter = optional.get(); + var converter = optional.get(); result = converter.convert(message); } else { result = convert(message); } - return result; + return requireNonNull(result); } private static String convert(Message message) { - Collection values = message.getAllFields() - .values(); + var values = message.getAllFields().values(); String result; if (values.isEmpty()) { result = Identifier.EMPTY_ID; } else if (values.size() == 1) { - Object object = values.iterator() - .next(); + var object = values.iterator().next(); result = object instanceof Message ? toString((Message) object) : object.toString(); @@ -86,7 +82,7 @@ private static String convert(Message message) { } private static String messageWithMultipleFieldsToString(MessageOrBuilder message) { - String result = shortDebugString(message); + var result = shortDebugString(message); result = PATTERN_COLON_SPACE.matcher(result) .replaceAll(EQUAL_SIGN); return result; diff --git a/base/src/main/java/io/spine/base/RejectionThrowable.java b/base/src/main/java/io/spine/base/RejectionThrowable.java index 1c6ddfe28b..c478a4058a 100644 --- a/base/src/main/java/io/spine/base/RejectionThrowable.java +++ b/base/src/main/java/io/spine/base/RejectionThrowable.java @@ -92,8 +92,8 @@ public Timestamp timestamp() { public synchronized RejectionThrowable initProducer(Any producerId) { checkNotNull(producerId); if (this.producerId != null) { - Object unpackedId = Identifier.unpack(producerId); - String stringId = Stringifiers.toString(unpackedId); + var unpackedId = Identifier.unpack(producerId); + var stringId = Stringifiers.toString(unpackedId); throw newIllegalStateException("Producer already initialized: `%s`.", stringId); } this.producerId = producerId; diff --git a/base/src/main/java/io/spine/base/RejectionType.java b/base/src/main/java/io/spine/base/RejectionType.java index ae2bdfa942..3221b70044 100644 --- a/base/src/main/java/io/spine/base/RejectionType.java +++ b/base/src/main/java/io/spine/base/RejectionType.java @@ -59,8 +59,8 @@ public final class RejectionType extends MessageType { */ public static boolean test(Descriptor type) { checkNotNull(type); - boolean topLevel = isTopLevel(type); - FileName fileName = FileName.from(type.getFile()); + var topLevel = isTopLevel(type); + var fileName = FileName.from(type.getFile()); return topLevel && fileName.isRejections(); } @@ -84,8 +84,8 @@ public RejectionType(Descriptor message) { * {@code false} otherwise. */ public static boolean isValidOuterClassName(SimpleClassName className) { - boolean result = className.value() - .endsWith(OUTER_CLASS_NAME_SUFFIX); + var result = className.value() + .endsWith(OUTER_CLASS_NAME_SUFFIX); return result; } @@ -96,7 +96,7 @@ public static boolean isValidOuterClassName(SimpleClassName className) { * @return the fully qualified class name for the rejection message */ public ClassName messageClass() { - ClassName outerClass = ClassName.of(javaPackage(), outerJavaClass); + var outerClass = ClassName.of(javaPackage(), outerJavaClass); return outerClass.withNested(simpleJavaClassName()); } @@ -126,7 +126,7 @@ public boolean equals(@Nullable Object obj) { if (!super.equals(obj)) { return false; } - RejectionType other = (RejectionType) obj; + var other = (RejectionType) obj; return Objects.equals(this.outerJavaClass, other.outerJavaClass); } } diff --git a/base/src/main/java/io/spine/base/Time.java b/base/src/main/java/io/spine/base/Time.java index 55a9bff05c..0c14a6b8dc 100644 --- a/base/src/main/java/io/spine/base/Time.java +++ b/base/src/main/java/io/spine/base/Time.java @@ -56,7 +56,7 @@ private Time() { * @see #setProvider(Provider) */ public static synchronized Timestamp currentTime() { - Timestamp result = timeProvider.currentTime(); + var result = timeProvider.currentTime(); return result; } @@ -168,13 +168,12 @@ private SystemTimeProvider() { */ @Override public Timestamp currentTime() { - long millis = System.currentTimeMillis(); - long seconds = (millis / 1000); + var millis = System.currentTimeMillis(); + var seconds = (millis / 1000); @SuppressWarnings("NumericCastThatLosesPrecision") - int nanos = (int) (millis % 1000) * (int) MILLISECONDS.toNanos(1); - int nanosOnly = IncrementalNanos.valueForTime(seconds, nanos); - Timestamp result = Timestamp - .newBuilder() + var nanos = (int) (millis % 1000) * (int) MILLISECONDS.toNanos(1); + var nanosOnly = IncrementalNanos.valueForTime(seconds, nanos); + var result = Timestamp.newBuilder() .setSeconds(seconds) .setNanos(nanos + nanosOnly) .build(); From 092d43d750e40d9d21a813f283784a3c25d57891 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Wed, 8 Dec 2021 19:24:16 +0200 Subject: [PATCH 11/27] Use `var`s in `io.spine.code` package and its subpackages. --- .../io/spine/code/fs/AbstractSourceFile.java | 7 +- .../main/java/io/spine/code/fs/FsObject.java | 3 +- .../io/spine/code/fs/SourceCodeDirectory.java | 5 +- .../java/io/spine/code/java/ClassName.java | 54 +++++++------- .../java/io/spine/code/java/PackageName.java | 13 ++-- .../io/spine/code/java/PrimitiveType.java | 5 +- .../io/spine/code/java/SimpleClassName.java | 22 +++--- .../io/spine/code/proto/AbstractOption.java | 4 +- .../java/io/spine/code/proto/CamelCase.java | 9 +-- .../io/spine/code/proto/ColumnOption.java | 21 ++---- .../spine/code/proto/DescriptorReference.java | 29 ++++---- .../io/spine/code/proto/EntityIdField.java | 6 +- .../spine/code/proto/EntityStateOption.java | 9 ++- .../io/spine/code/proto/FieldContext.java | 22 +++--- .../io/spine/code/proto/FieldDeclaration.java | 70 ++++++++---------- .../java/io/spine/code/proto/FieldName.java | 10 +-- .../java/io/spine/code/proto/FieldTypes.java | 15 ++-- .../io/spine/code/proto/FieldTypesProto.java | 15 ++-- .../io/spine/code/proto/FileDescriptors.java | 35 ++++----- .../java/io/spine/code/proto/FileName.java | 26 +++---- .../java/io/spine/code/proto/FileSet.java | 62 +++++++--------- .../main/java/io/spine/code/proto/Linker.java | 53 +++++++------- .../io/spine/code/proto/LocationPath.java | 16 ++-- .../code/proto/OptionExtensionRegistry.java | 22 +++--- .../java/io/spine/code/proto/PackageName.java | 8 +- .../code/proto/ProtoBelongsToModule.java | 6 +- .../io/spine/code/proto/RejectionsFile.java | 33 ++++----- .../java/io/spine/code/proto/ScalarType.java | 6 +- .../java/io/spine/code/proto/SourceFile.java | 14 ++-- .../proto/SourceProtoBelongsToModule.java | 3 +- .../java/io/spine/code/proto/TypeSet.java | 73 +++++++++---------- 31 files changed, 322 insertions(+), 354 deletions(-) diff --git a/base/src/main/java/io/spine/code/fs/AbstractSourceFile.java b/base/src/main/java/io/spine/code/fs/AbstractSourceFile.java index f5cd06ad78..f0861b9f80 100644 --- a/base/src/main/java/io/spine/code/fs/AbstractSourceFile.java +++ b/base/src/main/java/io/spine/code/fs/AbstractSourceFile.java @@ -33,7 +33,6 @@ import java.io.IOException; import java.nio.file.Path; -import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.io.IoPreconditions.checkExists; @@ -61,10 +60,10 @@ protected AbstractSourceFile(Path path) { */ @OverridingMethodsMustInvokeSuper protected void load() { - Path path = path(); + var path = path(); checkExists(path.toFile()); try { - List loaded = readAllLines(path); + var loaded = readAllLines(path); lines = ImmutableList.copyOf(loaded); } catch (IOException e) { throw newIllegalStateException(e, "Unable to read the file `%s`.", path); @@ -76,7 +75,7 @@ protected void load() { */ @OverridingMethodsMustInvokeSuper public void store() { - Path path = path(); + var path = path(); try { write(path, lines(), Charsets.UTF_8, TRUNCATE_EXISTING); } catch (IOException e) { diff --git a/base/src/main/java/io/spine/code/fs/FsObject.java b/base/src/main/java/io/spine/code/fs/FsObject.java index cd2f4348d1..b42f19d5c1 100644 --- a/base/src/main/java/io/spine/code/fs/FsObject.java +++ b/base/src/main/java/io/spine/code/fs/FsObject.java @@ -34,7 +34,6 @@ import java.util.Objects; import static com.google.common.base.Preconditions.checkNotNull; -import static java.util.Objects.requireNonNull; /** * Abstract base for source code objects on a file system. @@ -96,7 +95,7 @@ public boolean equals(Object obj) { if (!(obj instanceof FsObject)) { return false; } - FsObject other = (FsObject) obj; + var other = (FsObject) obj; return Objects.equals(this.path, other.path); } } diff --git a/base/src/main/java/io/spine/code/fs/SourceCodeDirectory.java b/base/src/main/java/io/spine/code/fs/SourceCodeDirectory.java index a7d7b98d29..9d5ad24b41 100644 --- a/base/src/main/java/io/spine/code/fs/SourceCodeDirectory.java +++ b/base/src/main/java/io/spine/code/fs/SourceCodeDirectory.java @@ -36,6 +36,7 @@ * A directory with source code files. */ @Immutable +@SuppressWarnings("unused") /* Part of the public API. */ public abstract class SourceCodeDirectory extends AbstractDirectory { protected SourceCodeDirectory(Path path) { @@ -44,13 +45,13 @@ protected SourceCodeDirectory(Path path) { public Path resolve(SourceCodeDirectory dir) { checkNotNull(dir); - Path result = path().resolve(dir.path()); + var result = path().resolve(dir.path()); return result; } public Path resolve(AbstractSourceFile file) { checkNotNull(file); - Path result = path().resolve(file.path()); + var result = path().resolve(file.path()); return result; } } diff --git a/base/src/main/java/io/spine/code/java/ClassName.java b/base/src/main/java/io/spine/code/java/ClassName.java index 94477a8e6b..799e768d2d 100644 --- a/base/src/main/java/io/spine/code/java/ClassName.java +++ b/base/src/main/java/io/spine/code/java/ClassName.java @@ -117,9 +117,10 @@ public static ClassName of(PackageName packageName, SimpleClassName simpleClassN * the file from which the outer class is generated * @return new instance of {@code ClassName} */ + @SuppressWarnings("unused") /* Part of the public API. */ public static ClassName outerClass(FileDescriptor file) { - PackageName packageName = PackageName.resolve(file.toProto()); - SimpleClassName simpleName = SimpleClassName.outerOf(file); + var packageName = PackageName.resolve(file.toProto()); + var simpleName = SimpleClassName.outerOf(file); return of(packageName, simpleName); } @@ -169,7 +170,7 @@ public static ClassName from(ServiceDescriptor serviceType) { } private static String javaPackageName(FileDescriptor file) { - PackageName packageName = PackageName.resolve(file.toProto()); + var packageName = PackageName.resolve(file.toProto()); return packageName.value() + DOT_SEPARATOR; } @@ -179,13 +180,13 @@ private static String javaPackageName(FileDescriptor file) { */ private static String outerClassPrefix(FileDescriptor file) { checkNotNull(file); - boolean multipleFiles = file.getOptions() - .getJavaMultipleFiles(); + var multipleFiles = file.getOptions() + .getJavaMultipleFiles(); if (multipleFiles) { return ""; } else { - String className = SimpleClassName.outerOf(file) - .value(); + var className = SimpleClassName.outerOf(file) + .value(); return className + OUTER_CLASS_DELIMITER; } } @@ -199,12 +200,12 @@ private static String containingClassPrefix(@Nullable Descriptor containingMessa return ""; } Deque parentClassNames = newLinkedList(); - Descriptor current = containingMessage; + var current = containingMessage; while (current != null) { parentClassNames.addFirst(current.getName() + OUTER_CLASS_DELIMITER); current = current.getContainingType(); } - String result = String.join("", parentClassNames); + var result = String.join("", parentClassNames); return result; } @@ -227,7 +228,7 @@ public ClassName withNested(SimpleClassName className) { * @see Class#getCanonicalName() */ public String canonicalName() { - String withDots = toDotted(value()); + var withDots = toDotted(value()); return withDots; } @@ -251,7 +252,7 @@ public String canonicalName() { */ @Internal public static String toDotted(String outerDelimited) { - String result = outerDelimited.replace(OUTER_CLASS_DELIMITER, DOT_SEPARATOR); + var result = outerDelimited.replace(OUTER_CLASS_DELIMITER, DOT_SEPARATOR); return result; } @@ -267,6 +268,7 @@ public static String toDotted(String outerDelimited) { * * @return {@code MessageOrBuilder} interface FQN */ + @SuppressWarnings("unused") /* Part of the public API. */ public ClassName orBuilder() { return of(value() + OR_BUILDER_SUFFIX); } @@ -274,10 +276,10 @@ public ClassName orBuilder() { private static ClassName construct(FileDescriptor file, String typeName, @Nullable Descriptor enclosing) { - String packageName = javaPackageName(file); - String outerClass = outerClassPrefix(file); - String enclosingTypes = containingClassPrefix(enclosing); - String result = packageName + outerClass + enclosingTypes + typeName; + var packageName = javaPackageName(file); + var outerClass = outerClassPrefix(file); + var enclosingTypes = containingClassPrefix(enclosing); + var result = packageName + outerClass + enclosingTypes + typeName; return of(result); } @@ -286,8 +288,8 @@ private static ClassName construct(FileDescriptor file, * classes, the most nested name will be returned. */ public SimpleClassName toSimple() { - String fullName = canonicalName(); - String result = afterDot(fullName); + var fullName = canonicalName(); + var result = afterDot(fullName); return SimpleClassName.create(result); } @@ -299,6 +301,7 @@ public SimpleClassName toSimple() { * @return this name without the package */ @Internal + @SuppressWarnings("unused") /* Part of the public API. */ public String withoutPackage() { return toDotted(afterDot(value())); } @@ -311,7 +314,7 @@ public String withoutPackage() { * @return the last part of the name */ private static String afterDot(String fullName) { - int lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR); + var lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR); return fullName.substring(lastDotIndex + 1); } @@ -319,14 +322,14 @@ private static String afterDot(String fullName) { * Obtains the name of the package of this class. */ public PackageName packageName() { - int packageEndIndex = packageEndIndex(); - String result = value().substring(0, packageEndIndex); + var packageEndIndex = packageEndIndex(); + var result = value().substring(0, packageEndIndex); return PackageName.of(result); } private int packageEndIndex() { - String fullName = value(); - int lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR); + var fullName = value(); + var lastDotIndex = fullName.lastIndexOf(DOT_SEPARATOR); checkState(lastDotIndex > 0, "%s should be qualified.", fullName); return lastDotIndex; } @@ -337,10 +340,11 @@ private int packageEndIndex() { *

If this class is top level, returns the simple name of this class. If this class is * nested, returns the name of the declaring top level class. */ + @SuppressWarnings("unused") /* Part of the public API. */ public SimpleClassName topLevelClass() { - String qualifiedClassName = afterDot(value()); - int delimiterIndex = qualifiedClassName.indexOf(OUTER_CLASS_DELIMITER); - String topLevelClassName = delimiterIndex >= 0 + var qualifiedClassName = afterDot(value()); + var delimiterIndex = qualifiedClassName.indexOf(OUTER_CLASS_DELIMITER); + var topLevelClassName = delimiterIndex >= 0 ? qualifiedClassName.substring(0, delimiterIndex) : qualifiedClassName; return SimpleClassName.create(topLevelClassName); diff --git a/base/src/main/java/io/spine/code/java/PackageName.java b/base/src/main/java/io/spine/code/java/PackageName.java index f32c9daaeb..396f6e2dc9 100644 --- a/base/src/main/java/io/spine/code/java/PackageName.java +++ b/base/src/main/java/io/spine/code/java/PackageName.java @@ -58,7 +58,7 @@ private PackageName(String value) { */ public static PackageName of(String value) { checkNotNull(value); - PackageName result = new PackageName(value); + var result = new PackageName(value); return result; } @@ -83,7 +83,7 @@ public static PackageName of(Class cls) { */ public PackageName nested(String name) { checkNotNull(name); - PackageName result = of(value() + delimiter() + name); + var result = of(value() + delimiter() + name); return result; } @@ -97,6 +97,7 @@ public static String delimiter() { /** * Obtains Java package delimiter as a single {@code char}. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static char delimiterChar() { return DELIMITER_CHAR; } @@ -105,20 +106,20 @@ public static char delimiterChar() { * Obtains a Java package name by the passed file descriptor. */ public static PackageName resolve(FileDescriptorProto file) { - String javaPackage = resolveName(file).trim(); + var javaPackage = resolveName(file).trim(); checkArgument( !javaPackage.isEmpty(), "Message classes generated from the file `%s` belong to the default package.%n" + "Please use `option java_package` or `package`" + " to specify a Java package for these types.", file.getName() ); - PackageName result = new PackageName(javaPackage); + var result = new PackageName(javaPackage); return result; } private static String resolveName(FileDescriptorProto file) { - String javaPackage = file.getOptions() - .getJavaPackage(); + var javaPackage = file.getOptions() + .getJavaPackage(); if (isNullOrEmpty(javaPackage)) { javaPackage = file.getPackage(); } diff --git a/base/src/main/java/io/spine/code/java/PrimitiveType.java b/base/src/main/java/io/spine/code/java/PrimitiveType.java index a416357550..ff9a196cbd 100644 --- a/base/src/main/java/io/spine/code/java/PrimitiveType.java +++ b/base/src/main/java/io/spine/code/java/PrimitiveType.java @@ -35,6 +35,7 @@ /** * Enumeration of the Java primitives used for representing Proto scalar types. */ +@SuppressWarnings("unused") /* Part of the public API. */ public enum PrimitiveType { INT(int.class, Integer.class), LONG(long.class, Long.class), @@ -59,7 +60,7 @@ public enum PrimitiveType { */ public static Optional> getWrapperClass(String primitiveType) { checkNotEmptyOrBlank(primitiveType); - for (PrimitiveType simpleType : values()) { + for (var simpleType : values()) { if (simpleType.matchesName(primitiveType)) { return Optional.of(simpleType.getWrapperClass()); } @@ -69,7 +70,7 @@ public static Optional> getWrapperClass(String primitiveType) } boolean matchesName(String typeName) { - boolean result = getName().equals(typeName); + var result = getName().equals(typeName); return result; } diff --git a/base/src/main/java/io/spine/code/java/SimpleClassName.java b/base/src/main/java/io/spine/code/java/SimpleClassName.java index 1644777671..16f7f676f6 100644 --- a/base/src/main/java/io/spine/code/java/SimpleClassName.java +++ b/base/src/main/java/io/spine/code/java/SimpleClassName.java @@ -79,8 +79,8 @@ public static SimpleClassName create(@ClassGetSimpleName String value) { */ public static SimpleClassName outerOf(FileDescriptorProto file) { checkNotNull(file); - String value = outerClassNameOf(file); - SimpleClassName result = create(value); + var value = outerClassNameOf(file); + var result = create(value); return result; } @@ -100,17 +100,16 @@ public static SimpleClassName outerOf(FileDescriptor file) { * {@linkplain Optional#empty() empty Optional} if the option is not set */ public static Optional declaredOuterClassName(FileDescriptor file) { - String className = declaredOuterClassName(file.toProto()); + var className = declaredOuterClassName(file.toProto()); if (className.isEmpty()) { return Optional.empty(); } - SimpleClassName result = outerOf(file); + var result = outerOf(file); return Optional.of(result); } private static String declaredOuterClassName(FileDescriptorProto file) { - String result = file.getOptions() - .getJavaOuterClassname(); + var result = file.getOptions().getJavaOuterClassname(); return result; } @@ -128,13 +127,12 @@ private static String declaredOuterClassName(FileDescriptorProto file) { */ private static String outerClassNameOf(FileDescriptorProto file) { checkNotNull(file); - String nameDeclaredInOptions = declaredOuterClassName(file); + var nameDeclaredInOptions = declaredOuterClassName(file); if (!nameDeclaredInOptions.isEmpty()) { return nameDeclaredInOptions; } - String className = - io.spine.code.proto.FileName.from(file) - .nameOnlyCamelCase(); + var className = io.spine.code.proto.FileName.from(file) + .nameOnlyCamelCase(); return className; } @@ -151,7 +149,7 @@ public static SimpleClassName ofBuilder() { */ public static SimpleClassName messageOrBuilder(@ClassGetSimpleName String typeName) { checkNotEmptyOrBlank(typeName); - SimpleClassName result = create(typeName + OR_BUILDER_SUFFIX); + var result = create(typeName + OR_BUILDER_SUFFIX); return result; } @@ -160,7 +158,7 @@ public static SimpleClassName messageOrBuilder(@ClassGetSimpleName String typeNa */ public static SimpleClassName ofMessage(Descriptor descriptor) { checkNotNull(descriptor); - SimpleClassName result = create(descriptor.getName()); + var result = create(descriptor.getName()); return result; } diff --git a/base/src/main/java/io/spine/code/proto/AbstractOption.java b/base/src/main/java/io/spine/code/proto/AbstractOption.java index 9c054951a0..0dc7efed27 100644 --- a/base/src/main/java/io/spine/code/proto/AbstractOption.java +++ b/base/src/main/java/io/spine/code/proto/AbstractOption.java @@ -75,7 +75,7 @@ protected GeneratedExtension extension() { @Override public Optional valueFrom(K object) { - E options = optionsFrom(object); + var options = optionsFrom(object); return options.hasExtension(extension) ? Optional.of(options.getExtension(this.extension)) : Optional.empty(); @@ -90,7 +90,7 @@ public boolean equals(Object o) { if (!(o instanceof AbstractOption)) { return false; } - AbstractOption option = (AbstractOption) o; + var option = (AbstractOption) o; return extension.getNumber() == option.extension.getNumber(); } diff --git a/base/src/main/java/io/spine/code/proto/CamelCase.java b/base/src/main/java/io/spine/code/proto/CamelCase.java index 90b365dcba..2293f22cd3 100644 --- a/base/src/main/java/io/spine/code/proto/CamelCase.java +++ b/base/src/main/java/io/spine/code/proto/CamelCase.java @@ -26,8 +26,6 @@ package io.spine.code.proto; -import java.util.Iterator; - import static java.lang.Character.toUpperCase; /** @@ -46,11 +44,10 @@ private CamelCase() { * {@code "TestHTTPRequest"}. */ static String convert(UnderscoredName name) { - Iterator iterator = name.words() - .iterator(); - StringBuilder builder = new StringBuilder(name.value().length()); + var iterator = name.words().iterator(); + var builder = new StringBuilder(name.value().length()); while (iterator.hasNext()) { - String word = iterator.next(); + var word = iterator.next(); if (!word.isEmpty()) { builder.append(toUpperCase(word.charAt(0))) .append(word.substring(1)); diff --git a/base/src/main/java/io/spine/code/proto/ColumnOption.java b/base/src/main/java/io/spine/code/proto/ColumnOption.java index 99f9576ea7..4ee83e50c1 100644 --- a/base/src/main/java/io/spine/code/proto/ColumnOption.java +++ b/base/src/main/java/io/spine/code/proto/ColumnOption.java @@ -27,12 +27,9 @@ package io.spine.code.proto; import com.google.common.collect.ImmutableList; -import io.spine.option.EntityOption; import io.spine.option.OptionsProto; import io.spine.type.MessageType; -import java.util.Optional; - import static com.google.common.collect.ImmutableList.toImmutableList; /** @@ -64,9 +61,8 @@ public static boolean hasColumns(MessageType messageType) { if (!declaresEntity(messageType)) { return false; } - boolean result = messageType.fields() - .stream() - .anyMatch(ColumnOption::isColumn); + var result = messageType.fields().stream() + .anyMatch(ColumnOption::isColumn); return result; } @@ -80,10 +76,9 @@ public static ImmutableList columnsOf(MessageType messageType) if (!declaresEntity(messageType)) { return ImmutableList.of(); } - ImmutableList result = messageType.fields() - .stream() - .filter(ColumnOption::isColumn) - .collect(toImmutableList()); + var result = messageType.fields().stream() + .filter(ColumnOption::isColumn) + .collect(toImmutableList()); return result; } @@ -102,8 +97,8 @@ public static boolean isColumn(FieldDeclaration field) { if (field.isCollection()) { return false; } - ColumnOption option = new ColumnOption(); - Optional value = option.valueFrom(field.descriptor()); + var option = new ColumnOption(); + var value = option.valueFrom(field.descriptor()); boolean isColumn = value.orElse(false); return isColumn; } @@ -113,7 +108,7 @@ public static boolean isColumn(FieldDeclaration field) { */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") // For readability. private static boolean declaresEntity(MessageType messageType) { - Optional entityOption = EntityStateOption.valueOf(messageType.descriptor()); + var entityOption = EntityStateOption.valueOf(messageType.descriptor()); return entityOption.isPresent(); } } diff --git a/base/src/main/java/io/spine/code/proto/DescriptorReference.java b/base/src/main/java/io/spine/code/proto/DescriptorReference.java index 2f665051bf..c866de328c 100644 --- a/base/src/main/java/io/spine/code/proto/DescriptorReference.java +++ b/base/src/main/java/io/spine/code/proto/DescriptorReference.java @@ -35,13 +35,11 @@ import java.io.File; import java.io.IOException; -import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Iterator; -import java.util.List; import static com.google.common.base.Charsets.UTF_8; import static com.google.common.base.Preconditions.checkNotNull; @@ -111,9 +109,8 @@ static Iterator loadAll() { */ @VisibleForTesting static Iterator loadFromResources(Collection resources) { - ClassLoader classLoader = DescriptorReference.class.getClassLoader(); - return resources - .stream() + var classLoader = DescriptorReference.class.getClassLoader(); + return resources.stream() .map(DescriptorReference::readCatalog) .flatMap(catalog -> LINE_SPLITTER.splitToList(catalog).stream()) .distinct() @@ -122,9 +119,9 @@ static Iterator loadFromResources(Collection resources) { } private static String readCatalog(URL resource) { - try (InputStream catalogStream = resource.openStream()) { - byte[] catalogBytes = toByteArray(catalogStream); - String catalog = new String(catalogBytes, UTF_8); + try (var catalogStream = resource.openStream()) { + var catalogBytes = toByteArray(catalogStream); + var catalog = new String(catalogBytes, UTF_8); return catalog; } catch (IOException e) { throw illegalStateWithCauseOf(e); @@ -141,13 +138,13 @@ private static String readCatalog(URL resource) { */ public void writeTo(Path directory) { checkNotNull(directory); - Path targetFile = directory.resolve(FILE_NAME); + var targetFile = directory.resolve(FILE_NAME); Ensure.ensureFile(targetFile); try { - List resources = Files.readAllLines(targetFile); + var resources = Files.readAllLines(targetFile); resources.add(reference); - String result = String.join(SEPARATOR, resources) - .trim(); + var result = String.join(SEPARATOR, resources) + .trim(); Files.write(targetFile, ImmutableList.of(result), TRUNCATE_EXISTING); } catch (IOException e) { throw illegalStateWithCauseOf(e); @@ -174,13 +171,13 @@ public void writeTo(Path directory) { @VisibleForTesting void writeTo(Path directory, String newline) { checkNotNull(directory); - Path targetFile = directory.resolve(FILE_NAME); + var targetFile = directory.resolve(FILE_NAME); Ensure.ensureFile(targetFile); try { - List resources = Files.readAllLines(targetFile); + var resources = Files.readAllLines(targetFile); resources.add(reference + newline); - String result = String.join(SEPARATOR, resources) - .trim(); + var result = String.join(SEPARATOR, resources) + .trim(); Files.write(targetFile, ImmutableList.of(result), TRUNCATE_EXISTING); } catch (IOException e) { throw illegalStateWithCauseOf(e); diff --git a/base/src/main/java/io/spine/code/proto/EntityIdField.java b/base/src/main/java/io/spine/code/proto/EntityIdField.java index cca7899c70..912fb6cc3f 100644 --- a/base/src/main/java/io/spine/code/proto/EntityIdField.java +++ b/base/src/main/java/io/spine/code/proto/EntityIdField.java @@ -26,7 +26,6 @@ package io.spine.code.proto; -import com.google.common.collect.ImmutableList; import io.spine.type.MessageType; import static com.google.common.base.Preconditions.checkArgument; @@ -38,6 +37,7 @@ * The first field of the Protobuf message marked with {@code (entity)} option, representing * its identifier. */ +@SuppressWarnings("unused") /* Part of the public API. */ public final class EntityIdField { private final FieldDeclaration declaration; @@ -57,11 +57,11 @@ public static EntityIdField of(MessageType messageType) { checkArgument(messageType.isEntityState(), "`EntityIdField` expected an `EntityState` descendant, " + "but got `%s`.", messageType.javaClassName()); - ImmutableList fields = messageType.fields(); + var fields = messageType.fields(); checkState(fields.size() > 0, "At least one field is expected to be declared " + "in the `EntityState` message of type `%s`.", messageType.javaClassName()); - FieldDeclaration declaration = fields.get(0); + var declaration = fields.get(0); checkState(!isColumn(declaration), "`EntityIdField` must not be marked as `(column)`." + " Please check the declaration of `%s` type.", messageType.toProto().getName()); return new EntityIdField(declaration); diff --git a/base/src/main/java/io/spine/code/proto/EntityStateOption.java b/base/src/main/java/io/spine/code/proto/EntityStateOption.java index 3a4be0e6f6..ef5aca7090 100644 --- a/base/src/main/java/io/spine/code/proto/EntityStateOption.java +++ b/base/src/main/java/io/spine/code/proto/EntityStateOption.java @@ -35,8 +35,9 @@ /** * An option for a message representing a state of the entity which defines its kind and visibility - * to queries. There are four kids of options, namely, Aggregate, Projection, Process Manager, - * and Entity). + * to queries. + * + *

There are four kids of options, namely, Aggregate, Projection, Process Manager, and Entity. */ @Immutable public final class EntityStateOption extends MessageOption { @@ -60,7 +61,7 @@ private EntityStateOption() { * to avoid instantiating an object. */ public static Optional valueOf(Descriptor message) { - EntityStateOption option = new EntityStateOption(); + var option = new EntityStateOption(); return option.valueFrom(message); } @@ -71,7 +72,7 @@ public static Optional valueOf(Descriptor message) { * {@code Optional} otherwise */ public static Optional entityKindOf(Descriptor message) { - Optional option = valueOf(message); + var option = valueOf(message); return option.map(EntityOption::getKind); } } diff --git a/base/src/main/java/io/spine/code/proto/FieldContext.java b/base/src/main/java/io/spine/code/proto/FieldContext.java index 1be3efa0cb..98bf2b1543 100644 --- a/base/src/main/java/io/spine/code/proto/FieldContext.java +++ b/base/src/main/java/io/spine/code/proto/FieldContext.java @@ -34,7 +34,7 @@ import java.util.Objects; import java.util.Optional; -import static com.google.common.base.Preconditions.checkNotNull; +import static java.util.Objects.requireNonNull; /** * Provides information about a proto field in the nesting hierarchy. @@ -119,7 +119,7 @@ public FieldContext forChild(FieldDeclaration child) { * @return the target descriptor */ public FieldDescriptor target() { - return checkNotNull(target, "Empty context cannot have a target."); + return requireNonNull(target, "Empty context cannot have a target."); } /** @@ -128,7 +128,7 @@ public FieldDescriptor target() { * @return the target declaration */ public FieldDeclaration targetDeclaration() { - FieldDescriptor target = target(); + var target = target(); return new FieldDeclaration(target); } @@ -165,19 +165,17 @@ public FieldPath fieldPath() { * @return {@code true} if this context has the same target and the same parent */ public boolean hasSameTargetAndParent(FieldContext other) { - String thisTargetName = target().getFullName(); - String otherTargetName = other.target() - .getFullName(); - boolean sameTarget = thisTargetName.equals(otherTargetName); + var thisTargetName = target().getFullName(); + var otherTargetName = other.target().getFullName(); + var sameTarget = thisTargetName.equals(otherTargetName); if (!sameTarget) { return false; } - Optional parentFromThis = targetParent() + var parentFromThis = targetParent() .map(FieldDescriptor::getFullName); - Optional parentFromOther = other - .targetParent() + var parentFromOther = other.targetParent() .map(FieldDescriptor::getFullName); - boolean bothHaveParents = parentFromThis.isPresent() && parentFromOther.isPresent(); + var bothHaveParents = parentFromThis.isPresent() && parentFromOther.isPresent(); return bothHaveParents && parentFromThis.get() .equals(parentFromOther.get()); } @@ -190,7 +188,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - FieldContext context = (FieldContext) o; + var context = (FieldContext) o; return Objects.equals(targetNameOrEmpty(), context.targetNameOrEmpty()) && Objects.equals(parent, context.parent); } diff --git a/base/src/main/java/io/spine/code/proto/FieldDeclaration.java b/base/src/main/java/io/spine/code/proto/FieldDeclaration.java index 45ba02c822..191a5852fe 100644 --- a/base/src/main/java/io/spine/code/proto/FieldDeclaration.java +++ b/base/src/main/java/io/spine/code/proto/FieldDeclaration.java @@ -30,11 +30,8 @@ import com.google.common.primitives.Primitives; import com.google.errorprone.annotations.Immutable; import com.google.protobuf.Any; -import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; -import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; -import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.base.MessageFile; @@ -46,7 +43,6 @@ import io.spine.type.KnownTypes; import io.spine.type.MessageType; import io.spine.type.TypeName; -import io.spine.type.TypeUrl; import io.spine.type.UnknownTypeException; import java.util.Optional; @@ -128,7 +124,7 @@ public boolean isDefault(Object fieldValue) { checkNotNull(fieldValue); if (isMessage()) { if (fieldValue instanceof Message) { - Message message = (Message) fieldValue; + var message = (Message) fieldValue; return Messages.isDefault(message) && sameMessageType(message); } else { return false; @@ -139,9 +135,8 @@ public boolean isDefault(Object fieldValue) { } private boolean sameMessageType(Message msg) { - String messageClassName = msg.getClass() - .getName(); - String fieldClassName = messageClassName(); + var messageClassName = msg.getClass().getName(); + var fieldClassName = messageClassName(); return fieldClassName.equals(messageClassName); } @@ -160,16 +155,16 @@ public String javaTypeName() { } private static String javaTypeName(FieldDescriptor field) { - FieldDescriptor.Type fieldType = field.getType(); + var fieldType = field.getType(); if (fieldType == MESSAGE) { - MessageType messageType = + var messageType = new MessageType(field.getMessageType()); return messageType.javaClassName() .canonicalName(); } if (fieldType == ENUM) { - EnumType enumType = EnumType.create(field.getEnumType()); + var enumType = EnumType.create(field.getEnumType()); return enumType.javaClassName() .canonicalName(); } @@ -178,14 +173,14 @@ private static String javaTypeName(FieldDescriptor field) { } private String messageClassName() { - TypeName typeName = TypeName.from(field.getMessageType()); - KnownTypes knownTypes = KnownTypes.instance(); + var typeName = TypeName.from(field.getMessageType()); + var knownTypes = KnownTypes.instance(); try { - TypeUrl fieldType = typeName.toUrl(); - ClassName className = knownTypes.classNameOf(fieldType); + var fieldType = typeName.toUrl(); + var className = knownTypes.classNameOf(fieldType); return className.value(); } catch (UnknownTypeException e) { - String allTypeUrls = knownTypes.printAllTypes(); + var allTypeUrls = knownTypes.printAllTypes(); throw newIllegalStateException( e, "Cannot find a type %s in the list of known types:%n%s", typeName, allTypeUrls @@ -207,7 +202,7 @@ private String messageClassName() { * @return {@code true} if the field is an entity ID, {@code false} otherwise */ public boolean isId() { - boolean fieldMatches = isFirstField() && isNotCollection(); + var fieldMatches = isFirstField() && isNotCollection(); return fieldMatches && (isCommandsFile() || isEntityField()); } @@ -307,7 +302,7 @@ public JavaType javaType() { @Internal public MessageType messageType() { checkState(isMessage()); - Descriptor messageType = descriptor().getMessageType(); + var messageType = descriptor().getMessageType(); return new MessageType(messageType); } @@ -318,9 +313,9 @@ public MessageType messageType() { public ClassName className() { if (isScalar()) { @SuppressWarnings("OptionalGetWithoutIsPresent") // checked in `if` - ScalarType scalarType = ScalarType.of(descriptor().toProto()).get(); - Class type = scalarType.javaClass(); - Class wrapped = Primitives.wrap(type); + var scalarType = ScalarType.of(descriptor().toProto()).get(); + var type = scalarType.javaClass(); + var wrapped = Primitives.wrap(type); return ClassName.of(wrapped); } return ClassName.of(javaTypeName()); @@ -328,16 +323,15 @@ public ClassName className() { /** Obtains the descriptor of the value of a map. */ public FieldDeclaration valueDeclaration() { - FieldDescriptor valueDescriptor = FieldTypes.valueDescriptor(field); + var valueDescriptor = FieldTypes.valueDescriptor(field); return new FieldDeclaration(valueDescriptor); } private boolean isEntityField() { - EntityOption entityOption = - field.getContainingType() - .getOptions() - .getExtension(OptionsProto.entity); - EntityOption.Kind entityKind = entityOption.getKind(); + var entityOption = field.getContainingType() + .getOptions() + .getExtension(OptionsProto.entity); + var entityKind = entityOption.getKind(); return entityKind.getNumber() > 0; } @@ -355,8 +349,8 @@ private boolean isFirstField() { } private boolean isCommandsFile() { - FileDescriptor file = field.getFile(); - boolean result = MessageFile.COMMANDS.test(file.toProto()); + var file = field.getFile(); + var result = MessageFile.COMMANDS.test(file.toProto()); return result; } @@ -364,8 +358,8 @@ private boolean isCommandsFile() { * Returns the name of the getter generated by the Protobuf Java plugin for the field. */ public String javaGetterName() { - String camelCasedName = name().toCamelCase(); - String result = format("get%s", camelCasedName); + var camelCasedName = name().toCamelCase(); + var result = format("get%s", camelCasedName); return result; } @@ -374,8 +368,9 @@ public String javaGetterName() { * * @return the leading field comments or {@code Optional.empty()} if there are no comments */ + @SuppressWarnings("unused") /* Part of the public API. */ public Optional leadingComments() { - LocationPath fieldPath = fieldPath(); + var fieldPath = fieldPath(); return declaringMessage.leadingComments(fieldPath); } @@ -387,15 +382,14 @@ public Optional leadingComments() { * @return the field location path */ private LocationPath fieldPath() { - LocationPath locationPath = - new LocationPath(declaringMessage.path()) - .append(FIELD_FIELD_NUMBER) - .append(fieldIndex()); + var locationPath = new LocationPath(declaringMessage.path()) + .append(FIELD_FIELD_NUMBER) + .append(fieldIndex()); return locationPath; } private int fieldIndex() { - FieldDescriptorProto proto = this.field.toProto(); + var proto = this.field.toProto(); return declaringMessage.descriptor() .toProto() .getFieldList() @@ -410,7 +404,7 @@ public boolean equals(Object o) { if (!(o instanceof FieldDeclaration)) { return false; } - FieldDeclaration that = (FieldDeclaration) o; + var that = (FieldDeclaration) o; return Objects.equal(declaringMessage, that.declaringMessage) && Objects.equal(field.getFullName(), that.field.getFullName()); } diff --git a/base/src/main/java/io/spine/code/proto/FieldName.java b/base/src/main/java/io/spine/code/proto/FieldName.java index 0c47b618bf..90f195d1bb 100644 --- a/base/src/main/java/io/spine/code/proto/FieldName.java +++ b/base/src/main/java/io/spine/code/proto/FieldName.java @@ -96,8 +96,8 @@ public static FieldName of(FieldDescriptorProto field) { */ @Override public List words() { - String[] words = WORD_SEPARATOR_PATTERN.split(value()); - ImmutableList result = ImmutableList.copyOf(words); + var words = WORD_SEPARATOR_PATTERN.split(value()); + var result = ImmutableList.copyOf(words); return result; } @@ -105,8 +105,8 @@ public List words() { * Obtains the field name in {@code javaCase}. */ public String javaCase() { - String camelCase = toCamelCase(); - String result = Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1); + var camelCase = toCamelCase(); + var result = Character.toLowerCase(camelCase.charAt(0)) + camelCase.substring(1); return result; } @@ -114,7 +114,7 @@ public String javaCase() { * Obtains this field name as a single-entry field path. */ public FieldPath asPath() { - Field field = Field.named(value()); + var field = Field.named(value()); return field.path(); } } diff --git a/base/src/main/java/io/spine/code/proto/FieldTypes.java b/base/src/main/java/io/spine/code/proto/FieldTypes.java index 319d04bd06..b74f27613a 100644 --- a/base/src/main/java/io/spine/code/proto/FieldTypes.java +++ b/base/src/main/java/io/spine/code/proto/FieldTypes.java @@ -26,7 +26,6 @@ package io.spine.code.proto; -import com.google.protobuf.DescriptorProtos.FieldDescriptorProto; import com.google.protobuf.Descriptors.FieldDescriptor; import static com.google.common.base.Preconditions.checkArgument; @@ -62,7 +61,7 @@ private FieldTypes() { */ public static boolean isMessage(FieldDescriptor field) { checkNotNull(field); - boolean isMessage = field.getType() == MESSAGE; + var isMessage = field.getType() == MESSAGE; return isMessage; } @@ -78,7 +77,7 @@ public static boolean isMessage(FieldDescriptor field) { */ public static boolean isRepeated(FieldDescriptor field) { checkNotNull(field); - FieldDescriptorProto proto = field.toProto(); + var proto = field.toProto(); return FieldTypesProto.isRepeated(proto); } @@ -91,7 +90,7 @@ public static boolean isRepeated(FieldDescriptor field) { */ public static boolean isMap(FieldDescriptor field) { checkNotNull(field); - FieldDescriptorProto proto = field.toProto(); + var proto = field.toProto(); return FieldTypesProto.isMap(proto); } @@ -111,8 +110,8 @@ public static FieldDescriptor keyDescriptor(FieldDescriptor field) { checkArgument(isMap(field), "Trying to get key descriptor for the non-map field %s.", field.getName()); - FieldDescriptor descriptor = field.getMessageType() - .findFieldByName(MAP_ENTRY_KEY); + var descriptor = field.getMessageType() + .findFieldByName(MAP_ENTRY_KEY); return descriptor; } @@ -132,8 +131,8 @@ public static FieldDescriptor valueDescriptor(FieldDescriptor field) { checkArgument(isMap(field), "Trying to get value descriptor for the non-map field %s.", field.getName()); - FieldDescriptor descriptor = field.getMessageType() - .findFieldByName(MAP_ENTRY_VALUE); + var descriptor = field.getMessageType() + .findFieldByName(MAP_ENTRY_VALUE); return descriptor; } } diff --git a/base/src/main/java/io/spine/code/proto/FieldTypesProto.java b/base/src/main/java/io/spine/code/proto/FieldTypesProto.java index 1abc021843..a18d0c19d5 100644 --- a/base/src/main/java/io/spine/code/proto/FieldTypesProto.java +++ b/base/src/main/java/io/spine/code/proto/FieldTypesProto.java @@ -56,7 +56,7 @@ private FieldTypesProto() { */ public static boolean isRepeated(FieldDescriptorProto field) { checkNotNull(field); - boolean result = field.getLabel() == LABEL_REPEATED && !isMap(field); + var result = field.getLabel() == LABEL_REPEATED && !isMap(field); return result; } @@ -77,8 +77,8 @@ public static boolean isMap(FieldDescriptorProto field) { if (field.getType() != TYPE_MESSAGE) { return false; } - boolean result = field.getTypeName() - .endsWith('.' + getEntryNameFor(field)); + var result = field.getTypeName() + .endsWith('.' + getEntryNameFor(field)); return result; } @@ -94,7 +94,8 @@ public static boolean isMap(FieldDescriptorProto field) { * @return the name of the map field */ public static String getEntryNameFor(FieldDescriptorProto mapField) { - FieldName fieldName = FieldName.of(mapField); + checkNotNull(mapField); + var fieldName = FieldName.of(mapField); return fieldName.toCamelCase() + ENTRY_SUFFIX; } @@ -119,14 +120,16 @@ public static boolean isMessage(FieldDescriptorProto fieldDescriptor) { * the field descriptor whose type name to modify * @return the type name without leading dot */ + @SuppressWarnings("unused") /* Part of the public API. */ public static String trimTypeName(FieldDescriptorProto fieldDescriptor) { - String typeName = fieldDescriptor.getTypeName(); + checkNotNull(fieldDescriptor); + var typeName = fieldDescriptor.getTypeName(); checkNotNull(typeName); if (typeName.isEmpty()) { return typeName; } - String trimmedName = removeLeadingDot(typeName); + var trimmedName = removeLeadingDot(typeName); return trimmedName; } diff --git a/base/src/main/java/io/spine/code/proto/FileDescriptors.java b/base/src/main/java/io/spine/code/proto/FileDescriptors.java index d1b201eab3..42d11b228d 100644 --- a/base/src/main/java/io/spine/code/proto/FileDescriptors.java +++ b/base/src/main/java/io/spine/code/proto/FileDescriptors.java @@ -34,9 +34,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; import java.net.URL; -import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.function.Function; @@ -112,12 +110,11 @@ private static FluentLogger.Api _debug() { descriptorSet); List files; - try (FileInputStream fis = new FileInputStream(descriptorSet)) { - FileDescriptorSet fileSet = FileDescriptorSetReader.parse(fis); - files = fileSet.getFileList() - .stream() - .filter(filter) - .collect(toList()); + try (var fis = new FileInputStream(descriptorSet)) { + var fileSet = FileDescriptorSetReader.parse(fis); + files = fileSet.getFileList().stream() + .filter(filter) + .collect(toList()); } catch (IOException e) { throw newIllegalStateException( e, "Cannot get proto file descriptors. Path: `%s`.", descriptorSet @@ -134,8 +131,8 @@ private static FluentLogger.Api _debug() { * contained in the loaded files */ static Set load() { - Iterator resources = DescriptorReference.loadAll(); - Set files = stream(resources) + var resources = DescriptorReference.loadAll(); + var files = stream(resources) .map(FileDescriptors::loadFrom) .flatMap(set -> set.getFileList().stream()) .filter(distinctBy(FileDescriptorProto::getName)) @@ -162,8 +159,8 @@ static Set load() { private static Predicate distinctBy(Function selector) { Set seen = newHashSet(); return element -> { - K key = selector.apply(element); - boolean newKey = seen.add(key); + var key = selector.apply(element); + var newKey = seen.add(key); return newKey; }; } @@ -179,8 +176,8 @@ private static FileDescriptorSet loadFrom(Resource resource) { } private static FileDescriptorSet doLoadFrom(Resource resource) { - try (InputStream stream = resource.open()) { - FileDescriptorSet parsed = FileDescriptorSetReader.parse(stream); + try (var stream = resource.open()) { + var parsed = FileDescriptorSetReader.parse(stream); return parsed; } catch (IOException e) { throw newIllegalStateException( @@ -195,10 +192,10 @@ private static FileDescriptorSet doLoadFrom(Resource resource) { * Tells if two descriptors represent the same file. */ public static boolean sameFiles(FileDescriptor f1, FileDescriptor f2) { - boolean sameName = f2.getFullName() - .equals(f1.getFullName()); - boolean samePackage = f2.getPackage() - .equals(f1.getPackage()); + var sameName = f2.getFullName() + .equals(f1.getFullName()); + var samePackage = f2.getPackage() + .equals(f1.getPackage()); return sameName && samePackage; } @@ -206,7 +203,7 @@ public static boolean sameFiles(FileDescriptor f1, FileDescriptor f2) { * Verifies if the passed file declares types under the "google" package. */ public static boolean isGoogle(FileDescriptor file) { - PackageName packageName = PackageName.of(file.getPackage()); + var packageName = PackageName.of(file.getPackage()); return packageName.isGoogle(); } } diff --git a/base/src/main/java/io/spine/code/proto/FileName.java b/base/src/main/java/io/spine/code/proto/FileName.java index 9b9d44e737..26a815efe6 100644 --- a/base/src/main/java/io/spine/code/proto/FileName.java +++ b/base/src/main/java/io/spine/code/proto/FileName.java @@ -71,7 +71,7 @@ public static FileName of(String value) { */ public static FileName from(FileDescriptorProto descriptor) { checkNotNull(descriptor); - FileName result = of(descriptor.getName()); + var result = of(descriptor.getName()); return result; } @@ -87,8 +87,8 @@ public static FileName from(FileDescriptor descriptor) { */ @Override public List words() { - String[] words = nameOnly().split(WORD_SEPARATOR); - ImmutableList result = ImmutableList.copyOf(words); + var words = nameOnly().split(WORD_SEPARATOR); + var result = ImmutableList.copyOf(words); return result; } @@ -96,9 +96,9 @@ public List words() { * Obtains the file name without path and extension. */ private String nameOnly() { - String name = nameWithoutExtension(); - int lastBackslashIndex = name.lastIndexOf(PATH_SEPARATOR); - String result = name.substring(lastBackslashIndex + 1); + var name = nameWithoutExtension(); + var lastBackslashIndex = name.lastIndexOf(PATH_SEPARATOR); + var result = name.substring(lastBackslashIndex + 1); return result; } @@ -106,9 +106,9 @@ private String nameOnly() { * Returns the file name with extension but without path. */ public String nameWithExtension() { - String fullName = value(); - int lastBackslashIndex = fullName.lastIndexOf(PATH_SEPARATOR); - String result = fullName.substring(lastBackslashIndex + 1); + var fullName = value(); + var lastBackslashIndex = fullName.lastIndexOf(PATH_SEPARATOR); + var result = fullName.substring(lastBackslashIndex + 1); return result; } @@ -123,14 +123,14 @@ public String nameOnlyCamelCase() { * Returns the file name without extension but including path. */ public String nameWithoutExtension() { - String value = value(); - int extensionIndex = value.lastIndexOf(EXTENSION); - String result = value.substring(0, extensionIndex); + var value = value(); + var extensionIndex = value.lastIndexOf(EXTENSION); + var result = value.substring(0, extensionIndex); return result; } private boolean matches(MessageFile file) { - boolean result = value().endsWith(file.suffix()); + var result = value().endsWith(file.suffix()); return result; } diff --git a/base/src/main/java/io/spine/code/proto/FileSet.java b/base/src/main/java/io/spine/code/proto/FileSet.java index b82d7210d0..ea280142e1 100644 --- a/base/src/main/java/io/spine/code/proto/FileSet.java +++ b/base/src/main/java/io/spine/code/proto/FileSet.java @@ -46,7 +46,6 @@ import java.util.Optional; import java.util.Set; import java.util.function.Predicate; -import java.util.logging.Level; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Maps.newHashMap; @@ -113,15 +112,11 @@ public static FileSet parse(File descriptorSet) { * @return new file set */ public static FileSet parseAsKnownFiles(File descriptorSet) { - Set fileNames = FileDescriptors.parse(descriptorSet) - .stream() - .map(FileName::from) - .collect(toSet()); - Map knownFiles = - KnownTypes.instance() - .asTypeSet() - .allTypes() - .stream() + var fileNames = FileDescriptors.parse(descriptorSet).stream() + .map(FileName::from) + .collect(toSet()); + var allTypes = KnownTypes.instance().asTypeSet().allTypes(); + var knownFiles = allTypes.stream() .map(Type::file) .filter(descr -> fileNames.contains(FileName.from(descr.getFile()))) .collect(toMap(FileName::from, // File name as the key. @@ -131,14 +126,14 @@ public static FileSet parseAsKnownFiles(File descriptorSet) { if (knownFiles.size() != fileNames.size()) { onUnknownFiles(knownFiles.keySet(), fileNames, descriptorSet); } - FileSet result = new FileSet(knownFiles); + var result = new FileSet(knownFiles); return result; } private static void onUnknownFiles(Set knownFiles, Set requestedFiles, File descriptorSetFile) { - Level detailLevel = FINE; + var detailLevel = FINE; logger.atWarning().log( "Some files are unknown. " + "%s files are present in classpath but %s files are discovered in `%s`.%n" + @@ -150,8 +145,7 @@ private static void onUnknownFiles(Set knownFiles, detailLevel ); logger.at(detailLevel) - .log("Could not find files: %s.", lazy(() -> requestedFiles - .stream() + .log("Could not find files: %s.", lazy(() -> requestedFiles.stream() .filter(fileName -> !knownFiles.contains(fileName)) .map(FileName::toString) .collect(joining(", ")))); @@ -185,7 +179,7 @@ public static FileSet load() { */ public static FileSet of(Iterable protoDescriptors) { checkNotNull(protoDescriptors); - ImmutableSet descriptors = ImmutableSet.copyOf(protoDescriptors); + var descriptors = ImmutableSet.copyOf(protoDescriptors); return link(descriptors); } @@ -194,9 +188,9 @@ public static FileSet of(Iterable protoDescriptors) { */ public List topLevelMessages() { ImmutableList.Builder result = ImmutableList.builder(); - for (FileDescriptor file : files()) { - SourceFile sourceFile = SourceFile.from(file); - List declarations = sourceFile.topLevelMessages(); + for (var file : files()) { + var sourceFile = SourceFile.from(file); + var declarations = sourceFile.topLevelMessages(); result.addAll(declarations); } return result.build(); @@ -210,8 +204,8 @@ public List topLevelMessages() { */ public List findMessageTypes(Predicate predicate) { ImmutableList.Builder result = ImmutableList.builder(); - for (FileDescriptor file : files()) { - SourceFile sourceFile = SourceFile.from(file); + for (var file : files()) { + var sourceFile = SourceFile.from(file); Collection declarations = sourceFile.allThat(predicate); result.addAll(declarations); } @@ -228,11 +222,11 @@ public FileSet union(FileSet another) { if (this.isEmpty()) { return another; } - int expectedSize = this.files.size() + another.files.size(); + var expectedSize = this.files.size() + another.files.size(); Map files = newHashMapWithExpectedSize(expectedSize); files.putAll(this.files); files.putAll(another.files); - FileSet result = new FileSet(files); + var result = new FileSet(files); return result; } @@ -248,8 +242,8 @@ public FileSet filter(Predicate predicate) { .stream() .filter(predicate) .collect(toList()); - FileSet newFileSet = newInstance(); - for (FileDescriptor file : filteredFiles) { + var newFileSet = newInstance(); + for (var file : filteredFiles) { newFileSet.add(file); } return newFileSet; @@ -275,7 +269,7 @@ FileDescriptor[] toArray() { * {@code false} otherwise. */ public boolean contains(FileName fileName) { - Optional found = tryFind(fileName); + var found = tryFind(fileName); return found.isPresent(); } @@ -284,8 +278,8 @@ public boolean contains(FileName fileName) { * {@code false} otherwise. */ public boolean containsAll(Collection fileNames) { - FileSet found = find(fileNames); - boolean result = found.size() == fileNames.size(); + var found = find(fileNames); + var result = found.size() == fileNames.size(); return result; } @@ -294,8 +288,8 @@ public boolean containsAll(Collection fileNames) { */ public FileSet find(Collection fileNames) { Map found = newHashMapWithExpectedSize(fileNames.size()); - for (FileName name : fileNames) { - Optional file = tryFind(name); + for (var name : fileNames) { + var file = tryFind(name); file.ifPresent(fileDescr -> found.put(name, fileDescr)); } return new FileSet(found); @@ -317,9 +311,9 @@ public Optional tryFind(FileName fileName) { */ @CanIgnoreReturnValue public boolean add(FileDescriptor file) { - FileName name = FileName.from(file); + var name = FileName.from(file); Object previous = files.put(name, file); - boolean isNew = previous == null; + var isNew = previous == null; return isNew; } @@ -327,7 +321,7 @@ public boolean add(FileDescriptor file) { * Obtains the size of the set. */ public int size() { - int result = files.size(); + var result = files.size(); return result; } @@ -335,7 +329,7 @@ public int size() { * Verifies if the set is empty. */ public boolean isEmpty() { - boolean result = files.isEmpty(); + var result = files.isEmpty(); return result; } @@ -365,7 +359,7 @@ public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } - FileSet other = (FileSet) obj; + var other = (FileSet) obj; return Objects.equals(this.files, other.files); } } diff --git a/base/src/main/java/io/spine/code/proto/Linker.java b/base/src/main/java/io/spine/code/proto/Linker.java index 2c5eb0f16f..a0a74b2727 100644 --- a/base/src/main/java/io/spine/code/proto/Linker.java +++ b/base/src/main/java/io/spine/code/proto/Linker.java @@ -36,7 +36,6 @@ import com.google.protobuf.Descriptors.FileDescriptor; import java.util.Collection; -import java.util.Iterator; import java.util.List; import static com.google.common.base.Preconditions.checkState; @@ -71,10 +70,10 @@ final class Linker { } static FileSet link(Collection files) { - Linker linker = new Linker(files); + var linker = new Linker(files); @SuppressWarnings("FloggerSplitLogStatement") // See: https://github.com/SpineEventEngine/base/issues/612 - FluentLogger.Api debug = logger.atFine(); + var debug = logger.atFine(); debug.log("Trying to link %d files.", files.size()); try { linker.resolve(); @@ -82,9 +81,9 @@ static FileSet link(Collection files) { throw newIllegalStateException(e, "Unable to link descriptor set files."); } debug.log("Linking complete. %s", linker); - FileSet result = linker.resolved() - .union(linker.partiallyResolved()) - .union(linker.unresolved()); + var result = linker.resolved() + .union(linker.partiallyResolved()) + .union(linker.unresolved()); return result; } @@ -98,11 +97,11 @@ void resolve() throws DescriptorValidationException { } private void findNoDependencies() throws DescriptorValidationException { - Iterator iterator = remaining.iterator(); + var iterator = remaining.iterator(); while (iterator.hasNext()) { - FileDescriptorProto next = iterator.next(); + var next = iterator.next(); if (next.getDependencyCount() == 0) { - FileDescriptor fd = buildFrom(next, NO_DEPENDENCIES, true); + var fd = buildFrom(next, NO_DEPENDENCIES, true); resolved.add(fd); iterator.remove(); } @@ -114,21 +113,21 @@ private void findNoDependencies() throws DescriptorValidationException { * or no more resolved files found. */ private void findResolved() throws DescriptorValidationException { - boolean resolvedFound = true; + var resolvedFound = true; while (!remaining.isEmpty() && resolvedFound) { resolvedFound = doFindResolved(); } } private boolean doFindResolved() throws DescriptorValidationException { - boolean result = false; - Iterator iterator = remaining.iterator(); + var result = false; + var iterator = remaining.iterator(); while (iterator.hasNext()) { - FileDescriptorProto next = iterator.next(); - Collection dependencyList = dependencies(next); + var next = iterator.next(); + var dependencyList = dependencies(next); if (resolved.containsAll(dependencyList)) { - FileSet dependencies = resolved.find(dependencyList); - FileDescriptor newResolved = buildFrom(next, dependencies.toArray(), true); + var dependencies = resolved.find(dependencyList); + var newResolved = buildFrom(next, dependencies.toArray(), true); resolved.add(newResolved); result = true; iterator.remove(); @@ -138,22 +137,22 @@ private boolean doFindResolved() throws DescriptorValidationException { } private void findPartiallyResolved() throws DescriptorValidationException { - boolean partiallyResolvedFound = true; + var partiallyResolvedFound = true; while (!remaining.isEmpty() && partiallyResolvedFound) { partiallyResolvedFound = doFindPartiallyResolved(); } } private boolean doFindPartiallyResolved() throws DescriptorValidationException { - boolean result = false; - FileSet partialAndResolved = resolved.union(partiallyResolved); - Iterator iterator = remaining.iterator(); + var result = false; + var partialAndResolved = resolved.union(partiallyResolved); + var iterator = remaining.iterator(); while (iterator.hasNext()) { - FileDescriptorProto next = iterator.next(); - Collection dependencyList = dependencies(next); - FileSet dependencies = partialAndResolved.find(dependencyList); + var next = iterator.next(); + var dependencyList = dependencies(next); + var dependencies = partialAndResolved.find(dependencyList); if (dependencies.isEmpty()) { - FileDescriptor newPartial = buildFrom(next, dependencies.toArray(), true); + var newPartial = buildFrom(next, dependencies.toArray(), true); partiallyResolved.add(newPartial); partialAndResolved.add(newPartial); result = true; @@ -173,8 +172,8 @@ private boolean doFindPartiallyResolved() throws DescriptorValidationException { */ private void addUnresolved() throws DescriptorValidationException { while (!remaining.isEmpty()) { - FileDescriptorProto first = remaining.get(0); - FileDescriptor fd = buildFrom(first, NO_DEPENDENCIES, true); + var first = remaining.get(0); + var fd = buildFrom(first, NO_DEPENDENCIES, true); unresolved.add(fd); remaining.remove(first); } @@ -204,8 +203,8 @@ FileSet unresolved() { return unresolved; } - @SuppressWarnings("DuplicateStringLiteralInspection") // field names @Override + @SuppressWarnings("DuplicateStringLiteralInspection") // field names public String toString() { return MoreObjects.toStringHelper(this) .add("input", namesForDisplay(input)) diff --git a/base/src/main/java/io/spine/code/proto/LocationPath.java b/base/src/main/java/io/spine/code/proto/LocationPath.java index 1a7ff6672e..114736edcf 100644 --- a/base/src/main/java/io/spine/code/proto/LocationPath.java +++ b/base/src/main/java/io/spine/code/proto/LocationPath.java @@ -84,7 +84,7 @@ public static LocationPath fromMessage(Descriptor descriptor) { path.add(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER); if (!MessageType.isTopLevel(descriptor)) { Deque parentPath = new ArrayDeque<>(); - Descriptor containingType = descriptor.getContainingType(); + var containingType = descriptor.getContainingType(); while (containingType != null) { parentPath.addFirst(containingType.getIndex()); containingType = containingType.getContainingType(); @@ -92,7 +92,7 @@ public static LocationPath fromMessage(Descriptor descriptor) { path.addAll(parentPath); } path.add(descriptor.getIndex()); - ImmutableList list = path.build(); + var list = path.build(); return new LocationPath(list, false); } @@ -100,9 +100,9 @@ public static LocationPath fromMessage(Descriptor descriptor) { * Appends the path item to the end of this path. */ LocationPath append(Integer... items) { - ImmutableList candidates = ImmutableList.copyOf(items); + var candidates = ImmutableList.copyOf(items); checkPath(candidates); - ImmutableList combined = toBuilder().addAll(candidates).build(); + var combined = toBuilder().addAll(candidates).build(); return new LocationPath(combined, false); } @@ -128,9 +128,9 @@ private static void checkItem(Integer item) { * Converts the instance to the {@code SourceCodeInfo.Location} instance in the given file. */ public SourceCodeInfo.Location toLocationIn(FileDescriptorProto file) { - List thisPath = toList(); - List locations = file.getSourceCodeInfo().getLocationList(); - for (SourceCodeInfo.Location location : locations) { + var thisPath = toList(); + var locations = file.getSourceCodeInfo().getLocationList(); + for (var location : locations) { if (thisPath.equals(location.getPathList())) { return location; } @@ -149,7 +149,7 @@ public boolean equals(Object o) { if (!(o instanceof LocationPath)) { return false; } - LocationPath that = (LocationPath) o; + var that = (LocationPath) o; return path.equals(that.path); } diff --git a/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java b/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java index c16a4b82fc..83f725f632 100644 --- a/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java +++ b/base/src/main/java/io/spine/code/proto/OptionExtensionRegistry.java @@ -26,11 +26,9 @@ package io.spine.code.proto; -import com.google.common.collect.ImmutableSet; import com.google.protobuf.Extension; import com.google.protobuf.ExtensionRegistry; import io.spine.option.OptionsProto; -import io.spine.validate.option.ValidatingOptionFactory; import io.spine.validate.option.ValidatingOptionsLoader; /** @@ -63,28 +61,26 @@ public static ExtensionRegistry instance() { * spine/options.proto} extensions. */ private static ExtensionRegistry optionExtensions() { - ExtensionRegistry registry = ExtensionRegistry.newInstance(); + var registry = ExtensionRegistry.newInstance(); OptionsProto.registerAllExtensions(registry); registerCustomOptions(registry); return registry; } private static void registerCustomOptions(ExtensionRegistry target) { - ImmutableSet implementations = - ValidatingOptionsLoader.INSTANCE.implementations(); + var implementations = ValidatingOptionsLoader.INSTANCE.implementations(); implementations.stream() - .flatMap(factory -> factory.all().stream()) - .map(AbstractOption::extension) - .filter(extension -> isExtensionRegistered(target, extension)) - .forEach(target::add); + .flatMap(factory -> factory.all().stream()) + .map(AbstractOption::extension) + .filter(extension -> isExtensionRegistered(target, extension)) + .forEach(target::add); } private static boolean isExtensionRegistered(ExtensionRegistry registry, Extension extension) { - String name = extension.getDescriptor() - .getFullName(); - boolean mutableAbsent = registry.findMutableExtensionByName(name) == null; - boolean immutableAbsent = registry.findImmutableExtensionByName(name) == null; + var name = extension.getDescriptor().getFullName(); + var mutableAbsent = registry.findMutableExtensionByName(name) == null; + var immutableAbsent = registry.findImmutableExtensionByName(name) == null; return mutableAbsent && immutableAbsent; } } diff --git a/base/src/main/java/io/spine/code/proto/PackageName.java b/base/src/main/java/io/spine/code/proto/PackageName.java index aeb269f2b8..ea84f05268 100644 --- a/base/src/main/java/io/spine/code/proto/PackageName.java +++ b/base/src/main/java/io/spine/code/proto/PackageName.java @@ -53,7 +53,7 @@ private PackageName(String value) { */ public static PackageName of(String value) { checkNotNull(value); - PackageName result = new PackageName(value); + var result = new PackageName(value); return result; } @@ -62,8 +62,8 @@ public static PackageName of(String value) { */ public static PackageName of(Descriptor message) { checkNotNull(message); - PackageName result = of(message.getFile() - .getPackage()); + var result = of(message.getFile() + .getPackage()); return result; } @@ -88,7 +88,7 @@ public static String delimiter() { */ public boolean isInnerOf(PackageName parentCandidate) { checkNotNull(parentCandidate); - boolean result = value().startsWith(parentCandidate.value()); + var result = value().startsWith(parentCandidate.value()); return result; } diff --git a/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java b/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java index 59904c4686..e8b18a946d 100644 --- a/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java +++ b/base/src/main/java/io/spine/code/proto/ProtoBelongsToModule.java @@ -44,9 +44,8 @@ public abstract class ProtoBelongsToModule implements Predicate { @Override public boolean test(SourceFile file) { - Path filePath = resolve(file); - boolean exists = filePath.toFile() - .exists(); + var filePath = resolve(file); + var exists = filePath.toFile().exists(); logger.atFinest() .log("Checking if the file `%s` exists, result: `%b`.", filePath, exists); return exists; @@ -55,6 +54,7 @@ public boolean test(SourceFile file) { /** * Obtains this predicate operating with {@link FileDescriptor} instead of {@link SourceFile}. */ + @SuppressWarnings("unused") /* Part of the public API. */ public Predicate forDescriptor() { Predicate result = descriptor -> test(SourceFile.from(descriptor)); return result; diff --git a/base/src/main/java/io/spine/code/proto/RejectionsFile.java b/base/src/main/java/io/spine/code/proto/RejectionsFile.java index 1430593ce7..0d0e52b87b 100644 --- a/base/src/main/java/io/spine/code/proto/RejectionsFile.java +++ b/base/src/main/java/io/spine/code/proto/RejectionsFile.java @@ -28,13 +28,11 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FileDescriptor; import io.spine.base.RejectionType; import io.spine.code.java.SimpleClassName; import java.util.List; -import java.util.Optional; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; @@ -67,12 +65,12 @@ public static RejectionsFile from(SourceFile file) { checkNotNull(file); checkMatchesConvention(file); - RejectionsFile result = new RejectionsFile(file.descriptor()); + var result = new RejectionsFile(file.descriptor()); return result; } private static void checkMatchesConvention(SourceFile file) { - FileDescriptor descriptor = file.descriptor(); + var descriptor = file.descriptor(); checkArgument(isRejections(descriptor), "`%s`. A rejection file must have a name ending in `rejections.proto`.", file); @@ -80,7 +78,7 @@ private static void checkMatchesConvention(SourceFile file) { "`%s`. A rejection file should generate Java classes into a single file. " + "Please set `java_multiple_files` to `false`.", file); - Optional outerClass = SimpleClassName.declaredOuterClassName(descriptor); + var outerClass = SimpleClassName.declaredOuterClassName(descriptor); outerClass.ifPresent(name -> checkArgument( isValidOuterClassName(name), "%s. A rejection file must have the `java_outer_classname` ending in " + @@ -92,11 +90,12 @@ private static void checkMatchesConvention(SourceFile file) { /** * Obtains rejection messages declared in the file. */ + @SuppressWarnings("unused") /* Part of the public API. */ public List rejectionDeclarations() { ImmutableList.Builder result = ImmutableList.builder(); - FileDescriptor file = descriptor(); - for (Descriptor type : file.getMessageTypes()) { - RejectionType declaration = new RejectionType(type); + var file = descriptor(); + for (var type : file.getMessageTypes()) { + var declaration = new RejectionType(type); result.add(declaration); } return result.build(); @@ -110,16 +109,16 @@ private static boolean isRejections(FileDescriptor file) { /** * Obtains rejection files from the passed set of files. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static ImmutableSet findAll(FileSet fileSet) { - ImmutableSet result = - fileSet.files() - .stream() - .filter(RejectionsFile::isRejections) - .map(file -> { - SourceFile sourceFile = SourceFile.from(file); - return from(sourceFile); - }) - .collect(toImmutableSet()); + checkNotNull(fileSet); + var result = fileSet.files().stream() + .filter(RejectionsFile::isRejections) + .map(file -> { + var sourceFile = SourceFile.from(file); + return from(sourceFile); + }) + .collect(toImmutableSet()); return result; } } diff --git a/base/src/main/java/io/spine/code/proto/ScalarType.java b/base/src/main/java/io/spine/code/proto/ScalarType.java index 1baf8dde87..3dd64a28f2 100644 --- a/base/src/main/java/io/spine/code/proto/ScalarType.java +++ b/base/src/main/java/io/spine/code/proto/ScalarType.java @@ -88,7 +88,7 @@ public static String javaTypeName(Type protoScalar) { * @return the corresponding Java type */ public static Class javaType(Type protoScalar) { - for (ScalarType scalarType : values()) { + for (var scalarType : values()) { if (scalarType.protoScalarType == protoScalar) { return scalarType.javaClass; } @@ -112,8 +112,8 @@ public static boolean isScalarType(FieldDescriptorProto field) { * @see #isScalarType(com.google.protobuf.DescriptorProtos.FieldDescriptorProto) */ public static Optional of(FieldDescriptorProto field) { - Type type = field.getType(); - for (ScalarType scalarType : values()) { + var type = field.getType(); + for (var scalarType : values()) { if (scalarType.protoScalarType() == type) { return Optional.of(scalarType); } diff --git a/base/src/main/java/io/spine/code/proto/SourceFile.java b/base/src/main/java/io/spine/code/proto/SourceFile.java index ccc61f7d4b..2766743dcd 100644 --- a/base/src/main/java/io/spine/code/proto/SourceFile.java +++ b/base/src/main/java/io/spine/code/proto/SourceFile.java @@ -28,7 +28,6 @@ import com.google.common.collect.ImmutableList; import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FileDescriptor; import io.spine.base.RejectionType; import io.spine.code.fs.AbstractSourceFile; @@ -40,7 +39,6 @@ import java.nio.file.Paths; import java.util.Collection; import java.util.List; -import java.util.Optional; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; @@ -67,7 +65,7 @@ public static SourceFile from(FileDescriptor file) { private static Path toPath(FileDescriptor file) { checkNotNull(file); - Path result = Paths.get(file.getName()); + var result = Paths.get(file.getName()); return result; } @@ -93,15 +91,15 @@ public boolean isRejections() { .getJavaMultipleFiles()) { return false; } - Optional outerClass = SimpleClassName.declaredOuterClassName(descriptor); + var outerClass = SimpleClassName.declaredOuterClassName(descriptor); - if (!outerClass.isPresent()) { + if (outerClass.isEmpty()) { // There's no outer class name given in options. // Assuming the file name ends with `rejections.proto`, it's a good rejections file. return true; } - boolean result = RejectionType.isValidOuterClassName(outerClass.get()); + var result = RejectionType.isValidOuterClassName(outerClass.get()); return result; } @@ -129,8 +127,8 @@ public List topLevelMessages() { */ public List allThat(Predicate predicate) { ImmutableList.Builder result = ImmutableList.builder(); - for (Descriptor messageType : descriptor.getMessageTypes()) { - MessageType declaration = new MessageType(messageType); + for (var messageType : descriptor.getMessageTypes()) { + var declaration = new MessageType(messageType); _debug().log("Testing `%s` to match `%s`.", declaration, predicate); if (predicate.test(messageType.toProto())) { result.add(declaration); diff --git a/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java b/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java index 149a6a5d2a..9ced5ca7c0 100644 --- a/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java +++ b/base/src/main/java/io/spine/code/proto/SourceProtoBelongsToModule.java @@ -34,6 +34,7 @@ /** * A predicate determining if the given {@code .proto} source belongs to the specified module. */ +@SuppressWarnings("unused") /* Part of the public API. */ public final class SourceProtoBelongsToModule extends ProtoBelongsToModule { /** An absolute path to the root folder for the {@code .proto} files in the module. */ @@ -47,7 +48,7 @@ public SourceProtoBelongsToModule(File rootDirectory) { @Override protected Path resolve(SourceFile file) { - Path result = rootPath.resolve(file.path()); + var result = rootPath.resolve(file.path()); return result; } } diff --git a/base/src/main/java/io/spine/code/proto/TypeSet.java b/base/src/main/java/io/spine/code/proto/TypeSet.java index 0538262a46..b1117b3469 100644 --- a/base/src/main/java/io/spine/code/proto/TypeSet.java +++ b/base/src/main/java/io/spine/code/proto/TypeSet.java @@ -85,9 +85,9 @@ private TypeSet(Builder builder) { * Obtains message and enum types declared in the passed file. */ public static TypeSet from(FileDescriptor file) { - TypeSet messages = MessageType.allFrom(file); - TypeSet enums = EnumType.allFrom(file); - TypeSet services = ServiceType.allFrom(file); + var messages = MessageType.allFrom(file); + var enums = EnumType.allFrom(file); + var services = ServiceType.allFrom(file); return new TypeSet(messages.messageTypes, enums.enumTypes, services.serviceTypes); } @@ -95,8 +95,8 @@ public static TypeSet from(FileDescriptor file) { * Obtains message and enum types declared in the files represented by the passed set. */ public static TypeSet from(FileSet fileSet) { - TypeSet result = new TypeSet(); - for (FileDescriptor file : fileSet.files()) { + var result = new TypeSet(); + for (var file : fileSet.files()) { result = result.union(from(file)); } return result; @@ -105,10 +105,12 @@ public static TypeSet from(FileSet fileSet) { /** * Obtains message types declared in the passed file set. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static ImmutableCollection onlyMessages(FileSet fileSet) { - TypeSet result = new TypeSet(); - for (FileDescriptor file : fileSet.files()) { - TypeSet messageTypes = MessageType.allFrom(file); + checkNotNull(fileSet); + var result = new TypeSet(); + for (var file : fileSet.files()) { + var messageTypes = MessageType.allFrom(file); result = result.union(messageTypes); } return result.messageTypes.values(); @@ -117,8 +119,9 @@ public static ImmutableCollection onlyMessages(FileSet fileSet) { /** * Obtains message types declared in the passed file. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static ImmutableCollection onlyMessages(FileDescriptor file) { - TypeSet typeSet = MessageType.allFrom(file); + var typeSet = MessageType.allFrom(file); return typeSet.messageTypes.values(); } @@ -126,10 +129,10 @@ public static ImmutableCollection onlyMessages(FileDescriptor file) * Obtains the size of the set. */ public int size() { - int messagesCount = messageTypes.size(); - int enumsCount = enumTypes.size(); - int servicesCount = serviceTypes.size(); - int result = messagesCount + enumsCount + servicesCount; + var messagesCount = messageTypes.size(); + var enumsCount = enumTypes.size(); + var servicesCount = serviceTypes.size(); + var result = messagesCount + enumsCount + servicesCount; return result; } @@ -168,7 +171,7 @@ public int size() { * @see #find(TypeName) */ public boolean contains(TypeName typeName) { - boolean result = find(typeName).isPresent(); + var result = find(typeName).isPresent(); return result; } @@ -176,7 +179,7 @@ public boolean contains(TypeName typeName) { * Verifies if the set is empty. */ public boolean isEmpty() { - boolean empty = size() == 0; + var empty = size() == 0; return empty; } @@ -184,7 +187,7 @@ public boolean isEmpty() { * Writes all the types in this set into a {@link TypeRegistry}. */ public TypeRegistry toTypeRegistry() { - TypeRegistry.Builder registry = TypeRegistry.newBuilder(); + var registry = TypeRegistry.newBuilder(); messageTypes.values() .stream() .map(Type::descriptor) @@ -202,19 +205,16 @@ public TypeSet union(TypeSet another) { if (this.isEmpty()) { return another; } - ImmutableMap messages = - unite(this.messageTypes, another.messageTypes); - ImmutableMap enums = - unite(this.enumTypes, another.enumTypes); - ImmutableMap services = - unite(this.serviceTypes, another.serviceTypes); - TypeSet result = new TypeSet(messages, enums, services); + var messages = unite(this.messageTypes, another.messageTypes); + var enums = unite(this.enumTypes, another.enumTypes); + var services = unite(this.serviceTypes, another.serviceTypes); + var result = new TypeSet(messages, enums, services); return result; } private static > ImmutableMap unite(Map left, Map right) { - // Use HashMap instead of ImmutableMap.Builder to deal with duplicates. + // Use `HashMap` instead of `ImmutableMap.Builder` to deal with duplicates. Map union = newHashMapWithExpectedSize(left.size() + right.size()); union.putAll(left); union.putAll(right); @@ -225,8 +225,7 @@ public TypeSet union(TypeSet another) { * Obtains all the types contained in this set. */ public ImmutableSet> allTypes() { - ImmutableSet> types = ImmutableSet - .>builder() + var types = ImmutableSet.>builder() .addAll(messagesAndEnums()) .addAll(serviceTypes.values()) .build(); @@ -237,8 +236,7 @@ public TypeSet union(TypeSet another) { * Obtains message and enum types contained in this set. */ public Set> messagesAndEnums() { - ImmutableSet> types = ImmutableSet - .>builder() + var types = ImmutableSet.>builder() .addAll(messageTypes.values()) .addAll(enumTypes.values()) .build(); @@ -274,7 +272,7 @@ public boolean equals(Object o) { if (!(o instanceof TypeSet)) { return false; } - TypeSet typeSet = (TypeSet) o; + var typeSet = (TypeSet) o; return Objects.equal(messageTypes, typeSet.messageTypes) && Objects.equal(enumTypes, typeSet.enumTypes); } @@ -294,11 +292,10 @@ public String toString() { } private static String namesForDisplay(Map types) { - return types.keySet() - .stream() - .map(TypeName::value) - .sorted() - .collect(joining(lineSeparator())); + return types.keySet().stream() + .map(TypeName::value) + .sorted() + .collect(joining(lineSeparator())); } /** @@ -327,21 +324,21 @@ private Builder() { @CanIgnoreReturnValue public Builder add(MessageType type) { - TypeName name = type.name(); + var name = type.name(); messageTypes.put(name, type); return this; } @CanIgnoreReturnValue public Builder add(EnumType type) { - TypeName name = type.name(); + var name = type.name(); enumTypes.put(name, type); return this; } @CanIgnoreReturnValue public Builder add(ServiceType type) { - TypeName name = type.name(); + var name = type.name(); serviceTypes.put(name, type); return this; } @@ -349,7 +346,7 @@ public Builder add(ServiceType type) { @CanIgnoreReturnValue public Builder addAll(Iterable types) { checkNotNull(types); - ImmutableMap map = uniqueIndex(types, MessageType::name); + var map = uniqueIndex(types, MessageType::name); messageTypes.putAll(map); return this; } From 5e9ed3e992310c845b65dc018436f618a26ffdf9 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 13:54:18 +0200 Subject: [PATCH 12/27] Use `var`s in `io.spine.environment` package. --- .../io/spine/environment/Environment.java | 33 +++++++++---------- .../io/spine/environment/EnvironmentType.java | 2 +- .../java/io/spine/environment/Production.java | 3 +- .../main/java/io/spine/environment/Tests.java | 9 +++-- .../io/spine/environment/TestsProperty.java | 6 ++-- 5 files changed, 24 insertions(+), 29 deletions(-) diff --git a/base/src/main/java/io/spine/environment/Environment.java b/base/src/main/java/io/spine/environment/Environment.java index 383806c492..1aa7652b75 100644 --- a/base/src/main/java/io/spine/environment/Environment.java +++ b/base/src/main/java/io/spine/environment/Environment.java @@ -28,7 +28,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; -import com.google.common.flogger.FluentLogger; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.spine.annotation.SPI; import io.spine.logging.Logging; @@ -176,9 +175,8 @@ private Environment(Environment copy) { @CanIgnoreReturnValue private Environment register(EnvironmentType type) { if (!knownTypes.contains(type)) { - ImmutableList currentlyKnown = knownTypes; - knownTypes = ImmutableList - .builder() + var currentlyKnown = knownTypes; + knownTypes = ImmutableList.builder() .add(type) .addAll(currentlyKnown) .build(); @@ -248,8 +246,8 @@ public Environment createCopy() { * @return whether the current environment type matches the specified one */ public boolean is(Class type) { - Class current = type(); - boolean result = type.isAssignableFrom(current); + var current = type(); + var result = type.isAssignableFrom(current); return result; } @@ -274,13 +272,12 @@ public Class type() { } private Class firstEnabled() { - EnvironmentType result = - knownTypes.stream() - .filter(EnvironmentType::enabled) - .findFirst() - .orElseThrow(() -> newIllegalStateException( - "`Environment` could not find an active environment type." - )); + var result = knownTypes.stream() + .filter(EnvironmentType::enabled) + .findFirst() + .orElseThrow(() -> newIllegalStateException( + "`Environment` could not find an active environment type." + )); return result.getClass(); } @@ -306,7 +303,7 @@ public void setTo(Class type) { checkNotNull(type); if (CustomEnvironmentType.class.isAssignableFrom(type)) { @SuppressWarnings("unchecked") // checked one line above - Class customType = + var customType = (Class) type; register(customType); } @@ -318,7 +315,7 @@ private void setCurrentType(@Nullable Class newCurren this.currentType = newCurrent; @SuppressWarnings("FloggerSplitLogStatement") // See: https://github.com/SpineEventEngine/base/issues/612 - FluentLogger.Api info = _info(); + var info = _info(); if (previous == null) { if (newCurrent != null) { info.log("`Environment` set to `%s`.", newCurrent.getName()); @@ -327,9 +324,9 @@ private void setCurrentType(@Nullable Class newCurren if (previous.equals(newCurrent)) { info.log("`Environment` stays `%s`.", newCurrent.getName()); } else { - String newType = newCurrent != null - ? backtick(newCurrent.getName()) - : "undefined"; + var newType = newCurrent != null + ? backtick(newCurrent.getName()) + : "undefined"; info.log("`Environment` turned from `%s` to %s.", previous.getName(), newType); } } diff --git a/base/src/main/java/io/spine/environment/EnvironmentType.java b/base/src/main/java/io/spine/environment/EnvironmentType.java index 4c00965ed5..25ee1a8cdc 100644 --- a/base/src/main/java/io/spine/environment/EnvironmentType.java +++ b/base/src/main/java/io/spine/environment/EnvironmentType.java @@ -67,7 +67,7 @@ public final boolean equals(Object obj) { if (obj == null) { return false; } - boolean result = getClass().equals(obj.getClass()); + var result = getClass().equals(obj.getClass()); return result; } } diff --git a/base/src/main/java/io/spine/environment/Production.java b/base/src/main/java/io/spine/environment/Production.java index b7c1f2ff03..4684807922 100644 --- a/base/src/main/java/io/spine/environment/Production.java +++ b/base/src/main/java/io/spine/environment/Production.java @@ -52,8 +52,7 @@ private Production() { @Override protected boolean enabled() { - boolean tests = Tests.type() - .enabled(); + var tests = Tests.type().enabled(); return !tests; } } diff --git a/base/src/main/java/io/spine/environment/Tests.java b/base/src/main/java/io/spine/environment/Tests.java index 53437e8386..860beea404 100644 --- a/base/src/main/java/io/spine/environment/Tests.java +++ b/base/src/main/java/io/spine/environment/Tests.java @@ -91,15 +91,14 @@ private Tests() { */ @Override protected boolean enabled() { - TestsProperty property = new TestsProperty(); + var property = new TestsProperty(); if (property.isSet()) { return property.value(); } - String stacktrace = Throwables.getStackTraceAsString(new RuntimeException("")); - boolean result = - knownTestingFrameworks().stream() - .anyMatch(stacktrace::contains); + var stacktrace = Throwables.getStackTraceAsString(new RuntimeException("")); + var result = knownTestingFrameworks().stream() + .anyMatch(stacktrace::contains); return result; } } diff --git a/base/src/main/java/io/spine/environment/TestsProperty.java b/base/src/main/java/io/spine/environment/TestsProperty.java index 9d169f1e0d..934c4005bf 100644 --- a/base/src/main/java/io/spine/environment/TestsProperty.java +++ b/base/src/main/java/io/spine/environment/TestsProperty.java @@ -76,7 +76,7 @@ final class TestsProperty { private final @Nullable String value; TestsProperty() { - String propValue = System.getProperty(KEY); + var propValue = System.getProperty(KEY); if (propValue != null) { propValue = QUOTES_OR_SPACE.matcher(propValue) .replaceAll(""); @@ -99,8 +99,8 @@ boolean isSet() { */ boolean value() { checkState(value != null); - boolean result = TESTS_VALUES.stream() - .anyMatch(value::equalsIgnoreCase); + var result = TESTS_VALUES.stream() + .anyMatch(value::equalsIgnoreCase); return result; } From 34c1da5503c2d50b51e2fdd42a236bf5db0679a1 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 13:55:59 +0200 Subject: [PATCH 13/27] Use `var`s in `io.spine.io` package. --- base/src/main/java/io/spine/io/Copy.java | 17 ++++++++--------- base/src/main/java/io/spine/io/Delete.java | 4 ++-- base/src/main/java/io/spine/io/Files2.java | 10 +++++----- .../main/java/io/spine/io/IoPreconditions.java | 2 +- base/src/main/java/io/spine/io/Resource.java | 11 +++++------ .../java/io/spine/io/ResourceDirectory.java | 6 +++--- .../main/java/io/spine/io/ResourceObject.java | 2 +- 7 files changed, 25 insertions(+), 27 deletions(-) diff --git a/base/src/main/java/io/spine/io/Copy.java b/base/src/main/java/io/spine/io/Copy.java index 75e2bc1331..581aa64a71 100644 --- a/base/src/main/java/io/spine/io/Copy.java +++ b/base/src/main/java/io/spine/io/Copy.java @@ -33,7 +33,6 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.function.BiPredicate; import java.util.function.Predicate; -import java.util.stream.Stream; import static com.google.common.collect.ImmutableList.toImmutableList; import static io.spine.io.IoPreconditions.checkIsDirectory; @@ -140,19 +139,19 @@ private static void doCopy(Path dir, Path target, Predicate matching, boolean withEnclosingDir) throws IOException { - Path oldParent = withEnclosingDir + var oldParent = withEnclosingDir ? dir.getParent() : dir; - ImmutableList paths = contentOf(dir, matching); - for (Path path : paths) { - Path relative = oldParent.relativize(path); - Path newPath = target.resolve(relative); + var paths = contentOf(dir, matching); + for (var path : paths) { + var relative = oldParent.relativize(path); + var newPath = target.resolve(relative); if (isDirectory(path)) { if (!exists(newPath)) { createDirectories(newPath); } } else if (isRegularFile(path)) { - Path containingDir = newPath.getParent(); + var containingDir = newPath.getParent(); if (!exists(containingDir)) { createDirectories(containingDir); } @@ -168,8 +167,8 @@ private static void doCopy(Path dir, private static ImmutableList contentOf(Path dir, Predicate matching) throws IOException { BiPredicate predicate = (path, attrs) -> matching.test(path); - try (Stream found = find(dir, Integer.MAX_VALUE, predicate)) { - ImmutableList paths = found.collect(toImmutableList()); + try (var found = find(dir, Integer.MAX_VALUE, predicate)) { + var paths = found.collect(toImmutableList()); return paths; } } diff --git a/base/src/main/java/io/spine/io/Delete.java b/base/src/main/java/io/spine/io/Delete.java index 20e6c67041..67fb9e2dc1 100644 --- a/base/src/main/java/io/spine/io/Delete.java +++ b/base/src/main/java/io/spine/io/Delete.java @@ -56,7 +56,7 @@ private Delete() { */ public static void deleteRecursivelyOnShutdownHook(Path directory) { checkNotNull(directory); - Runtime runtime = Runtime.getRuntime(); + var runtime = Runtime.getRuntime(); runtime.addShutdownHook(new Thread(() -> deleteRecursively(directory))); } @@ -72,7 +72,7 @@ public static void deleteRecursivelyOnShutdownHook(Path directory) { */ @CanIgnoreReturnValue public static boolean deleteRecursively(Path directory) { - boolean success = FilesKt.deleteRecursively(directory.toFile()); + var success = FilesKt.deleteRecursively(directory.toFile()); if (!success) { logger.atWarning() .log("Unable to delete the directory `%s`.", directory); diff --git a/base/src/main/java/io/spine/io/Files2.java b/base/src/main/java/io/spine/io/Files2.java index 537a58e46d..01c2636cf3 100644 --- a/base/src/main/java/io/spine/io/Files2.java +++ b/base/src/main/java/io/spine/io/Files2.java @@ -27,7 +27,6 @@ package io.spine.io; import java.io.File; -import java.nio.file.Path; import static com.google.common.base.Preconditions.checkNotNull; @@ -48,18 +47,19 @@ public static boolean existsNonEmpty(File file) { if (!file.exists()) { return false; } - boolean nonEmpty = file.length() > 0; + var nonEmpty = file.length() > 0; return nonEmpty; } /** * Normalizes and transforms the passed path to an absolute file reference. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static File toAbsolute(String path) { checkNotNull(path); - File file = new File(path); - Path normalized = file.toPath().normalize(); - File result = normalized.toAbsolutePath().toFile(); + var file = new File(path); + var normalized = file.toPath().normalize(); + var result = normalized.toAbsolutePath().toFile(); return result; } diff --git a/base/src/main/java/io/spine/io/IoPreconditions.java b/base/src/main/java/io/spine/io/IoPreconditions.java index 57dde12d72..bceb763bfd 100644 --- a/base/src/main/java/io/spine/io/IoPreconditions.java +++ b/base/src/main/java/io/spine/io/IoPreconditions.java @@ -72,7 +72,7 @@ public static File checkExists(File file) throws IllegalStateException { @CanIgnoreReturnValue public static Path checkExists(Path path) throws IllegalArgumentException { checkNotNull(path); - File file = path.toFile(); + var file = path.toFile(); checkArgument(file.exists(), DOES_NOT_EXIST, file); return path; } diff --git a/base/src/main/java/io/spine/io/Resource.java b/base/src/main/java/io/spine/io/Resource.java index 2e1c7304cd..e27c7ef2ed 100644 --- a/base/src/main/java/io/spine/io/Resource.java +++ b/base/src/main/java/io/spine/io/Resource.java @@ -28,7 +28,6 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; -import com.google.common.collect.UnmodifiableIterator; import com.google.common.io.CharStreams; import java.io.BufferedReader; @@ -82,9 +81,9 @@ public static Resource file(String path, ClassLoader classLoader) { * @return the URLs to the resolved resource files */ public ImmutableList locateAll() { - Enumeration resources = resourceEnumeration(); - UnmodifiableIterator iterator = Iterators.forEnumeration(resources); - ImmutableList result = ImmutableList.copyOf(iterator); + var resources = resourceEnumeration(); + var iterator = Iterators.forEnumeration(resources); + var result = ImmutableList.copyOf(iterator); if (result.isEmpty()) { throw cannotFind(); } @@ -93,7 +92,7 @@ public ImmutableList locateAll() { private Enumeration resourceEnumeration() { try { - Enumeration resources = resources(); + var resources = resources(); return resources; } catch (IOException e) { throw illegalStateWithCauseOf(e); @@ -110,7 +109,7 @@ private Enumeration resourceEnumeration() { * @return new {@link InputStream} */ public InputStream open() { - URL resource = locate(); + var resource = locate(); try { return resource.openStream(); } catch (IOException e) { diff --git a/base/src/main/java/io/spine/io/ResourceDirectory.java b/base/src/main/java/io/spine/io/ResourceDirectory.java index b3501cb024..1616837d36 100644 --- a/base/src/main/java/io/spine/io/ResourceDirectory.java +++ b/base/src/main/java/io/spine/io/ResourceDirectory.java @@ -78,7 +78,7 @@ public Path toPath() { @Nullable URL url = locate(); checkState(url != null, "Unable to locate resource directory: `%s`.", path()); try { - Path result = Paths.get(url.toURI()); + var result = Paths.get(url.toURI()); return result; } catch (URISyntaxException e) { throw illegalStateWithCauseOf(e); @@ -111,7 +111,7 @@ public void copyContentTo(Path target) throws IOException { public void copyContentTo(Path target, Predicate matching) throws IOException { checkTarget(target); checkNotNull(matching); - Path from = toPath(); + var from = toPath(); copyContent(from, target, matching); } @@ -139,7 +139,7 @@ public void copyTo(Path target) throws IOException { public void copyTo(Path target, Predicate matching) throws IOException { checkTarget(target); checkNotNull(matching); - Path from = toPath(); + var from = toPath(); copyDir(from, target, matching); } diff --git a/base/src/main/java/io/spine/io/ResourceObject.java b/base/src/main/java/io/spine/io/ResourceObject.java index 6ba4b7de72..7c4e22b749 100644 --- a/base/src/main/java/io/spine/io/ResourceObject.java +++ b/base/src/main/java/io/spine/io/ResourceObject.java @@ -118,7 +118,7 @@ public boolean equals(Object o) { if (!(o instanceof ResourceObject)) { return false; } - ResourceObject other = (ResourceObject) o; + var other = (ResourceObject) o; return path.equals(other.path); } From bb07ef8ca36b0d751904cccb436f8ebdeb5e4fb6 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 13:57:10 +0200 Subject: [PATCH 14/27] Use `var`s in `io.spine.json` package. --- base/src/main/java/io/spine/json/Json.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/base/src/main/java/io/spine/json/Json.java b/base/src/main/java/io/spine/json/Json.java index c5d9401e6b..ffab33465e 100644 --- a/base/src/main/java/io/spine/json/Json.java +++ b/base/src/main/java/io/spine/json/Json.java @@ -85,7 +85,7 @@ private Json() { */ public static String toJson(Message message) { checkNotNull(message); - String result = toJson(message, printer); + var result = toJson(message, printer); return result; } @@ -100,7 +100,7 @@ public static String toJson(Message message) { */ public static String toCompactJson(Message message) { checkNotNull(message); - String result = toJson(message, compactPrinter); + var result = toJson(message, compactPrinter); return result; } @@ -109,7 +109,7 @@ private static String toJson(Message message, Printer printer) { try { result = printer.print(message); } catch (InvalidProtocolBufferException e) { - Throwable rootCause = getRootCause(e); + var rootCause = getRootCause(e); throw new UnknownTypeException(rootCause); } checkState(result != null); @@ -121,9 +121,9 @@ public static T fromJson(String json, Class messageClass) checkNotNull(json); checkNotNull(messageClass); try { - Message.Builder messageBuilder = builderFor(messageClass); + var messageBuilder = builderFor(messageClass); parser.merge(json, messageBuilder); - T result = (T) messageBuilder.build(); + var result = (T) messageBuilder.build(); return result; } catch (InvalidProtocolBufferException e) { throw newIllegalArgumentException( From 588d972a3853716106c2461df2b8cc2facdef039 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 13:57:32 +0200 Subject: [PATCH 15/27] Use `var`s in `io.spine.logging` package. --- .../main/java/io/spine/logging/FloggerClassValue.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/base/src/main/java/io/spine/logging/FloggerClassValue.java b/base/src/main/java/io/spine/logging/FloggerClassValue.java index 8bed569ef5..35134bd5f4 100644 --- a/base/src/main/java/io/spine/logging/FloggerClassValue.java +++ b/base/src/main/java/io/spine/logging/FloggerClassValue.java @@ -60,10 +60,9 @@ private FloggerClassValue() { } private static Constructor ctor() { - Class loggerBackendClass = LoggerBackend.class; + var loggerBackendClass = LoggerBackend.class; try { - Constructor constructor = - FluentLogger.class.getDeclaredConstructor(loggerBackendClass); + var constructor = FluentLogger.class.getDeclaredConstructor(loggerBackendClass); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { @@ -78,9 +77,9 @@ private static Constructor ctor() { @Override protected FluentLogger computeValue(Class type) { checkNotNull(type); - LoggerBackend backend = Platform.getBackend(type.getName()); + var backend = Platform.getBackend(type.getName()); try { - FluentLogger logger = constructor.newInstance(backend); + var logger = constructor.newInstance(backend); return logger; } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { logger.atSevere() From a95f5146f42ef6e19e3831e7022259b3bd0fae0b Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 14:01:17 +0200 Subject: [PATCH 16/27] Use `var`s in `io.spine.protobuf` package. --- .../java/io/spine/protobuf/AnyPacker.java | 27 +++++++------- .../io/spine/protobuf/BytesConverter.java | 5 +-- .../src/main/java/io/spine/protobuf/Diff.java | 19 ++++------ .../java/io/spine/protobuf/Durations2.java | 35 +++++++++--------- .../java/io/spine/protobuf/EnumConverter.java | 23 ++++++------ .../main/java/io/spine/protobuf/Messages.java | 19 +++++----- .../io/spine/protobuf/PackingIterator.java | 4 +- .../io/spine/protobuf/PrimitiveConverter.java | 37 ++++++++----------- .../io/spine/protobuf/ProtoConverter.java | 2 +- .../java/io/spine/protobuf/TypeConverter.java | 25 +++++++------ 10 files changed, 92 insertions(+), 104 deletions(-) diff --git a/base/src/main/java/io/spine/protobuf/AnyPacker.java b/base/src/main/java/io/spine/protobuf/AnyPacker.java index 3859ca42a8..e5dd1d3e11 100644 --- a/base/src/main/java/io/spine/protobuf/AnyPacker.java +++ b/base/src/main/java/io/spine/protobuf/AnyPacker.java @@ -72,9 +72,9 @@ public static Any pack(Message message) { if (message instanceof Any) { return (Any) message; } - TypeUrl typeUrl = TypeUrl.from(message.getDescriptorForType()); - String typeUrlPrefix = typeUrl.prefix(); - Any result = Any.pack(message, typeUrlPrefix); + var typeUrl = TypeUrl.from(message.getDescriptorForType()); + var typeUrlPrefix = typeUrl.prefix(); + var result = Any.pack(message, typeUrlPrefix); return result; } @@ -87,7 +87,7 @@ public static Any pack(Message message) { */ public static Message unpack(Any any) { checkNotNull(any); - TypeUrl typeUrl = TypeUrl.ofEnclosed(any); + var typeUrl = TypeUrl.ofEnclosed(any); Class messageClass = typeUrl.getMessageClass(); return unpack(any, messageClass); } @@ -116,14 +116,13 @@ public static T unpack(Any any, Class cls) { checkNotNull(any); checkNotNull(cls); - T defaultInstance = Messages.defaultInstance(cls); - TypeUrl expectedTypeUrl = TypeUrl.of(defaultInstance); + var defaultInstance = Messages.defaultInstance(cls); + var expectedTypeUrl = TypeUrl.of(defaultInstance); checkType(any, expectedTypeUrl); try { @SuppressWarnings("unchecked") // Ensured by the check above. - T result = (T) defaultInstance - .getParserForType() - .parseFrom(any.getValue()); + var result = (T) defaultInstance.getParserForType() + .parseFrom(any.getValue()); return result; } catch (InvalidProtocolBufferException e) { throw new UnexpectedTypeException(e); @@ -164,10 +163,10 @@ public static Iterator pack(Iterator iterator) { public static Function<@Nullable Any, @Nullable T> unpackFunc(Class type) { checkNotNull(type); - T defaultInstance = Messages.defaultInstance(type); + var defaultInstance = Messages.defaultInstance(type); @SuppressWarnings("unchecked") - Parser parser = (Parser) defaultInstance.getParserForType(); - TypeUrl expectedTypeUrl = TypeUrl.of(defaultInstance); + var parser = (Parser) defaultInstance.getParserForType(); + var expectedTypeUrl = TypeUrl.of(defaultInstance); return any -> any == null ? null : parseMessage(parser, expectedTypeUrl, any); @@ -177,7 +176,7 @@ public static Iterator pack(Iterator iterator) { parseMessage(Parser parser, TypeUrl expectedTypeUrl, Any any) { checkType(any, expectedTypeUrl); try { - T message = parser.parseFrom(any.getValue()); + var message = parser.parseFrom(any.getValue()); return message; } catch (InvalidProtocolBufferException e) { throw new UnexpectedTypeException(e); @@ -185,7 +184,7 @@ public static Iterator pack(Iterator iterator) { } private static void checkType(Any any, TypeUrl expectedType) { - TypeUrl actualType = TypeUrl.ofEnclosed(any); + var actualType = TypeUrl.ofEnclosed(any); if (!actualType.equals(expectedType)) { throw new UnexpectedTypeException(expectedType, actualType); } diff --git a/base/src/main/java/io/spine/protobuf/BytesConverter.java b/base/src/main/java/io/spine/protobuf/BytesConverter.java index aa071fa075..d3ac581dd5 100644 --- a/base/src/main/java/io/spine/protobuf/BytesConverter.java +++ b/base/src/main/java/io/spine/protobuf/BytesConverter.java @@ -36,14 +36,13 @@ final class BytesConverter extends ProtoConverter { @Override protected ByteString toObject(BytesValue input) { - ByteString result = input.getValue(); + var result = input.getValue(); return result; } @Override protected BytesValue toMessage(ByteString input) { - BytesValue bytes = BytesValue - .newBuilder() + var bytes = BytesValue.newBuilder() .setValue(input) .build(); return bytes; diff --git a/base/src/main/java/io/spine/protobuf/Diff.java b/base/src/main/java/io/spine/protobuf/Diff.java index fcab76b695..8e1a2885de 100644 --- a/base/src/main/java/io/spine/protobuf/Diff.java +++ b/base/src/main/java/io/spine/protobuf/Diff.java @@ -28,12 +28,10 @@ import com.google.common.base.Objects; import com.google.common.collect.ImmutableSet; -import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.code.proto.FieldDeclaration; -import java.util.Map; import java.util.Set; import static com.google.common.base.Preconditions.checkArgument; @@ -77,19 +75,16 @@ public static Diff between(M a, M b) { checkNotNull(a); checkNotNull(b); checkArgument(a.getClass().equals(b.getClass())); - ImmutableSet fields = - symmetricDifference(decompose(a), decompose(b)) - .stream() - .map(tuple -> tuple.declaration) - .collect(toImmutableSet()); + var fields = symmetricDifference(decompose(a), decompose(b)).stream() + .map(tuple -> tuple.declaration) + .collect(toImmutableSet()); return new Diff(fields); } private static Set decompose(Message message) { - Map fieldMap = message.getAllFields(); - return fieldMap - .entrySet() - .stream() + var fieldMap = message.getAllFields(); + var entries = fieldMap.entrySet(); + return entries.stream() .map(entry -> new FieldTuple( new FieldDeclaration(entry.getKey()), entry.getValue() )) @@ -129,7 +124,7 @@ public boolean equals(Object o) { if (!(o instanceof FieldTuple)) { return false; } - FieldTuple tuple = (FieldTuple) o; + var tuple = (FieldTuple) o; return Objects.equal(declaration, tuple.declaration) && Objects.equal(value, tuple.value); } diff --git a/base/src/main/java/io/spine/protobuf/Durations2.java b/base/src/main/java/io/spine/protobuf/Durations2.java index 0ef2c0e083..2ba700a993 100644 --- a/base/src/main/java/io/spine/protobuf/Durations2.java +++ b/base/src/main/java/io/spine/protobuf/Durations2.java @@ -148,7 +148,7 @@ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) { if (d2 == null) { return d1; } - Duration result = Durations.add(d1, d2); + var result = Durations.add(d1, d2); return result; } @@ -157,7 +157,7 @@ public static Duration add(@Nullable Duration d1, @Nullable Duration d2) { * {@code Duration} instance with hours and minutes. */ public static Duration hoursAndMinutes(long hours, long minutes) { - Duration result = add(hours(hours), minutes(minutes)); + var result = add(hours(hours), minutes(minutes)); return result; } @@ -167,8 +167,8 @@ public static Duration hoursAndMinutes(long hours, long minutes) { */ public static boolean isPositiveOrZero(Duration value) { checkNotNull(value); - long millis = toMillis(value); - boolean result = millis >= 0; + var millis = toMillis(value); + var result = millis >= 0; return result; } @@ -178,9 +178,9 @@ public static boolean isPositiveOrZero(Duration value) { */ public static boolean isPositive(Duration value) { checkNotNull(value); - boolean secondsPositive = value.getSeconds() > 0; - boolean nanosPositive = value.getNanos() > 0; - boolean result = secondsPositive || nanosPositive; + var secondsPositive = value.getSeconds() > 0; + var nanosPositive = value.getNanos() > 0; + var result = secondsPositive || nanosPositive; return result; } @@ -188,9 +188,9 @@ public static boolean isPositive(Duration value) { /** Returns {@code true} if the passed value is zero, {@code false} otherwise. */ public static boolean isZero(Duration value) { checkNotNull(value); - boolean noSeconds = value.getSeconds() == 0; - boolean noNanos = value.getNanos() == 0; - boolean result = noSeconds && noNanos; + var noSeconds = value.getSeconds() == 0; + var noNanos = value.getNanos() == 0; + var result = noSeconds && noNanos; return result; } @@ -199,7 +199,7 @@ public static boolean isZero(Duration value) { * {@code false} otherwise. */ public static boolean isGreaterThan(Duration value, Duration another) { - boolean result = compare(value, another) > 0; + var result = compare(value, another) > 0; return result; } @@ -208,7 +208,7 @@ public static boolean isGreaterThan(Duration value, Duration another) { * {@code false} otherwise. */ public static boolean isLessThan(Duration value, Duration another) { - boolean result = compare(value, another) < 0; + var result = compare(value, another) < 0; return result; } @@ -228,7 +228,7 @@ public static boolean isNegative(Duration value) { */ public static Duration of(java.time.Duration value) { checkNotNull(value); - Duration result = converter().convert(value); + var result = converter().convert(value); return requireNonNull(result); } @@ -238,7 +238,7 @@ public static Duration of(java.time.Duration value) { @SuppressWarnings("unused") public static java.time.Duration toJavaTime(Duration value) { checkNotNull(value); - java.time.Duration result = + var result = converter().reverse() .convert(value); return requireNonNull(result); @@ -255,10 +255,9 @@ public static java.time.Duration toJavaTime(Duration value) { */ public static Duration parse(String str) { checkNotNull(str); - Duration result = - Stringifiers.forDuration() - .reverse() - .convert(str); + var result = Stringifiers.forDuration() + .reverse() + .convert(str); return requireNonNull(result); } diff --git a/base/src/main/java/io/spine/protobuf/EnumConverter.java b/base/src/main/java/io/spine/protobuf/EnumConverter.java index cca4849fa1..aaa7bdb43c 100644 --- a/base/src/main/java/io/spine/protobuf/EnumConverter.java +++ b/base/src/main/java/io/spine/protobuf/EnumConverter.java @@ -58,9 +58,9 @@ final class EnumConverter extends ProtoConverter toObject(EnumValue input) { - String name = input.getName(); + var name = input.getName(); if (name.isEmpty()) { - int number = input.getNumber(); + var number = input.getNumber(); return findByNumber(number); } else { return findByName(name); @@ -74,17 +74,17 @@ protected Enum toObject(EnumValue input) { * if enum constant with such a number is not present */ private Enum findByNumber(int number) { - Enum[] constants = type.getEnumConstants(); - for (Enum constant : constants) { - boolean isUnrecognized = isUnrecognized(constant); + var constants = type.getEnumConstants(); + for (var constant : constants) { + var isUnrecognized = isUnrecognized(constant); if (isUnrecognized && number == -1) { return constant; } if (isUnrecognized) { continue; } - ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) constant; - int valueNumber = asProtoEnum.getNumber(); + var asProtoEnum = (ProtocolMessageEnum) constant; + var valueNumber = asProtoEnum.getNumber(); if (number == valueNumber) { return constant; } @@ -105,16 +105,15 @@ private static boolean isUnrecognized(Enum consta */ @SuppressWarnings({"unchecked", "rawtypes"}) // Checked at runtime. private Enum findByName(String name) { - Enum result = Enum.valueOf((Class) type, name); + var result = Enum.valueOf((Class) type, name); return (Enum) result; } @Override protected EnumValue toMessage(Enum input) { - String name = input.name(); - ProtocolMessageEnum asProtoEnum = (ProtocolMessageEnum) input; - EnumValue value = EnumValue - .newBuilder() + var name = input.name(); + var asProtoEnum = (ProtocolMessageEnum) input; + var value = EnumValue.newBuilder() .setName(name) .setNumber(asProtoEnum.getNumber()) .build(); diff --git a/base/src/main/java/io/spine/protobuf/Messages.java b/base/src/main/java/io/spine/protobuf/Messages.java index d14dce79c4..672eb198c7 100644 --- a/base/src/main/java/io/spine/protobuf/Messages.java +++ b/base/src/main/java/io/spine/protobuf/Messages.java @@ -44,6 +44,7 @@ public final class Messages { /** The name of a message builder factory method. */ + @SuppressWarnings("unused") /* Part of the public API. */ public static final String METHOD_NEW_BUILDER = "newBuilder"; /** @@ -68,7 +69,7 @@ private Messages() { public static M defaultInstance(Class messageClass) { checkNotNull(messageClass); @SuppressWarnings("unchecked") // Ensured by the `MessageCacheLoader` implementation. - M result = (M) defaultInstances.getUnchecked(messageClass); + var result = (M) defaultInstances.getUnchecked(messageClass); return result; } @@ -79,12 +80,12 @@ public static M defaultInstance(Class messageClass) { public static Message.Builder builderFor(Class cls) { checkNotNull(cls); try { - Message message = defaultInstance(cls); - Message.Builder builder = message.toBuilder(); + var message = defaultInstance(cls); + var builder = message.toBuilder(); return builder; } catch (UncheckedExecutionException e) { - String errMsg = format("Class `%s` must be a generated proto message.", - cls.getCanonicalName()); + var errMsg = format("Class `%s` must be a generated proto message.", + cls.getCanonicalName()); throw new IllegalArgumentException(errMsg, e); } } @@ -97,7 +98,7 @@ public static Message ensureMessage(Message msgOrAny) { checkNotNull(msgOrAny); Message commandMessage; if (msgOrAny instanceof Any) { - Any any = (Any) msgOrAny; + var any = (Any) msgOrAny; commandMessage = AnyPacker.unpack(any); } else { commandMessage = msgOrAny; @@ -120,8 +121,8 @@ private static LoadingCache, Message> loadingCache(int */ public static boolean isDefault(Message object) { checkNotNull(object); - boolean result = object.getDefaultInstanceForType() - .equals(object); + var result = object.getDefaultInstanceForType() + .equals(object); return result; } @@ -134,7 +135,7 @@ public static boolean isDefault(Message object) { */ public static boolean isNotDefault(Message object) { checkNotNull(object); - boolean result = !isDefault(object); + var result = !isDefault(object); return result; } diff --git a/base/src/main/java/io/spine/protobuf/PackingIterator.java b/base/src/main/java/io/spine/protobuf/PackingIterator.java index 7db2ce52f1..58857c4c2c 100644 --- a/base/src/main/java/io/spine/protobuf/PackingIterator.java +++ b/base/src/main/java/io/spine/protobuf/PackingIterator.java @@ -62,8 +62,8 @@ public boolean hasNext() { */ @Override public Any next() { - Message next = source.next(); - Any result = next != null + var next = source.next(); + var result = next != null ? AnyPacker.pack(next) : Any.getDefaultInstance(); return result; diff --git a/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java b/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java index f8fd5ef658..f8aeee1df4 100644 --- a/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java +++ b/base/src/main/java/io/spine/protobuf/PrimitiveConverter.java @@ -39,6 +39,7 @@ import com.google.protobuf.UInt64Value; import static com.google.common.base.Preconditions.checkArgument; +import static java.util.Objects.requireNonNull; /** * Converts the primitive and built-in types to the corresponding {@link Message}s and back. @@ -81,22 +82,22 @@ final class PrimitiveConverter extends ProtoConverter boxedType = input.getClass(); - Converter converter = wrapperConverter(boxedType); - T result = converter.convert(input); - return result; + var converter = wrapperConverter(boxedType); + var result = converter.convert(input); + return requireNonNull(result); } @Override protected M toMessage(T input) { - Class cls = input.getClass(); - Converter converter = primitiveConverter(cls); - M result = converter.convert(input); - return result; + var cls = input.getClass(); + var converter = primitiveConverter(cls); + var result = converter.convert(input); + return requireNonNull(result); } private Converter wrapperConverter(Class boxedType) { @SuppressWarnings("unchecked") - Converter converter = (Converter) PROTO_WRAPPER_TO_CONVERTER.get(boxedType); + var converter = (Converter) PROTO_WRAPPER_TO_CONVERTER.get(boxedType); checkArgument( converter != null, "Could not find a primitive type for `%s`.", @@ -107,7 +108,7 @@ private Converter wrapperConverter(Class boxedType) { private Converter primitiveConverter(Class cls) { @SuppressWarnings("unchecked") - Converter converter = (Converter) PRIMITIVE_TO_CONVERTER.get(cls); + var converter = (Converter) PRIMITIVE_TO_CONVERTER.get(cls); checkArgument( converter != null, "Could not find a wrapper type for `%s`.", @@ -125,8 +126,7 @@ protected Integer unwrap(Int32Value message) { @Override protected Int32Value wrap(Integer value) { - return Int32Value - .newBuilder() + return Int32Value.newBuilder() .setValue(value) .build(); } @@ -141,8 +141,7 @@ protected Long unwrap(Int64Value message) { @Override protected Int64Value wrap(Long value) { - return Int64Value - .newBuilder() + return Int64Value.newBuilder() .setValue(value) .build(); } @@ -189,8 +188,7 @@ protected Float unwrap(FloatValue message) { @Override protected FloatValue wrap(Float value) { - return FloatValue - .newBuilder() + return FloatValue.newBuilder() .setValue(value) .build(); } @@ -205,8 +203,7 @@ protected Double unwrap(DoubleValue message) { @Override protected DoubleValue wrap(Double value) { - return DoubleValue - .newBuilder() + return DoubleValue.newBuilder() .setValue(value) .build(); } @@ -221,8 +218,7 @@ protected Boolean unwrap(BoolValue message) { @Override protected BoolValue wrap(Boolean value) { - return BoolValue - .newBuilder() + return BoolValue.newBuilder() .setValue(value) .build(); } @@ -237,8 +233,7 @@ protected String unwrap(StringValue message) { @Override protected StringValue wrap(String value) { - return StringValue - .newBuilder() + return StringValue.newBuilder() .setValue(value) .build(); } diff --git a/base/src/main/java/io/spine/protobuf/ProtoConverter.java b/base/src/main/java/io/spine/protobuf/ProtoConverter.java index a0caedb353..705ab21d31 100644 --- a/base/src/main/java/io/spine/protobuf/ProtoConverter.java +++ b/base/src/main/java/io/spine/protobuf/ProtoConverter.java @@ -72,7 +72,7 @@ static Converter forType(Class type) { converter = new PrimitiveConverter<>(); } @SuppressWarnings("unchecked") // Logically checked. - Converter result = (Converter) converter; + var result = (Converter) converter; return result; } diff --git a/base/src/main/java/io/spine/protobuf/TypeConverter.java b/base/src/main/java/io/spine/protobuf/TypeConverter.java index 6425d3af2f..b3f1203369 100644 --- a/base/src/main/java/io/spine/protobuf/TypeConverter.java +++ b/base/src/main/java/io/spine/protobuf/TypeConverter.java @@ -37,6 +37,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.protobuf.AnyPacker.unpack; +import static java.util.Objects.requireNonNull; /** * A utility for converting the {@linkplain Message Protobuf Messages} (in form of {@link Any}) into @@ -83,9 +84,9 @@ public static T toObject(Any message, Class target) { checkNotNull(target); checkNotRawEnum(message, target); Converter converter = ProtoConverter.forType(target); - Message genericMessage = unpack(message); - T result = converter.convert(genericMessage); - return result; + var genericMessage = unpack(message); + var result = converter.convert(genericMessage); + return requireNonNull(result); } /** @@ -100,8 +101,8 @@ public static T toObject(Any message, Class target) { */ public static Any toAny(T value) { checkNotNull(value); - Message message = toMessage(value); - Any result = AnyPacker.pack(message); + var message = toMessage(value); + var result = AnyPacker.pack(message); return result; } @@ -116,10 +117,10 @@ public static Any toAny(T value) { */ public static Message toMessage(T value) { @SuppressWarnings("unchecked" /* Must be checked at runtime. */) - Class srcClass = (Class) value.getClass(); - Converter converter = ProtoConverter.forType(srcClass); - Message message = converter.reverse().convert(value); - checkNotNull(message); + var srcClass = (Class) value.getClass(); + var converter = ProtoConverter.forType(srcClass); + var message = converter.reverse().convert(value); + requireNonNull(message); return message; } @@ -138,7 +139,7 @@ public static Message toMessage(T value) { */ public static M toMessage(T value, Class messageClass) { checkNotNull(messageClass); - Message message = toMessage(value); + var message = toMessage(value); return messageClass.cast(message); } @@ -152,8 +153,8 @@ private static void checkNotRawEnum(Any message, Class target) { if (!target.isEnum()) { return; } - String typeUrl = message.getTypeUrl(); - String enumValueTypeUrl = ENUM_VALUE_TYPE_URL.value(); + var typeUrl = message.getTypeUrl(); + var enumValueTypeUrl = ENUM_VALUE_TYPE_URL.value(); checkArgument( enumValueTypeUrl.equals(typeUrl), "Currently the conversion of enum types packed as `%s` is not supported. " + From 50cbe410a4ef0d3dabad90c2647490e9079ec9e2 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 14:08:04 +0200 Subject: [PATCH 17/27] Use `var`s in `io.spine.query` package. --- .../io/spine/query/AbstractQueryBuilder.java | 26 ++++---- .../io/spine/query/CartesianProducts.java | 63 +++++++++---------- .../src/main/java/io/spine/query/Columns.java | 4 +- .../io/spine/query/ComparisonOperator.java | 6 +- .../java/io/spine/query/CustomCriterion.java | 2 +- .../java/io/spine/query/Distribution.java | 12 ++-- .../java/io/spine/query/EntityCriterion.java | 3 +- .../main/java/io/spine/query/EntityQuery.java | 21 ++++--- .../io/spine/query/EntityQueryBuilder.java | 15 ++--- .../main/java/io/spine/query/Expression.java | 12 ++-- .../main/java/io/spine/query/IdCriterion.java | 10 +-- .../main/java/io/spine/query/IdParameter.java | 2 +- .../java/io/spine/query/OrExpression.java | 4 +- .../java/io/spine/query/QueryPredicate.java | 43 +++++++------ .../java/io/spine/query/RecordColumn.java | 2 +- .../java/io/spine/query/RecordCriterion.java | 2 +- .../main/java/io/spine/query/RecordQuery.java | 10 +-- .../io/spine/query/RecordQueryBuilder.java | 4 +- base/src/main/java/io/spine/query/SortBy.java | 3 +- .../src/main/java/io/spine/query/Subject.java | 2 +- .../java/io/spine/query/SubjectParameter.java | 2 +- .../java/io/spine/query/TransformToDnf.java | 44 +++++++------ 22 files changed, 144 insertions(+), 148 deletions(-) diff --git a/base/src/main/java/io/spine/query/AbstractQueryBuilder.java b/base/src/main/java/io/spine/query/AbstractQueryBuilder.java index 89659b5b0e..7a899db143 100644 --- a/base/src/main/java/io/spine/query/AbstractQueryBuilder.java +++ b/base/src/main/java/io/spine/query/AbstractQueryBuilder.java @@ -117,7 +117,7 @@ public IdParameter whichIds() { @Override public QueryPredicate predicate() { - QueryPredicate result = rootBuilder.build(); + var result = rootBuilder.build(); return result; } @@ -157,16 +157,16 @@ public final B withMask(FieldMask mask) { @Override @CanIgnoreReturnValue public final B withMask(String ...maskPaths) { - ImmutableList pathList = ImmutableList.copyOf(maskPaths); + var pathList = ImmutableList.copyOf(maskPaths); return withMask(pathList); } @Override @CanIgnoreReturnValue public final B withMask(Field... fields) { - ImmutableList paths = Arrays.stream(fields) - .map(Field::toString) - .collect(toImmutableList()); + var paths = Arrays.stream(fields) + .map(Field::toString) + .collect(toImmutableList()); return withMask(paths); } @@ -180,8 +180,8 @@ public final B withMask(Field... fields) { * @see #withMask(String...) */ final B withMask(Collection paths) { - Class recordType = whichRecordType(); - FieldMask fieldMask = fromStringList(recordType, paths); + var recordType = whichRecordType(); + var fieldMask = fromStringList(recordType, paths); return withMask(fieldMask); } @@ -206,7 +206,7 @@ public final B sortDescendingBy(RecordColumn column) { @CanIgnoreReturnValue @SuppressWarnings("OverloadedVarargsMethod") /* For convenience. */ public final B either(Either... parameters) { - List> asList = Arrays.asList(parameters); + var asList = Arrays.asList(parameters); return either(asList); } @@ -214,11 +214,11 @@ public final B either(Either... parameters) { @CanIgnoreReturnValue @SuppressWarnings("ReturnValueIgnored") /* `Either` values applied one by one. */ public final B either(Iterable> parameters) { - QueryPredicate.Builder previous = currentPredicate; + var previous = currentPredicate; - QueryPredicate.Builder either = QueryPredicate.newBuilder(currentPredicate, OR); - for (Either parameter : parameters) { - QueryPredicate.Builder and = QueryPredicate.newBuilder(either, AND); + var either = QueryPredicate.newBuilder(currentPredicate, OR); + for (var parameter : parameters) { + var and = QueryPredicate.newBuilder(either, AND); currentPredicate = and; parameter.apply(thisRef()); @@ -277,7 +277,7 @@ protected final B setIdParameter(IdParameter value) { @CanIgnoreReturnValue protected final B replacePredicate(QueryPredicate value) { checkNotNull(value); - QueryPredicate.Builder asBuilder = value.toBuilder(); + var asBuilder = value.toBuilder(); return replacePredicate(asBuilder); } diff --git a/base/src/main/java/io/spine/query/CartesianProducts.java b/base/src/main/java/io/spine/query/CartesianProducts.java index 297ab61d01..1df8b4e4e6 100644 --- a/base/src/main/java/io/spine/query/CartesianProducts.java +++ b/base/src/main/java/io/spine/query/CartesianProducts.java @@ -64,7 +64,7 @@ void cartesianSimpleParams(List> simpleParams, checkNotNull(simpleParams); checkNotNull(expression); checkNotNull(result); - for (SubjectParameter givenParam : simpleParams) { + for (var givenParam : simpleParams) { paramOverSimpleParams(givenParam, expression.params(), result); paramOverCustomParams(givenParam, expression.customParams(), result); paramOverChildren(givenParam, expression.children(), result); @@ -88,7 +88,7 @@ void cartesianChildren(List> children, checkNotNull(children); checkNotNull(expression); checkNotNull(result); - for (Expression firstChild : children) { + for (var firstChild : children) { childOverSimpleParams(firstChild, expression.params(), result); childOverCustomParams(firstChild, expression.customParams(), result); childOverChildren(firstChild, expression.children(), result); @@ -112,7 +112,7 @@ void cartesianCustomParams(List> customParams, checkNotNull(customParams); checkNotNull(expression); checkNotNull(result); - for (CustomSubjectParameter customParam : customParams) { + for (var customParam : customParams) { customOverSimple(customParam, expression, result); customOverCustom(customParam, expression, result); customOverChildren(customParam, expression, result); @@ -132,11 +132,11 @@ void cartesianCustomParams(List> customParams, void paramOverSimpleParams(SubjectParameter param, ImmutableList> simpleParams, OrBuilder result) { - for (SubjectParameter simpleParam : simpleParams) { + for (var simpleParam : simpleParams) { AndBuilder childBuilder = AndExpression.newBuilder(); - AndExpression childAnd = childBuilder.addParam(param) - .addParam(simpleParam) - .build(); + var childAnd = childBuilder.addParam(param) + .addParam(simpleParam) + .build(); result.addExpression(childAnd); } } @@ -154,11 +154,11 @@ void paramOverSimpleParams(SubjectParameter param, void paramOverCustomParams(SubjectParameter param, ImmutableList> customParams, OrBuilder result) { - for (CustomSubjectParameter customParam : customParams) { + for (var customParam : customParams) { AndBuilder childBuilder = AndExpression.newBuilder(); - AndExpression childAnd = childBuilder.addParam(param) - .addCustomParam(customParam) - .build(); + var childAnd = childBuilder.addParam(param) + .addCustomParam(customParam) + .build(); result.addExpression(childAnd); } } @@ -175,11 +175,10 @@ void paramOverCustomParams(SubjectParameter param, private static void paramOverChildren(SubjectParameter param, ImmutableList> children, OrBuilder result) { - for (Expression child : children) { + for (var child : children) { AndBuilder childBuilder = AndExpression.newBuilder(); addChild(child, childBuilder); - AndExpression childAnd = childBuilder.addParam(param) - .build(); + var childAnd = childBuilder.addParam(param).build(); result.addExpression(childAnd); } } @@ -196,11 +195,10 @@ private static void paramOverChildren(SubjectParameter param, private static void customOverChildren(CustomSubjectParameter customParam, OrExpression expression, OrBuilder result) { - for (Expression secondChild : expression.children()) { + for (var secondChild : expression.children()) { AndBuilder childBuilder = AndExpression.newBuilder(); addChild(secondChild, childBuilder); - AndExpression childAnd = childBuilder.addCustomParam(customParam) - .build(); + var childAnd = childBuilder.addCustomParam(customParam).build(); result.addExpression(childAnd); } } @@ -217,11 +215,11 @@ private static void customOverChildren(CustomSubjectParameter customPa private static void customOverCustom(CustomSubjectParameter customParam, OrExpression second, OrBuilder result) { - for (CustomSubjectParameter secondCustom : second.customParams()) { + for (var secondCustom : second.customParams()) { AndBuilder childBuilder = AndExpression.newBuilder(); - AndExpression childAnd = childBuilder.addCustomParam(customParam) - .addCustomParam(secondCustom) - .build(); + var childAnd = childBuilder.addCustomParam(customParam) + .addCustomParam(secondCustom) + .build(); result.addExpression(childAnd); } } @@ -238,11 +236,11 @@ private static void customOverCustom(CustomSubjectParameter customPara private static void customOverSimple(CustomSubjectParameter customParam, OrExpression expression, OrBuilder result) { - for (SubjectParameter secondParam : expression.params()) { + for (var secondParam : expression.params()) { AndBuilder childBuilder = AndExpression.newBuilder(); - AndExpression childAnd = childBuilder.addCustomParam(customParam) - .addParam(secondParam) - .build(); + var childAnd = childBuilder.addCustomParam(customParam) + .addParam(secondParam) + .build(); result.addExpression(childAnd); } } @@ -260,11 +258,10 @@ private static void customOverSimple(CustomSubjectParameter customPara void childOverSimpleParams(Expression child, ImmutableList> simpleParams, OrBuilder result) { - for (SubjectParameter simpleParam : simpleParams) { + for (var simpleParam : simpleParams) { AndBuilder childBuilder = AndExpression.newBuilder(); addChild(child, childBuilder); - AndExpression childAnd = childBuilder.addParam(simpleParam) - .build(); + var childAnd = childBuilder.addParam(simpleParam).build(); result.addExpression(childAnd); } } @@ -282,11 +279,11 @@ void childOverSimpleParams(Expression child, void childOverCustomParams(Expression child, ImmutableList> customParams, OrBuilder result) { - for (CustomSubjectParameter customParam : customParams) { + for (var customParam : customParams) { AndBuilder childBuilder = AndExpression.newBuilder(); addChild(child, childBuilder); - AndExpression childAnd = childBuilder.addCustomParam(customParam) - .build(); + var childAnd = childBuilder.addCustomParam(customParam) + .build(); result.addExpression(childAnd); } } @@ -303,11 +300,11 @@ void childOverCustomParams(Expression child, private static void childOverChildren(Expression child, ImmutableList> children, OrBuilder result) { - for (Expression orChild : children) { + for (var orChild : children) { AndBuilder childBuilder = AndExpression.newBuilder(); addChild(child, childBuilder); addChild(orChild, childBuilder); - AndExpression childAnd = childBuilder.build(); + var childAnd = childBuilder.build(); result.addExpression(childAnd); } } diff --git a/base/src/main/java/io/spine/query/Columns.java b/base/src/main/java/io/spine/query/Columns.java index 1ac5276b6a..6df66583ef 100644 --- a/base/src/main/java/io/spine/query/Columns.java +++ b/base/src/main/java/io/spine/query/Columns.java @@ -76,8 +76,8 @@ private Columns(ImmutableList> delegate) { @SafeVarargs public static Columns of(RecordColumn... columns) { checkNotNull(columns); - ImmutableList> asList = ImmutableList.copyOf(columns); - Columns result = new Columns<>(asList); + var asList = ImmutableList.copyOf(columns); + var result = new Columns<>(asList); return result; } diff --git a/base/src/main/java/io/spine/query/ComparisonOperator.java b/base/src/main/java/io/spine/query/ComparisonOperator.java index 9950646348..d7b2bf0d97 100644 --- a/base/src/main/java/io/spine/query/ComparisonOperator.java +++ b/base/src/main/java/io/spine/query/ComparisonOperator.java @@ -118,14 +118,14 @@ public boolean eval(@Nullable Object left, @Nullable Object right) { ); } if (left instanceof Timestamp) { - Timestamp firstT = (Timestamp) left; - Timestamp secondT = (Timestamp) right; + var firstT = (Timestamp) left; + var secondT = (Timestamp) right; return Timestamps.compare(firstT, secondT) > 0; } if (left instanceof Comparable) { Comparable cmpLeft = (Comparable) left; Comparable cmpRight = (Comparable) right; - int comparisonResult = cmpLeft.compareTo(cmpRight); + var comparisonResult = cmpLeft.compareTo(cmpRight); return comparisonResult > 0; } throw new UnsupportedOperationException(format( diff --git a/base/src/main/java/io/spine/query/CustomCriterion.java b/base/src/main/java/io/spine/query/CustomCriterion.java index 93b4f2271f..3c8ae9c382 100644 --- a/base/src/main/java/io/spine/query/CustomCriterion.java +++ b/base/src/main/java/io/spine/query/CustomCriterion.java @@ -73,7 +73,7 @@ final class CustomCriterion> { @CanIgnoreReturnValue public B is(V value) { checkNotNull(value); - CustomSubjectParameter param = new CustomSubjectParameter<>(column, value, EQUALS); + var param = new CustomSubjectParameter<>(column, value, EQUALS); return builder.addCustomParameter(param); } } diff --git a/base/src/main/java/io/spine/query/Distribution.java b/base/src/main/java/io/spine/query/Distribution.java index d27ef237fe..c4000fe33d 100644 --- a/base/src/main/java/io/spine/query/Distribution.java +++ b/base/src/main/java/io/spine/query/Distribution.java @@ -95,7 +95,7 @@ private static OrExpression distributeCnj(AndExpression and, OrExpress private static void distributeChildren(AndExpression and, List> orChildren, OrExpression.OrBuilder result) { - for (Expression child : orChildren) { + for (var child : orChildren) { AndBuilder childBuilder = AndExpression.newBuilder(); and.copyTo(childBuilder); if (child.operator() == AND) { @@ -104,7 +104,7 @@ private static void distributeChildren(AndExpression and, } else { childBuilder.addExpression(child); } - AndExpression childAnd = childBuilder.build(); + var childAnd = childBuilder.build(); result.addExpression(childAnd); } } @@ -126,11 +126,11 @@ private static void distributeChildren(AndExpression and, distributeCustomParams(AndExpression and, List> customParams, OrExpression.OrBuilder result) { - for (CustomSubjectParameter param : customParams) { + for (var param : customParams) { AndBuilder childBuilder = AndExpression.newBuilder(); and.copyTo(childBuilder); childBuilder.addCustomParam(param); - AndExpression childAnd = childBuilder.build(); + var childAnd = childBuilder.build(); result.addExpression(childAnd); } } @@ -151,11 +151,11 @@ private static void distributeChildren(AndExpression and, private static void distributeSimpleParams(AndExpression and, List> disjunctiveParams, OrExpression.OrBuilder result) { - for (SubjectParameter param : disjunctiveParams) { + for (var param : disjunctiveParams) { AndBuilder childBuilder = AndExpression.newBuilder(); and.copyTo(childBuilder); childBuilder.addParam(param); - AndExpression childAnd = childBuilder.build(); + var childAnd = childBuilder.build(); result.addExpression(childAnd); } } diff --git a/base/src/main/java/io/spine/query/EntityCriterion.java b/base/src/main/java/io/spine/query/EntityCriterion.java index 6bb65a4776..51f6e4adc0 100644 --- a/base/src/main/java/io/spine/query/EntityCriterion.java +++ b/base/src/main/java/io/spine/query/EntityCriterion.java @@ -40,6 +40,7 @@ * @param * the type of the builder in scope of which this criterion exists */ +@SuppressWarnings("unused") /* Part of the public API. */ public final class EntityCriterion, V, B extends EntityQueryBuilder> @@ -63,7 +64,7 @@ public EntityCriterion(EntityColumn column, B builder) { protected B addParameter(B builder, EntityColumn col, ComparisonOperator operator, V value) { - EntitySubjectParameter parameter = new EntitySubjectParameter<>(col, value, operator); + var parameter = new EntitySubjectParameter<>(col, value, operator); return builder.addParameter(parameter); } } diff --git a/base/src/main/java/io/spine/query/EntityQuery.java b/base/src/main/java/io/spine/query/EntityQuery.java index a99e364853..105ee04251 100644 --- a/base/src/main/java/io/spine/query/EntityQuery.java +++ b/base/src/main/java/io/spine/query/EntityQuery.java @@ -26,7 +26,6 @@ package io.spine.query; -import com.google.protobuf.FieldMask; import io.spine.base.EntityState; /** @@ -43,6 +42,7 @@ * the type of a particular {@linkplain EntityQueryBuilder query builder} implementation * to create the query instances */ +@SuppressWarnings("AbstractClassNeverImplemented") /* Part of the public API. */ public abstract class EntityQuery, B extends EntityQueryBuilder> @@ -68,13 +68,14 @@ public final B toBuilder() { /** * Creates a {@link RecordQuery} instance with the same attributes as this entity query. */ + @SuppressWarnings("unused") /* Part of the public API. */ public final RecordQuery toRecordQuery() { - Subject subject = subject(); - Class idType = subject.idType(); - Class recordType = subject.recordType(); - RecordQueryBuilder destination = RecordQuery.newBuilder(idType, recordType); + var subject = subject(); + var idType = subject.idType(); + var recordType = subject.recordType(); + var destination = RecordQuery.newBuilder(idType, recordType); doCopyTo(destination); - RecordQuery result = destination.build(); + var result = destination.build(); return result; } @@ -107,7 +108,7 @@ private void copyIdParameter(AbstractQueryBuilder destination) { * Copies the top-level predicate from the current query instance to the destination builder. */ private void copyPredicate(AbstractQueryBuilder destination) { - QueryPredicate predicate = subject().predicate(); + var predicate = subject().predicate(); destination.replacePredicate(predicate); } @@ -115,7 +116,7 @@ private void copyPredicate(AbstractQueryBuilder destination) { * Copies the field mask value from the current instance to the destination builder. */ private void copyMask(AbstractQueryBuilder destination) { - FieldMask sourceMask = mask(); + var sourceMask = mask(); if (sourceMask != null) { destination.withMask(sourceMask); } @@ -125,7 +126,7 @@ private void copyMask(AbstractQueryBuilder destination) { * Copies the limit value from the current instance to the destination builder. */ private void copyLimit(AbstractQueryBuilder destination) { - Integer sourceLimit = limit(); + var sourceLimit = limit(); if (sourceLimit != null) { destination.limit(sourceLimit); } @@ -135,7 +136,7 @@ private void copyLimit(AbstractQueryBuilder destination) { * Copies the sorting directives from the current instance to the destination builder. */ private void copySorting(AbstractQueryBuilder destination) { - for (SortBy sourceSortBy : sorting()) { + for (var sourceSortBy : sorting()) { destination.addSorting(sourceSortBy); } } diff --git a/base/src/main/java/io/spine/query/EntityQueryBuilder.java b/base/src/main/java/io/spine/query/EntityQueryBuilder.java index 20493b2c62..57d2955a90 100644 --- a/base/src/main/java/io/spine/query/EntityQueryBuilder.java +++ b/base/src/main/java/io/spine/query/EntityQueryBuilder.java @@ -26,7 +26,6 @@ package io.spine.query; -import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import io.spine.base.EntityState; import io.spine.base.SubscribableField; @@ -50,6 +49,7 @@ * the type of a particular {@link EntityQuery} implementation which this builder * is aimed to build */ +@SuppressWarnings("AbstractClassNeverImplemented") /* Part of the public API. */ public abstract class EntityQueryBuilder, B extends EntityQueryBuilder, @@ -94,11 +94,12 @@ public final B where(CustomColumn column, V value) { * @return this instance of query builder, for chaining */ @CanIgnoreReturnValue + @SuppressWarnings("unused") /* Part of the public API. */ public final B withMask(SubscribableField... fields) { - ImmutableList paths = Arrays.stream(fields) - .map(f -> f.getField() - .toString()) - .collect(toImmutableList()); + var paths = Arrays.stream(fields) + .map(f -> f.getField() + .toString()) + .collect(toImmutableList()); return withMask(paths); } @@ -117,8 +118,8 @@ public final B withMask(SubscribableField... fields) { */ public final T build(Function, T> transformer) { checkNotNull(transformer); - Q query = build(); - T result = transformer.apply(query); + var query = build(); + var result = transformer.apply(query); return result; } } diff --git a/base/src/main/java/io/spine/query/Expression.java b/base/src/main/java/io/spine/query/Expression.java index 1c5bffaafc..91742095a7 100644 --- a/base/src/main/java/io/spine/query/Expression.java +++ b/base/src/main/java/io/spine/query/Expression.java @@ -102,7 +102,7 @@ final LogicalOperator operator() { * Returns a copy of this expression, but without child expressions. */ final E withoutChildren() { - Builder builder = createBuilder(); + var builder = createBuilder(); copyParams(builder); copyCustomParams(builder); return builder.build(); @@ -119,7 +119,7 @@ final boolean hasChildren() { * Tells whether this expression has neither parameters nor children. */ final boolean isEmpty() { - boolean result = + var result = params().isEmpty() && customParams().isEmpty() && children().isEmpty(); @@ -136,7 +136,7 @@ && customParams().isEmpty() * of the passed expression. */ E concat(E another) { - Builder result = createBuilder(); + var result = createBuilder(); copyTo(result); another.copyTo(result); return result.build(); @@ -167,7 +167,7 @@ private void copyParams(Builder result) { * Creates a new {@code Builder} with the same content as this expression. */ Builder toBuilder() { - Builder result = createBuilder(); + var result = createBuilder(); copyTo(result); return result; } @@ -214,7 +214,7 @@ B addParam(SubjectParameter parameter) { @CanIgnoreReturnValue B addParams(Iterable> parameters) { checkNotNull(parameters); - for (SubjectParameter param : parameters) { + for (var param : parameters) { addParam(param); } return thisRef(); @@ -236,7 +236,7 @@ B addCustomParam(CustomSubjectParameter parameter) { @CanIgnoreReturnValue B addCustomParams(Iterable> parameters) { checkNotNull(parameters); - for (CustomSubjectParameter param : parameters) { + for (var param : parameters) { addCustomParam(param); } return thisRef(); diff --git a/base/src/main/java/io/spine/query/IdCriterion.java b/base/src/main/java/io/spine/query/IdCriterion.java index ce57b313d6..74e2e738ce 100644 --- a/base/src/main/java/io/spine/query/IdCriterion.java +++ b/base/src/main/java/io/spine/query/IdCriterion.java @@ -54,7 +54,7 @@ public IdCriterion(B builder) { */ @CanIgnoreReturnValue public B is(I value) { - IdParameter parameter = IdParameter.is(value); + var parameter = IdParameter.is(value); return builder.setIdParameter(parameter); } @@ -65,8 +65,8 @@ public B is(I value) { @CanIgnoreReturnValue @SuppressWarnings("OverloadedVarargsMethod") /* For convenience. */ public final B in(I... values) { - ImmutableSet asSet = ImmutableSet.copyOf(values); - IdParameter parameter = IdParameter.in(asSet); + var asSet = ImmutableSet.copyOf(values); + var parameter = IdParameter.in(asSet); return builder.setIdParameter(parameter); } @@ -75,8 +75,8 @@ public final B in(I... values) { */ @CanIgnoreReturnValue public final B in(Iterable values) { - ImmutableSet asList = ImmutableSet.copyOf(values); - IdParameter parameter = IdParameter.in(asList); + var asList = ImmutableSet.copyOf(values); + var parameter = IdParameter.in(asList); return builder.setIdParameter(parameter); } } diff --git a/base/src/main/java/io/spine/query/IdParameter.java b/base/src/main/java/io/spine/query/IdParameter.java index 67927b6abe..588228e967 100644 --- a/base/src/main/java/io/spine/query/IdParameter.java +++ b/base/src/main/java/io/spine/query/IdParameter.java @@ -72,7 +72,7 @@ public boolean equals(Object o) { if (!(o instanceof IdParameter)) { return false; } - IdParameter parameter = (IdParameter) o; + var parameter = (IdParameter) o; return Objects.equals(values, parameter.values); } diff --git a/base/src/main/java/io/spine/query/OrExpression.java b/base/src/main/java/io/spine/query/OrExpression.java index 615ef35681..25a5879254 100644 --- a/base/src/main/java/io/spine/query/OrExpression.java +++ b/base/src/main/java/io/spine/query/OrExpression.java @@ -60,9 +60,7 @@ static OrBuilder newBuilder() { */ static OrBuilder asOrBuilder(Expression expression) { @SuppressWarnings("unchecked") - OrBuilder resultBuilder = (OrBuilder) - asOr(expression) - .toBuilder(); + var resultBuilder = (OrBuilder) asOr(expression).toBuilder(); return resultBuilder; } diff --git a/base/src/main/java/io/spine/query/QueryPredicate.java b/base/src/main/java/io/spine/query/QueryPredicate.java index 24e042e8de..060d33c1e9 100644 --- a/base/src/main/java/io/spine/query/QueryPredicate.java +++ b/base/src/main/java/io/spine/query/QueryPredicate.java @@ -166,7 +166,7 @@ public ImmutableList> children() { * @see Disjunctive normal form */ public QueryPredicate toDnf() { - QueryPredicate result = new TransformToDnf().apply(this); + var result = new TransformToDnf().apply(this); return result; } @@ -192,19 +192,19 @@ public boolean isEmpty() { } private static void copyChildren(QueryPredicate predicate, Builder builder) { - for (QueryPredicate child : predicate.children) { + for (var child : predicate.children) { builder.addPredicate(child); } } private static void copyCustomParams(QueryPredicate predicate, Builder builder) { - for (CustomSubjectParameter customParam : predicate.customParameters) { + for (var customParam : predicate.customParameters) { builder.addCustom(customParam); } } private static void copyParams(QueryPredicate predicate, Builder builder) { - for (SubjectParameter parameter : predicate.parameters) { + for (var parameter : predicate.parameters) { builder.add(parameter); } } @@ -226,12 +226,12 @@ private static void copyParams(QueryPredicate predicate, Builder build checkNotNull(operator); Builder builder = newBuilder(operator); - for (QueryPredicate predicate : predicates) { + for (var predicate : predicates) { copyParams(predicate, builder); copyCustomParams(predicate, builder); copyChildren(predicate, builder); } - QueryPredicate result = builder.build(); + var result = builder.build(); return result; } @@ -254,7 +254,7 @@ public boolean equals(Object o) { if (!(o instanceof QueryPredicate)) { return false; } - QueryPredicate predicate = (QueryPredicate) o; + var predicate = (QueryPredicate) o; return operator == predicate.operator && Objects.equals(parameters, predicate.parameters) && Objects.equals(customParameters, predicate.customParameters) && @@ -334,7 +334,7 @@ Builder add(SubjectParameter parameter) { @CanIgnoreReturnValue Builder addParams(Iterable> parameters) { checkNotNull(parameters); - for (SubjectParameter parameter : parameters) { + for (var parameter : parameters) { add(parameter); } return this; @@ -358,7 +358,7 @@ Builder addCustom(CustomSubjectParameter parameter) { @CanIgnoreReturnValue Builder addCustomParams(Iterable> parameters) { checkNotNull(parameters); - for (CustomSubjectParameter parameter : parameters) { + for (var parameter : parameters) { addCustom(parameter); } return this; @@ -388,7 +388,7 @@ boolean isTopLevel() { QueryPredicate build() { optimizeForOnlyChild(); flattenSimilarChildren(); - QueryPredicate result = new QueryPredicate<>(this); + var result = new QueryPredicate<>(this); appendToParent(result); return result; } @@ -410,13 +410,13 @@ QueryPredicate build() { */ private void optimizeForOnlyChild() { if (isTopLevel() && hasNoParams() && children.size() == 1) { - QueryPredicate onlyChild = children.get(0); + var onlyChild = children.get(0); this.operator = onlyChild.operator(); addParams(onlyChild.parameters()); addCustomParams(onlyChild.customParameters()); children.clear(); - ImmutableList> grandChildren = onlyChild.children; - for (QueryPredicate grandChild : grandChildren) { + var grandChildren = onlyChild.children; + for (var grandChild : grandChildren) { addPredicate(grandChild); } } @@ -427,12 +427,11 @@ private void optimizeForOnlyChild() { * the same logical operator as this builder. */ private void flattenSimilarChildren() { - long differentChildrenCount = - children.stream() - .filter(c -> c.operator != operator()) - .count(); + var differentChildrenCount = children.stream() + .filter(c -> c.operator != operator()) + .count(); if (differentChildrenCount == 0) { - for (QueryPredicate child : children) { + for (var child : children) { copyParams(child, this); copyCustomParams(child, this); copyChildren(child, this); @@ -454,11 +453,11 @@ private boolean hasNoParams() { */ private void appendToParent(QueryPredicate result) { if (parent != null) { - boolean simplified = false; + var simplified = false; - int childrenSize = children.size(); - int paramCount = parameters.size(); - int customCount = customParameters.size(); + var childrenSize = children.size(); + var paramCount = parameters.size(); + var customCount = customParameters.size(); if (operator() == parent.operator()) { copyParams(result, parent); diff --git a/base/src/main/java/io/spine/query/RecordColumn.java b/base/src/main/java/io/spine/query/RecordColumn.java index 8081d8fe8e..82a825d078 100644 --- a/base/src/main/java/io/spine/query/RecordColumn.java +++ b/base/src/main/java/io/spine/query/RecordColumn.java @@ -162,7 +162,7 @@ public boolean equals(Object o) { if (!super.equals(o)) { return false; } - RecordColumn column = (RecordColumn) o; + var column = (RecordColumn) o; return valueType.equals(column.valueType) && getter.equals(column.getter); } diff --git a/base/src/main/java/io/spine/query/RecordCriterion.java b/base/src/main/java/io/spine/query/RecordCriterion.java index bd24e4c72e..b5f8d7178c 100644 --- a/base/src/main/java/io/spine/query/RecordCriterion.java +++ b/base/src/main/java/io/spine/query/RecordCriterion.java @@ -61,7 +61,7 @@ public final class RecordCriterion RecordColumn col, ComparisonOperator operator, V value) { - RecordSubjectParameter parameter = new RecordSubjectParameter<>(col, operator, value); + var parameter = new RecordSubjectParameter<>(col, operator, value); return builder.addParameter(parameter); } } diff --git a/base/src/main/java/io/spine/query/RecordQuery.java b/base/src/main/java/io/spine/query/RecordQuery.java index d0e09dd444..f1cfdc7b24 100644 --- a/base/src/main/java/io/spine/query/RecordQuery.java +++ b/base/src/main/java/io/spine/query/RecordQuery.java @@ -95,7 +95,7 @@ public final RecordQueryBuilder toBuilder() { * field masks, sorting, or limit are ignored. */ public final RecordQuery and(RecordPredicates builder) { - RecordQuery result = joinToRootPredicate(builder, AND); + var result = joinToRootPredicate(builder, AND); return result; } @@ -107,15 +107,15 @@ public final RecordQuery and(RecordPredicates builder) { * field masks, sorting, or limit are ignored. */ public final RecordQuery either(RecordPredicates predicates) { - RecordQuery result = joinToRootPredicate(predicates, OR); + var result = joinToRootPredicate(predicates, OR); return result; } @SuppressWarnings({"ReturnValueIgnored", "ResultOfMethodCallIgnored"}) /* Adjusting builders. */ private RecordQuery joinToRootPredicate(RecordPredicates predicates, LogicalOperator operator) { - QueryPredicate sourcePredicate = subject().predicate(); - RecordQueryBuilder originBuilder = toBuilder(); + var sourcePredicate = subject().predicate(); + var originBuilder = toBuilder(); if(sourcePredicate.operator() == operator.counterpart()) { QueryPredicate.Builder newRoot = QueryPredicate.newBuilder(operator); newRoot.addPredicate(sourcePredicate); @@ -126,7 +126,7 @@ private RecordQuery joinToRootPredicate(RecordPredicates predicates, } else { originBuilder.either(predicates::apply); } - RecordQuery result = originBuilder.build(); + var result = originBuilder.build(); return result; } } diff --git a/base/src/main/java/io/spine/query/RecordQueryBuilder.java b/base/src/main/java/io/spine/query/RecordQueryBuilder.java index ea059cc498..478d2d8bdf 100644 --- a/base/src/main/java/io/spine/query/RecordQueryBuilder.java +++ b/base/src/main/java/io/spine/query/RecordQueryBuilder.java @@ -85,8 +85,8 @@ public RecordQuery build() { */ public T build(Function, T> transformer) { checkNotNull(transformer); - RecordQuery query = build(); - T result = transformer.apply(query); + var query = build(); + var result = transformer.apply(query); return result; } diff --git a/base/src/main/java/io/spine/query/SortBy.java b/base/src/main/java/io/spine/query/SortBy.java index 60dc0c800a..498aa9675a 100644 --- a/base/src/main/java/io/spine/query/SortBy.java +++ b/base/src/main/java/io/spine/query/SortBy.java @@ -63,6 +63,7 @@ public C column() { /** * Returns the direction, in which the column values should be sorted. */ + @SuppressWarnings("unused") /* Part of the public API. */ public Direction direction() { return direction; } @@ -75,7 +76,7 @@ public boolean equals(Object o) { if (!(o instanceof SortBy)) { return false; } - SortBy by = (SortBy) o; + var by = (SortBy) o; return column.equals(by.column) && direction == by.direction; } diff --git a/base/src/main/java/io/spine/query/Subject.java b/base/src/main/java/io/spine/query/Subject.java index 6311b18169..5fbcb04d94 100644 --- a/base/src/main/java/io/spine/query/Subject.java +++ b/base/src/main/java/io/spine/query/Subject.java @@ -121,7 +121,7 @@ public boolean equals(Object o) { if (!(o instanceof Subject)) { return false; } - Subject subject = (Subject) o; + var subject = (Subject) o; return id.equals(subject.id) && recordType.equals(subject.recordType) && predicate.equals(subject.predicate); diff --git a/base/src/main/java/io/spine/query/SubjectParameter.java b/base/src/main/java/io/spine/query/SubjectParameter.java index 8e1e7d4de2..9f05899874 100644 --- a/base/src/main/java/io/spine/query/SubjectParameter.java +++ b/base/src/main/java/io/spine/query/SubjectParameter.java @@ -88,7 +88,7 @@ public boolean equals(Object o) { if (!(o instanceof SubjectParameter)) { return false; } - SubjectParameter parameter = (SubjectParameter) o; + var parameter = (SubjectParameter) o; return column.equals(parameter.column) && value.equals(parameter.value) && operator == parameter.operator; diff --git a/base/src/main/java/io/spine/query/TransformToDnf.java b/base/src/main/java/io/spine/query/TransformToDnf.java index 6f2841e857..6c3d9604e3 100644 --- a/base/src/main/java/io/spine/query/TransformToDnf.java +++ b/base/src/main/java/io/spine/query/TransformToDnf.java @@ -26,17 +26,15 @@ package io.spine.query; -import io.spine.query.OrExpression.OrBuilder; - import java.util.ArrayDeque; import java.util.Deque; import java.util.List; import java.util.Queue; import java.util.function.UnaryOperator; -import static com.google.common.base.Preconditions.checkNotNull; import static io.spine.query.LogicalOperator.AND; import static io.spine.query.LogicalOperator.OR; +import static java.util.Objects.requireNonNull; /** * Transforms the {@link QueryPredicate} into its disjunctive normal form. @@ -63,9 +61,9 @@ final class TransformToDnf implements UnaryOperator> { @Override public QueryPredicate apply(QueryPredicate source) { - Expression expression = asExpression(source); - Expression flat = flatten(expression); - QueryPredicate result = fromExpression(flat); + var expression = asExpression(source); + var flat = flatten(expression); + var result = fromExpression(flat); return result; } @@ -82,11 +80,11 @@ public QueryPredicate apply(QueryPredicate source) { builder.addParams(predicate.parameters()) .addCustomParams(predicate.customParameters()); - for (QueryPredicate child : predicate.children()) { - Expression expression = asExpression(child); + for (var child : predicate.children()) { + var expression = asExpression(child); builder.addExpression(expression); } - Expression result = builder.build(); + var result = builder.build(); return result; } @@ -97,11 +95,11 @@ private static QueryPredicate fromExpression(Expression expression) QueryPredicate.Builder builder = QueryPredicate.newBuilder(expression.operator()); builder.addParams(expression.params()) .addCustomParams(expression.customParams()); - for (Expression childExpression : expression.children()) { - QueryPredicate childPredicate = fromExpression(childExpression); + for (var childExpression : expression.children()) { + var childPredicate = fromExpression(childExpression); builder.addPredicate(childPredicate); } - QueryPredicate result = builder.build(); + var result = builder.build(); return result; } @@ -125,10 +123,10 @@ private static QueryPredicate fromExpression(Expression expression) private static Expression handleOr(Expression expression) { Expression flattened; - Deque> flatExpressions = flatten(expression.children()); - OrBuilder resultBuilder = OrExpression.asOrBuilder(expression) - .clearChildren(); - for (Expression flatExpression : flatExpressions) { + var flatExpressions = flatten(expression.children()); + var resultBuilder = OrExpression.asOrBuilder(expression) + .clearChildren(); + for (var flatExpression : flatExpressions) { if (flatExpression.operator() == OR) { OrExpression.asOr(flatExpression) .copyTo(resultBuilder); @@ -143,16 +141,16 @@ private static QueryPredicate fromExpression(Expression expression) private static Expression handleAnd(Expression expression) { Expression flattened; Queue> flatExpressions = flatten(expression.children()); - Expression paramExpression = expression.withoutChildren(); + var paramExpression = expression.withoutChildren(); if (!paramExpression.isEmpty()) { flatExpressions.add(paramExpression); } - Expression head = flatExpressions.poll(); - checkNotNull(head, "Head of the expression tree cannot be `null`."); + var head = flatExpressions.poll(); + requireNonNull(head, "Head of the expression tree cannot be `null`."); while (!flatExpressions.isEmpty()) { - Expression next = flatExpressions.poll(); - Expression distributed = Distribution.conjunctive(head, next); + var next = flatExpressions.poll(); + var distributed = Distribution.conjunctive(head, next); head = flatten(distributed); } flattened = head; @@ -161,9 +159,9 @@ private static QueryPredicate fromExpression(Expression expression) private static Deque> flatten(List> children) { Deque> flatExpressions = new ArrayDeque<>(); - for (Expression child : children) { + for (var child : children) { if (child.hasChildren()) { - Expression flattenedChild = flatten(child); + var flattenedChild = flatten(child); flatExpressions.add(flattenedChild); } else { flatExpressions.add(child); From b6407a89effe6dd89fd3cef3b2c16e47bea56542 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 14:12:33 +0200 Subject: [PATCH 18/27] Use `var`s in `io.spine.reflect` package. --- .../io/spine/reflect/GenericTypeIndex.java | 8 ++- .../java/io/spine/reflect/Invokables.java | 20 +++---- .../java/io/spine/reflect/IsDirectParent.java | 8 +-- base/src/main/java/io/spine/reflect/J2Kt.java | 14 ++--- .../java/io/spine/reflect/PackageGraph.java | 52 +++++++++---------- .../java/io/spine/reflect/PackageInfo.java | 46 ++++++++-------- .../src/main/java/io/spine/reflect/Types.java | 40 +++++++------- 7 files changed, 88 insertions(+), 100 deletions(-) diff --git a/base/src/main/java/io/spine/reflect/GenericTypeIndex.java b/base/src/main/java/io/spine/reflect/GenericTypeIndex.java index 876e4023b5..4e46ed092e 100644 --- a/base/src/main/java/io/spine/reflect/GenericTypeIndex.java +++ b/base/src/main/java/io/spine/reflect/GenericTypeIndex.java @@ -74,13 +74,11 @@ public interface GenericTypeIndex { */ default Class argumentIn(Class cls) { checkNotNull(cls); - @SuppressWarnings("rawtypes") - Class indexClass = getClass(); + var indexClass = getClass(); @SuppressWarnings("unchecked") /* The type cast is ensured by the declaration of the `GenericTypeIndex` interface. */ - Class superclassOfPassed = (Class) - Types.argumentIn(indexClass, GenericTypeIndex.class, 0); - Class result = Types.argumentIn(cls, superclassOfPassed, index()); + var superclassOfPassed = (Class) Types.argumentIn(indexClass, GenericTypeIndex.class, 0); + var result = Types.argumentIn(cls, superclassOfPassed, index()); return result; } } diff --git a/base/src/main/java/io/spine/reflect/Invokables.java b/base/src/main/java/io/spine/reflect/Invokables.java index e06170257d..245a445ef6 100644 --- a/base/src/main/java/io/spine/reflect/Invokables.java +++ b/base/src/main/java/io/spine/reflect/Invokables.java @@ -63,7 +63,7 @@ private Invokables() { */ public static MethodHandle asHandle(Method method) { checkNotNull(method); - MethodHandle result = invokePreservingAccessibility( + var result = invokePreservingAccessibility( method, Invokable::from, publicLookup::unreflect, @@ -95,8 +95,8 @@ public static MethodHandle asHandle(Method method) { public static C callParameterlessCtor(Class type) { checkNotNull(type); - Constructor ctor = ensureParameterlessCtor(type); - C result = invokePreservingAccessibility( + var ctor = ensureParameterlessCtor(type); + var result = invokePreservingAccessibility( ctor, Invokable::from, Constructor::newInstance, @@ -121,7 +121,7 @@ public static Object setAccessibleAndInvoke(Method method, Object target) { checkNotNull(method); checkNotNull(target); - Object result = invokePreservingAccessibility( + var result = invokePreservingAccessibility( method, Invokable::from, m -> m.invoke(target), @@ -148,8 +148,8 @@ public static Object setAccessibleAndInvoke(Method method, Object target) { private static Constructor ensureParameterlessCtor(Class type) { checkNotNull(type); @SuppressWarnings("unchecked" /* safe, as `Class` only declares `Constructor`. */) - Constructor[] ctors = (Constructor[]) type.getDeclaredConstructors(); - for (Constructor ctor : ctors) { + var ctors = (Constructor[]) type.getDeclaredConstructors(); + for (var ctor : ctors) { if (ctor.getParameterCount() == 0) { return ctor; } @@ -189,14 +189,14 @@ private static R invokePreservingAccessibility(T reflectiveObject, Function> makeInvokable, ReflectiveFunction fn, Supplier onError) { - Invokable invokable = makeInvokable.apply(reflectiveObject); - boolean accessible = invokable.isAccessible(); + var invokable = makeInvokable.apply(reflectiveObject); + var accessible = invokable.isAccessible(); try { invokable.setAccessible(true); - R result = fn.apply(reflectiveObject); + var result = fn.apply(reflectiveObject); return result; } catch (RuntimeException | ReflectiveOperationException e) { - String message = onError.get(); + var message = onError.get(); throw newIllegalStateException(e, message); } finally { invokable.setAccessible(accessible); diff --git a/base/src/main/java/io/spine/reflect/IsDirectParent.java b/base/src/main/java/io/spine/reflect/IsDirectParent.java index 0b037d45e9..ba59097540 100644 --- a/base/src/main/java/io/spine/reflect/IsDirectParent.java +++ b/base/src/main/java/io/spine/reflect/IsDirectParent.java @@ -47,18 +47,18 @@ private IsDirectParent(Package child) { static Predicate of(Package child) { checkNotNull(child); - IsDirectParent result = new IsDirectParent(child); + var result = new IsDirectParent(child); return result; } @Override public boolean test(Package candidate) { - String commonPrefix = Strings.commonPrefix(candidate.getName(), childName); + var commonPrefix = Strings.commonPrefix(candidate.getName(), childName); if (commonPrefix.isEmpty()) { return false; } - String remainingPath = childName.substring(commonPrefix.length()); - boolean hasOnlyOneDot = remainingPath.lastIndexOf('.') == 0; + var remainingPath = childName.substring(commonPrefix.length()); + var hasOnlyOneDot = remainingPath.lastIndexOf('.') == 0; return hasOnlyOneDot; } } diff --git a/base/src/main/java/io/spine/reflect/J2Kt.java b/base/src/main/java/io/spine/reflect/J2Kt.java index 6876825034..652d7504cb 100644 --- a/base/src/main/java/io/spine/reflect/J2Kt.java +++ b/base/src/main/java/io/spine/reflect/J2Kt.java @@ -67,19 +67,19 @@ private J2Kt() { */ public static Optional> findKotlinMethod(Method javaMethod) { checkNotNull(javaMethod); - Class javaClass = javaMethod.getDeclaringClass(); + var javaClass = javaMethod.getDeclaringClass(); if (!isKotlin(javaClass)) { return Optional.empty(); } KClass kotlinClass = Reflection.getOrCreateKotlinClass(javaClass); if (isStatic(javaMethod.getModifiers())) { - Optional> companion = objectOrCompanion(kotlinClass); - if (!companion.isPresent()) { + var companion = objectOrCompanion(kotlinClass); + if (companion.isEmpty()) { return Optional.empty(); } kotlinClass = companion.get(); } - Optional> result = tryMatch(javaMethod, kotlinClass); + var result = tryMatch(javaMethod, kotlinClass); return result; } @@ -140,16 +140,16 @@ private SameMethod(Method javaMethod) { @Override public boolean test(KCallable method) { - boolean nameMatches = name.equals(method.getName()); + var nameMatches = name.equals(method.getName()); if (!nameMatches) { return false; } - boolean paramsMatch = paramTypesOf(method).equals(javaParamTypes); + var paramsMatch = paramTypesOf(method).equals(javaParamTypes); return paramsMatch; } private static List paramTypesOf(KCallable method) { - List params = method.getParameters(); + var params = method.getParameters(); return params.stream() .skip(1) // `this` instance as the first parameter. .map(KParameter::getType) diff --git a/base/src/main/java/io/spine/reflect/PackageGraph.java b/base/src/main/java/io/spine/reflect/PackageGraph.java index acda8e4e63..c6465f4c8f 100644 --- a/base/src/main/java/io/spine/reflect/PackageGraph.java +++ b/base/src/main/java/io/spine/reflect/PackageGraph.java @@ -34,13 +34,11 @@ import com.google.common.graph.Graph; import com.google.common.graph.GraphBuilder; import com.google.common.graph.ImmutableGraph; -import com.google.common.graph.MutableGraph; import com.google.errorprone.annotations.Immutable; import java.util.ArrayDeque; import java.util.Arrays; import java.util.List; -import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.function.Predicate; @@ -69,6 +67,7 @@ * */ @Immutable +@SuppressWarnings("UnstableApiUsage") /* Using Guava. */ public final class PackageGraph implements Graph { /** The instance to which we delegate. */ @@ -82,7 +81,7 @@ private PackageGraph(Graph graph) { * Obtains alphabetically sorted list of packages visible to the caller's {@code ClassLoader}. */ private static ImmutableList packages() { - Package[] knownPackages = Package.getPackages(); + var knownPackages = Package.getPackages(); Arrays.sort(knownPackages, comparing(Package::getName)); return ImmutableList.copyOf(knownPackages); } @@ -116,39 +115,36 @@ public static PackageGraph containing(String packagePrefix) { */ public static PackageGraph matching(Predicate predicate) { checkNotNull(predicate); - List filteredPackages = filterPackages(predicate); + var filteredPackages = filterPackages(predicate); return create(filteredPackages); } private static List filterPackages(Predicate predicate) { - List result = packages().stream() - .filter(predicate) - .collect(toList()); + var result = packages().stream() + .filter(predicate) + .collect(toList()); return result; } private static PackageGraph create(List filteredPackages) { - Graph mutableGraph = buildGraph(filteredPackages); - PackageGraph result = new PackageGraph(mutableGraph); + var mutableGraph = buildGraph(filteredPackages); + var result = new PackageGraph(mutableGraph); return result; } private static Graph buildGraph(List packages) { - MutableGraph graph = GraphBuilder - .directed() - .nodeOrder(ElementOrder.natural()) - .build(); + var graph = GraphBuilder.directed() + .nodeOrder(ElementOrder.natural()) + .build(); Queue queue = new ArrayDeque<>(packages); - Package first = queue.poll(); + var first = queue.poll(); while (first != null) { - final Package current = first; - Optional directParent = - graph.nodes() - .stream() - .filter((node) -> IsDirectParent.of(current) - .test(node.getValue())) - .findFirst(); - PackageInfo newNode = PackageInfo.of(current); + final var current = first; + var directParent = graph.nodes().stream() + .filter((node) -> IsDirectParent.of(current) + .test(node.getValue())) + .findFirst(); + var newNode = PackageInfo.of(current); if (directParent.isPresent()) { graph.putEdge(newNode, directParent.get()); } else { @@ -161,9 +157,9 @@ private static Graph buildGraph(List packages) { @VisibleForTesting boolean contains(Package p) { - Optional result = nodes().stream() - .filter((node) -> node.isAbout(p)) - .findAny(); + var result = nodes().stream() + .filter((node) -> node.isAbout(p)) + .findAny(); return result.isPresent(); } @@ -292,15 +288,15 @@ public Filter exclude(String packagePrefix) { */ @Override public boolean test(Package aPackage) { - String packageName = aPackage.getName(); + var packageName = aPackage.getName(); if (inclusions.stream() - .anyMatch(packageName::startsWith)) { + .anyMatch(packageName::startsWith)) { return true; } return exclusions.stream() - .noneMatch(packageName::startsWith); + .noneMatch(packageName::startsWith); } } } diff --git a/base/src/main/java/io/spine/reflect/PackageInfo.java b/base/src/main/java/io/spine/reflect/PackageInfo.java index 8c3099075f..09cbe32224 100644 --- a/base/src/main/java/io/spine/reflect/PackageInfo.java +++ b/base/src/main/java/io/spine/reflect/PackageInfo.java @@ -65,7 +65,7 @@ private PackageInfo(Package value) { */ public static PackageInfo of(Package value) { checkNotNull(value); - PackageInfo result = new PackageInfo(value); + var result = new PackageInfo(value); return result; } @@ -74,7 +74,7 @@ public static PackageInfo of(Package value) { */ public static PackageInfo of(Class cls) { checkNotNull(cls); - PackageInfo result = new PackageInfo(cls.getPackage()); + var result = new PackageInfo(cls.getPackage()); return result; } @@ -95,15 +95,15 @@ public static PackageInfo of(Class cls) { public Optional findAnnotation(Class annotationClass) { checkNotNull(annotationClass); - Optional result = getAnnotation(annotationClass); + var result = getAnnotation(annotationClass); if (result.isPresent()) { return result; } List goingUp = new ArrayList<>(parents()); goingUp.sort(reverseOrder()); - for (PackageInfo parent : goingUp) { - Optional ofParent = parent.getAnnotation(annotationClass); + for (var parent : goingUp) { + var ofParent = parent.getAnnotation(annotationClass); if (ofParent.isPresent()) { return ofParent; } @@ -121,8 +121,8 @@ public Optional findAnnotation(Class annotationClas * @see #findAnnotation(Class) */ public Optional getAnnotation(Class annotationClass) { - A annotation = value.getAnnotation(annotationClass); - Optional result = Optional.ofNullable(annotation); + var annotation = value.getAnnotation(annotationClass); + var result = Optional.ofNullable(annotation); return result; } @@ -130,21 +130,19 @@ public Optional getAnnotation(Class annotationClass * Obtains parents of this package in the alphabetical order. */ private List parents() { - Package[] pack = Package.getPackages(); - String packageName = getName(); - List parentList = - Arrays.stream(pack) - .filter((p) -> { - String parentName = p.getName(); - return packageName.startsWith(parentName) && - !packageName.equals(parentName); - }) - .sorted(comparing(Package::getName)) - .collect(toList()); - List result = - parentList.stream() - .map(PackageInfo::of) - .collect(toList()); + var pack = Package.getPackages(); + var packageName = getName(); + var parentList = Arrays.stream(pack) + .filter((p) -> { + var parentName = p.getName(); + return packageName.startsWith(parentName) && + !packageName.equals(parentName); + }) + .sorted(comparing(Package::getName)) + .collect(toList()); + var result = parentList.stream() + .map(PackageInfo::of) + .collect(toList()); return result; } @@ -158,7 +156,7 @@ public Package getValue() { /** Returns {@code true} if the enclosed package value is equal to the passed instance. */ boolean isAbout(Package p) { checkNotNull(p); - boolean result = value.equals(p); + var result = value.equals(p); return result; } @@ -182,7 +180,7 @@ public boolean equals(Object o) { if (!(o instanceof PackageInfo)) { return false; } - PackageInfo node = (PackageInfo) o; + var node = (PackageInfo) o; return Objects.equals(value, node.value); } diff --git a/base/src/main/java/io/spine/reflect/Types.java b/base/src/main/java/io/spine/reflect/Types.java index e3e37a7162..50155ca9f3 100644 --- a/base/src/main/java/io/spine/reflect/Types.java +++ b/base/src/main/java/io/spine/reflect/Types.java @@ -66,9 +66,9 @@ public static Type mapTypeOf(Class keyClass, Class valueClass) { checkNotNull(keyClass); checkNotNull(valueClass); // @formatter:off - Type type = new TypeToken>() {} - .where(new TypeParameter() {}, keyClass) - .where(new TypeParameter() {}, valueClass) + var type = new TypeToken>() {} + .where(new TypeParameter<>() {}, keyClass) + .where(new TypeParameter<>() {}, valueClass) .getType(); // @formatter:on return type; @@ -86,8 +86,8 @@ public static Type mapTypeOf(Class keyClass, Class valueClass) { public static Type listTypeOf(Class elementClass) { checkNotNull(elementClass); // @formatter:off - Type type = new TypeToken>() {} - .where(new TypeParameter() {}, elementClass) + var type = new TypeToken>() {} + .where(new TypeParameter<>() {}, elementClass) .getType(); // @formatter:on return type; @@ -103,8 +103,8 @@ public static Type listTypeOf(Class elementClass) { public static boolean isEnumClass(Type type) { checkNotNull(type); if (type instanceof Class) { - Class cls = (Class) type; - boolean isEnum = cls.isEnum(); + var cls = (Class) type; + var isEnum = cls.isEnum(); return isEnum; } return false; @@ -120,8 +120,8 @@ public static boolean isEnumClass(Type type) { public static boolean isMessageClass(Type type) { checkNotNull(type); if (type instanceof Class) { - Class cls = (Class) type; - boolean isMessage = Message.class.isAssignableFrom(cls); + var cls = (Class) type; + var isMessage = Message.class.isAssignableFrom(cls); return isMessage; } return false; @@ -144,14 +144,13 @@ public static boolean isMessageClass(Type type) { */ public static ImmutableList resolveArguments(Type type) { checkNotNull(type); - TypeToken token = TypeToken.of(type); + var token = TypeToken.of(type); TypeVariable>[] params = token.getRawType() .getTypeParameters(); - ImmutableList result = - Arrays.stream(params) - .map(token::resolveType) - .map(TypeToken::getType) - .collect(toImmutableList()); + var result = Arrays.stream(params) + .map(token::resolveType) + .map(TypeToken::getType) + .collect(toImmutableList()); return result; } @@ -173,13 +172,10 @@ public static ImmutableList resolveArguments(Type type) { Class argumentIn(Class cls, Class genericSuperclass, int argNumber) { checkNotNull(cls); checkNotNull(genericSuperclass); - TypeToken supertypeToken = - TypeToken.of(cls) - .getSupertype(genericSuperclass); - ImmutableList typeArgs = resolveArguments(supertypeToken.getType()); - Type argValue = typeArgs.get(argNumber); - Class result = TypeToken.of(argValue) - .getRawType(); + var supertypeToken = TypeToken.of(cls).getSupertype(genericSuperclass); + var typeArgs = resolveArguments(supertypeToken.getType()); + var argValue = typeArgs.get(argNumber); + var result = TypeToken.of(argValue).getRawType(); return result; } } From ad68e4b1489250fbbb80d9a27f64c6f87c1669df Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 14:19:59 +0200 Subject: [PATCH 19/27] Use `var`s in `io.spine.security` package. --- .../java/io/spine/security/CallerProvider.java | 12 ++++++------ .../java/io/spine/security/InvocationGuard.java | 14 +++++++------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/base/src/main/java/io/spine/security/CallerProvider.java b/base/src/main/java/io/spine/security/CallerProvider.java index 22e01b6f11..34a9c0b50a 100644 --- a/base/src/main/java/io/spine/security/CallerProvider.java +++ b/base/src/main/java/io/spine/security/CallerProvider.java @@ -44,9 +44,9 @@ static CallerProvider instance() { * Obtains the class of the object which calls the method from which this method * is being called. */ - Class callerClass() { - Class[] context = getClassContext(); - Class result = context[2]; + Class callerClass() { + var context = getClassContext(); + var result = context[2]; return result; } @@ -54,9 +54,9 @@ Class callerClass() { * Obtains the class preceding in call chain the class which calls the * method from which this method is being called. */ - Class previousCallerClass() { - Class[] context = getClassContext(); - Class result = context[3]; + Class previousCallerClass() { + var context = getClassContext(); + var result = context[3]; return result; } } diff --git a/base/src/main/java/io/spine/security/InvocationGuard.java b/base/src/main/java/io/spine/security/InvocationGuard.java index 16a97754ad..e48d703a8d 100644 --- a/base/src/main/java/io/spine/security/InvocationGuard.java +++ b/base/src/main/java/io/spine/security/InvocationGuard.java @@ -47,8 +47,8 @@ private InvocationGuard() { */ public static void allowOnly(@FullyQualifiedName String allowedCallerClass) { checkNotNull(allowedCallerClass); - Class callingClass = CallerProvider.instance() - .previousCallerClass(); + var callingClass = CallerProvider.instance() + .previousCallerClass(); if (!allowedCallerClass.equals(callingClass.getName())) { throw nonAllowedCaller(callingClass); } @@ -61,9 +61,9 @@ public static void allowOnly(@FullyQualifiedName String firstClass, @FullyQualifiedName String... otherClasses) { checkNotNull(firstClass); checkNotNull(otherClasses); - Class callingClass = CallerProvider.instance() - .previousCallerClass(); - ImmutableSet<@FullyQualifiedName String> allowedCallers = ImmutableSet + var callingClass = CallerProvider.instance() + .previousCallerClass(); + var allowedCallers = ImmutableSet .<@FullyQualifiedName String>builder() .add(firstClass) .add(otherClasses) @@ -73,8 +73,8 @@ public static void allowOnly(@FullyQualifiedName String firstClass, } } - private static SecurityException nonAllowedCaller(@ClassGetName Class callingClass) { - String msg = format( + private static SecurityException nonAllowedCaller(@ClassGetName Class callingClass) { + var msg = format( "The class `%s` is not allowed to perform this operation.", callingClass.getName() ); throw new SecurityException(msg); From 66fce096b8cfc729df1b42fbe1d48571ec8b43ae Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 14:24:20 +0200 Subject: [PATCH 20/27] Use `var`s in `io.spine.string` package. --- .../io/spine/string/DurationStringifier.java | 2 +- .../java/io/spine/string/EnumStringifier.java | 2 +- .../java/io/spine/string/FnStringifier.java | 5 ++- .../main/java/io/spine/string/ListQuoter.java | 6 +-- .../java/io/spine/string/ListStringifier.java | 20 ++++----- .../main/java/io/spine/string/MapQuoter.java | 11 +++-- .../java/io/spine/string/MapStringifier.java | 41 +++++++++---------- .../src/main/java/io/spine/string/Quoter.java | 11 +++-- .../main/java/io/spine/string/Registrar.java | 18 ++++---- .../io/spine/string/StringifierRegistry.java | 8 ++-- .../string/StringifierWithConverter.java | 4 +- .../java/io/spine/string/Stringifiers.java | 20 ++++----- 12 files changed, 73 insertions(+), 75 deletions(-) diff --git a/base/src/main/java/io/spine/string/DurationStringifier.java b/base/src/main/java/io/spine/string/DurationStringifier.java index 076b4a0890..f9630610aa 100644 --- a/base/src/main/java/io/spine/string/DurationStringifier.java +++ b/base/src/main/java/io/spine/string/DurationStringifier.java @@ -51,7 +51,7 @@ static DurationStringifier getInstance() { @Override protected String toString(Duration duration) { - String result = Durations.toString(duration); + var result = Durations.toString(duration); return result; } diff --git a/base/src/main/java/io/spine/string/EnumStringifier.java b/base/src/main/java/io/spine/string/EnumStringifier.java index 42d1f3f1fa..bd51af3370 100644 --- a/base/src/main/java/io/spine/string/EnumStringifier.java +++ b/base/src/main/java/io/spine/string/EnumStringifier.java @@ -54,7 +54,7 @@ protected final String toString(E e) { @Override protected final E fromString(String s) { - E result = Enum.valueOf(enumClass, s); + var result = Enum.valueOf(enumClass, s); return result; } diff --git a/base/src/main/java/io/spine/string/FnStringifier.java b/base/src/main/java/io/spine/string/FnStringifier.java index 21dd928b4e..100b6b0358 100644 --- a/base/src/main/java/io/spine/string/FnStringifier.java +++ b/base/src/main/java/io/spine/string/FnStringifier.java @@ -36,6 +36,7 @@ * @param * type of stringified objects */ +@SuppressWarnings({"unused", "AbstractClassNeverImplemented"}) /* Part of the public API. */ public abstract class FnStringifier extends SerializableStringifier { private static final long serialVersionUID = 0L; @@ -54,13 +55,13 @@ protected FnStringifier(String identity, @Override protected final String toString(T obj) { - String result = printer.apply(obj); + var result = printer.apply(obj); return result; } @Override protected final T fromString(String s) { - T result = parser.apply(s); + var result = parser.apply(s); return result; } } diff --git a/base/src/main/java/io/spine/string/ListQuoter.java b/base/src/main/java/io/spine/string/ListQuoter.java index 9f19009588..fcb96a2bd8 100644 --- a/base/src/main/java/io/spine/string/ListQuoter.java +++ b/base/src/main/java/io/spine/string/ListQuoter.java @@ -47,9 +47,9 @@ final class ListQuoter extends Quoter { @Override String quote(String stringToQuote) { checkNotNull(stringToQuote); - String escaped = QUOTE_PATTERN.matcher(stringToQuote) - .replaceAll(ESCAPED_QUOTE); - String result = QUOTE_CHAR + escaped + QUOTE_CHAR; + var escaped = QUOTE_PATTERN.matcher(stringToQuote) + .replaceAll(ESCAPED_QUOTE); + var result = QUOTE_CHAR + escaped + QUOTE_CHAR; return result; } diff --git a/base/src/main/java/io/spine/string/ListStringifier.java b/base/src/main/java/io/spine/string/ListStringifier.java index e7cb22e1de..9488a3961c 100644 --- a/base/src/main/java/io/spine/string/ListStringifier.java +++ b/base/src/main/java/io/spine/string/ListStringifier.java @@ -116,26 +116,26 @@ final class ListStringifier extends Stringifier> { protected String toString(List list) { Converter quoter = Quoter.forLists(); List convertedItems = new ArrayList<>(); - for (T item : list) { - String convertedItem = elementStringifier.andThen(quoter) - .convert(item); + for (var item : list) { + var convertedItem = elementStringifier.andThen(quoter) + .convert(item); convertedItems.add(convertedItem); } - String result = Joiner.on(delimiter) - .join(convertedItems); + var result = Joiner.on(delimiter) + .join(convertedItems); return result; } @Override protected List fromString(String s) { - String escapedString = escaper.escape(s); + var escapedString = escaper.escape(s); List items = newArrayList(splitter.split(escapedString)); Converter quoter = Quoter.forLists(); - Converter converter = quoter.reverse() - .andThen(elementStringifier.reverse()); + var converter = quoter.reverse() + .andThen(elementStringifier.reverse()); List result = newArrayList(); - for (String item : items) { - T convertedItem = converter.convert(item); + for (var item : items) { + var convertedItem = converter.convert(item); result.add(convertedItem); } return result; diff --git a/base/src/main/java/io/spine/string/MapQuoter.java b/base/src/main/java/io/spine/string/MapQuoter.java index 0f7fb3951f..a31335eb92 100644 --- a/base/src/main/java/io/spine/string/MapQuoter.java +++ b/base/src/main/java/io/spine/string/MapQuoter.java @@ -26,7 +26,6 @@ package io.spine.string; -import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; @@ -45,11 +44,11 @@ final class MapQuoter extends Quoter { @Override String quote(String stringToQuote) { checkNotNull(stringToQuote); - Matcher matcher = compile(QUOTE_PATTERN).matcher(stringToQuote); - String unslashed = matcher.find() ? - matcher.replaceAll(BACKSLASH + matcher.group()) : - stringToQuote; - String result = QUOTE_CHAR + unslashed + QUOTE_CHAR; + var matcher = compile(QUOTE_PATTERN).matcher(stringToQuote); + var unslashed = matcher.find() ? + matcher.replaceAll(BACKSLASH + matcher.group()) : + stringToQuote; + var result = QUOTE_CHAR + unslashed + QUOTE_CHAR; return result; } diff --git a/base/src/main/java/io/spine/string/MapStringifier.java b/base/src/main/java/io/spine/string/MapStringifier.java index a2f16c0598..09823e680b 100644 --- a/base/src/main/java/io/spine/string/MapStringifier.java +++ b/base/src/main/java/io/spine/string/MapStringifier.java @@ -121,9 +121,8 @@ final class MapStringifier extends Stringifier> { private static Splitter.MapSplitter createMapSplitter(String bucketPattern, String keyValuePattern) { - Splitter.MapSplitter result = - Splitter.onPattern(bucketPattern) - .withKeyValueSeparator(Splitter.onPattern(keyValuePattern)); + var result = Splitter.onPattern(bucketPattern) + .withKeyValueSeparator(Splitter.onPattern(keyValuePattern)); return result; } @@ -135,40 +134,40 @@ private static String createKeyValuePattern() { @Override protected String toString(Map obj) { Converter quoter = Quoter.forMaps(); - Converter keyConverter = keyStringifier.andThen(quoter); - Converter valueConverter = valueStringifier.andThen(quoter); + var keyConverter = keyStringifier.andThen(quoter); + var valueConverter = valueStringifier.andThen(quoter); Map resultMap = newLinkedHashMap(); - for (Map.Entry entry : obj.entrySet()) { - String convertedKey = keyConverter.convert(entry.getKey()); - String convertedValue = valueConverter.convert(entry.getValue()); + for (var entry : obj.entrySet()) { + var convertedKey = keyConverter.convert(entry.getKey()); + var convertedValue = valueConverter.convert(entry.getValue()); resultMap.put(convertedKey, convertedValue); } - String result = Joiner.on(delimiter) - .withKeyValueSeparator(KEY_VALUE_DELIMITER) - .join(resultMap); + var result = Joiner.on(delimiter) + .withKeyValueSeparator(KEY_VALUE_DELIMITER) + .join(resultMap); return result; } @Override protected Map fromString(String s) { - String escapedString = escaper.escape(s); - Map buckets = splitter.split(escapedString); - Map resultMap = convert(buckets); + var escapedString = escaper.escape(s); + var buckets = splitter.split(escapedString); + var resultMap = convert(buckets); return resultMap; } private Map convert(Map buckets) { Converter quoter = Quoter.forMaps(); - Converter keyConverter = quoter.reverse() - .andThen(keyStringifier.reverse()); - Converter valueConverter = quoter.reverse() - .andThen(valueStringifier.reverse()); + var keyConverter = quoter.reverse() + .andThen(keyStringifier.reverse()); + var valueConverter = quoter.reverse() + .andThen(valueStringifier.reverse()); Map resultMap = newHashMap(); try { - for (Map.Entry bucket : buckets.entrySet()) { - K convertedKey = keyConverter.convert(bucket.getKey()); - V convertedValue = valueConverter.convert(bucket.getValue()); + for (var bucket : buckets.entrySet()) { + var convertedKey = keyConverter.convert(bucket.getKey()); + var convertedValue = valueConverter.convert(bucket.getValue()); resultMap.put(convertedKey, convertedValue); } return resultMap; diff --git a/base/src/main/java/io/spine/string/Quoter.java b/base/src/main/java/io/spine/string/Quoter.java index bf72c9aec8..468ee56ef4 100644 --- a/base/src/main/java/io/spine/string/Quoter.java +++ b/base/src/main/java/io/spine/string/Quoter.java @@ -74,9 +74,8 @@ protected String doBackward(String s) { * @return the created pattern */ static String createDelimiterPattern(char delimiter) { - String quotedDelimiter = Pattern.quote(String.valueOf(delimiter)); - String result = compile(DELIMITER_PATTERN_PREFIX + quotedDelimiter) - .pattern(); + var quotedDelimiter = Pattern.quote(String.valueOf(delimiter)); + var result = compile(DELIMITER_PATTERN_PREFIX + quotedDelimiter).pattern(); return result; } @@ -96,9 +95,9 @@ static Quoter forLists() { static String unquoteValue(String value, Pattern pattern) { checkQuoted(value); - String unquoted = value.substring(2, value.length() - 2); - String unescaped = pattern.matcher(unquoted) - .replaceAll(""); + var unquoted = value.substring(2, value.length() - 2); + var unescaped = pattern.matcher(unquoted) + .replaceAll(""); return unescaped; } diff --git a/base/src/main/java/io/spine/string/Registrar.java b/base/src/main/java/io/spine/string/Registrar.java index 92588263de..36c26a63f1 100644 --- a/base/src/main/java/io/spine/string/Registrar.java +++ b/base/src/main/java/io/spine/string/Registrar.java @@ -30,7 +30,6 @@ import com.google.common.reflect.TypeToken; import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; @@ -55,10 +54,11 @@ public Registrar(List> stringifiers) { /** * Registers stringifiers. */ + @SuppressWarnings("unused") /* Part of the public API. */ public void register() { - StringifierRegistry registry = StringifierRegistry.instance(); + var registry = StringifierRegistry.instance(); stringifiers.forEach((stringifier) -> { - Class dataClass = getDataClass(stringifier.getClass()); + var dataClass = getDataClass(stringifier.getClass()); registry.register(stringifier, dataClass); }); } @@ -66,13 +66,13 @@ public void register() { /** * Obtains the class handled by the passed class of stringifiers. */ + @SuppressWarnings("rawtypes") /* Avoiding the generics hell. */ private static Class getDataClass(Class stringifierClass) { - TypeToken supertypeToken = TypeToken.of(stringifierClass) - .getSupertype(Stringifier.class); - ParameterizedType genericSupertype = - (ParameterizedType) supertypeToken.getType(); - Type[] typeArguments = genericSupertype.getActualTypeArguments(); - Type typeArgument = typeArguments[0]; + var supertypeToken = TypeToken.of(stringifierClass) + .getSupertype(Stringifier.class); + var genericSupertype = (ParameterizedType) supertypeToken.getType(); + var typeArguments = genericSupertype.getActualTypeArguments(); + var typeArgument = typeArguments[0]; return (Class) typeArgument; } } diff --git a/base/src/main/java/io/spine/string/StringifierRegistry.java b/base/src/main/java/io/spine/string/StringifierRegistry.java index 4cceb63fcf..c487ba162e 100644 --- a/base/src/main/java/io/spine/string/StringifierRegistry.java +++ b/base/src/main/java/io/spine/string/StringifierRegistry.java @@ -102,23 +102,23 @@ static Stringifier getFor(Type typeOfT) { Optional> optional = instance().find(typeOfT); if (optional.isPresent()) { - Stringifier stringifier = optional.get(); + var stringifier = optional.get(); return stringifier; } if (isEnumClass(typeOfT)) { @SuppressWarnings({"unchecked", "rawtypes"}) // OK since the type is checked above. - Stringifier result = (Stringifier) newForEnum((Class) typeOfT); + var result = (Stringifier) newForEnum((Class) typeOfT); return result; } if (isMessageClass(typeOfT)) { @SuppressWarnings("unchecked") // OK since the type is checked above. - Stringifier result = (Stringifier) newForMessage((Class) typeOfT); + var result = (Stringifier) newForMessage((Class) typeOfT); return result; } - String errMsg = format("No stringifier registered for the type: %s", typeOfT); + var errMsg = format("No stringifier registered for the type: %s", typeOfT); throw new MissingStringifierException(errMsg); } diff --git a/base/src/main/java/io/spine/string/StringifierWithConverter.java b/base/src/main/java/io/spine/string/StringifierWithConverter.java index fb12188348..e1fb30f9d1 100644 --- a/base/src/main/java/io/spine/string/StringifierWithConverter.java +++ b/base/src/main/java/io/spine/string/StringifierWithConverter.java @@ -53,13 +53,13 @@ protected StringifierWithConverter(String identity) { @Override protected String toString(T obj) { - String result = converter().reverse().convert(obj); + var result = converter().reverse().convert(obj); return requireNonNull(result); } @Override protected T fromString(String s) { - T result = converter().convert(s); + var result = converter().convert(s); return requireNonNull(result); } } diff --git a/base/src/main/java/io/spine/string/Stringifiers.java b/base/src/main/java/io/spine/string/Stringifiers.java index 6049dff349..ad8844e901 100644 --- a/base/src/main/java/io/spine/string/Stringifiers.java +++ b/base/src/main/java/io/spine/string/Stringifiers.java @@ -84,7 +84,7 @@ public static String toString(T object, Type typeOfT) { checkNotNull(object); checkNotNull(typeOfT); Stringifier stringifier = StringifierRegistry.getFor(typeOfT); - String result = stringifier.convert(object); + var result = stringifier.convert(object); return requireNonNull(result); } @@ -105,8 +105,8 @@ public static T fromString(String str, Class typeOfT) { checkNotNull(str); checkNotNull(typeOfT); Stringifier stringifier = StringifierRegistry.getFor(typeOfT); - T result = stringifier.reverse() - .convert(str); + var result = stringifier.reverse() + .convert(str); return requireNonNull(result); } @@ -250,7 +250,7 @@ public static Stringifier> newForListOf(Class elementClass, char */ public static > Stringifier newForEnum(Class enumClass) { checkNotNull(enumClass); - EnumStringifier result = new EnumStringifier<>(enumClass); + var result = new EnumStringifier<>(enumClass); return result; } @@ -265,7 +265,7 @@ public static > Stringifier newForEnum(Class enumClass) */ static Stringifier newForMessage(Class messageClass) { checkNotNull(messageClass); - DefaultMessageStringifier result = new DefaultMessageStringifier<>(messageClass); + var result = new DefaultMessageStringifier<>(messageClass); return result; } @@ -277,11 +277,11 @@ static Stringifier newForMessage(Class messageClass) { * @return the constructed escaper */ static Escaper createEscaper(char charToEscape) { - String escapedChar = "\\" + charToEscape; - Escaper result = Escapers.builder() - .addEscape('\"', "\\\"") - .addEscape(charToEscape, escapedChar) - .build(); + var escapedChar = "\\" + charToEscape; + var result = Escapers.builder() + .addEscape('\"', "\\\"") + .addEscape(charToEscape, escapedChar) + .build(); return result; } } From ca292f0471d55331adb1ef9e0dab9ba92b16f1b6 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 15:06:15 +0200 Subject: [PATCH 21/27] Use `var`s in `io.spine.type` package. --- .../src/main/java/io/spine/type/EnumType.java | 12 +- .../main/java/io/spine/type/KnownTypes.java | 39 ++++--- .../main/java/io/spine/type/MessageClass.java | 8 +- .../main/java/io/spine/type/MessageType.java | 107 ++++++++---------- .../java/io/spine/type/NestedTypeName.java | 18 +-- .../main/java/io/spine/type/ServiceType.java | 4 +- base/src/main/java/io/spine/type/Type.java | 12 +- .../src/main/java/io/spine/type/TypeName.java | 31 +++-- base/src/main/java/io/spine/type/TypeUrl.java | 36 +++--- 9 files changed, 120 insertions(+), 147 deletions(-) diff --git a/base/src/main/java/io/spine/type/EnumType.java b/base/src/main/java/io/spine/type/EnumType.java index 4213233089..72074a4342 100644 --- a/base/src/main/java/io/spine/type/EnumType.java +++ b/base/src/main/java/io/spine/type/EnumType.java @@ -66,7 +66,7 @@ public ClassName javaClassName() { @Override public Optional> containingType() { - Descriptor parent = descriptor().getContainingType(); + var parent = descriptor().getContainingType(); return Optional.ofNullable(parent) .map(MessageType::new); } @@ -79,13 +79,13 @@ public static EnumType create(EnumDescriptor descriptor) { // Need to go through top level enums and those nested messages. public static TypeSet allFrom(FileDescriptor file) { checkNotNull(file); - TypeSet.Builder result = TypeSet.newBuilder(); + var result = TypeSet.newBuilder(); - for (EnumDescriptor enumDescriptor : file.getEnumTypes()) { + for (var enumDescriptor : file.getEnumTypes()) { result.add(create(enumDescriptor)); } - for (Descriptor messageType : file.getMessageTypes()) { + for (var messageType : file.getMessageTypes()) { addNested(messageType, result); } return result.build(); @@ -93,11 +93,11 @@ public static TypeSet allFrom(FileDescriptor file) { @SuppressWarnings("MethodWithMultipleLoops") // Need to go through enums and nested messages. private static void addNested(Descriptor messageType, TypeSet.Builder set) { - for (EnumDescriptor enumDescriptor : messageType.getEnumTypes()) { + for (var enumDescriptor : messageType.getEnumTypes()) { set.add(create(enumDescriptor)); } - for (Descriptor nestedType : messageType.getNestedTypes()) { + for (var nestedType : messageType.getNestedTypes()) { addNested(nestedType, set); } } diff --git a/base/src/main/java/io/spine/type/KnownTypes.java b/base/src/main/java/io/spine/type/KnownTypes.java index 66d44923c9..dcc67683d1 100644 --- a/base/src/main/java/io/spine/type/KnownTypes.java +++ b/base/src/main/java/io/spine/type/KnownTypes.java @@ -27,7 +27,6 @@ package io.spine.type; import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.flogger.FluentLogger; import com.google.errorprone.annotations.Immutable; @@ -97,16 +96,16 @@ private KnownTypes(TypeSet types) { } private static KnownTypes load() { - TypeSet types = loadTypeSet(); - KnownTypes result = new KnownTypes(types); + var types = loadTypeSet(); + var result = new KnownTypes(types); return result; } @SuppressWarnings("MethodOnlyUsedFromInnerClass") private KnownTypes extendWith(TypeSet moreTypes) { checkNotNull(moreTypes); - TypeSet combined = typeSet.union(moreTypes); - KnownTypes result = new KnownTypes(combined); + var combined = typeSet.union(moreTypes); + var result = new KnownTypes(combined); return result; } @@ -127,8 +126,8 @@ private ImmutableSet messageTypes() { * Loads known types from the classpath. */ private static TypeSet loadTypeSet() { - FileSet protoDefinitions = FileSet.load(); - TypeSet types = TypeSet.from(protoDefinitions); + var protoDefinitions = FileSet.load(); + var types = TypeSet.from(protoDefinitions); return types; } @@ -147,7 +146,7 @@ public ClassName classNameOf(TypeUrl type) throws UnknownTypeException { throw new UnknownTypeException(type.toTypeName() .value()); } - ClassName result = instance().get(type); + var result = instance().get(type); return result; } @@ -184,7 +183,7 @@ public TypeRegistry typeRegistry() { * @return set of {@link TypeUrl TypeUrl}s of types that belong to the given package */ public Set allFromPackage(String packageName) { - Set result = allUrls().stream() + var result = allUrls().stream() .filter(url -> url.toTypeName() .belongsTo(packageName)) .collect(toSet()); @@ -199,8 +198,8 @@ public Set allFromPackage(String packageName) { * @return {@code true} if the given type is known, {@code false} otherwise */ public boolean contains(TypeUrl typeUrl) { - TypeName name = typeUrl.toTypeName(); - boolean result = typeSet.contains(name); + var name = typeUrl.toTypeName(); + var result = typeSet.contains(name); return result; } @@ -210,25 +209,25 @@ public boolean contains(TypeUrl typeUrl) { * @see TypeSet#find(TypeName) */ Optional> find(TypeName typeName) { - Optional> type = typeSet.find(typeName); + var type = typeSet.find(typeName); return type; } private Type get(TypeName name) throws UnknownTypeException { - Type result = typeSet.find(name) - .orElseThrow(() -> new UnknownTypeException(name.value())); + var result = typeSet.find(name) + .orElseThrow(() -> new UnknownTypeException(name.value())); return result; } private ClassName get(TypeUrl typeUrl) { - Type type = get(typeUrl.toTypeName()); - ClassName result = type.javaClassName(); + var type = get(typeUrl.toTypeName()); + var result = type.javaClassName(); return result; } @Override public String toString() { - StringBuilder result = new StringBuilder(KnownTypes.class.getSimpleName()); + var result = new StringBuilder(KnownTypes.class.getSimpleName()); result.append(':') .append(lineSeparator()); NEW_LINE_JOINER.appendTo(result, allUrlList()); @@ -246,8 +245,7 @@ public String printAllTypes() { * Obtains alphabetically sorted list of URLs of all known types. */ private List allUrlList() { - ImmutableList result = allUrls() - .stream() + var result = allUrls().stream() .map(TypeUrl::value) .sorted() .collect(toImmutableList()); @@ -292,12 +290,13 @@ private static KnownTypes instance() { * @throws java.lang.SecurityException * if called from the client code */ + @SuppressWarnings("unused") /* Part of the public API. */ public static void extendWith(TypeSet moreKnownTypes) { InvocationGuard.allowOnly("io.spine.tools.type.MoreKnownTypes"); logger.atFine().log("Adding types `%s` to known types.", moreKnownTypes); lock.lock(); try { - KnownTypes extended = instance.extendWith(moreKnownTypes); + var extended = instance.extendWith(moreKnownTypes); instance = extended; ExternalConstraints.updateFrom(instance.messageTypes()); } finally { diff --git a/base/src/main/java/io/spine/type/MessageClass.java b/base/src/main/java/io/spine/type/MessageClass.java index 6d26c1e105..d35d1f9a23 100644 --- a/base/src/main/java/io/spine/type/MessageClass.java +++ b/base/src/main/java/io/spine/type/MessageClass.java @@ -84,14 +84,14 @@ public TypeName typeName() { interfacesOf(Class cls) { checkNotNull(cls); ImmutableSet.Builder> builder = ImmutableSet.builder(); - Class[] interfaces = cls.getInterfaces(); + var interfaces = cls.getInterfaces(); Queue> deque = new ArrayDeque<>(Arrays.asList(interfaces)); while (!deque.isEmpty()) { - Class anInterface = deque.poll(); + var anInterface = deque.poll(); if (Message.class.isAssignableFrom(anInterface) && !anInterface.equals(Message.class)) { @SuppressWarnings("unchecked") - Class cast = (Class) anInterface; + var cast = (Class) anInterface; builder.add(cast); } interfaces = anInterface.getInterfaces(); @@ -113,7 +113,7 @@ public boolean equals(Object o) { if (!super.equals(o)) { return false; } - MessageClass other = (MessageClass) o; + var other = (MessageClass) o; return typeUrl.equals(other.typeUrl); } diff --git a/base/src/main/java/io/spine/type/MessageType.java b/base/src/main/java/io/spine/type/MessageType.java index 42550db89f..46289d5092 100644 --- a/base/src/main/java/io/spine/type/MessageType.java +++ b/base/src/main/java/io/spine/type/MessageType.java @@ -28,12 +28,8 @@ import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.Immutable; -import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.DescriptorProtos.FileDescriptorProto; -import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.Descriptors.Descriptor; -import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Message; import io.spine.base.UuidValue; @@ -44,13 +40,10 @@ import io.spine.code.proto.LocationPath; import io.spine.code.proto.TypeSet; import io.spine.logging.Logging; -import io.spine.option.EntityOption; import io.spine.option.OptionsProto; import java.util.Deque; -import java.util.List; import java.util.Optional; -import java.util.Set; import java.util.function.Predicate; import java.util.stream.Stream; @@ -83,10 +76,9 @@ public MessageType(Descriptor descriptor) { } private ImmutableList collectFields() { - List descriptors = descriptor().getFields(); - ImmutableList.Builder fields = - ImmutableList.builderWithExpectedSize(descriptors.size()); - for (FieldDescriptor field : descriptors) { + var descriptors = descriptor().getFields(); + var fields = ImmutableList.builderWithExpectedSize(descriptors.size()); + for (var field : descriptors) { fields.add(new FieldDeclaration(field, this)); } return fields.build(); @@ -105,8 +97,8 @@ public static MessageType of(Message message) { */ public static TypeSet allFrom(FileDescriptor file) { checkNotNull(file); - TypeSet.Builder result = TypeSet.newBuilder(); - for (Descriptor messageType : file.getMessageTypes()) { + var result = TypeSet.newBuilder(); + for (var messageType : file.getMessageTypes()) { addType(messageType, result); } return result.build(); @@ -117,9 +109,9 @@ private static void addType(Descriptor type, TypeSet.Builder set) { .getMapEntry()) { return; } - MessageType messageType = new MessageType(type); + var messageType = new MessageType(type); set.add(messageType); - for (Descriptor nestedType : type.getNestedTypes()) { + for (var nestedType : type.getNestedTypes()) { addType(nestedType, set); } } @@ -141,7 +133,7 @@ public final ClassName javaClassName() { @Override public Optional> containingType() { - Descriptor parent = descriptor().getContainingType(); + var parent = descriptor().getContainingType(); return Optional.ofNullable(parent) .map(MessageType::new); } @@ -156,7 +148,7 @@ public Class javaClass() { * Tells if this message is under the "google" package. */ public boolean isGoogle() { - boolean result = FileDescriptors.isGoogle(file()); + var result = FileDescriptors.isGoogle(file()); return result; } @@ -168,9 +160,9 @@ public boolean isCustom() { if (isGoogle()) { return false; } - FileDescriptor optionsProto = OptionsProto.getDescriptor(); - FileDescriptor file = file(); - boolean result = !sameFiles(optionsProto, file); + var optionsProto = OptionsProto.getDescriptor(); + var file = file(); + var result = !sameFiles(optionsProto, file); return result; } @@ -178,7 +170,7 @@ public boolean isCustom() { * Tells if this message is top-level in its file. */ public boolean isTopLevel() { - Descriptor descriptor = descriptor(); + var descriptor = descriptor(); return isTopLevel(descriptor); } @@ -186,7 +178,7 @@ public boolean isTopLevel() { * Verifies if the message is top-level (rather than nested). */ public static boolean isTopLevel(Descriptor descriptor) { - Descriptor parent = descriptor.getContainingType(); + var parent = descriptor.getContainingType(); return parent == null; } @@ -201,7 +193,7 @@ public boolean isNested() { * Tells if this message is a rejection. */ public boolean isRejection() { - boolean result = isTopLevel() && declaringFileName().isRejections(); + var result = isTopLevel() && declaringFileName().isRejections(); return result; } @@ -209,7 +201,7 @@ public boolean isRejection() { * Tells if this message is a command. */ public boolean isCommand() { - boolean result = isTopLevel() && declaringFileName().isCommands(); + var result = isTopLevel() && declaringFileName().isCommands(); return result; } @@ -219,7 +211,7 @@ public boolean isCommand() { *

Returns {@code false} if this type is a {@linkplain #isRejection() rejection}. */ public boolean isEvent() { - boolean result = isTopLevel() && declaringFileName().isEvents(); + var result = isTopLevel() && declaringFileName().isEvents(); return result; } @@ -234,11 +226,10 @@ public boolean isSignal() { * Tells if this message is an entity state. */ public boolean isEntityState() { - Optional entityKind = entityKindOf(descriptor()); - boolean result = - entityKind.isPresent() - && entityKind.get() != UNRECOGNIZED - && entityKind.get() != KIND_UNKNOWN; + var entityKind = entityKindOf(descriptor()); + var result = entityKind.isPresent() + && entityKind.get() != UNRECOGNIZED + && entityKind.get() != KIND_UNKNOWN; return result; } @@ -251,11 +242,10 @@ public ImmutableList nestedTypesThat(Predicate pre Deque deque = newLinkedList(nestedDeclarations); while (!deque.isEmpty()) { - MessageType nestedDeclaration = deque.pollFirst(); + var nestedDeclaration = deque.pollFirst(); assert nestedDeclaration != null; // Cannot be null since the queue is not empty. - DescriptorProto nestedDescriptor = nestedDeclaration.descriptor() - .toProto(); + var nestedDescriptor = nestedDeclaration.descriptor().toProto(); if (predicate.test(nestedDescriptor)) { result.add(nestedDeclaration); @@ -271,11 +261,10 @@ public ImmutableList nestedTypesThat(Predicate pre * empty list if no nested types are declared. */ private ImmutableList immediateNested() { - ImmutableList result = - descriptor().getNestedTypes() - .stream() - .map(MessageType::new) - .collect(toImmutableList()); + var descriptors = descriptor().getNestedTypes(); + var result = descriptors.stream() + .map(MessageType::new) + .collect(toImmutableList()); return result; } @@ -285,15 +274,12 @@ private ImmutableList immediateNested() { *

Includes only the immediate declarations. Types declared inside the types declared inside * this type are not obtained. */ + @SuppressWarnings("unused") /* Part of the public API. */ public ImmutableList> nestedDeclarations() { - Stream> messageTypes = descriptor() - .getNestedTypes() - .stream() - .map(MessageType::new); - Stream> enumTypes = descriptor() - .getEnumTypes() - .stream() - .map(EnumType::create); + var nestedDescriptors = descriptor().getNestedTypes(); + Stream> messageTypes = nestedDescriptors.stream().map(MessageType::new); + var enumDescriptors = descriptor().getEnumTypes(); + Stream> enumTypes = enumDescriptors.stream().map(EnumType::create); return concat(messageTypes, enumTypes) .collect(toImmutableList()); } @@ -315,8 +301,7 @@ public ImmutableList fields() { * @return the field declaration */ public FieldDeclaration field(String name) { - FieldDescriptor fieldDescriptor = descriptor() - .findFieldByName(name); + var fieldDescriptor = descriptor().findFieldByName(name); checkArgument(fieldDescriptor != null, name); return new FieldDeclaration(fieldDescriptor, this); } @@ -327,7 +312,7 @@ public FieldDeclaration field(String name) { * @return the message location path */ public LocationPath path() { - LocationPath result = LocationPath.fromMessage(descriptor()); + var result = LocationPath.fromMessage(descriptor()); return result; } @@ -350,8 +335,9 @@ public LocationPath path() { * @see * Protobuf plugin configuration */ + @SuppressWarnings("unused") /* Part of the public API. */ public Optional leadingComments() { - LocationPath messagePath = path(); + var messagePath = path(); return leadingComments(messagePath); } @@ -364,9 +350,7 @@ public Optional leadingComments() { * a descriptor was generated without source code information */ public Optional leadingComments(LocationPath locationPath) { - FileDescriptorProto file = descriptor() - .getFile() - .toProto(); + var file = descriptor().getFile().toProto(); if (!file.hasSourceCodeInfo()) { _warn().log( "Unable to obtain proto source code info. " + @@ -376,7 +360,7 @@ public Optional leadingComments(LocationPath locationPath) { return Optional.empty(); } - DescriptorProtos.SourceCodeInfo.Location location = locationPath.toLocationIn(file); + var location = locationPath.toLocationIn(file); return location.hasLeadingComments() ? Optional.of(location.getLeadingComments()) : Optional.empty(); @@ -386,14 +370,14 @@ public Optional leadingComments(LocationPath locationPath) { * Determines if the message type represents a {@link UuidValue}. */ public boolean isUuidValue() { - ImmutableList fields = fields(); + var fields = fields(); if (fields.size() != 1) { return false; } - FieldDeclaration theField = fields.get(0); - FieldName uuid = FieldName.of("uuid"); - boolean nameMatches = uuid.equals(theField.name()); - boolean typeMatches = theField.isString(); + var theField = fields.get(0); + var uuid = FieldName.of("uuid"); + var nameMatches = uuid.equals(theField.name()); + var typeMatches = theField.isString(); return nameMatches && typeMatches; } @@ -407,10 +391,11 @@ public boolean isUuidValue() { * @return {@code true} if this type is marked with an option with the given name, * {@code false} otherwise */ + @SuppressWarnings("unused") /* Part of the public API. */ public boolean hasOption(String optionName) { checkNotEmptyOrBlank(optionName,"Option name must not be null empty."); - MessageOptions options = descriptor().getOptions(); - Set presentOptions = options.getAllFields().keySet(); + var options = descriptor().getOptions(); + var presentOptions = options.getAllFields().keySet(); return presentOptions.stream() .anyMatch(op -> optionName.equals(op.getName())); } diff --git a/base/src/main/java/io/spine/type/NestedTypeName.java b/base/src/main/java/io/spine/type/NestedTypeName.java index f65e6f2b95..75f552c4d4 100644 --- a/base/src/main/java/io/spine/type/NestedTypeName.java +++ b/base/src/main/java/io/spine/type/NestedTypeName.java @@ -28,12 +28,8 @@ import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; -import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.Descriptors.Descriptor; import io.spine.value.StringTypeValue; -import java.util.Optional; - import static io.spine.type.TypeName.NESTED_TYPE_SEPARATOR; /** @@ -60,18 +56,16 @@ private NestedTypeName(ImmutableList names) { */ static NestedTypeName of(Type type) { ImmutableList.Builder names = ImmutableList.builder(); - String unqualified = type.descriptor() - .getName(); + var unqualified = type.descriptor() + .getName(); names.add(unqualified); - Optional> parent = type.containingType(); + var parent = type.containingType(); while (parent.isPresent()) { - Type containingType = parent.get(); - names.add(containingType.descriptor() - .getName()); + var containingType = parent.get(); + names.add(containingType.descriptor().getName()); parent = containingType.containingType(); } - ImmutableList fullSimpleName = names.build() - .reverse(); + var fullSimpleName = names.build().reverse(); return new NestedTypeName(fullSimpleName); } diff --git a/base/src/main/java/io/spine/type/ServiceType.java b/base/src/main/java/io/spine/type/ServiceType.java index a6672e4fd6..d42542048a 100644 --- a/base/src/main/java/io/spine/type/ServiceType.java +++ b/base/src/main/java/io/spine/type/ServiceType.java @@ -66,8 +66,8 @@ public static ServiceType of(ServiceDescriptor descriptor) { */ public static TypeSet allFrom(FileDescriptor file) { checkNotNull(file); - TypeSet.Builder result = TypeSet.newBuilder(); - for (ServiceDescriptor type : file.getServices()) { + var result = TypeSet.newBuilder(); + for (var type : file.getServices()) { result.add(of(type)); } return result.build(); diff --git a/base/src/main/java/io/spine/type/Type.java b/base/src/main/java/io/spine/type/Type.java index b97be6dacc..cb4e0d0f8e 100644 --- a/base/src/main/java/io/spine/type/Type.java +++ b/base/src/main/java/io/spine/type/Type.java @@ -31,7 +31,6 @@ import com.google.common.cache.CacheBuilder; import com.google.errorprone.annotations.Immutable; import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.Descriptors; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.GenericDescriptor; @@ -116,8 +115,8 @@ public TypeName name() { * Loads the Java class representing this Protobuf type. */ public Class javaClass() { - String clsName = javaClassName().value(); - Class result = knownClasses.getIfPresent(clsName); + var clsName = javaClassName().value(); + var result = knownClasses.getIfPresent(clsName); if (result == null) { try { result = Class.forName(clsName); @@ -138,8 +137,8 @@ public Class javaClass() { * Obtains package for the corresponding Java type. */ public PackageName javaPackage() { - FileDescriptorProto fileDescr = descriptor.getFile().toProto(); - PackageName result = PackageName.resolve(fileDescr); + var fileDescr = descriptor.getFile().toProto(); + var result = PackageName.resolve(fileDescr); return result; } @@ -172,6 +171,7 @@ public final NestedTypeName nestedSimpleName() { * {@link com.google.protobuf.Message.Builder} and * {@link com.google.protobuf.MessageOrBuilder} */ + @SuppressWarnings("unused") /* Part of the public API. */ public final boolean supportsBuilders() { return supportsBuilders; } @@ -199,7 +199,7 @@ public boolean equals(Object o) { if (!(o instanceof Type)) { return false; } - Type type = (Type) o; + var type = (Type) o; return Objects.equal(descriptor.getFullName(), type.descriptor.getFullName()); } diff --git a/base/src/main/java/io/spine/type/TypeName.java b/base/src/main/java/io/spine/type/TypeName.java index a0cb1b7a04..4e08bef5b3 100644 --- a/base/src/main/java/io/spine/type/TypeName.java +++ b/base/src/main/java/io/spine/type/TypeName.java @@ -33,8 +33,6 @@ import com.google.protobuf.Message; import io.spine.value.StringTypeValue; -import java.util.List; - import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; @@ -115,9 +113,9 @@ public static TypeName from(Descriptor descriptor) { * Returns the unqualified name of the Protobuf type, for example: {@code StringValue}. */ public String simpleName() { - String typeName = value(); - List tokens = packageSplitter.splitToList(typeName); - String result = tokens.get(tokens.size() - 1); + var typeName = value(); + var tokens = packageSplitter.splitToList(typeName); + var result = tokens.get(tokens.size() - 1); return result; } @@ -151,10 +149,10 @@ public Class toJavaClass() throws UnknownTypeException { * @throws UnknownTypeException if the type is not found among known types */ public Class toMessageClass() throws UnknownTypeException { - Class cls = toJavaClass(); + var cls = toJavaClass(); checkState(Message.class.isAssignableFrom(cls)); @SuppressWarnings("unchecked") - Class result = (Class) cls; + var result = (Class) cls; return result; } @@ -168,10 +166,10 @@ public Class toMessageClass() throws UnknownTypeException * @throws UnknownTypeException if the type is not found among known types */ public > Class toEnumClass() throws UnknownTypeException { - Class cls = toJavaClass(); + var cls = toJavaClass(); checkState(Enum.class.isAssignableFrom(cls)); @SuppressWarnings("unchecked") - Class result = (Class) cls; + var result = (Class) cls; return result; } @@ -187,7 +185,7 @@ public GenericDescriptor genericDescriptor() { * and it represents an enum. */ public Descriptor messageDescriptor() { - Descriptor result = (Descriptor) genericDescriptor(); + var result = (Descriptor) genericDescriptor(); return result; } @@ -195,17 +193,16 @@ public Descriptor messageDescriptor() { * Verifies if the type belongs to the passed package. */ boolean belongsTo(String packageName) { - String typeName = value(); - boolean inPackage = - typeName.startsWith(packageName) - && typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR; + var typeName = value(); + var inPackage = typeName.startsWith(packageName) + && typeName.charAt(packageName.length()) == PACKAGE_SEPARATOR; return inPackage; } Type type() { - Type result = KnownTypes.instance() - .find(this) - .orElseThrow(() -> new UnknownTypeException(value())); + var result = KnownTypes.instance() + .find(this) + .orElseThrow(() -> new UnknownTypeException(value())); return result; } } diff --git a/base/src/main/java/io/spine/type/TypeUrl.java b/base/src/main/java/io/spine/type/TypeUrl.java index a34868aaf1..b4b1438b1a 100644 --- a/base/src/main/java/io/spine/type/TypeUrl.java +++ b/base/src/main/java/io/spine/type/TypeUrl.java @@ -33,7 +33,6 @@ import com.google.protobuf.AnyOrBuilder; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.EnumDescriptor; -import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Descriptors.GenericDescriptor; import com.google.protobuf.Descriptors.ServiceDescriptor; import com.google.protobuf.InvalidProtocolBufferException; @@ -43,7 +42,6 @@ import io.spine.option.OptionsProto; import java.io.Serializable; -import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; @@ -89,7 +87,7 @@ private static TypeUrl create(String prefix, String typeName) { @VisibleForTesting static String composeTypeUrl(String prefix, String typeName) { - String url = prefix + SEPARATOR + typeName; + var url = prefix + SEPARATOR + typeName; return url; } @@ -110,7 +108,7 @@ public static TypeUrl of(Message msg) { */ public static TypeUrl from(Descriptor descriptor) { checkNotNull(descriptor); - String prefix = prefixFor(descriptor); + var prefix = prefixFor(descriptor); return create(prefix, descriptor.getFullName()); } @@ -121,7 +119,7 @@ public static TypeUrl from(Descriptor descriptor) { */ public static TypeUrl from(EnumDescriptor descriptor) { checkNotNull(descriptor); - String prefix = prefixFor(descriptor); + var prefix = prefixFor(descriptor); return create(prefix, descriptor.getFullName()); } @@ -132,7 +130,7 @@ public static TypeUrl from(EnumDescriptor descriptor) { */ public static TypeUrl from(ServiceDescriptor descriptor) { checkNotNull(descriptor); - String prefix = prefixFor(descriptor); + var prefix = prefixFor(descriptor); return create(prefix, descriptor.getFullName()); } @@ -148,7 +146,7 @@ public static TypeUrl parse(String typeUrl) { checkArgument(!typeUrl.isEmpty()); checkArgument(isTypeUrl(typeUrl), "Malformed type URL: %s", typeUrl); - TypeUrl result = doParse(typeUrl); + var result = doParse(typeUrl); return result; } @@ -157,17 +155,17 @@ private static boolean isTypeUrl(String str) { } private static TypeUrl doParse(String typeUrl) { - List strings = splitter.splitToList(typeUrl); + var strings = splitter.splitToList(typeUrl); if (strings.size() != 2) { throw malformedTypeUrl(typeUrl); } - String prefix = strings.get(0); - String typeName = strings.get(1); + var prefix = strings.get(0); + var typeName = strings.get(1); return create(prefix, typeName); } private static IllegalArgumentException malformedTypeUrl(String typeUrl) { - String errMsg = format("Invalid Protobuf type URL encountered: %s", typeUrl); + var errMsg = format("Invalid Protobuf type URL encountered: %s", typeUrl); throw new IllegalArgumentException(new InvalidProtocolBufferException(errMsg)); } @@ -178,7 +176,7 @@ private static IllegalArgumentException malformedTypeUrl(String typeUrl) { * @return a type URL */ public static TypeUrl ofEnclosed(AnyOrBuilder any) { - TypeUrl typeUrl = doParse(any.getTypeUrl()); + var typeUrl = doParse(any.getTypeUrl()); return typeUrl; } @@ -186,8 +184,8 @@ public static TypeUrl ofEnclosed(AnyOrBuilder any) { * Obtains the type URL for the passed message class. */ public static TypeUrl of(Class cls) { - Message defaultInstance = defaultInstance(cls); - TypeUrl result = of(defaultInstance); + var defaultInstance = defaultInstance(cls); + var result = of(defaultInstance); return result; } @@ -201,14 +199,14 @@ public static TypeUrl of(Class cls) { * OptionsProto#typeUrlPrefix file option}. */ private static String prefixFor(GenericDescriptor descriptor) { - FileDescriptor file = descriptor.getFile(); + var file = descriptor.getFile(); if (file.getPackage() .startsWith(PackageName.googleProtobuf() .value())) { return Prefix.GOOGLE_APIS.value(); } - String result = file.getOptions() - .getExtension(OptionsProto.typeUrlPrefix); + var result = file.getOptions() + .getExtension(OptionsProto.typeUrlPrefix); return result; } @@ -259,7 +257,7 @@ public TypeName toTypeName() { * Obtains string representation of the URL. */ public String value() { - String result = composeTypeUrl(prefix, typeName.value()); + var result = composeTypeUrl(prefix, typeName.value()); return result; } @@ -275,7 +273,7 @@ public boolean equals(Object o) { if (!(o instanceof TypeUrl)) { return false; } - TypeUrl typeUrl = (TypeUrl) o; + var typeUrl = (TypeUrl) o; return Objects.equals(prefix, typeUrl.prefix) && Objects.equals(typeName, typeUrl.typeName); } From a0f7862294807bbd609e2798a069810e7f08ae9a Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 15:09:45 +0200 Subject: [PATCH 22/27] Use `var`s in `io.spine.util` package. --- base/src/main/java/io/spine/util/Exceptions.java | 14 +++++++------- base/src/main/java/io/spine/util/Math2.java | 2 +- .../src/main/java/io/spine/util/NamedProperty.java | 4 +++- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/base/src/main/java/io/spine/util/Exceptions.java b/base/src/main/java/io/spine/util/Exceptions.java index 1332f3fd8a..92f9b37b1c 100644 --- a/base/src/main/java/io/spine/util/Exceptions.java +++ b/base/src/main/java/io/spine/util/Exceptions.java @@ -96,7 +96,7 @@ public static UnsupportedOperationException unsupported(String message) { public static UnsupportedOperationException unsupported(String format, Object... args) { checkNotNull(format); checkNotNull(args); - String msg = formatMessage(format, args); + var msg = formatMessage(format, args); return unsupported(msg); } @@ -133,7 +133,7 @@ public static UnsupportedOperationException unsupported() { */ public static IllegalStateException illegalStateWithCauseOf(Throwable throwable) { checkNotNull(throwable); - Throwable rootCause = getRootCause(throwable); + var rootCause = getRootCause(throwable); throw new IllegalStateException(rootCause); } @@ -146,7 +146,7 @@ public static IllegalStateException illegalStateWithCauseOf(Throwable throwable) */ public static IllegalArgumentException illegalArgumentWithCauseOf(Throwable throwable) { checkNotNull(throwable); - Throwable rootCause = getRootCause(throwable); + var rootCause = getRootCause(throwable); throw new IllegalArgumentException(rootCause); } @@ -166,7 +166,7 @@ private static String formatMessage(String format, Object[] args) { */ public static IllegalArgumentException newIllegalArgumentException(String format, Object... args) { - String errMsg = formatMessage(format, args); + var errMsg = formatMessage(format, args); throw new IllegalArgumentException(errMsg); } @@ -183,7 +183,7 @@ public static IllegalArgumentException newIllegalArgumentException(Throwable cau String format, Object... args) { checkNotNull(cause); - String errMsg = formatMessage(format, args); + var errMsg = formatMessage(format, args); throw new IllegalArgumentException(errMsg, cause); } @@ -197,7 +197,7 @@ public static IllegalArgumentException newIllegalArgumentException(Throwable cau */ public static IllegalStateException newIllegalStateException(String format, Object... args) { - String errMsg = formatMessage(format, args); + var errMsg = formatMessage(format, args); throw new IllegalStateException(errMsg); } @@ -215,7 +215,7 @@ public static IllegalStateException newIllegalStateException(Throwable cause, String format, Object... args) { checkNotNull(cause); - String errMsg = formatMessage(format, args); + var errMsg = formatMessage(format, args); throw new IllegalStateException(errMsg, cause); } } diff --git a/base/src/main/java/io/spine/util/Math2.java b/base/src/main/java/io/spine/util/Math2.java index b518a53b2e..1979807f9f 100644 --- a/base/src/main/java/io/spine/util/Math2.java +++ b/base/src/main/java/io/spine/util/Math2.java @@ -61,7 +61,7 @@ public static long safeMultiply(long a, int b) { default: // fall through. } - long total = a * b; + var total = a * b; if (total / b != a) { throwOverflow(a, b); } diff --git a/base/src/main/java/io/spine/util/NamedProperty.java b/base/src/main/java/io/spine/util/NamedProperty.java index f28f548890..e01553331b 100644 --- a/base/src/main/java/io/spine/util/NamedProperty.java +++ b/base/src/main/java/io/spine/util/NamedProperty.java @@ -41,6 +41,7 @@ * @param * the type of the object holding the property from which we get the value */ +@SuppressWarnings({"unused", "AbstractClassNeverImplemented"}) /* Part of the public API. */ public abstract class NamedProperty { private final String name; @@ -59,10 +60,11 @@ protected NamedProperty(String name) { /** * Obtains the class of the value. */ + @SuppressWarnings("unused") /* Part of the public API. */ protected Class getValueClass() { @SuppressWarnings("unchecked") /* The type is ensured by the first generic param of this class declaration. */ - Class cls = (Class) GenericParameter.PROPERTY_TYPE.argumentIn(getClass()); + var cls = (Class) GenericParameter.PROPERTY_TYPE.argumentIn(getClass()); return cls; } From cc7d59539b0c436475c6067bea9271b6fdc872a1 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 15:19:51 +0200 Subject: [PATCH 23/27] Use `var`s in `io.spine.validate` package and its subpackages. --- .../java/io/spine/validate/Alternative.java | 14 +-- .../io/spine/validate/ComparableNumber.java | 6 +- .../io/spine/validate/ConstraintCache.java | 4 +- .../java/io/spine/validate/ConstraintFor.java | 3 +- .../java/io/spine/validate/Constraints.java | 6 +- .../io/spine/validate/ExceptionFactory.java | 19 ++- .../validate/ExternalConstraintOptions.java | 28 ++--- .../spine/validate/ExternalConstraints.java | 19 ++- .../validate/ExternalMessageConstraint.java | 36 +++--- .../io/spine/validate/FieldAwareMessage.java | 13 +-- .../io/spine/validate/FieldConstraints.java | 6 +- .../java/io/spine/validate/FieldValue.java | 19 ++- .../io/spine/validate/MessageValidator.java | 110 ++++++++---------- .../java/io/spine/validate/MessageValue.java | 12 +- .../io/spine/validate/NumberConversion.java | 10 +- .../java/io/spine/validate/NumberText.java | 12 +- .../io/spine/validate/RequiredFieldCheck.java | 17 ++- .../main/java/io/spine/validate/Validate.java | 51 ++++---- .../io/spine/validate/ValidatingBuilder.java | 2 +- .../spine/validate/diags/ViolationText.java | 36 +++--- .../option/FieldValidatingOption.java | 28 +++-- .../java/io/spine/validate/option/Goes.java | 20 ++-- .../spine/validate/option/GoesConstraint.java | 2 +- .../io/spine/validate/option/IfMissing.java | 4 +- .../spine/validate/option/MaxConstraint.java | 8 +- .../spine/validate/option/MinConstraint.java | 8 +- .../validate/option/PatternConstraint.java | 13 +-- .../io/spine/validate/option/RangeDecl.java | 5 +- .../validate/option/RangedConstraint.java | 3 +- .../io/spine/validate/option/Required.java | 10 +- .../validate/option/RequiredConstraint.java | 5 +- .../spine/validate/option/RequiredField.java | 7 +- .../validate/option/ValidateConstraint.java | 5 +- .../option/ValidatingOptionsLoader.java | 2 +- 34 files changed, 250 insertions(+), 293 deletions(-) diff --git a/base/src/main/java/io/spine/validate/Alternative.java b/base/src/main/java/io/spine/validate/Alternative.java index 554d1d98d0..24675f6e9c 100644 --- a/base/src/main/java/io/spine/validate/Alternative.java +++ b/base/src/main/java/io/spine/validate/Alternative.java @@ -33,7 +33,6 @@ import io.spine.type.MessageType; import java.util.Collection; -import java.util.List; import java.util.regex.Pattern; import static com.google.common.collect.ImmutableSet.toImmutableSet; @@ -79,19 +78,18 @@ private Alternative(ImmutableSet fields) { */ public static ImmutableSet parse(String notation, MessageType type) { ImmutableSet.Builder alternatives = ImmutableSet.builder(); - String whiteSpaceRemoved = WHITESPACE.matcher(notation) - .replaceAll(""); - Iterable parts = orSplitter.split(whiteSpaceRemoved); - for (String part : parts) { - List fieldNames = andSplitter.splitToList(part); + var whiteSpaceRemoved = WHITESPACE.matcher(notation) + .replaceAll(""); + var parts = orSplitter.split(whiteSpaceRemoved); + for (var part : parts) { + var fieldNames = andSplitter.splitToList(part); alternatives.add(ofCombination(fieldNames, type)); } return alternatives.build(); } private static Alternative ofCombination(Collection fieldNames, MessageType type) { - ImmutableSet fields = fieldNames - .stream() + var fields = fieldNames.stream() .map(type::field) .collect(toImmutableSet()); return new Alternative(fields); diff --git a/base/src/main/java/io/spine/validate/ComparableNumber.java b/base/src/main/java/io/spine/validate/ComparableNumber.java index 49b62ab544..fb9d54dd41 100644 --- a/base/src/main/java/io/spine/validate/ComparableNumber.java +++ b/base/src/main/java/io/spine/validate/ComparableNumber.java @@ -66,8 +66,8 @@ public Number value() { public int compareTo(Number anotherNumber) { checkNotNull(anotherNumber); - long thisLong = longValue(); - long thatLong = anotherNumber.longValue(); + var thisLong = longValue(); + var thatLong = anotherNumber.longValue(); if (thisLong == thatLong) { return Double.compare(doubleValue(), anotherNumber.doubleValue()); } @@ -109,7 +109,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - ComparableNumber number = (ComparableNumber) o; + var number = (ComparableNumber) o; return Objects.equal(value, number.value); } diff --git a/base/src/main/java/io/spine/validate/ConstraintCache.java b/base/src/main/java/io/spine/validate/ConstraintCache.java index 94a15cfb06..ede0d1cb09 100644 --- a/base/src/main/java/io/spine/validate/ConstraintCache.java +++ b/base/src/main/java/io/spine/validate/ConstraintCache.java @@ -91,7 +91,7 @@ static Constraints customForType(MessageType type, FieldContext context) { private static Constraints fromCache(LoadingCache constraints, MessageType type, FieldContext context) { - Key key = new Key(type, context); + var key = new Key(type, context); try { return constraints.get(key); } catch (@SuppressWarnings("OverlyBroadCatchBlock") @@ -122,7 +122,7 @@ public boolean equals(Object o) { if (!(o instanceof Key)) { return false; } - Key key = (Key) o; + var key = (Key) o; return Objects.equal(type, key.type) && Objects.equal(fieldContext, key.fieldContext); } diff --git a/base/src/main/java/io/spine/validate/ConstraintFor.java b/base/src/main/java/io/spine/validate/ConstraintFor.java index a57f3e91c8..b25d3d2484 100644 --- a/base/src/main/java/io/spine/validate/ConstraintFor.java +++ b/base/src/main/java/io/spine/validate/ConstraintFor.java @@ -28,7 +28,6 @@ import com.google.errorprone.annotations.Immutable; import com.google.protobuf.DescriptorProtos.DescriptorProto; -import com.google.protobuf.DescriptorProtos.MessageOptions; import io.spine.code.proto.MessageOption; import io.spine.option.OptionsProto; @@ -50,7 +49,7 @@ final class ConstraintFor extends MessageOption { * Obtains the value of the option based on its {@linkplain DescriptorProto descriptor}. */ Optional valueFrom(DescriptorProto message) { - MessageOptions options = message.getOptions(); + var options = message.getOptions(); return options.hasExtension(extension()) ? Optional.of(options.getExtension(extension())) : Optional.empty(); diff --git a/base/src/main/java/io/spine/validate/Constraints.java b/base/src/main/java/io/spine/validate/Constraints.java index 0ae0832267..1606738d0d 100644 --- a/base/src/main/java/io/spine/validate/Constraints.java +++ b/base/src/main/java/io/spine/validate/Constraints.java @@ -91,16 +91,16 @@ static Constraints loadFor(MessageType type, FieldContext context) { private static void addRequiredField(MessageType type, ImmutableList.Builder constraintBuilder) { - RequiredField requiredField = new RequiredField(); + var requiredField = new RequiredField(); if (requiredField.valuePresent(type.descriptor())) { - Constraint requiredFieldConstraint = requiredField.constraintFor(type); + var requiredFieldConstraint = requiredField.constraintFor(type); constraintBuilder.add(requiredFieldConstraint); } } private static void scanIsRequired(MessageType type, ImmutableList.Builder builder) { - IsRequired option = new IsRequired(); + var option = new IsRequired(); type.descriptor() .getOneofs() .stream() diff --git a/base/src/main/java/io/spine/validate/ExceptionFactory.java b/base/src/main/java/io/spine/validate/ExceptionFactory.java index 02f8b9b7af..3eccbc920c 100644 --- a/base/src/main/java/io/spine/validate/ExceptionFactory.java +++ b/base/src/main/java/io/spine/validate/ExceptionFactory.java @@ -48,8 +48,8 @@ * @param type of the {@linkplain io.spine.type.MessageClass} of {@code |M|}. * @param type of an error code to use for error reporting; must be a Protobuf enum value */ -@SuppressWarnings("unused") @Internal +@SuppressWarnings({"unused", "AbstractClassNeverImplemented"}) /* Part of the public API. */ public abstract class ExceptionFactory, @@ -106,14 +106,13 @@ private String formatExceptionMessage() { } private Error createError() { - ValidationError validationError = error(); - R errorCode = getErrorCode(); - String errorType = errorCode.getDescriptorForType() - .getFullName(); - String errorText = errorText(); + var validationError = error(); + var errorCode = getErrorCode(); + var errorType = errorCode.getDescriptorForType() + .getFullName(); + var errorText = errorText(); - Error.Builder error = Error - .newBuilder() + var error = Error.newBuilder() .setType(errorType) .setCode(errorCode.getNumber()) .setValidationError(validationError) @@ -130,8 +129,8 @@ private ValidationError error() { } private String errorText() { - String errorTextTemplate = getErrorText(); - String violationsText = violationsText(); + var errorTextTemplate = getErrorText(); + var violationsText = violationsText(); return format("%s %s", errorTextTemplate, violationsText); } diff --git a/base/src/main/java/io/spine/validate/ExternalConstraintOptions.java b/base/src/main/java/io/spine/validate/ExternalConstraintOptions.java index 4433da53b3..0ef61b2246 100644 --- a/base/src/main/java/io/spine/validate/ExternalConstraintOptions.java +++ b/base/src/main/java/io/spine/validate/ExternalConstraintOptions.java @@ -77,11 +77,11 @@ private ExternalConstraintOptions(ImmutableMap optio */ public static Optional getOptionValue(FieldContext fieldContext, GeneratedExtension option) { - ImmutableMap options = Holder.instance.options; - for (FieldContext context : options.keySet()) { - FieldOptions fieldOptions = options.get(context); + var options = Holder.instance.options; + for (var context : options.keySet()) { + var fieldOptions = options.get(context); if (fieldContext.hasSameTargetAndParent(context) && fieldOptions.hasExtension(option)) { - T optionValue = fieldOptions.getExtension(option); + var optionValue = fieldOptions.getExtension(option); // A option is set explicitly if it was found in external constraints. return Optional.of(optionValue); } @@ -115,8 +115,8 @@ static void updateFrom(Iterable externalConstraints) logger.atFine() .log("Updating external constraint options from constraints `%s`.", externalConstraints); - ImmutableMap currentOptions = instance.options; - ImmutableMap newOptions = new Builder() + var currentOptions = instance.options; + var newOptions = new Builder() .buildFrom(externalConstraints); Map options = newHashMapWithExpectedSize(currentOptions.size() + newOptions.size()); @@ -139,26 +139,26 @@ private ImmutableMap build() { private ImmutableMap buildFrom(Iterable constraints) { - for (ExternalMessageConstraint constraint : constraints) { + for (var constraint : constraints) { putAll(constraint); } return ImmutableMap.copyOf(state); } private void putAll(ExternalMessageConstraint constraint) { - Descriptor constraintDescriptor = constraint.getDescriptor(); + var constraintDescriptor = constraint.getDescriptor(); Collection targets = constraint.getTargets(); - for (FieldDescriptor target : targets) { + for (var target : targets) { put(constraintDescriptor, target); } } private void put(Descriptor constraint, FieldDescriptor target) { - Descriptor targetType = target.getMessageType(); - for (FieldDescriptor constraintField : constraint.getFields()) { - FieldDescriptor subTarget = targetType.findFieldByName(constraintField.getName()); - FieldContext targetContext = FieldContext.create(target); - FieldContext subTargetContext = targetContext.forChild(subTarget); + var targetType = target.getMessageType(); + for (var constraintField : constraint.getFields()) { + var subTarget = targetType.findFieldByName(constraintField.getName()); + var targetContext = FieldContext.create(target); + var subTargetContext = targetContext.forChild(subTarget); state.put(subTargetContext, constraintField.getOptions()); } } diff --git a/base/src/main/java/io/spine/validate/ExternalConstraints.java b/base/src/main/java/io/spine/validate/ExternalConstraints.java index af8d3f4b2f..cc3d8d7a3c 100644 --- a/base/src/main/java/io/spine/validate/ExternalConstraints.java +++ b/base/src/main/java/io/spine/validate/ExternalConstraints.java @@ -30,7 +30,6 @@ import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import com.google.common.flogger.FluentLogger; -import com.google.protobuf.DescriptorProtos; import com.google.protobuf.Descriptors.Descriptor; import io.spine.annotation.Internal; import io.spine.type.KnownTypes; @@ -103,7 +102,7 @@ static ImmutableSet all() { * {@code false} otherwise */ public static boolean isDefinedFor(Descriptor containerType, String fieldName) { - for (ExternalMessageConstraint constraint : all()) { + for (var constraint : all()) { if (constraint.hasTarget(containerType, fieldName)) { return true; } @@ -123,7 +122,7 @@ public static void updateFrom(ImmutableSet types) { * Builds external constraints for known Protobuf types. */ private static ImmutableSet constraintsFor(KnownTypes knownTypes) { - ImmutableSet types = checkNotNull(knownTypes) + var types = checkNotNull(knownTypes) .asTypeSet() .messageTypes(); return constraintsFor(types); @@ -146,8 +145,8 @@ private static ImmutableSet constraintsFor(KnownTypes */ private static ExternalMessageConstraint toConstraint(MessageType type) { checkNotNull(type); - ConstraintFor constraintFor = new ConstraintFor(); - String constraintTargets = constraintFor + var constraintFor = new ConstraintFor(); + var constraintTargets = constraintFor .valueFrom(type.toProto()) .orElseThrow(() -> newIllegalArgumentException(type.name() .value())); @@ -188,8 +187,8 @@ private static void updateFrom(ImmutableSet types) { checkNotNull(types); logger.atFine() .log("Updating external constraints from types `%s`.", types); - ImmutableSet currentConstraints = instance.constraints; - ImmutableSet newConstraints = constraintsFor(types); + var currentConstraints = instance.constraints; + var newConstraints = constraintsFor(types); Set constraints = newHashSetWithExpectedSize(currentConstraints.size() + newConstraints.size()); constraints.addAll(currentConstraints); @@ -207,9 +206,9 @@ private static class HasExternalConstraint implements Predicate { @Override public boolean test(MessageType input) { checkNotNull(input); - DescriptorProtos.DescriptorProto proto = input.toProto(); - boolean result = new ConstraintFor().valueFrom(proto) - .isPresent(); + var proto = input.toProto(); + var result = new ConstraintFor().valueFrom(proto) + .isPresent(); logger.atFine() .log("[HasExternalConstraint] Tested `%s` with the result of `%b`.", proto.getName(), result); diff --git a/base/src/main/java/io/spine/validate/ExternalMessageConstraint.java b/base/src/main/java/io/spine/validate/ExternalMessageConstraint.java index b130314fc0..18197c380b 100644 --- a/base/src/main/java/io/spine/validate/ExternalMessageConstraint.java +++ b/base/src/main/java/io/spine/validate/ExternalMessageConstraint.java @@ -104,8 +104,8 @@ private static boolean isSame(FieldDescriptor field, Descriptor containerType, private static ImmutableSet constructTargets(Descriptor constraint, Iterable targetPaths) { ImmutableSet.Builder targets = ImmutableSet.builder(); - for (String targetPath : targetPaths) { - FieldDescriptor target = getTargetDescriptor(targetPath); + for (var targetPath : targetPaths) { + var target = getTargetDescriptor(targetPath); checkConstraintFields(constraint, target); targets.add(target); } @@ -120,18 +120,18 @@ private static boolean isSame(FieldDescriptor field, Descriptor containerType, * @return the field descriptor */ private static FieldDescriptor getTargetDescriptor(String targetPath) { - int typeAndFieldNameBound = targetPath.lastIndexOf(FIELD_NAME_SEPARATOR); + var typeAndFieldNameBound = targetPath.lastIndexOf(FIELD_NAME_SEPARATOR); if (typeAndFieldNameBound == -1) { - String msg = "Invalid external constraint target `%s`. " + + var msg = "Invalid external constraint target `%s`. " + "Proper format is `package.TargetMessage.target_field`."; throw newIllegalStateException(msg, targetPath); } - String fieldName = targetPath.substring(typeAndFieldNameBound + 1); - String targetMessageType = targetPath.substring(0, typeAndFieldNameBound); - Descriptor message = TypeName.of(targetMessageType) - .messageDescriptor(); - FieldDescriptor field = message.findFieldByName(fieldName); + var fieldName = targetPath.substring(typeAndFieldNameBound + 1); + var targetMessageType = targetPath.substring(0, typeAndFieldNameBound); + var message = TypeName.of(targetMessageType) + .messageDescriptor(); + var field = message.findFieldByName(fieldName); if (field == null) { throw newIllegalStateException("The field '%s' is not found in the '%s' message.", fieldName, message.getName()); @@ -141,7 +141,7 @@ private static FieldDescriptor getTargetDescriptor(String targetPath) { private static FieldDescriptor checkTargetType(FieldDescriptor targetDescriptor) { if (targetDescriptor.getJavaType() != MESSAGE) { - String errMsg = "External constraint target must be a Message. Specified type is `%s`."; + var errMsg = "External constraint target must be a Message. Specified type is `%s`."; throw newIllegalStateException(errMsg, targetDescriptor.getJavaType()); } return targetDescriptor; @@ -158,20 +158,20 @@ private static FieldDescriptor checkTargetType(FieldDescriptor targetDescriptor) * the target of the constraint */ private static void checkConstraintFields(Descriptor constraint, FieldDescriptor target) { - for (FieldDescriptor constraintField : constraint.getFields()) { - Descriptor targetType = target.getMessageType(); - String fieldName = constraintField.getName(); - FieldDescriptor targetField = targetType.findFieldByName(fieldName); + for (var constraintField : constraint.getFields()) { + var targetType = target.getMessageType(); + var fieldName = constraintField.getName(); + var targetField = targetType.findFieldByName(fieldName); if (targetField == null) { - String msg = "The external constraint '%s' declares the field `%s`, " + + var msg = "The external constraint '%s' declares the field `%s`, " + "which was not found in the `%s` message."; throw newIllegalStateException(msg, constraint.getFullName(), fieldName, targetType.getName()); } - boolean isCorrectType = constraintField.getJavaType() == targetField.getJavaType(); + var isCorrectType = constraintField.getJavaType() == targetField.getJavaType(); if (!isCorrectType) { - String errMsg = "`%s` must be of type `%s`."; + var errMsg = "`%s` must be of type `%s`."; throw newIllegalStateException(errMsg, constraintField.getFullName(), targetField.getJavaType()); } @@ -187,7 +187,7 @@ public boolean equals(Object o) { return false; } - ExternalMessageConstraint other = (ExternalMessageConstraint) o; + var other = (ExternalMessageConstraint) o; return typeUrl().equals(other.typeUrl()); } diff --git a/base/src/main/java/io/spine/validate/FieldAwareMessage.java b/base/src/main/java/io/spine/validate/FieldAwareMessage.java index eff1f225aa..0f0ba16387 100644 --- a/base/src/main/java/io/spine/validate/FieldAwareMessage.java +++ b/base/src/main/java/io/spine/validate/FieldAwareMessage.java @@ -34,7 +34,6 @@ import io.spine.annotation.GeneratedMixin; import io.spine.annotation.Internal; -import java.util.List; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; @@ -72,13 +71,13 @@ default Object readValue(FieldDescriptor field) { */ @VisibleForTesting default boolean checkFieldsReachable() { - Descriptors.Descriptor msgDescriptor = getDescriptorForType(); - List fields = msgDescriptor.getFields(); + var msgDescriptor = getDescriptorForType(); + var fields = msgDescriptor.getFields(); - for (FieldDescriptor field : fields) { - Object value = getField(field); - Object actual = readValue(field); - boolean equals = Objects.equals(actual, value); + for (var field : fields) { + var value = getField(field); + var actual = readValue(field); + var equals = Objects.equals(actual, value); checkArgument(equals, "" + "`readValue(field)` is implemented incorrectly for the `%s` field in `%s`", field, getClass()); diff --git a/base/src/main/java/io/spine/validate/FieldConstraints.java b/base/src/main/java/io/spine/validate/FieldConstraints.java index abb75962c0..c6314ba242 100644 --- a/base/src/main/java/io/spine/validate/FieldConstraints.java +++ b/base/src/main/java/io/spine/validate/FieldConstraints.java @@ -28,9 +28,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.flogger.FluentLogger; -import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import io.spine.code.proto.FieldContext; -import io.spine.code.proto.FieldDeclaration; import io.spine.validate.option.FieldValidatingOption; import io.spine.validate.option.StandardOptionFactory; import io.spine.validate.option.ValidatingOptionFactory; @@ -86,8 +84,8 @@ static Stream customConstraintsFor(FieldContext field) { private static Stream findConstraints(FieldContext field, ImmutableSet factories) { checkNotNull(field); - FieldDeclaration declaration = field.targetDeclaration(); - JavaType type = declaration.javaType(); + var declaration = field.targetDeclaration(); + var type = declaration.javaType(); switch (type) { case INT: return constraintsFrom(factories, ValidatingOptionFactory::forInt, field); diff --git a/base/src/main/java/io/spine/validate/FieldValue.java b/base/src/main/java/io/spine/validate/FieldValue.java index 877b3c185b..3ff53c812c 100644 --- a/base/src/main/java/io/spine/validate/FieldValue.java +++ b/base/src/main/java/io/spine/validate/FieldValue.java @@ -31,7 +31,6 @@ import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor; import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; -import com.google.protobuf.Message; import com.google.protobuf.ProtocolMessageEnum; import io.spine.annotation.Internal; import io.spine.code.proto.FieldContext; @@ -97,13 +96,13 @@ private FieldValue(Collection values, FieldContext context, FieldDeclaration static FieldValue of(Object rawValue, FieldContext context) { checkNotNull(rawValue); checkNotNull(context); - Object value = rawValue instanceof ProtocolMessageEnum + var value = rawValue instanceof ProtocolMessageEnum ? ((ProtocolMessageEnum) rawValue).getValueDescriptor() : rawValue; - FieldDescriptor fieldDescriptor = context.target(); - FieldDeclaration declaration = new FieldDeclaration(fieldDescriptor); + var fieldDescriptor = context.target(); + var declaration = new FieldDeclaration(fieldDescriptor); - FieldValue result = resolveType(declaration, context, value); + var result = resolveType(declaration, context, value); return result; } @@ -120,10 +119,10 @@ static FieldValue of(Object rawValue, FieldContext context) { private static FieldValue resolveType(FieldDeclaration field, FieldContext context, Object value) { if (value instanceof List) { - List values = (List) value; + var values = (List) value; return new FieldValue(values, context, field); } else if (value instanceof Map) { - Map map = (Map) value; + var map = (Map) value; return new FieldValue(map.values(), context, field); } else { return new FieldValue(ImmutableList.of(value), context, field); @@ -145,8 +144,8 @@ public JavaType javaType() { if (!declaration.isMap()) { return declaration.javaType(); } - JavaType result = declaration.valueDeclaration() - .javaType(); + var result = declaration.valueDeclaration() + .javaType(); return result; } @@ -214,7 +213,7 @@ private static boolean isDefault(Object singleValue) { if (singleValue instanceof EnumValueDescriptor) { return ((EnumValueDescriptor) singleValue).getNumber() == 0; } - Message thisAsMessage = TypeConverter.toMessage(singleValue); + var thisAsMessage = TypeConverter.toMessage(singleValue); return Messages.isDefault(thisAsMessage); } diff --git a/base/src/main/java/io/spine/validate/MessageValidator.java b/base/src/main/java/io/spine/validate/MessageValidator.java index 625dc05e09..65c27586fc 100644 --- a/base/src/main/java/io/spine/validate/MessageValidator.java +++ b/base/src/main/java/io/spine/validate/MessageValidator.java @@ -33,12 +33,10 @@ import com.google.protobuf.Descriptors; import com.google.protobuf.Message; import io.spine.base.Field; -import io.spine.base.FieldPath; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; import io.spine.code.proto.FieldName; import io.spine.type.MessageType; -import io.spine.type.TypeName; import io.spine.validate.option.DistinctConstraint; import io.spine.validate.option.GoesConstraint; import io.spine.validate.option.IsRequiredConstraint; @@ -54,7 +52,6 @@ import java.util.List; import java.util.Optional; import java.util.Set; -import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkNotNull; @@ -101,8 +98,8 @@ private MessageValidator(MessageValue message) { @Override public void visitRange(RangedConstraint constraint) { checkNotNull(constraint); - FieldValue value = message.valueOf(constraint.field()); - Range range = constraint.range(); + var value = message.valueOf(constraint.field()); + var range = constraint.range(); checkTypeConsistency(range, value); value.values() .map(Number.class::cast) @@ -116,7 +113,7 @@ public void visitRange(RangedConstraint constraint) { public void visitRequired(RequiredConstraint constraint) { checkNotNull(constraint); if (constraint.optionValue()) { - FieldValue fieldValue = message.valueOf(constraint.field()); + var fieldValue = message.valueOf(constraint.field()); if (fieldValue.isDefault()) { violations.add(violation(constraint, fieldValue)); } @@ -126,12 +123,12 @@ public void visitRequired(RequiredConstraint constraint) { @Override public void visitPattern(PatternConstraint constraint) { checkNotNull(constraint); - FieldValue fieldValue = message.valueOf(constraint.field()); - String regex = constraint.regex(); - int flags = constraint.flagsMask(); + var fieldValue = message.valueOf(constraint.field()); + var regex = constraint.regex(); + var flags = constraint.flagsMask(); @SuppressWarnings("MagicConstant") - Pattern compiledPattern = Pattern.compile(regex, flags); - boolean partialMatch = constraint.allowsPartialMatch(); + var compiledPattern = Pattern.compile(regex, flags); + var partialMatch = constraint.allowsPartialMatch(); fieldValue.nonDefault() .filter(value -> partialMatch ? noPartialMatch(compiledPattern, (String) value) @@ -144,20 +141,20 @@ public void visitPattern(PatternConstraint constraint) { } private static boolean noCompleteMatch(Pattern pattern, String value) { - Matcher matcher = pattern.matcher(value); + var matcher = pattern.matcher(value); return !matcher.matches(); } private static boolean noPartialMatch(Pattern pattern, String value) { - Matcher matcher = pattern.matcher(value); + var matcher = pattern.matcher(value); return !matcher.find(); } @Override public void visitDistinct(DistinctConstraint constraint) { checkNotNull(constraint); - FieldValue fieldValue = message.valueOf(constraint.field()); - ImmutableSet duplicates = findDuplicates(fieldValue); + var fieldValue = message.valueOf(constraint.field()); + var duplicates = findDuplicates(fieldValue); violations.addAll( duplicates.stream() .map(duplicate -> violation(constraint, fieldValue, duplicate)) @@ -168,23 +165,21 @@ public void visitDistinct(DistinctConstraint constraint) { @Override public void visitGoesWith(GoesConstraint constraint) { checkNotNull(constraint); - FieldDeclaration field = constraint.field(); - FieldValue value = message.valueOf(field); - Optional declaration = withField(message, constraint); - String withFieldName = constraint.optionValue().getWith(); + var field = constraint.field(); + var value = message.valueOf(field); + var declaration = withField(message, constraint); + var withFieldName = constraint.optionValue().getWith(); checkState( declaration.isPresent(), "The field `%s` specified in the `(goes).with` option is not found.", withFieldName ); - FieldDeclaration withField = declaration.get(); + var withField = declaration.get(); if (!value.isDefault() && fieldValueNotSet(withField)) { - ConstraintViolation withFieldNotSet = - violation(constraint, value) - .toBuilder() - .addParam(field.name().value()) - .addParam(withFieldName) - .build(); + var withFieldNotSet = violation(constraint, value).toBuilder() + .addParam(field.name().value()) + .addParam(withFieldName) + .build(); violations.add(withFieldNotSet); } } @@ -192,16 +187,16 @@ public void visitGoesWith(GoesConstraint constraint) { @Override public void visitValidate(ValidateConstraint constraint) { checkNotNull(constraint); - FieldValue fieldValue = message.valueOf(constraint.field()); + var fieldValue = message.valueOf(constraint.field()); if (!fieldValue.isDefault()) { - List childViolations = fieldValue + var childViolations = fieldValue .values() .map(val -> ensureMessage((Message) val)) .map(msg -> childViolations(fieldValue.context(), msg)) .flatMap(List::stream) .collect(toList()); if (!childViolations.isEmpty()) { - ConstraintViolation parentViolation = violation(constraint, fieldValue) + var parentViolation = violation(constraint, fieldValue) .toBuilder() .addAllViolation(childViolations) .build(); @@ -213,24 +208,23 @@ public void visitValidate(ValidateConstraint constraint) { @Override public void visitRequiredField(RequiredFieldConstraint constraint) { checkNotNull(constraint); - RequiredFieldCheck check = new RequiredFieldCheck(constraint.optionValue(), - constraint.alternatives(), - message); - Optional violation = check.perform(); + var check = new RequiredFieldCheck(constraint.optionValue(), + constraint.alternatives(), + message); + var violation = check.perform(); violation.ifPresent(violations::add); } @Override public void visitRequiredOneof(IsRequiredConstraint constraint) { checkNotNull(constraint); - Optional fieldValue = message.valueOf(constraint.declaration()); - boolean noneSet = !fieldValue.isPresent(); + var fieldValue = message.valueOf(constraint.declaration()); + var noneSet = fieldValue.isEmpty(); if (noneSet) { - FieldName oneofName = constraint.oneofName(); - Field oneofField = Field.named(oneofName.value()); - MessageType targetType = constraint.targetType(); - ConstraintViolation violation = ConstraintViolation - .newBuilder() + var oneofName = constraint.oneofName(); + var oneofField = Field.named(oneofName.value()); + var targetType = constraint.targetType(); + var violation = ConstraintViolation.newBuilder() .setMsgFormat(constraint.errorMessage(message.context())) .setFieldPath(oneofField.path()) .setTypeName(targetType.name().value()) @@ -242,7 +236,7 @@ public void visitRequiredOneof(IsRequiredConstraint constraint) { @Override public void visitCustom(CustomConstraint constraint) { checkNotNull(constraint); - ImmutableList violations = constraint.validate(message); + var violations = constraint.validate(message); this.violations.addAll(violations); } @@ -257,7 +251,7 @@ public Optional translate() { if (violations.isEmpty()) { return Optional.empty(); } - ValidationError error = ValidationError + var error = ValidationError .newBuilder() .addAllConstraintViolation(violations) .build(); @@ -265,8 +259,8 @@ public Optional translate() { } private static List childViolations(FieldContext field, Message message) { - MessageValue messageValue = nestedIn(field, ensureMessage(message)); - MessageValidator childInterpreter = new MessageValidator(messageValue); + var messageValue = nestedIn(field, ensureMessage(message)); + var childInterpreter = new MessageValidator(messageValue); return Constraints .of(MessageType.of(message), field) .runThrough(childInterpreter) @@ -276,8 +270,8 @@ private static List childViolations(FieldContext field, Mes private static void checkTypeConsistency(Range range, FieldValue value) { if (range.hasLowerBound() && range.hasUpperBound()) { - NumberText upper = range.upperEndpoint().toText(); - NumberText lower = range.lowerEndpoint().toText(); + var upper = range.upperEndpoint().toText(); + var lower = range.lowerEndpoint().toText(); if (!upper.isOfSameType(lower)) { throw newIllegalStateException( "Boundaries have inconsistent types: lower is `%s`, upper is `%s`.", @@ -291,15 +285,15 @@ private static void checkTypeConsistency(Range range, FieldVal } private static void checkSingleBoundary(Range range, FieldValue value) { - NumberText singleBoundary = range.hasLowerBound() - ? range.lowerEndpoint().toText() - : range.upperEndpoint().toText(); + var singleBoundary = range.hasLowerBound() + ? range.lowerEndpoint().toText() + : range.upperEndpoint().toText(); checkBoundaryAndValue(singleBoundary, value); } private static void checkBoundaryAndValue(NumberText boundary, FieldValue value) { - ComparableNumber boundaryNumber = boundary.toNumber(); - Number valueNumber = (Number) value.singleValue(); + var boundaryNumber = boundary.toNumber(); + var valueNumber = (Number) value.singleValue(); if (!NumberConversion.check(boundaryNumber, valueNumber)) { throw newIllegalStateException( "Boundary values must have types consistent with the values they bind: " + @@ -331,8 +325,8 @@ private boolean fieldValueNotSet(FieldDeclaration field) { private static Optional withField(MessageValue messageValue, GoesConstraint constraint) { - FieldName withField = FieldName.of(constraint.optionValue().getWith()); - for (FieldDeclaration field : messageValue.declaration().fields()) { + var withField = FieldName.of(constraint.optionValue().getWith()); + for (var field : messageValue.declaration().fields()) { if (withField.equals(field.name())) { return Optional.of(field); } @@ -347,12 +341,10 @@ private static ConstraintViolation violation(Constraint constraint, FieldValue v private static ConstraintViolation violation(Constraint constraint, FieldValue value, @Nullable Object violatingValue) { - FieldContext context = value.context(); - FieldPath fieldPath = context.fieldPath(); - TypeName typeName = constraint.targetType() - .name(); - ConstraintViolation.Builder violation = ConstraintViolation - .newBuilder() + var context = value.context(); + var fieldPath = context.fieldPath(); + var typeName = constraint.targetType().name(); + var violation = ConstraintViolation.newBuilder() .setMsgFormat(constraint.errorMessage(context)) .setFieldPath(fieldPath) .setTypeName(typeName.value()); diff --git a/base/src/main/java/io/spine/validate/MessageValue.java b/base/src/main/java/io/spine/validate/MessageValue.java index b48bedadf5..81f6bd6709 100644 --- a/base/src/main/java/io/spine/validate/MessageValue.java +++ b/base/src/main/java/io/spine/validate/MessageValue.java @@ -128,7 +128,7 @@ public MessageType declaration() { * or {@code Optional.empty()} if the message doesn't contain the field */ public Optional valueOf(String fieldName) { - FieldDescriptor field = descriptor.findFieldByName(fieldName); + var field = descriptor.findFieldByName(fieldName); return valueOf(field); } @@ -169,7 +169,7 @@ public FieldValue valueOf(FieldDeclaration field) { public Optional valueOf(OneofDescriptor oneof) { checkArgument(descriptor.getOneofs() .contains(oneof)); - FieldDescriptor field = message.getOneofFieldDescriptor(oneof); + var field = message.getOneofFieldDescriptor(oneof); return valueOfNullable(field); } @@ -197,15 +197,15 @@ private Optional valueOfNullable(@Nullable FieldDescriptor field) { if (field == null) { return Optional.empty(); } - FieldValue fieldValue = valueOfField(field); + var fieldValue = valueOfField(field); return Optional.of(fieldValue); } private FieldValue valueOfField(FieldDescriptor field) { - FieldContext fieldContext = context.forChild(field); - Object rawValue = readValue(field); + var fieldContext = context.forChild(field); + var rawValue = readValue(field); @SuppressWarnings("Immutable") // field values are immutable - FieldValue value = FieldValue.of(rawValue, fieldContext); + var value = FieldValue.of(rawValue, fieldContext); return value; } diff --git a/base/src/main/java/io/spine/validate/NumberConversion.java b/base/src/main/java/io/spine/validate/NumberConversion.java index 715a6eed1b..c1c8b3fba6 100644 --- a/base/src/main/java/io/spine/validate/NumberConversion.java +++ b/base/src/main/java/io/spine/validate/NumberConversion.java @@ -53,9 +53,9 @@ private NumberConversion() { static boolean check(Number number, Number anotherNumber) { checkNotNull(number); checkNotNull(anotherNumber); - Number unwrappedNumber = unwrap(number); - Number unwrappedAnotherNumber = unwrap(anotherNumber); - for (ConversionChecker caster : CHECKERS) { + var unwrappedNumber = unwrap(number); + var unwrappedAnotherNumber = unwrap(anotherNumber); + for (var caster : CHECKERS) { if (caster.supports(unwrappedNumber)) { return caster.isConvertible(unwrappedAnotherNumber); } @@ -86,8 +86,8 @@ private interface ConversionChecker { * the caster. */ default boolean isConvertible(Number number) { - Class numberClass = number.getClass(); - for (Class type : convertibleTypes()) { + var numberClass = number.getClass(); + for (var type : convertibleTypes()) { if (type.equals(numberClass)) { return true; } diff --git a/base/src/main/java/io/spine/validate/NumberText.java b/base/src/main/java/io/spine/validate/NumberText.java index 0c8354b25e..c4659bc042 100644 --- a/base/src/main/java/io/spine/validate/NumberText.java +++ b/base/src/main/java/io/spine/validate/NumberText.java @@ -90,8 +90,8 @@ public NumberText(String text) { * the specified one. */ public boolean isOfSameType(NumberText anotherNumber) { - Class classOfThisNumber = value.getClass(); - Class classOfAnotherNumber = anotherNumber.value.getClass(); + var classOfThisNumber = value.getClass(); + var classOfAnotherNumber = anotherNumber.value.getClass(); return classOfThisNumber.equals(classOfAnotherNumber); } @@ -103,7 +103,7 @@ public ComparableNumber toNumber() { } private static Number parseNumber(String text) { - List wholeAndDecimal = DECIMAL_SPLIT.splitToList(text); + var wholeAndDecimal = DECIMAL_SPLIT.splitToList(text); hasOnlyWholeAndDecimal(wholeAndDecimal); if (hasDecimalPart(wholeAndDecimal)) { return Double.parseDouble(text); @@ -112,7 +112,7 @@ private static Number parseNumber(String text) { } private static boolean hasDecimalPart(List wholeAndDecimal) { - boolean hasOnlyWhole = wholeAndDecimal.size() <= 1; + var hasOnlyWhole = wholeAndDecimal.size() <= 1; return !hasOnlyWhole && !wholeAndDecimal.get(1) .isEmpty(); } @@ -120,7 +120,7 @@ private static boolean hasDecimalPart(List wholeAndDecimal) { private static void hasOnlyWholeAndDecimal(Collection wholeAndDecimal) throws IllegalStateException { if (wholeAndDecimal.size() > 2) { - String malformedNumber = String.join("", wholeAndDecimal); + var malformedNumber = String.join("", wholeAndDecimal); throw newIllegalStateException("Found malformed number: %s.", malformedNumber); } } @@ -143,7 +143,7 @@ public boolean equals(Object o) { if (o == null || getClass() != o.getClass()) { return false; } - NumberText text = (NumberText) o; + var text = (NumberText) o; return Objects.equal(this.value, text.value); } } diff --git a/base/src/main/java/io/spine/validate/RequiredFieldCheck.java b/base/src/main/java/io/spine/validate/RequiredFieldCheck.java index e280608d99..27075c988b 100644 --- a/base/src/main/java/io/spine/validate/RequiredFieldCheck.java +++ b/base/src/main/java/io/spine/validate/RequiredFieldCheck.java @@ -28,7 +28,6 @@ import com.google.common.collect.ImmutableSet; import io.spine.base.FieldPath; -import io.spine.code.proto.FieldDeclaration; import java.util.Optional; @@ -57,26 +56,24 @@ final class RequiredFieldCheck { } Optional perform() { - boolean matches = alternatives - .stream() + var matches = alternatives.stream() .anyMatch(this::allPresent); return matches ? Optional.empty() - : Optional.of(ConstraintViolation - .newBuilder() + : Optional.of(ConstraintViolation.newBuilder() .setMsgFormat(ERROR_MESSAGE) .setFieldPath(fieldPath()) .setTypeName(typeName()) .addParam(optionValue) .build() - ); + ); } private boolean allPresent(Alternative alternative) { - for (FieldDeclaration declaration : alternative.fields()) { - String fieldName = declaration.name().value(); - Optional field = message.valueOf(fieldName); - FieldValue value = field.orElseThrow( + for (var declaration : alternative.fields()) { + var fieldName = declaration.name().value(); + var field = message.valueOf(fieldName); + var value = field.orElseThrow( () -> fieldNotFound(message, fieldName) ); if (value.isDefault()) { diff --git a/base/src/main/java/io/spine/validate/Validate.java b/base/src/main/java/io/spine/validate/Validate.java index a5e3972517..4fb14fd329 100644 --- a/base/src/main/java/io/spine/validate/Validate.java +++ b/base/src/main/java/io/spine/validate/Validate.java @@ -33,14 +33,11 @@ import io.spine.annotation.Internal; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; -import io.spine.code.proto.FieldName; import io.spine.protobuf.Diff; import io.spine.type.MessageType; -import io.spine.type.TypeName; import io.spine.validate.option.SetOnce; import java.util.List; -import java.util.Optional; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.toImmutableSet; @@ -65,7 +62,7 @@ private Validate() { */ public static void checkValid(Message message) throws ValidationException { checkNotNull(message); - List violations = violationsOf(message); + var violations = violationsOf(message); if (!violations.isEmpty()) { throw new ValidationException(violations); } @@ -103,14 +100,12 @@ private static List validateAtRuntime(Message message) { */ @Internal @SuppressWarnings("WeakerAccess") // see apiNote. - public static List + public static List validateAtRuntime(Message message, FieldContext context) { - Optional error = - Constraints.of(MessageType.of(message), context) - .runThrough(new MessageValidator(message, context)); - List violations = - error.map(ValidationError::getConstraintViolationList) - .orElse(ImmutableList.of()); + var error = Constraints.of(MessageType.of(message), context) + .runThrough(new MessageValidator(message, context)); + var violations = error.map(ValidationError::getConstraintViolationList) + .orElse(ImmutableList.of()); return violations; } @@ -127,12 +122,10 @@ private static List validateAtRuntime(Message message) { */ public static List violationsOfCustomConstraints(Message message) { checkNotNull(message); - Optional error = - Constraints.onlyCustom(MessageType.of(message), FieldContext.empty()) - .runThrough(new MessageValidator(message)); - List violations = - error.map(ValidationError::getConstraintViolationList) - .orElse(ImmutableList.of()); + var error = Constraints.onlyCustom(MessageType.of(message), FieldContext.empty()) + .runThrough(new MessageValidator(message)); + var violations = error.map(ValidationError::getConstraintViolationList) + .orElse(ImmutableList.of()); return violations; } @@ -153,7 +146,7 @@ public static List violationsOfCustomConstraints(Message me public static void checkValidChange(M previous, M current) { checkNotNull(previous); checkNotNull(current); - ImmutableSet setOnceViolations = validateChange(previous, current); + var setOnceViolations = validateChange(previous, current); if (!setOnceViolations.isEmpty()) { throw new ValidationException(setOnceViolations); } @@ -177,16 +170,15 @@ public static void checkValidChange(M previous, M current) { checkNotNull(previous); checkNotNull(current); - Diff diff = Diff.between(previous, current); - ImmutableSet violations = current - .getDescriptorForType() + var diff = Diff.between(previous, current); + var violations = current.getDescriptorForType() .getFields() .stream() .map(FieldDeclaration::new) .filter(Validate::isNonOverridable) .filter(diff::contains) .filter(field -> { - Object fieldValue = previous.getField(field.descriptor()); + var fieldValue = previous.getField(field.descriptor()); return !field.isDefault(fieldValue); }) .map(Validate::violatedSetOnce) @@ -211,9 +203,9 @@ public static void checkValidChange(M previous, M current) { private static boolean isNonOverridable(FieldDeclaration field) { checkNotNull(field); - boolean marked = markedSetOnce(field); + var marked = markedSetOnce(field); if (marked) { - boolean setOnceInapplicable = field.isCollection(); + var setOnceInapplicable = field.isCollection(); if (setOnceInapplicable) { onSetOnceMisuse(field); return false; @@ -226,13 +218,13 @@ private static boolean isNonOverridable(FieldDeclaration field) { } private static boolean markedSetOnce(FieldDeclaration declaration) { - Optional setOnceDeclaration = SetOnce.from(declaration.descriptor()); + var setOnceDeclaration = SetOnce.from(declaration.descriptor()); boolean setOnceValue = setOnceDeclaration.orElse(false); return setOnceValue; } private static void onSetOnceMisuse(FieldDeclaration field) { - FieldName fieldName = field.name(); + var fieldName = field.name(); logger.atSevere() .log("Error found in `%s`. " + "Repeated and map fields cannot be marked as `(set_once) = true`.", @@ -240,10 +232,9 @@ private static void onSetOnceMisuse(FieldDeclaration field) { } private static ConstraintViolation violatedSetOnce(FieldDeclaration declaration) { - TypeName declaringTypeName = declaration.declaringType().name(); - FieldName fieldName = declaration.name(); - ConstraintViolation violation = ConstraintViolation - .newBuilder() + var declaringTypeName = declaration.declaringType().name(); + var fieldName = declaration.name(); + var violation = ConstraintViolation.newBuilder() .setMsgFormat("Attempted to change the value of the field `%s.%s` which has " + "`(set_once) = true` and is already set.") .addParam(declaringTypeName.value()) diff --git a/base/src/main/java/io/spine/validate/ValidatingBuilder.java b/base/src/main/java/io/spine/validate/ValidatingBuilder.java index ef433b6191..363bab5af7 100644 --- a/base/src/main/java/io/spine/validate/ValidatingBuilder.java +++ b/base/src/main/java/io/spine/validate/ValidatingBuilder.java @@ -72,7 +72,7 @@ public interface ValidatingBuilder extends Message.Builder { * if the message is invalid */ default @Validated M vBuild() throws ValidationException { - M message = build(); + var message = build(); Validate.checkValid(message); return message; } diff --git a/base/src/main/java/io/spine/validate/diags/ViolationText.java b/base/src/main/java/io/spine/validate/diags/ViolationText.java index e0f50f7df9..ee16513230 100644 --- a/base/src/main/java/io/spine/validate/diags/ViolationText.java +++ b/base/src/main/java/io/spine/validate/diags/ViolationText.java @@ -29,7 +29,6 @@ import com.google.protobuf.Message; import io.spine.annotation.Internal; import io.spine.base.Field; -import io.spine.base.FieldPath; import io.spine.option.OptionsProto; import io.spine.validate.ConstraintViolation; @@ -68,36 +67,35 @@ public static ViolationText of(ConstraintViolation violation) { * a new line. */ public static String ofAll(Collection violations) { - String result = - violations.stream() - .map(ViolationText::of) - .map(ViolationText::toString) - .collect(joining(lineSeparator())); + var result = violations.stream() + .map(ViolationText::of) + .map(ViolationText::toString) + .collect(joining(lineSeparator())); return result; } @Override public String toString() { - StringBuilder builder = buildMessage(); - for (ConstraintViolation violation : this.violation.getViolationList()) { + var builder = buildMessage(); + for (var violation : this.violation.getViolationList()) { builder.append(lineSeparator()); - ViolationText nested = of(violation); + var nested = of(violation); builder.append(nested); } return builder.toString(); } private StringBuilder buildMessage() { - String typeName = violation.getTypeName(); - FieldPath path = violation.getFieldPath(); - String fieldPath = path.getFieldNameCount() == 0 + var typeName = violation.getTypeName(); + var path = violation.getFieldPath(); + var fieldPath = path.getFieldNameCount() == 0 ? "" : Field.withPath(path).toString(); - String format = violation.getMsgFormat(); + var format = violation.getMsgFormat(); List params = violation.getParamList(); - String formattedMessage = format(format, params.toArray()); + var formattedMessage = format(format, params.toArray()); - StringBuilder result = new StringBuilder(); + var result = new StringBuilder(); appendPrefix(result, typeName); appendPrefix(result, fieldPath); result.append(formattedMessage); @@ -125,10 +123,10 @@ private static void appendPrefix(StringBuilder target, String prefix) { */ @Internal public static String errorMessage(Message option, String customMsg) { - String defaultMsg = option.getDescriptorForType() - .getOptions() - .getExtension(OptionsProto.defaultMessage); - String msg = customMsg.isEmpty() ? defaultMsg : customMsg; + var defaultMsg = option.getDescriptorForType() + .getOptions() + .getExtension(OptionsProto.defaultMessage); + var msg = customMsg.isEmpty() ? defaultMsg : customMsg; return msg; } } diff --git a/base/src/main/java/io/spine/validate/option/FieldValidatingOption.java b/base/src/main/java/io/spine/validate/option/FieldValidatingOption.java index f51a0d5cec..43a4b8097a 100644 --- a/base/src/main/java/io/spine/validate/option/FieldValidatingOption.java +++ b/base/src/main/java/io/spine/validate/option/FieldValidatingOption.java @@ -65,27 +65,26 @@ protected FieldValidatingOption(GeneratedExtension optionExtens * {@link #valueFrom(FieldContext)}. */ protected T optionValue(FieldContext field) throws IllegalStateException { - Optional option = valueFrom(field); + var option = valueFrom(field); return option.orElseThrow(() -> { - FieldDescriptor descriptor = extension().getDescriptor(); + var descriptor = extension().getDescriptor(); - String fieldName = field.targetDeclaration() - .name() - .value(); - String containingTypeName = descriptor.getContainingType() - .getName(); + var fieldName = field.targetDeclaration() + .name() + .value(); + var containingTypeName = descriptor.getContainingType() + .getName(); return couldNotGetOptionValueFrom(fieldName, containingTypeName); }); } private IllegalStateException couldNotGetOptionValueFrom(String fieldName, String containingTypeName) { - String optionName = extension().getDescriptor() - .getName(); - String message = format("Could not get value of option %s from field %s in message %s.", - optionName, - fieldName, - containingTypeName); + var optionName = extension().getDescriptor().getName(); + var message = format("Could not get value of option %s from field %s in message %s.", + optionName, + fieldName, + containingTypeName); return new IllegalStateException(message); } @@ -105,8 +104,7 @@ private IllegalStateException couldNotGetOptionValueFrom(String fieldName, * {@code (constraint_for)} options. */ public Optional valueFrom(FieldContext context) { - Optional externalConstraint = - ExternalConstraintOptions.getOptionValue(context, extension()); + var externalConstraint = ExternalConstraintOptions.getOptionValue(context, extension()); return externalConstraint.isPresent() ? externalConstraint : valueFrom(context.target()); diff --git a/base/src/main/java/io/spine/validate/option/Goes.java b/base/src/main/java/io/spine/validate/option/Goes.java index 422515c09c..d3c91367d1 100644 --- a/base/src/main/java/io/spine/validate/option/Goes.java +++ b/base/src/main/java/io/spine/validate/option/Goes.java @@ -27,13 +27,11 @@ package io.spine.validate.option; import com.google.errorprone.annotations.Immutable; -import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; import io.spine.logging.Logging; import io.spine.option.GoesOption; import io.spine.option.OptionsProto; -import io.spine.type.MessageType; import io.spine.validate.Constraint; import static java.lang.String.format; @@ -67,8 +65,8 @@ && canBeRequired(field) } private boolean canBeRequired(FieldContext context) { - FieldDeclaration field = context.targetDeclaration(); - String warning = format( + var field = context.targetDeclaration(); + var warning = format( "Field `%s` cannot be checked for presence. `(goes).with` is obsolete.", field ); @@ -76,15 +74,15 @@ private boolean canBeRequired(FieldContext context) { } private boolean canPairedBeRequired(FieldContext context) { - GoesOption option = optionValue(context); - String pairedFieldName = option.getWith().trim(); + var option = optionValue(context); + var pairedFieldName = option.getWith().trim(); if (pairedFieldName.isEmpty()) { return false; } - FieldDeclaration field = context.targetDeclaration(); - MessageType messageType = field.declaringType(); - FieldDeclaration pairedField = messageType.field(pairedFieldName); - String warningMessage = format( + var field = context.targetDeclaration(); + var messageType = field.declaringType(); + var pairedField = messageType.field(pairedFieldName); + var warningMessage = format( "Field `%s` paired with `%s` cannot be checked for presence. " + "`(goes).with` at %s is obsolete.", pairedField, field, field @@ -93,7 +91,7 @@ private boolean canPairedBeRequired(FieldContext context) { } private boolean checkType(FieldDeclaration field, String warningMessage) { - JavaType type = field.javaType(); + var type = field.javaType(); if (field.isCollection() || Required.CAN_BE_REQUIRED.contains(type)) { return true; } else { diff --git a/base/src/main/java/io/spine/validate/option/GoesConstraint.java b/base/src/main/java/io/spine/validate/option/GoesConstraint.java index e8f82372a4..165fd8fe50 100644 --- a/base/src/main/java/io/spine/validate/option/GoesConstraint.java +++ b/base/src/main/java/io/spine/validate/option/GoesConstraint.java @@ -49,7 +49,7 @@ public final class GoesConstraint extends FieldConstraint { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ public String errorMessage(FieldContext field) { - GoesOption option = optionValue(); + var option = optionValue(); return ViolationText.errorMessage(option, option.getMsgFormat()); } diff --git a/base/src/main/java/io/spine/validate/option/IfMissing.java b/base/src/main/java/io/spine/validate/option/IfMissing.java index 3e8c3a7771..c1680d4fd3 100644 --- a/base/src/main/java/io/spine/validate/option/IfMissing.java +++ b/base/src/main/java/io/spine/validate/option/IfMissing.java @@ -32,8 +32,6 @@ import io.spine.option.IfMissingOption; import io.spine.option.OptionsProto; -import java.util.Optional; - /** * A field option that defines custom error message if a field is {@code required} but missing. */ @@ -50,7 +48,7 @@ public IfMissing() { * have its own option value. */ public IfMissingOption valueOrDefault(FieldDescriptor field) { - Optional option = valueFrom(field); + var option = valueFrom(field); return option.orElse(IfMissingOption.getDefaultInstance()); } } diff --git a/base/src/main/java/io/spine/validate/option/MaxConstraint.java b/base/src/main/java/io/spine/validate/option/MaxConstraint.java index 12b815315e..9e706e83b9 100644 --- a/base/src/main/java/io/spine/validate/option/MaxConstraint.java +++ b/base/src/main/java/io/spine/validate/option/MaxConstraint.java @@ -48,8 +48,8 @@ public final class MaxConstraint extends RangedConstraint { } private static Range maxRange(MaxOption option) { - boolean inclusive = !option.getExclusive(); - NumberText maxValue = new NumberText(option.getValue()); + var inclusive = !option.getExclusive(); + var maxValue = new NumberText(option.getValue()); return inclusive ? Range.atMost(maxValue.toNumber()) : Range.lessThan(maxValue.toNumber()); @@ -58,8 +58,8 @@ private static Range maxRange(MaxOption option) { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ protected String compileErrorMessage(Range range) { - MaxOption max = optionValue(); - String template = ViolationText.errorMessage(max, max.getMsgFormat()); + var max = optionValue(); + var template = ViolationText.errorMessage(max, max.getMsgFormat()); return format(template, orEqualTo(range.upperBoundType()), range.upperEndpoint()); } diff --git a/base/src/main/java/io/spine/validate/option/MinConstraint.java b/base/src/main/java/io/spine/validate/option/MinConstraint.java index 6dd58fe50d..3526fca74a 100644 --- a/base/src/main/java/io/spine/validate/option/MinConstraint.java +++ b/base/src/main/java/io/spine/validate/option/MinConstraint.java @@ -49,8 +49,8 @@ public final class MinConstraint extends RangedConstraint { } private static Range minRange(MinOption option) { - boolean inclusive = !option.getExclusive(); - NumberText minValue = new NumberText(option.getValue()); + var inclusive = !option.getExclusive(); + var minValue = new NumberText(option.getValue()); return inclusive ? Range.atLeast(minValue.toNumber()) : Range.greaterThan(minValue.toNumber()); @@ -59,8 +59,8 @@ private static Range minRange(MinOption option) { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ protected String compileErrorMessage(Range range) { - MinOption min = optionValue(); - String template = ViolationText.errorMessage(min, min.getMsgFormat()); + var min = optionValue(); + var template = ViolationText.errorMessage(min, min.getMsgFormat()); return format(template, orEqualTo(range.lowerBoundType()), range.lowerEndpoint()); } diff --git a/base/src/main/java/io/spine/validate/option/PatternConstraint.java b/base/src/main/java/io/spine/validate/option/PatternConstraint.java index e09afca590..29590e65b7 100644 --- a/base/src/main/java/io/spine/validate/option/PatternConstraint.java +++ b/base/src/main/java/io/spine/validate/option/PatternConstraint.java @@ -30,7 +30,6 @@ import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; import io.spine.option.PatternOption; -import io.spine.option.PatternOption.Modifier; import io.spine.validate.ConstraintTranslator; import io.spine.validate.diags.ViolationText; @@ -53,7 +52,7 @@ public final class PatternConstraint extends FieldConstraint { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ public String errorMessage(FieldContext field) { - PatternOption option = optionValue(); + var option = optionValue(); return ViolationText.errorMessage(option, option.getMsgFormat()); } @@ -76,8 +75,8 @@ public String regex() { * substring. */ public boolean allowsPartialMatch() { - PatternOption option = optionValue(); - Modifier modifier = option.getModifier(); + var option = optionValue(); + var modifier = option.getModifier(); return modifier.getPartialMatch(); } @@ -87,9 +86,9 @@ public boolean allowsPartialMatch() { *

If no modifiers are specified, returns {@code 0}. */ public int flagsMask() { - int result = 0; - PatternOption option = optionValue(); - Modifier modifier = option.getModifier(); + var result = 0; + var option = optionValue(); + var modifier = option.getModifier(); if (modifier.getDotAll()) { result |= DOTALL; } diff --git a/base/src/main/java/io/spine/validate/option/RangeDecl.java b/base/src/main/java/io/spine/validate/option/RangeDecl.java index 18bf1fca85..2480bd4572 100644 --- a/base/src/main/java/io/spine/validate/option/RangeDecl.java +++ b/base/src/main/java/io/spine/validate/option/RangeDecl.java @@ -31,7 +31,6 @@ import io.spine.validate.ComparableNumber; import io.spine.validate.NumberText; -import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkState; @@ -88,12 +87,12 @@ final class RangeDecl { * Transforms the passed range declaration into a range of numbers. */ static Range compile(String rangeOptionValue, FieldDeclaration field) { - RangeDecl decl = new RangeDecl(rangeOptionValue, field); + var decl = new RangeDecl(rangeOptionValue, field); return decl.toRange(); } private RangeDecl(String rangeOptionValue, FieldDeclaration field) { - Matcher rangeMatcher = NUMBER_RANGE.matcher(rangeOptionValue.trim()); + var rangeMatcher = NUMBER_RANGE.matcher(rangeOptionValue.trim()); checkState(rangeMatcher.matches(), "Malformed range `%s` on the field `%s`. " + "Must have a form of `[a..b]` " + diff --git a/base/src/main/java/io/spine/validate/option/RangedConstraint.java b/base/src/main/java/io/spine/validate/option/RangedConstraint.java index a648166d0d..7ec35ad7d3 100644 --- a/base/src/main/java/io/spine/validate/option/RangedConstraint.java +++ b/base/src/main/java/io/spine/validate/option/RangedConstraint.java @@ -30,7 +30,6 @@ import com.google.common.collect.Range; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.ImmutableTypeParameter; -import com.google.protobuf.Descriptors.FieldDescriptor.JavaType; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; import io.spine.validate.ComparableNumber; @@ -62,7 +61,7 @@ public abstract class RangedConstraint<@ImmutableTypeParameter T> extends FieldC @SuppressWarnings("EnumSwitchStatementWhichMissesCases") private static void verifyType(FieldDeclaration field, Range range) { - JavaType fieldType = field.javaType(); + var fieldType = field.javaType(); switch (fieldType) { case INT: // Fallthrough intended. case LONG: { diff --git a/base/src/main/java/io/spine/validate/option/Required.java b/base/src/main/java/io/spine/validate/option/Required.java index 2f76954fb9..f99e37b6a5 100644 --- a/base/src/main/java/io/spine/validate/option/Required.java +++ b/base/src/main/java/io/spine/validate/option/Required.java @@ -79,9 +79,7 @@ public static Required create(boolean strict) { } private boolean notAssumingRequired(FieldContext context) { - boolean defaultValue = context - .targetDeclaration() - .isId(); + var defaultValue = context.targetDeclaration().isId(); return valueFrom(context.target()) .orElse(defaultValue); } @@ -101,9 +99,9 @@ public boolean shouldValidate(FieldContext context) { * a value that the option is applied to */ void checkUsage(FieldDeclaration field) { - JavaType type = field.javaType(); + var type = field.javaType(); if (!CAN_BE_REQUIRED.contains(type) && field.isNotCollection()) { - String typeName = field.descriptor().getType().name(); + var typeName = field.descriptor().getType().name(); _warn().log("The field `%s.%s` has the type %s and" + " should not be declared as `(required)`.", field.declaringType().name(), @@ -115,7 +113,7 @@ void checkUsage(FieldDeclaration field) { @Override public Constraint constraintFor(FieldContext context) { checkUsage(context.targetDeclaration()); - boolean value = notAssumingRequired(context); + var value = notAssumingRequired(context); return new RequiredConstraint(value, context.targetDeclaration()); } } diff --git a/base/src/main/java/io/spine/validate/option/RequiredConstraint.java b/base/src/main/java/io/spine/validate/option/RequiredConstraint.java index c93508e7f9..632726293f 100644 --- a/base/src/main/java/io/spine/validate/option/RequiredConstraint.java +++ b/base/src/main/java/io/spine/validate/option/RequiredConstraint.java @@ -29,7 +29,6 @@ import com.google.errorprone.annotations.Immutable; import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; -import io.spine.option.IfMissingOption; import io.spine.validate.ConstraintTranslator; import io.spine.validate.diags.ViolationText; @@ -48,8 +47,8 @@ public final class RequiredConstraint extends FieldConstraint { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ public String errorMessage(FieldContext field) { - IfMissing ifMissing = new IfMissing(); - IfMissingOption option = ifMissing.valueOrDefault(field.target()); + var ifMissing = new IfMissing(); + var option = ifMissing.valueOrDefault(field.target()); return ViolationText.errorMessage(option, option.getMsgFormat()); } diff --git a/base/src/main/java/io/spine/validate/option/RequiredField.java b/base/src/main/java/io/spine/validate/option/RequiredField.java index d14c6e18fc..cc8c6e0049 100644 --- a/base/src/main/java/io/spine/validate/option/RequiredField.java +++ b/base/src/main/java/io/spine/validate/option/RequiredField.java @@ -30,6 +30,7 @@ import com.google.protobuf.Descriptors.Descriptor; import io.spine.type.MessageType; import io.spine.validate.Constraint; +import org.checkerframework.checker.nullness.qual.Nullable; import java.util.Optional; @@ -59,8 +60,8 @@ public final class RequiredField implements ValidatingOption valueFrom(Descriptor message) { - String result = message.getOptions() - .getExtension(requiredField); + @Nullable String result = message.getOptions() + .getExtension(requiredField); return result == null || result.isEmpty() ? Optional.empty() : Optional.of(result); @@ -68,7 +69,7 @@ public Optional valueFrom(Descriptor message) { @Override public Constraint constraintFor(MessageType messageType) { - String expression = valueFrom(messageType.descriptor()).orElse(""); + var expression = valueFrom(messageType.descriptor()).orElse(""); return new RequiredFieldConstraint(expression, messageType); } } diff --git a/base/src/main/java/io/spine/validate/option/ValidateConstraint.java b/base/src/main/java/io/spine/validate/option/ValidateConstraint.java index 1a890aedf1..af7d5e868b 100644 --- a/base/src/main/java/io/spine/validate/option/ValidateConstraint.java +++ b/base/src/main/java/io/spine/validate/option/ValidateConstraint.java @@ -28,7 +28,6 @@ import io.spine.code.proto.FieldContext; import io.spine.code.proto.FieldDeclaration; -import io.spine.option.IfInvalidOption; import io.spine.validate.ConstraintTranslator; import io.spine.validate.diags.ViolationText; @@ -45,8 +44,8 @@ public final class ValidateConstraint extends FieldConstraint { @Override @SuppressWarnings("deprecation") /* Old validation won't migrate to the new error messages. */ public String errorMessage(FieldContext field) { - IfInvalid option = new IfInvalid(); - IfInvalidOption ifInvalid = option.valueOrDefault(field.target()); + var option = new IfInvalid(); + var ifInvalid = option.valueOrDefault(field.target()); return ViolationText.errorMessage(ifInvalid, ifInvalid.getMsgFormat()); } diff --git a/base/src/main/java/io/spine/validate/option/ValidatingOptionsLoader.java b/base/src/main/java/io/spine/validate/option/ValidatingOptionsLoader.java index 9aefeebe98..a67791419b 100644 --- a/base/src/main/java/io/spine/validate/option/ValidatingOptionsLoader.java +++ b/base/src/main/java/io/spine/validate/option/ValidatingOptionsLoader.java @@ -46,7 +46,7 @@ public enum ValidatingOptionsLoader { private final ImmutableSet implementations; ValidatingOptionsLoader() { - ServiceLoader loader = load(ValidatingOptionFactory.class); + var loader = load(ValidatingOptionFactory.class); this.implementations = ImmutableSet.copyOf(loader); } From c966e3a80ccb024d49cd0e693313b9095f6cd8d2 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Thu, 9 Dec 2021 15:20:09 +0200 Subject: [PATCH 24/27] Use `var`s in `io.spine.value` package. --- base/src/main/java/io/spine/value/ComparableStringValue.java | 2 +- base/src/main/java/io/spine/value/ValueHolder.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/base/src/main/java/io/spine/value/ComparableStringValue.java b/base/src/main/java/io/spine/value/ComparableStringValue.java index a9015b67dd..182c0411ed 100644 --- a/base/src/main/java/io/spine/value/ComparableStringValue.java +++ b/base/src/main/java/io/spine/value/ComparableStringValue.java @@ -50,7 +50,7 @@ protected ComparableStringValue(String value) { @Override public int compareTo(T o) { - int result = value().compareTo(o.value()); + var result = value().compareTo(o.value()); return result; } } diff --git a/base/src/main/java/io/spine/value/ValueHolder.java b/base/src/main/java/io/spine/value/ValueHolder.java index f9099074a8..7581062656 100644 --- a/base/src/main/java/io/spine/value/ValueHolder.java +++ b/base/src/main/java/io/spine/value/ValueHolder.java @@ -65,7 +65,7 @@ public boolean equals(@Nullable Object obj) { if (!(obj instanceof ValueHolder)) { return false; } - ValueHolder other = (ValueHolder) obj; + var other = (ValueHolder) obj; return Objects.equals(this.value, other.value); } } From e56636598ed45930f35c0b7f00df7ffcc71f7624 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Fri, 10 Dec 2021 15:45:30 +0200 Subject: [PATCH 25/27] Extract the "constant" part from the stream processing. --- base/src/main/java/io/spine/reflect/PackageGraph.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/base/src/main/java/io/spine/reflect/PackageGraph.java b/base/src/main/java/io/spine/reflect/PackageGraph.java index c6465f4c8f..14f2ae1920 100644 --- a/base/src/main/java/io/spine/reflect/PackageGraph.java +++ b/base/src/main/java/io/spine/reflect/PackageGraph.java @@ -140,9 +140,9 @@ private static Graph buildGraph(List packages) { var first = queue.poll(); while (first != null) { final var current = first; + var isDirectParent = IsDirectParent.of(current); var directParent = graph.nodes().stream() - .filter((node) -> IsDirectParent.of(current) - .test(node.getValue())) + .filter((node) -> isDirectParent.test(node.getValue())) .findFirst(); var newNode = PackageInfo.of(current); if (directParent.isPresent()) { From 57c384b245e54f534d9ac2baed73fe975665c062 Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Fri, 10 Dec 2021 15:46:01 +0200 Subject: [PATCH 26/27] Reformat the ternary expression. --- base/src/main/java/io/spine/string/MapQuoter.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/base/src/main/java/io/spine/string/MapQuoter.java b/base/src/main/java/io/spine/string/MapQuoter.java index a31335eb92..1256e91695 100644 --- a/base/src/main/java/io/spine/string/MapQuoter.java +++ b/base/src/main/java/io/spine/string/MapQuoter.java @@ -45,9 +45,9 @@ final class MapQuoter extends Quoter { String quote(String stringToQuote) { checkNotNull(stringToQuote); var matcher = compile(QUOTE_PATTERN).matcher(stringToQuote); - var unslashed = matcher.find() ? - matcher.replaceAll(BACKSLASH + matcher.group()) : - stringToQuote; + var unslashed = matcher.find() + ? matcher.replaceAll(BACKSLASH + matcher.group()) + : stringToQuote; var result = QUOTE_CHAR + unslashed + QUOTE_CHAR; return result; } From b0b373759eb32a4397eec0547a55920730a16cef Mon Sep 17 00:00:00 2001 From: Alex Tymchenko Date: Fri, 10 Dec 2021 15:49:55 +0200 Subject: [PATCH 27/27] Simplify the implementation. --- base/src/main/java/io/spine/reflect/PackageGraph.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/base/src/main/java/io/spine/reflect/PackageGraph.java b/base/src/main/java/io/spine/reflect/PackageGraph.java index 14f2ae1920..222e8dbc4b 100644 --- a/base/src/main/java/io/spine/reflect/PackageGraph.java +++ b/base/src/main/java/io/spine/reflect/PackageGraph.java @@ -137,9 +137,8 @@ private static Graph buildGraph(List packages) { .nodeOrder(ElementOrder.natural()) .build(); Queue queue = new ArrayDeque<>(packages); - var first = queue.poll(); - while (first != null) { - final var current = first; + var current = queue.poll(); + while (current != null) { var isDirectParent = IsDirectParent.of(current); var directParent = graph.nodes().stream() .filter((node) -> isDirectParent.test(node.getValue())) @@ -150,7 +149,7 @@ private static Graph buildGraph(List packages) { } else { graph.addNode(newNode); } - first = queue.poll(); + current = queue.poll(); } return graph; }