diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 694a589..adbc339 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -33,6 +33,8 @@ on: - '.github/pr-labeler.yml' - 'renovate.json' - '.whitesource' + - '.idea/**' + - '.gitignore' permissions: # only required for workflows in private repositories @@ -71,4 +73,4 @@ jobs: - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@b56ba49b26e50535fa1e7f7db0f4f7b4bf65d80d # v3.28.10 - name: Check OSS Index with Gradle - run: ./gradlew ossIndexAudit -PossIndexUsername=${{ secrets.OSS_INDEX_USER }} -PossIndexPassword=${{ secrets.OSS_INDEX_PASSWORD }} + run: ./gradlew ossIndexAudit -PossIndexUsername=${{ secrets.OSS_INDEX_USER }} -PossIndexPassword=${{ secrets.OSS_INDEX_PASSWORD }} --info diff --git a/.github/workflows/gradle-ci.yml b/.github/workflows/gradle-ci.yml index ac5a3f5..8556f94 100644 --- a/.github/workflows/gradle-ci.yml +++ b/.github/workflows/gradle-ci.yml @@ -24,6 +24,8 @@ on: - 'renovate.json' - '.whitesource' - 'config/ossindex/exclusions.txt' + - '.idea/**' + - '.gitignore' permissions: read-all @@ -70,5 +72,6 @@ jobs: uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0 with: token: ${{ secrets.CODECOV_TOKEN }} - file: ./build/reports/jacoco/report.xml + files: ./build/reports/jacoco/report.xml + disable_search: true fail_ci_if_error: false diff --git a/.github/workflows/gradle-oss-index-scan.yml b/.github/workflows/gradle-oss-index-scan.yml index 5549c88..9e19e96 100644 --- a/.github/workflows/gradle-oss-index-scan.yml +++ b/.github/workflows/gradle-oss-index-scan.yml @@ -25,4 +25,4 @@ jobs: - name: Set up Gradle uses: gradle/actions/setup-gradle@94baf225fe0a508e581a564467443d0e2379123b # v4.3.0 - name: Check dependencies with Gradle - run: ./gradlew ossIndexAudit -PossIndexUsername=${{ secrets.OSS_INDEX_USER }} -PossIndexPassword=${{ secrets.OSS_INDEX_PASSWORD }} + run: ./gradlew ossIndexAudit -PossIndexUsername=${{ secrets.OSS_INDEX_USER }} -PossIndexPassword=${{ secrets.OSS_INDEX_PASSWORD }} --info diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml index 3ef6753..048eb83 100644 --- a/.github/workflows/gradle.yml +++ b/.github/workflows/gradle.yml @@ -28,6 +28,8 @@ on: - 'gradlew' - 'gradlew.bat' - 'config/ossindex/exclusions.txt' + - '.idea/**' + - '.gitignore' permissions: read-all @@ -74,5 +76,6 @@ jobs: uses: codecov/codecov-action@0565863a31f2c772f9f0395002a31e3f06189574 # v5.4.0 with: token: ${{ secrets.CODECOV_TOKEN }} - file: ./build/reports/jacoco/report.xml + files: ./build/reports/jacoco/report.xml + disable_search: true fail_ci_if_error: false diff --git a/.gitignore b/.gitignore index 5629f08..93c59ee 100644 --- a/.gitignore +++ b/.gitignore @@ -14,7 +14,12 @@ build/ .sts4-cache ### IntelliJ IDEA ### -.idea +.idea/** +!.idea/icon.png +!.idea/codeStyles +!.idea/codeStyles/** +!.idea/inspectionProfiles +!.idea/inspectionProfiles/** *.iws *.iml *.ipr diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..8fa0e68 --- /dev/null +++ b/.idea/codeStyles/Project.xml @@ -0,0 +1,36 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml new file mode 100644 index 0000000..79ee123 --- /dev/null +++ b/.idea/codeStyles/codeStyleConfig.xml @@ -0,0 +1,5 @@ + + + + \ No newline at end of file diff --git a/.idea/icon.png b/.idea/icon.png new file mode 100644 index 0000000..02ed90d Binary files /dev/null and b/.idea/icon.png differ diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..b812853 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,19 @@ + + + + \ No newline at end of file diff --git a/build.gradle b/build.gradle deleted file mode 100644 index 325d497..0000000 --- a/build.gradle +++ /dev/null @@ -1,290 +0,0 @@ -//file:noinspection DependencyNotationArgument -plugins { - id 'java' - id 'checkstyle' - id 'jacoco' - id 'maven-publish' - id 'signing' - alias(libs.plugins.lombok) - alias(libs.plugins.versioner) - alias(libs.plugins.index.scan) - alias(libs.plugins.owasp.dependencycheck) - alias(libs.plugins.cyclonedx.bom) - alias(libs.plugins.licensee.plugin) - alias(libs.plugins.nexus.publish.plugin) -} - -group = 'com.github.nagyesta' - -apply from: "config/ossindex/ossIndexAudit.gradle" - -project.ext { - gitToken = project.hasProperty('githubToken') ? (project.property('githubToken') as String) : '' - gitUser = project.hasProperty('githubUser') ? (project.property('githubUser') as String) : '' - ossrhUser = project.hasProperty('ossrhUsername') ? (project.property('ossrhUsername') as String) : '' - ossrhPass = project.hasProperty('ossrhPassword') ? (project.property('ossrhPassword') as String) : '' - ossIndexUser = project.hasProperty('ossIndexUsername') ? (project.property('ossIndexUsername') as String) : '' - ossIndexPass = project.hasProperty('ossIndexPassword') ? (project.property('ossIndexPassword') as String) : '' - artifactDisplayName = "Cache-Only" - artifactDescription = "Cache-Only is a minimal library augmenting the Spring cache abstraction with a way for caching bulk API calls." - repoUrl = 'https://github.com/nagyesta/cache-only' - licenseName = 'MIT License' - licenseUrl = 'https://raw.githubusercontent.com/nagyesta/cache-only/main/LICENSE' - maintainerId = 'nagyesta' - maintainerName = 'Istvan Zoltan Nagy' - maintainerUrl = 'https://github.com/nagyesta/' - scmConnection = 'scm:git:https://github.com/nagyesta/cache-only.git' - scmProjectUrl = 'https://github.com/nagyesta/cache-only/' -} - -versioner { - startFrom { - major = 0 - minor = 0 - patch = 1 - } - match { - major = '{major}' - minor = '{minor}' - patch = '{patch}' - } - pattern { - pattern = "%M.%m.%p" - } - git { - authentication { - https { - token = project.ext.gitToken - } - } - } - tag { - prefix = 'v' - useCommitMessage = true - } -} - -versioner.apply() - -repositories { - mavenCentral() -} - -java { - sourceCompatibility = JavaVersion.VERSION_17 - withJavadocJar() - withSourcesJar() -} - -javadoc.options.addStringOption('Xdoclint:none', '-quiet') - -dependencies { - annotationProcessor libs.lombok - compileOnly libs.jetbrains.annotations - testCompileOnly libs.jetbrains.annotations - implementation libs.slf4j.api - implementation libs.commons.collections4 - implementation libs.spring.context.support - testImplementation libs.jupiter.core - testRuntimeOnly("org.junit.platform:junit-platform-launcher") - testImplementation libs.mockito.core - testImplementation libs.spring.test - testImplementation libs.spring.context.support - testImplementation libs.logback.classic -} - -cyclonedxBom { - includeConfigs = ["runtimeClasspath"] - skipConfigs = ["compileClasspath", "testCompileClasspath"] - skipProjects = [] - projectType = "library" - schemaVersion = "1.5" - destination = file("build/reports") - outputName = "bom" - outputFormat = "json" - //noinspection UnnecessaryQualifiedReference - final def attachmentText = new org.cyclonedx.model.AttachmentText() - attachmentText.setText(file("LICENSE").readBytes().encodeBase64().toString()) - attachmentText.setEncoding("base64") - attachmentText.setContentType("text/plain") - //noinspection UnnecessaryQualifiedReference - final def license = new org.cyclonedx.model.License() - license.setName(project.ext.licenseName) - license.setLicenseText(attachmentText) - license.setUrl(project.ext.licenseUrl) - setLicenseChoice { - it.addLicense(license) - } -} - -licensee { - allow("Apache-2.0") - allow("MIT") -} - -tasks.register('copyLegalDocs', Copy.class) { - from file("${projectDir}/LICENSE") - from layout.buildDirectory.file("reports/licensee/artifacts.json").get().asFile - from layout.buildDirectory.file("reports/bom.json").get().asFile - into layout.buildDirectory.dir("resources/main/META-INF").get().asFile - rename('artifacts.json', 'dependency-licenses.json') - rename('bom.json', 'SBOM.json') -} -tasks.copyLegalDocs.dependsOn(tasks.licensee) -tasks.copyLegalDocs.dependsOn(tasks.cyclonedxBom) -tasks.javadoc.dependsOn(tasks.copyLegalDocs) -tasks.compileTestJava.dependsOn(tasks.copyLegalDocs) -tasks.checkstyleMain.dependsOn(tasks.copyLegalDocs) -tasks.processResources.finalizedBy(tasks.copyLegalDocs) - -jacocoTestReport { - reports { - xml.required.set(true) - xml.outputLocation.set(layout.buildDirectory.file("reports/jacoco/report.xml").get().asFile) - csv.required.set(false) - html.required.set(true) - html.outputLocation.set(layout.buildDirectory.dir("reports/jacoco/html").get().asFile) - } -} - -test { - useJUnitPlatform() -} -test.finalizedBy jacocoTestReport -jacocoTestReport.finalizedBy jacocoTestCoverageVerification - -jacoco { - toolVersion = libs.versions.jacoco.get() -} - -jacocoTestCoverageVerification { - inputs.file(layout.buildDirectory.file("reports/jacoco/report.xml").get().asFile) - outputs.file(layout.buildDirectory.file("reports/jacoco/jacocoTestCoverageVerification").get().asFile) - - violationRules { - rule { - limit { - counter = 'LINE' - value = 'COVEREDRATIO' - minimum = 0.8 - } - limit { - counter = 'BRANCH' - value = 'COVEREDRATIO' - minimum = 0.8 - } - excludes = [ - ] - } - rule { - element = 'CLASS' - limit { - counter = 'LINE' - value = 'COVEREDRATIO' - minimum = 0.5 - } - limit { - counter = 'BRANCH' - value = 'COVEREDRATIO' - minimum = 0.5 - } - excludes = [ - "com.github.nagyesta.cacheonly.raw.BatchServiceCaller", - "com.github.nagyesta.cacheonly.transform.NoOpPartialCacheSupport" - ] - } - } - doLast { - layout.buildDirectory.file("reports/jacoco/jacocoTestCoverageVerification").get().asFile.write("Passed") - } -} -jar.dependsOn check - -tasks.withType(Checkstyle).configureEach { - configProperties = [base_dir: rootDir.toString(), cache_file: layout.buildDirectory.file("checkstyle/cacheFile").get().asFile] - reports { - xml.required.set(false) - html.required.set(true) - html.stylesheet resources.text - .fromFile(rootProject.file('config/checkstyle/checkstyle-stylesheet.xsl') as String) - } -} -checkstyle.toolVersion = libs.versions.checkstyle.get() - -nexusPublishing { - repositories { - sonatype { - username = project.ext.ossrhUser - password = project.ext.ossrhPass - } - } -} - -publishing { - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/nagyesta/cache-only") - credentials { - username = project.ext.gitUser - password = project.ext.gitToken - } - } - } - publications { - //noinspection GroovyAssignabilityCheck - mavenJava(MavenPublication) { - from components.java - artifactId = "${project.name}" - pom { - name = "${project.artifactDisplayName}" - description = "${project.artifactDescription}" - url = project.ext.repoUrl - licenses { - license { - name = project.ext.licenseName - url = project.ext.licenseUrl - } - } - developers { - developer { - id = project.ext.maintainerId - name = project.ext.maintainerName - url = project.ext.maintainerUrl - } - } - scm { - connection = project.ext.scmConnection - developerConnection = project.ext.scmConnection - url = project.ext.scmProjectUrl - } - withXml { - //noinspection GroovyImplicitNullArgumentCall - asNode().dependencies.'*'.findAll() { - it.scope.text() == 'runtime' - }.each { it.scope*.value = 'compile' } - } - } - } - } -} - - -//Disable metadata publishing and rely on Maven only -tasks.withType(GenerateModuleMetadata).configureEach { - enabled = false -} - -ossIndexAudit { - username = rootProject.ext.ossIndexUser - password = rootProject.ext.ossIndexPass - printBanner = false - colorEnabled = true - showAll = false - outputFormat = 'DEPENDENCY_GRAPH' - excludeVulnerabilityIds = rootProject.ext.ossIndexExclusions -} - -signing { - sign publishing.publications.mavenJava -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..b833e4f --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,352 @@ +@file:Suppress("SpellCheckingInspection") + +import groovy.util.Node +import groovy.util.NodeList +import org.apache.tools.ant.filters.ReplaceTokens +import org.sonatype.gradle.plugins.scan.ossindex.OutputFormat +import java.util.* + +plugins { + id("java") + jacoco + checkstyle + signing + `maven-publish` + alias(libs.plugins.lombok) + alias(libs.plugins.versioner) + alias(libs.plugins.index.scan) + alias(libs.plugins.owasp.dependencycheck) + alias(libs.plugins.cyclonedx.bom) + alias(libs.plugins.licensee.plugin) + alias(libs.plugins.nexus.publish.plugin) +} + +group = "com.github.nagyesta" + +apply("config/ossindex/ossIndexAudit.gradle.kts") + +buildscript { + fun optionalPropertyString(name: String): String { + return if (project.hasProperty(name)) { + project.property(name) as String + } else { + "" + } + } + + fun dockerAbortGroups(name: String): String { + return if (project.hasProperty(name)) { + "all" + } else { + "" + } + } + + extra.apply { + set("gitToken", optionalPropertyString("githubToken")) + set("gitUser", optionalPropertyString("githubUser")) + set("ossrhUser", optionalPropertyString("ossrhUsername")) + set("ossrhPass", optionalPropertyString("ossrhPassword")) + set("ossIndexUser", optionalPropertyString("ossIndexUsername")) + set("ossIndexPass", optionalPropertyString("ossIndexPassword")) + set("artifactDisplayName", "Cache-Only") + set( + "artifactDescription", + "Cache-Only is a minimal library augmenting the Spring cache abstraction with a way for caching bulk API calls." + ) + set("repoUrl", "https://github.com/nagyesta/cache-only") + set("licenseName", "MIT License") + set("licenseUrl", "https://raw.githubusercontent.com/nagyesta/cache-only/main/LICENSE") + set("maintainerId", "nagyesta") + set("maintainerName", "Istvan Zoltan Nagy") + set("maintainerUrl", "https://github.com/nagyesta/") + set("scmConnection", "scm:git:https://github.com/nagyesta/cache-only.git") + set("scmProjectUrl", "https://github.com/nagyesta/cache-only/") + set("githubMavenRepoUrl", "https://maven.pkg.github.com/nagyesta/cache-only") + set("ossrhMavenRepoUrl", "https://oss.sonatype.org/service/local/staging/deploy/maven2") + } +} + +versioner { + startFrom { + major = 0 + minor = 0 + patch = 1 + } + match { + major = "{major}" + minor = "{minor}" + patch = "{patch}" + } + pattern { + pattern = "%M.%m.%p" + } + git { + authentication { + https { + token = project.extra.get("gitToken").toString() + } + } + } + tag { + prefix = "v" + useCommitMessage = true + } +} + +versioner.apply() + +repositories { + mavenCentral() +} + +dependencies { + annotationProcessor(libs.lombok) + compileOnly(libs.jetbrains.annotations) + testCompileOnly(libs.jetbrains.annotations) + implementation(libs.slf4j.api) + implementation(libs.commons.collections4) + implementation(libs.spring.context.support) + testImplementation(libs.jupiter.core) + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + testImplementation(libs.mockito.core) + testImplementation(libs.spring.test) + testImplementation(libs.spring.context.support) + testImplementation(libs.logback.classic) +} + +licensee { + allow("Apache-2.0") + allow("MIT") + allowUrl("https://opensource.org/license/mit") +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } + withJavadocJar() + withSourcesJar() +} + +val copyLegalDocs = tasks.register("copyLegalDocs") { + from(file("${project.projectDir}/LICENSE")) + from(layout.buildDirectory.file("reports/licensee/artifacts.json").get().asFile) + from(layout.buildDirectory.file("reports/bom.json").get().asFile) + into(layout.buildDirectory.dir("resources/main/META-INF").get().asFile) + rename("artifacts.json", "dependency-licenses.json") + rename("bom.json", "SBOM.json") +}.get() +copyLegalDocs.dependsOn(tasks.licensee) +copyLegalDocs.dependsOn(tasks.cyclonedxBom) +tasks.javadoc.get().dependsOn(copyLegalDocs) +tasks.compileJava.get().dependsOn(copyLegalDocs) +tasks.processResources.get().finalizedBy(copyLegalDocs) + +tasks.test { + useJUnitPlatform() + finalizedBy(tasks.getByName("jacocoTestReport")) +} + +project.tasks.processResources { + val tokens = mapOf("version" to project.version) + filesMatching("**/application.properties") { + filter("tokens" to tokens) + } +} + +tasks.javadoc.configure { + (options as StandardJavadocDocletOptions).addBooleanOption("Xdoclint:none", true) + (options as StandardJavadocDocletOptions).addBooleanOption("Xdoclint:-missing", true) +} + +jacoco { + toolVersion = project.libs.versions.jacoco.get() +} + +tasks.jacocoTestReport { + reports { + xml.required.set(true) + xml.outputLocation.set(layout.buildDirectory.file("reports/jacoco/report.xml")) + csv.required.set(false) + html.required.set(true) + html.outputLocation.set(layout.buildDirectory.dir("reports/jacoco/html")) + } + dependsOn(tasks.test) + finalizedBy(tasks.getByName("jacocoTestCoverageVerification")) +} + +tasks.withType().configureEach { + inputs.file(layout.buildDirectory.file("reports/jacoco/report.xml")) + outputs.file(layout.buildDirectory.file("reports/jacoco/jacocoTestCoverageVerification")) + + violationRules { + rule { + limit { + counter = "LINE" + value = "COVEREDRATIO" + minimum = BigDecimal.valueOf(0.8) + } + limit { + counter = "BRANCH" + value = "COVEREDRATIO" + minimum = BigDecimal.valueOf(0.8) + } + excludes = listOf() + } + rule { + element = "CLASS" + limit { + counter = "LINE" + value = "COVEREDRATIO" + minimum = BigDecimal.valueOf(0.5) + } + limit { + counter = "BRANCH" + value = "COVEREDRATIO" + minimum = BigDecimal.valueOf(0.5) + } + excludes = mutableListOf( + "com.github.nagyesta.cacheonly.raw.BatchServiceCaller", + "com.github.nagyesta.cacheonly.transform.NoOpPartialCacheSupport" + ) + } + } + doLast { + layout.buildDirectory.file("reports/jacoco/jacocoTestCoverageVerification").get().asFile.writeText("Passed") + } +} + +tasks.jar.configure { + dependsOn(tasks.check) +} + +tasks.withType().configureEach { + configProperties = mutableMapOf( + "base_dir" to rootDir.absolutePath.toString(), + "cache_file" to layout.buildDirectory.file("checkstyle/cacheFile").get().asFile.absolutePath.toString() + ) + checkstyle.toolVersion = project.libs.versions.checkstyle.get() + checkstyle.configFile = project.file("config/checkstyle/checkstyle.xml") + reports { + xml.required.set(false) + html.required.set(true) + html.stylesheet = project.resources.text.fromFile("config/checkstyle/checkstyle-stylesheet.xsl") + } +} + +//Disable metadata publishing and rely on Maven only +tasks.withType().configureEach { + enabled = false +} + +ossIndexAudit { + username = project.extra.get("ossIndexUser").toString() + password = project.extra.get("ossIndexPass").toString() + isPrintBanner = false + isColorEnabled = true + isShowAll = false + outputFormat = OutputFormat.DEFAULT + @Suppress("UNCHECKED_CAST") + excludeVulnerabilityIds = project.extra.get("ossIndexExclusions") as MutableSet +} + +tasks.cyclonedxBom { + setProjectType("library") + setIncludeConfigs(listOf("runtimeClasspath")) + setSkipConfigs(listOf("compileClasspath", "testCompileClasspath")) + setSkipProjects(listOf()) + setSchemaVersion("1.5") + setDestination(file("build/reports")) + setOutputName("bom") + setOutputFormat("json") + //noinspection UnnecessaryQualifiedReference + val attachmentText = org.cyclonedx.model.AttachmentText() + attachmentText.text = Base64.getEncoder().encodeToString( + file("${project.project.projectDir}/LICENSE").readBytes() + ) + attachmentText.encoding = "base64" + attachmentText.contentType = "text/plain" + //noinspection UnnecessaryQualifiedReference + val license = org.cyclonedx.model.License() + license.name = "MIT License" + license.setLicenseText(attachmentText) + license.url = "https://raw.githubusercontent.com/nagyesta/cache-only/main/LICENSE" + setLicenseChoice { + it.addLicense(license) + } +} + +checkstyle { + toolVersion = project.libs.versions.checkstyle.get() +} + +nexusPublishing { + repositories { + sonatype { + username = project.extra.get("ossrhUser").toString() + password = project.extra.get("ossrhPass").toString() + } + } +} + +publishing { + repositories { + maven { + name = "GitHubPackages" + url = uri(project.extra.get("githubMavenRepoUrl").toString()) + credentials { + username = project.extra.get("gitUser").toString() + password = project.extra.get("gitToken").toString() + } + } + } + publications { + create("mavenJava") { + from(components["java"]) + artifactId = project.name + pom { + name.set(project.extra.get("artifactDisplayName").toString()) + description.set(project.extra.get("artifactDescription").toString()) + url.set(project.extra.get("repoUrl").toString()) + packaging = "jar" + licenses { + license { + name.set(project.extra.get("licenseName").toString()) + url.set(project.extra.get("licenseUrl").toString()) + } + } + developers { + developer { + id.set(project.extra.get("maintainerId").toString()) + name.set(project.extra.get("maintainerName").toString()) + email.set(project.extra.get("maintainerUrl").toString()) + } + } + scm { + connection.set(project.extra.get("scmConnection").toString()) + developerConnection.set(project.extra.get("scmConnection").toString()) + url.set(project.extra.get("scmProjectUrl").toString()) + } + } + pom.withXml { + asNode().apply { + (get("dependencies") as NodeList).forEach { depsNode -> + ((depsNode as Node).get("dependency") as NodeList).forEach { depNode -> + ((depNode as Node).get("scope") as NodeList).forEach { scope -> + if (scope is Node && "runtime" == scope.text()) { + scope.setValue("compile") + } + } + } + } + } + } + } + } +} + +signing { + sign(publishing.publications["mavenJava"]) +} diff --git a/config/ossindex/ossIndexAudit.gradle b/config/ossindex/ossIndexAudit.gradle deleted file mode 100644 index bb25bd9..0000000 --- a/config/ossindex/ossIndexAudit.gradle +++ /dev/null @@ -1,10 +0,0 @@ -def readExclusions() { - return rootProject.file("config/ossindex/exclusions.txt").readLines() - .stream() - .filter(s -> !s.isBlank()) - .toArray() -} - -project.ext { - ossIndexExclusions = readExclusions() -} diff --git a/config/ossindex/ossIndexAudit.gradle.kts b/config/ossindex/ossIndexAudit.gradle.kts new file mode 100644 index 0000000..f855baa --- /dev/null +++ b/config/ossindex/ossIndexAudit.gradle.kts @@ -0,0 +1,11 @@ +buildscript { + fun readExclusions(): MutableSet { + return rootProject.file("config/ossindex/exclusions.txt").readLines() + .stream() + .toList() + .filter { it.isNotBlank() } + .toMutableSet() + } + + extra.set("ossIndexExclusions", readExclusions()) +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index b99007c..d2c6b01 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,5 +1,5 @@ [versions] -slf4j = "2.0.16" +slf4j = "2.0.17" logback = "1.5.17" spring = "6.2.3" commonsCollections = "4.4" @@ -13,8 +13,8 @@ gitVersionerPlugin = "1.6.7" indexScanPlugin = "3.0.0" owaspPlugin = "12.1.0" -checkstyle = "10.12.2" -jacoco = "0.8.10" +checkstyle = "10.21.4" +jacoco = "0.8.12" cycloneDxBomPlugin = "2.2.0" licenseePlugin = "1.12.0" nexusPublishPlugin = "2.0.0" @@ -29,6 +29,10 @@ jupiter-core = { module = "org.junit.jupiter:junit-jupiter", version.ref = "jupi mockito-core = { module = "org.mockito:mockito-core", version.ref = "mockitoCore" } lombok = { module = "org.projectlombok:lombok", version.ref = "lombok" } jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrainsAnnotation" } +# used by Renovate +checkstyle = { module = "com.puppycrawl.tools:checkstyle", version.ref = "checkstyle" } +# used by Renovate +jacoco = { module = "org.jacoco:org.jacoco.core", version.ref = "jacoco" } [plugins] lombok = { id = "io.freefair.lombok", version.ref = "lombokPlugin" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index e475e82..bc297c6 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -36,14 +36,6 @@ - - - - - - - - @@ -60,14 +52,6 @@ - - - - - - - - @@ -81,11 +65,6 @@ - - - - - @@ -316,11 +295,6 @@ - - - - - @@ -365,18 +339,7 @@ - - - - - - - - - - - @@ -400,9 +363,6 @@ - - - @@ -415,14 +375,6 @@ - - - - - - - - @@ -433,11 +385,6 @@ - - - - - @@ -470,9 +417,6 @@ - - - @@ -564,12 +508,12 @@ - - - + + + - - + + @@ -614,6 +558,14 @@ + + + + + + + + @@ -746,22 +698,12 @@ - - - - - - - - - - - + + + - - - - + + @@ -769,16 +711,6 @@ - - - - - - - - - - @@ -799,11 +731,6 @@ - - - - - @@ -893,14 +820,6 @@ - - - - - - - - @@ -953,12 +872,12 @@ - - - + + + - - + + @@ -969,9 +888,9 @@ - - - + + + @@ -979,12 +898,12 @@ - - - + + + - - + + @@ -1208,6 +1127,11 @@ + + + + + @@ -1330,14 +1254,6 @@ - - - - - - - - @@ -1351,11 +1267,6 @@ - - - - - @@ -1369,14 +1280,6 @@ - - - - - - - - @@ -1393,14 +1296,6 @@ - - - - - - - - @@ -1414,16 +1309,6 @@ - - - - - - - - - - @@ -1754,16 +1639,16 @@ - - - - - + + + + + @@ -1903,21 +1788,11 @@ - - - - - - - - - - @@ -2011,41 +1886,41 @@ - - - + + + - - + + - - - + + + - - + + - - - + + + - - - + + + - - + + - - - + + + - - + + @@ -2069,12 +1944,12 @@ - - - + + + - - + + @@ -2238,84 +2113,41 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -2360,6 +2192,14 @@ + + + + + + + + @@ -2368,9 +2208,9 @@ - - - + + + @@ -2381,6 +2221,14 @@ + + + + + + + + @@ -2394,6 +2242,14 @@ + + + + + + + + @@ -2402,14 +2258,6 @@ - - - - - - - - @@ -2418,34 +2266,16 @@ - - - - - - - - - - - - - - - - - - @@ -2454,11 +2284,6 @@ - - - - - @@ -2783,12 +2608,12 @@ - - - + + + - - + + diff --git a/settings.gradle b/settings.gradle deleted file mode 100644 index 890d238..0000000 --- a/settings.gradle +++ /dev/null @@ -1 +0,0 @@ -rootProject.name = 'cache-only' diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..b737664 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "cache-only" diff --git a/src/main/java/com/github/nagyesta/cacheonly/core/AbstractCacheServiceTemplate.java b/src/main/java/com/github/nagyesta/cacheonly/core/AbstractCacheServiceTemplate.java index eff25a3..34207a7 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/core/AbstractCacheServiceTemplate.java +++ b/src/main/java/com/github/nagyesta/cacheonly/core/AbstractCacheServiceTemplate.java @@ -16,13 +16,7 @@ import org.slf4j.LoggerFactory; import org.springframework.util.Assert; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; +import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; @@ -36,7 +30,7 @@ * @param The type of the partial request. * @param The type of the partial response. * @param The type of the cache key. - * @param The type of the Id which allows unique association of partial request + * @param The type of the ID which allows unique association of partial request * and partial response pairs in the scope of the batch. */ public abstract class AbstractCacheServiceTemplate, @@ -63,9 +57,10 @@ public AbstractCacheServiceTemplate( @Nullable @Override - public BS callCacheableBatchService(final @NotNull BR request) throws BatchServiceException { - final long start = System.currentTimeMillis(); - Map requestMap = batchRequestTransformer.splitToPartialRequest(request); + public BS callCacheableBatchService( + final @NotNull BR request) throws BatchServiceException { + final var start = System.currentTimeMillis(); + var requestMap = batchRequestTransformer.splitToPartialRequest(request); try { logger.info("Processing batch of {} partial requests.", requestMap.size()); logger.trace("Processing batch of partial requests with ids: {}", requestMap.keySet()); @@ -82,16 +77,17 @@ public BS callCacheableBatchService(final @NotNull BR request) throws BatchServi fromCache.putAll(fetchAllFromOriginService(requestMap)); return batchResponseTransformer.mergeToBatchResponse(fromCache); } finally { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().debug("Total execution completed under {} ms.", end - start); } } @Nullable @Override - public BS callBatchServiceAndPutAllToCache(final @NotNull BR request) throws BatchServiceException { - final Map requestMap = batchRequestTransformer.splitToPartialRequest(request); - final Map response = fetchAllFromOriginService(requestMap); + public BS callBatchServiceAndPutAllToCache( + final @NotNull BR request) throws BatchServiceException { + final var requestMap = batchRequestTransformer.splitToPartialRequest(request); + final var response = fetchAllFromOriginService(requestMap); return batchResponseTransformer.mergeToBatchResponse(response); } @@ -103,12 +99,13 @@ public BS callBatchServiceAndPutAllToCache(final @NotNull BR request) throws Bat * @throws BatchServiceException When the resolution failed. */ @NotNull - protected Map fetchAllFromOriginService(final @NotNull Map requestMap) throws BatchServiceException { + protected Map fetchAllFromOriginService( + final @NotNull Map requestMap) throws BatchServiceException { final Map response; if (requestMap.isEmpty()) { response = Collections.emptyMap(); } else { - final List> partitions = partitionOriginRequests(requestMap); + final var partitions = partitionOriginRequests(requestMap); metricsCollector.partitionsCreated(partitions.size()); try { response = callOriginWithPartitions(partitions); @@ -129,19 +126,21 @@ protected Map fetchAllFromOriginService(final @NotNull Map request * @throws BatchServiceException When the origin call failed. */ @NotNull - protected abstract Map callOriginWithPartitions(@NotNull List> requestPartitions) throws BatchServiceException; + protected abstract Map callOriginWithPartitions( + @NotNull List> requestPartitions) throws BatchServiceException; /** * Evaluates whether the refresh strategy allows us to put to the cache and performs - * a put with all of the responses if it is allowed. + * a put with all the responses if it is allowed. * * @param strategy The refresh strategy. * @param request The request we need to use to find the cache keys when we put items into the cache. * @param response The response we need to put into the cache. */ - protected void populateCacheWithResponse(final @NotNull CacheRefreshStrategy strategy, - final @NotNull Map request, - final @NotNull Map response) { + protected void populateCacheWithResponse( + final @NotNull CacheRefreshStrategy strategy, + final @NotNull Map request, + final @NotNull Map response) { if (strategy.allowsCachePut()) { logger.trace("Responses passed for cache PUT with ids: {}", response.keySet()); logger.trace("Requests passed for cache PUT with ids: {}", request.keySet()); @@ -158,8 +157,8 @@ protected void populateCacheWithResponse(final @NotNull CacheRefreshStrategy str @NotNull private List> partitionOriginRequests(final @NotNull Map requestMap) { - final ArrayList keyList = new ArrayList<>(requestMap.keySet()); - final List> partitions = ListUtils.partition(keyList, batchServiceCaller.maxPartitionSize()); + final var keyList = new ArrayList<>(requestMap.keySet()); + final var partitions = ListUtils.partition(keyList, batchServiceCaller.maxPartitionSize()); logger.debug("Created {} partitions.", partitions.size()); return partitions.stream() .map(p -> p.stream().collect(Collectors.toMap(Function.identity(), requestMap::get))) @@ -167,8 +166,10 @@ private List> partitionOriginRequests(final @NotNull Map reque } @NotNull - private Map selectRemainingKeysToFetchFromOrigin(final @NotNull Map requestMap, final Map fromCache) { - final Set toBeFetched = batchServiceCaller.refreshStrategy() + private Map selectRemainingKeysToFetchFromOrigin( + final @NotNull Map requestMap, + final Map fromCache) { + final var toBeFetched = batchServiceCaller.refreshStrategy() .selectItemsForFetch(requestMap.keySet(), fromCache.keySet(), batchServiceCaller.maxPartitionSize()); logger.trace("Fetch will be performed for ids: {}", toBeFetched); logger.debug("Fetch will be performed for {} items.", toBeFetched.size()); @@ -177,8 +178,10 @@ private Map selectRemainingKeysToFetchFromOrigin(final @NotNull Map attemptFetchingFromCache(final @NotNull Map requestMap, - final @NotNull CacheRefreshStrategy strategy) throws CacheMissException { + private Map attemptFetchingFromCache( + final @NotNull Map requestMap, + final @NotNull CacheRefreshStrategy strategy) + throws CacheMissException { final Map result = new HashMap<>(); if (strategy.allowsCacheGet()) { metricsCollector.cacheGet(requestMap.size()); @@ -203,8 +206,10 @@ private Map attemptFetchingFromCache(final @NotNull Map requestMap * @throws CacheMissException When a request is not found and the strategy does not allow us to continue. */ @NotNull - protected abstract Map fetchAllFromCache(@NotNull CacheRefreshStrategy strategy, - @NotNull Map requestMap) throws CacheMissException; + protected abstract Map fetchAllFromCache( + @NotNull CacheRefreshStrategy strategy, + @NotNull Map requestMap) + throws CacheMissException; /** * Attempts to fetch a single entry from cache. @@ -215,13 +220,15 @@ protected abstract Map fetchAllFromCache(@NotNull CacheRefreshStrategy st * @throws CacheMissException When the request is not found and the strategy does not allow us to continue. */ @NotNull - protected Optional fetchOneFromCache(final @NotNull CacheRefreshStrategy strategy, - final @NotNull PR request) throws CacheMissException { - final Optional> key = Optional.ofNullable(partialCacheSupport.toCacheKey(request)); - final Optional fromCache = key.map(partialCacheSupport::getFromCache); - if (!fromCache.isPresent()) { + protected Optional fetchOneFromCache( + final @NotNull CacheRefreshStrategy strategy, + final @NotNull PR request) + throws CacheMissException { + final var key = Optional.ofNullable(partialCacheSupport.toCacheKey(request)); + final var fromCache = key.map(partialCacheSupport::getFromCache); + if (fromCache.isEmpty()) { if (strategy.shouldFailOnMiss()) { - throw new CacheMissException("Item with id not found in cache: " + key.map(CacheKey::getId).orElse(null)); + throw new CacheMissException("Item with id not found in cache: " + key.map(CacheKey::id).orElse(null)); } key.ifPresent(k -> logger.trace("Cache miss observed for key: {}", k)); } @@ -238,8 +245,10 @@ protected Optional fetchOneFromCache(final @NotNull CacheRefreshStrategy str * @throws BatchServiceException When the origin call fails. */ @NotNull - protected Map fetchSinglePartitionFromOrigin(final @NotNull Map requestMap, - final @NotNull CacheRefreshStrategy strategy) throws BatchServiceException { + protected Map fetchSinglePartitionFromOrigin( + final @NotNull Map requestMap, + final @NotNull CacheRefreshStrategy strategy) + throws BatchServiceException { final Map response = new HashMap<>(doFetchFromOrigin(requestMap)); logger().trace("Responses fetched for ids: {}", response.keySet()); logger().debug("Responses fetched for {} items.", response.size()); @@ -248,11 +257,13 @@ protected Map fetchSinglePartitionFromOrigin(final @NotNull Map re } @NotNull - private Map doFetchFromOrigin(final @NotNull Map requestMap) throws BatchServiceException { - final Optional
batchRequest = Optional.ofNullable(batchRequestTransformer().mergeToBatchRequest(requestMap)); + private Map doFetchFromOrigin( + final @NotNull Map requestMap) + throws BatchServiceException { + final var batchRequest = Optional.ofNullable(batchRequestTransformer().mergeToBatchRequest(requestMap)); Map response = Collections.emptyMap(); if (batchRequest.isPresent()) { - final Optional listResponse = Optional.ofNullable(batchServiceCaller().callBatchService(batchRequest.get())); + final var listResponse = Optional.ofNullable(batchServiceCaller().callBatchService(batchRequest.get())); response = listResponse.map(batchResponseTransformer()::splitToPartialResponse).orElse(Collections.emptyMap()); } return response; @@ -278,7 +289,8 @@ protected final Logger logger() { return logger; } - public final void setMetricsCollector(final BatchServiceCallMetricCollector metricsCollector) { + public final void setMetricsCollector( + final BatchServiceCallMetricCollector metricsCollector) { this.metricsCollector = metricsCollector; } } diff --git a/src/main/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategy.java b/src/main/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategy.java index 0449ce4..e126905 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategy.java +++ b/src/main/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategy.java @@ -4,11 +4,7 @@ import org.jetbrains.annotations.NotNull; import org.springframework.util.Assert; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; /** * Defines the supported strategies used for refreshing the cache using batch calls. @@ -22,9 +18,10 @@ public enum CacheRefreshStrategy { CACHE_ONLY { @NotNull @Override - public Set selectItemsForFetch(final @NotNull Set allRequestIds, - final @NotNull Set idsFoundInCache, - final int maxPartitionSize) { + public Set selectItemsForFetch( + final @NotNull Set allRequestIds, + final @NotNull Set idsFoundInCache, + final int maxPartitionSize) { assertInputIsValid(allRequestIds, idsFoundInCache, maxPartitionSize); return Collections.emptySet(); } @@ -42,13 +39,14 @@ public Set selectItemsForFetch(final @NotNull Set allRequestIds, OPPORTUNISTIC { @NotNull @Override - public Set selectItemsForFetch(final @NotNull Set allRequestIds, - final @NotNull Set idsFoundInCache, - final int maxPartitionSize) { + public Set selectItemsForFetch( + final @NotNull Set allRequestIds, + final @NotNull Set idsFoundInCache, + final int maxPartitionSize) { assertInputIsValid(allRequestIds, idsFoundInCache, maxPartitionSize); final Set result = new HashSet<>(SetUtils.difference(allRequestIds, idsFoundInCache)); - if (result.size() > 0) { - final int mustBeInLastPartition = result.size() % maxPartitionSize; + if (!result.isEmpty()) { + final var mustBeInLastPartition = result.size() % maxPartitionSize; final List fetchExtra = new ArrayList<>(idsFoundInCache); Collections.shuffle(fetchExtra); fetchExtra.stream() @@ -60,7 +58,7 @@ public Set selectItemsForFetch(final @NotNull Set allRequestIds, }, /** * If any of the items were not found in the cache, it won't even try the rest of the - * cached items and will call the real service for all of the items. This can reduce + * cached items and will call the real service for all the items. This can reduce * the overhead spent on caching when we know cache miss occurrences are likely signaling * a larger number of items missing. */ @@ -72,9 +70,10 @@ public boolean shouldFailOnMiss() { @NotNull @Override - public Set selectItemsForFetch(final @NotNull Set allRequestIds, - final @NotNull Set idsFoundInCache, - final int maxPartitionSize) { + public Set selectItemsForFetch( + final @NotNull Set allRequestIds, + final @NotNull Set idsFoundInCache, + final int maxPartitionSize) { assertInputIsValid(allRequestIds, idsFoundInCache, maxPartitionSize); Set result = SetUtils.difference(allRequestIds, idsFoundInCache); if (!result.isEmpty()) { @@ -129,27 +128,29 @@ public boolean allowsCachePut() { } /** - * Filters the set of request Ids considering the Ids found in the cache and the maximum + * Filters the set of request IDs considering the IDs found in the cache and the maximum * partition size. depending on the current strategy, we can decide to keep all or none - * of the request Ids selected for fetching (or anything in between these two extremes). + * of the request IDs selected for fetching (or anything in between these two extremes). * - * @param allRequestIds The set of all partial request Ids in the batch. - * @param idsFoundInCache The set of all partial request Ids we have found in cache. + * @param allRequestIds The set of all partial request IDs in the batch. + * @param idsFoundInCache The set of all partial request IDs we have found in cache. * @param maxPartitionSize The maximum partition size we can use in a single batch. * @param The type of the request Id. - * @return The set of request Ids we want to fetch. + * @return The set of request IDs we want to fetch. */ @NotNull - public Set selectItemsForFetch(final @NotNull Set allRequestIds, - final @NotNull Set idsFoundInCache, - final int maxPartitionSize) { + public Set selectItemsForFetch( + final @NotNull Set allRequestIds, + final @NotNull Set idsFoundInCache, + final int maxPartitionSize) { assertInputIsValid(allRequestIds, idsFoundInCache, maxPartitionSize); return SetUtils.difference(allRequestIds, idsFoundInCache); } - protected void assertInputIsValid(final @NotNull Set allRequestIds, - final @NotNull Set idsFoundInCache, - final int maxPartitionSize) { + protected void assertInputIsValid( + final @NotNull Set allRequestIds, + final @NotNull Set idsFoundInCache, + final int maxPartitionSize) { Assert.notNull(allRequestIds, "AllRequestIds cannot be null."); Assert.noNullElements(allRequestIds.toArray(), "AllRequestIds cannot contain null."); Assert.notNull(idsFoundInCache, "IdsFoundInCache cannot be null."); diff --git a/src/main/java/com/github/nagyesta/cacheonly/core/CachingServiceTemplate.java b/src/main/java/com/github/nagyesta/cacheonly/core/CachingServiceTemplate.java index 5d91ba8..999b3ab 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/core/CachingServiceTemplate.java +++ b/src/main/java/com/github/nagyesta/cacheonly/core/CachingServiceTemplate.java @@ -26,7 +26,7 @@ public interface CachingServiceTemplate { /** * Processes the provided batch request and returns an appropriate batch response. - * Does not read from cache but puts all of the returned partial responses into it. + * Does not read from cache but puts all the returned partial responses into it. * Can be ideal for background cache warm-ups. * * @param request The batch request we need to process. diff --git a/src/main/java/com/github/nagyesta/cacheonly/core/DefaultCacheServiceTemplate.java b/src/main/java/com/github/nagyesta/cacheonly/core/DefaultCacheServiceTemplate.java index 2c24123..41be1c8 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/core/DefaultCacheServiceTemplate.java +++ b/src/main/java/com/github/nagyesta/cacheonly/core/DefaultCacheServiceTemplate.java @@ -20,57 +20,62 @@ * @param The type of the partial request. * @param The type of the partial response. * @param The type of the cache key. - * @param The type of the Id which allows unique association of partial request + * @param The type of the ID which allows unique association of partial request * and partial response pairs in the scope of the batch. */ public class DefaultCacheServiceTemplate extends AbstractCacheServiceTemplate, PartialCacheSupport, BR, BS, PR, PS, C, I> { /** - * Creates a new instance and injects all of the dependencies which are necessary for it to work. + * Creates a new instance and injects all the dependencies which are necessary for it to work. * * @param partialCacheSupport The component defining how caching should work for a partial request. * @param batchRequestTransformer The component handling transformations between batch and partial requests. * @param batchResponseTransformer The component handling transformations between batch and partial responses. * @param batchServiceCaller The wrapper which is calling the real batch service in case of cache miss. */ - public DefaultCacheServiceTemplate(final @NotNull PartialCacheSupport partialCacheSupport, - final @NotNull BatchRequestTransformer batchRequestTransformer, - final @NotNull BatchResponseTransformer batchResponseTransformer, - final @NotNull BatchServiceCaller batchServiceCaller) { + public DefaultCacheServiceTemplate( + final @NotNull PartialCacheSupport partialCacheSupport, + final @NotNull BatchRequestTransformer batchRequestTransformer, + final @NotNull BatchResponseTransformer batchResponseTransformer, + final @NotNull BatchServiceCaller batchServiceCaller) { super(partialCacheSupport, batchRequestTransformer, batchResponseTransformer, batchServiceCaller); } @NotNull @Override - protected Map fetchAllFromCache(final @NotNull CacheRefreshStrategy strategy, - final @NotNull Map requestMap) throws CacheMissException { - final long start = System.currentTimeMillis(); + protected Map fetchAllFromCache( + final @NotNull CacheRefreshStrategy strategy, + final @NotNull Map requestMap) + throws CacheMissException { + final var start = System.currentTimeMillis(); final Map result = new HashMap<>(); try { - for (final Map.Entry entry : requestMap.entrySet()) { + for (final var entry : requestMap.entrySet()) { fetchOneFromCache(strategy, entry.getValue()) .ifPresent(v -> result.put(entry.getKey(), v)); } return result; } finally { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().debug("Fetch all from cache completed under {} ms.", end - start); } } @Override @NotNull - protected Map callOriginWithPartitions(final @NotNull List> requestPartitions) throws BatchServiceException { - final long start = System.currentTimeMillis(); + protected Map callOriginWithPartitions( + final @NotNull List> requestPartitions) + throws BatchServiceException { + final var start = System.currentTimeMillis(); final Map response = new HashMap<>(); try { - for (final Map partitionedMap : requestPartitions) { + for (final var partitionedMap : requestPartitions) { response.putAll(fetchSinglePartitionFromOrigin(partitionedMap, batchServiceCaller().refreshStrategy())); } return response; } finally { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().debug("Fetch all from origin completed under {} ms.", end - start); } } diff --git a/src/main/java/com/github/nagyesta/cacheonly/core/conurrent/ConcurrentCacheServiceTemplate.java b/src/main/java/com/github/nagyesta/cacheonly/core/conurrent/ConcurrentCacheServiceTemplate.java index a125b4e..92017db 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/core/conurrent/ConcurrentCacheServiceTemplate.java +++ b/src/main/java/com/github/nagyesta/cacheonly/core/conurrent/ConcurrentCacheServiceTemplate.java @@ -12,11 +12,7 @@ import java.util.List; import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; +import java.util.concurrent.*; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -29,7 +25,7 @@ * @param The type of the partial request. * @param The type of the partial response. * @param The type of the cache key. - * @param The type of the Id which allows unique association of partial request + * @param The type of the ID which allows unique association of partial request * and partial response pairs in the scope of the batch. */ public class ConcurrentCacheServiceTemplate @@ -41,7 +37,7 @@ public class ConcurrentCacheServiceTemplate private final ForkJoinPool originPool; /** - * Creates a new instance and injects all of the dependencies which are necessary for it to work. + * Creates a new instance and injects all the dependencies which are necessary for it to work. * * @param partialCacheSupport The component defining how caching should work for a partial request. * @param batchRequestTransformer The component handling transformations between batch and partial requests. @@ -60,9 +56,11 @@ public ConcurrentCacheServiceTemplate( @NotNull @Override - protected Map fetchAllFromCache(final @NotNull CacheRefreshStrategy strategy, - final @NotNull Map requestMap) throws CacheMissException { - final long start = System.currentTimeMillis(); + protected Map fetchAllFromCache( + final @NotNull CacheRefreshStrategy strategy, + final @NotNull Map requestMap) + throws CacheMissException { + final var start = System.currentTimeMillis(); final Map result = new ConcurrentHashMap<>(); try { callCacheParallel(strategy, requestMap, result::put); @@ -75,11 +73,11 @@ protected Map fetchAllFromCache(final @NotNull CacheRefreshStrategy strat result.clear(); } } catch (final InterruptedException | TimeoutException e) { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().warn("Cache call stopped after {} (timeout set to {}).", (end - start), partialCacheSupport().timeoutMillis(), e); result.clear(); } finally { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().debug("Fetch all from cache completed under {} ms.", end - start); } return result; @@ -87,9 +85,10 @@ protected Map fetchAllFromCache(final @NotNull CacheRefreshStrategy strat @NotNull @Override - protected Map callOriginWithPartitions(final @NotNull List> requestPartitions) + protected Map callOriginWithPartitions( + final @NotNull List> requestPartitions) throws BatchServiceException { - final long start = System.currentTimeMillis(); + final var start = System.currentTimeMillis(); final Map response = new ConcurrentHashMap<>(); try { callOriginParallel(requestPartitions, response::putAll); @@ -97,19 +96,20 @@ protected Map callOriginWithPartitions(final @NotNull List> re logger().error(e.getCause().getMessage(), e.getCause()); throw new BatchServiceException(e.getCause().getMessage(), e.getCause()); } catch (final InterruptedException | TimeoutException e) { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().warn("Origin call stopped after {} ms (timeout set to {}).", (end - start), batchServiceCaller().timeoutMillis(), e); throw new BatchServiceException("Origin call timed out.", e); } finally { - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); logger().debug("Fetch all from origin completed under {} ms.", end - start); } return response; } - private void callCacheParallel(final @NotNull CacheRefreshStrategy strategy, - final @NotNull Map requestMap, - final @NotNull BiConsumer resultConsumer) + private void callCacheParallel( + final @NotNull CacheRefreshStrategy strategy, + final @NotNull Map requestMap, + final @NotNull BiConsumer resultConsumer) throws InterruptedException, ExecutionException, TimeoutException { cachePool .submit(() -> requestMap.entrySet() @@ -119,8 +119,9 @@ private void callCacheParallel(final @NotNull CacheRefreshStrategy strategy, .get(partialCacheSupport().timeoutMillis(), TimeUnit.MILLISECONDS); } - private void callOriginParallel(final @NotNull List> requestPartitions, - final @NotNull Consumer> responseProcessor) + private void callOriginParallel( + final @NotNull List> requestPartitions, + final @NotNull Consumer> responseProcessor) throws InterruptedException, ExecutionException, TimeoutException { originPool .submit(() -> requestPartitions diff --git a/src/main/java/com/github/nagyesta/cacheonly/entity/CacheKey.java b/src/main/java/com/github/nagyesta/cacheonly/entity/CacheKey.java index 8f84e4a..fd044e6 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/entity/CacheKey.java +++ b/src/main/java/com/github/nagyesta/cacheonly/entity/CacheKey.java @@ -1,74 +1,12 @@ package com.github.nagyesta.cacheonly.entity; -import org.jetbrains.annotations.NotNull; - -import java.util.Objects; -import java.util.StringJoiner; - /** - * Represents a cache key and the Id which can help us find the request / response it belongs to. + * Represents a cache key and the ID which can help us find the request / response it belongs to. * * @param The type of the cache key. - * @param The type of the Id. + * @param The type of the ID. + * @param key The key we use for the cache. + * @param id The ID of the entity. */ -public final class CacheKey { - - private final C key; - private final I id; - - /** - * Creates a new instance. - * - * @param key The cache key value. - * @param id The Id of the partial request this key belongs to. - */ - public CacheKey(final @NotNull C key, final @NotNull I id) { - this.key = key; - this.id = id; - } - - /** - * Returns the cache key value. - * - * @return key - */ - @NotNull - public C getKey() { - return key; - } - - /** - * Returns the partial request Id. - * - * @return id - */ - @NotNull - public I getId() { - return id; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (!(o instanceof CacheKey)) { - return false; - } - final CacheKey cacheKey = (CacheKey) o; - return key.equals(cacheKey.key) && id.equals(cacheKey.id); - } - - @Override - public int hashCode() { - return Objects.hash(key, id); - } - - @Override - public String toString() { - return new StringJoiner(", ", CacheKey.class.getSimpleName() + "[", "]") - .add("key=" + key) - .add("id=" + id) - .toString(); - } +public record CacheKey(C key, I id) { } diff --git a/src/main/java/com/github/nagyesta/cacheonly/raw/concurrent/AsyncBatchServiceCaller.java b/src/main/java/com/github/nagyesta/cacheonly/raw/concurrent/AsyncBatchServiceCaller.java index 99038bf..4851772 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/raw/concurrent/AsyncBatchServiceCaller.java +++ b/src/main/java/com/github/nagyesta/cacheonly/raw/concurrent/AsyncBatchServiceCaller.java @@ -9,6 +9,7 @@ * @param
The type of the batch request. * @param The type of the batch response. */ -public interface AsyncBatchServiceCaller extends BatchServiceCaller, ConcurrentOperationSupport { +public interface AsyncBatchServiceCaller + extends BatchServiceCaller, ConcurrentOperationSupport { } diff --git a/src/main/java/com/github/nagyesta/cacheonly/raw/exception/BatchServiceException.java b/src/main/java/com/github/nagyesta/cacheonly/raw/exception/BatchServiceException.java index c7172b0..417a596 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/raw/exception/BatchServiceException.java +++ b/src/main/java/com/github/nagyesta/cacheonly/raw/exception/BatchServiceException.java @@ -23,8 +23,9 @@ public BatchServiceException(final @NotNull String message) { * @param message The message detailing the failure. * @param cause The cause of the failure. */ - public BatchServiceException(final @NotNull String message, - final @NotNull Throwable cause) { + public BatchServiceException( + final @NotNull String message, + final @NotNull Throwable cause) { super(message, cause); } } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/BatchRequestTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/BatchRequestTransformer.java index 7b60fa1..a39473b 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/BatchRequestTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/BatchRequestTransformer.java @@ -10,7 +10,7 @@ * * @param The type of the batch request. * @param

The type of the partial request. - * @param The type of the Id that can identify a partial request in the scope + * @param The type of the ID that can identify a partial request in the scope * of a batch. */ public interface BatchRequestTransformer { diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/BatchResponseTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/BatchResponseTransformer.java index d43b823..1a7832b 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/BatchResponseTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/BatchResponseTransformer.java @@ -10,7 +10,7 @@ * * @param The type of the batch response. * @param

The type of the partial response. - * @param The type of the Id that can identify a partial response and pair it + * @param The type of the ID that can identify a partial response and pair it * with a partial request of a batch request we try to respond to. */ public interface BatchResponseTransformer { diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/NoOpPartialCacheSupport.java b/src/main/java/com/github/nagyesta/cacheonly/transform/NoOpPartialCacheSupport.java index 96b833c..6b48059 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/NoOpPartialCacheSupport.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/NoOpPartialCacheSupport.java @@ -37,7 +37,9 @@ public CacheKey toCacheKey(final @NotNull PR partialRequest) { } @Override - public void putToCache(final @NotNull CacheKey key, final @NotNull PS entity) { + public void putToCache( + final @NotNull CacheKey key, + final @NotNull PS entity) { //noop } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/PartialCacheSupport.java b/src/main/java/com/github/nagyesta/cacheonly/transform/PartialCacheSupport.java index e458a72..3685d99 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/PartialCacheSupport.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/PartialCacheSupport.java @@ -6,6 +6,8 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; +import java.util.Optional; + /** * Defines how a given partial request-response pair should be cached. * @@ -54,7 +56,7 @@ public interface PartialCacheSupport { * * @return The cache */ - @NotNull + @Nullable default Cache obtainCache() { return getCacheManager().getCache(cacheName()); } @@ -66,7 +68,8 @@ default Cache obtainCache() { * @param entity The entity we want to cache. */ default void putToCache(final @NotNull CacheKey key, final @NotNull PS entity) { - obtainCache().put(key.getKey(), entity); + Optional.ofNullable(obtainCache()) + .ifPresent(cache -> cache.put(key.key(), entity)); } /** @@ -77,6 +80,8 @@ default void putToCache(final @NotNull CacheKey key, final @NotNull PS ent */ @Nullable default PS getFromCache(final @NotNull CacheKey key) { - return obtainCache().get(key.getKey(), getEntityClass()); + return Optional.ofNullable(obtainCache()) + .map(cache -> cache.get(key.key(), getEntityClass())) + .orElse(null); } } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractCollectionBasedTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractCollectionBasedTransformer.java index d65b9da..a9b2791 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractCollectionBasedTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractCollectionBasedTransformer.java @@ -27,10 +27,11 @@ public class AbstractCollectionBasedTransformer, P, I> { * Creates a new instance and defines how the {@link Collection} should be collected from a {@link java.util.stream.Stream}. * * @param collectionCollector The {@link Collector} we want to use to get a batch from a stream of elements. - * @param idFunction The transformation that can determine the Id of a given partial request (or response). + * @param idFunction The transformation that can determine the ID of a given partial request (or response). */ - public AbstractCollectionBasedTransformer(final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public AbstractCollectionBasedTransformer( + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { this(collectionCollector, idFunction, false); } @@ -38,12 +39,13 @@ public AbstractCollectionBasedTransformer(final @NotNull Collector coll * Creates a new instance and defines how the {@link Collection} should be collected from a {@link java.util.stream.Stream}. * * @param collectionCollector The {@link Collector} we want to use to get a batch from a stream of elements. - * @param idFunction The transformation that can determine the Id of a given partial request (or response). + * @param idFunction The transformation that can determine the ID of a given partial request (or response). * @param nullIfEmpty Flag telling the implementation whether we want to use null in case of an empty {@link Collection}. */ - public AbstractCollectionBasedTransformer(final @NotNull Collector collectionCollector, - final @NotNull Function idFunction, - final boolean nullIfEmpty) { + public AbstractCollectionBasedTransformer( + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction, + final boolean nullIfEmpty) { this.collectionCollector = collectionCollector; this.idFunction = idFunction; this.nullIfEmpty = nullIfEmpty; diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractMapBasedTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractMapBasedTransformer.java index b319e2a..82b72bc 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractMapBasedTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractMapBasedTransformer.java @@ -10,7 +10,7 @@ /** * Abstract transformer intended to be used in cases when the batch request (or response) - * is a simple {@link Map} of the partial requests (or responses) using the Id as key. + * is a simple {@link Map} of the partial requests (or responses) using the ID as key. * * @param The {@link Map} type used for the batch. * @param

The type of the partial request (or response) payload. @@ -28,7 +28,8 @@ public class AbstractMapBasedTransformer, P, I> { * * @param mergeMapCollector The collector we want to use when we merge partials to a batch. */ - public AbstractMapBasedTransformer(final @NotNull Collector, ?, C> mergeMapCollector) { + public AbstractMapBasedTransformer( + final @NotNull Collector, ?, C> mergeMapCollector) { this(mergeMapCollector, Map.Entry::getKey, Map.Entry::getValue, false); } @@ -42,10 +43,11 @@ public AbstractMapBasedTransformer(final @NotNull Collector, ?, * an Entry to a value in the partial entry. * @param nullIfEmpty True is we need to return null in case we are merging an empty map. */ - public AbstractMapBasedTransformer(final @NotNull Collector, ?, C> mergeMapCollector, - final @NotNull Function, I> splitKeyTransformer, - final @NotNull Function, P> splitValueTransformer, - final boolean nullIfEmpty) { + public AbstractMapBasedTransformer( + final @NotNull Collector, ?, C> mergeMapCollector, + final @NotNull Function, I> splitKeyTransformer, + final @NotNull Function, P> splitValueTransformer, + final boolean nullIfEmpty) { this.mergeMapCollector = mergeMapCollector; this.splitKeyTransformer = splitKeyTransformer; this.splitValueTransformer = splitValueTransformer; diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedCollectionBasedTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedCollectionBasedTransformer.java index f5ab2da..c380fd6 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedCollectionBasedTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedCollectionBasedTransformer.java @@ -20,7 +20,7 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Collection} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public class AbstractWrappedCollectionBasedTransformer, E, I> { @@ -31,37 +31,39 @@ public class AbstractWrappedCollectionBasedTransformer idFunction; /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public AbstractWrappedCollectionBasedTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public AbstractWrappedCollectionBasedTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { this(response -> cloneWrapper(response, instanceSupplier), collectionReadFunction, collectionWriteBiFunction, collectionCollector, idFunction); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public AbstractWrappedCollectionBasedTransformer(final @NotNull Function cloneFunction, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public AbstractWrappedCollectionBasedTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { this.cloneFunction = cloneFunction; this.collectionReadFunction = collectionReadFunction; this.collectionWriteBiFunction = collectionWriteBiFunction; @@ -70,8 +72,10 @@ public AbstractWrappedCollectionBasedTransformer(final @NotNull Function c } @NotNull - private static B cloneWrapper(final @NotNull B batch, final @NotNull Supplier instanceSupplier) { - final B target = instanceSupplier.get(); + private static B cloneWrapper( + final @NotNull B batch, + final @NotNull Supplier instanceSupplier) { + final var target = instanceSupplier.get(); BeanUtils.copyProperties(batch, target); return target; } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedMapBasedTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedMapBasedTransformer.java index 00dffe4..8fd9fb0 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedMapBasedTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/AbstractWrappedMapBasedTransformer.java @@ -20,7 +20,7 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Map} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public abstract class AbstractWrappedMapBasedTransformer, E, I> { @@ -30,32 +30,34 @@ public abstract class AbstractWrappedMapBasedTransformer, private final Collector, ?, C> mapCollector; /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public AbstractWrappedMapBasedTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public AbstractWrappedMapBasedTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { this(request -> cloneWrapper(request, instanceSupplier), mapReadFunction, mapWriteBiFunction, mapCollector); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public AbstractWrappedMapBasedTransformer(final @NotNull Function cloneFunction, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public AbstractWrappedMapBasedTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { this.cloneFunction = cloneFunction; this.mapReadFunction = mapReadFunction; this.mapWriteBiFunction = mapWriteBiFunction; @@ -63,8 +65,10 @@ public AbstractWrappedMapBasedTransformer(final @NotNull Function cloneFun } @NotNull - private static B cloneWrapper(final @NotNull B batch, final @NotNull Supplier instanceSupplier) { - final B target = instanceSupplier.get(); + private static B cloneWrapper( + final @NotNull B batch, + final @NotNull Supplier instanceSupplier) { + final var target = instanceSupplier.get(); BeanUtils.copyProperties(batch, target); return target; } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformer.java index f1f9e5e..57a3be8 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformer.java @@ -25,10 +25,11 @@ public class CollectionBasedRequestTransformer, P, I> * Creates a new instance and defines how the {@link Collection} should be collected from a {@link java.util.stream.Stream}. * * @param collectionCollector The {@link Collector} we want to use to get a batch from a stream of elements. - * @param idFunction The transformation that can determine the Id of a given partial request. + * @param idFunction The transformation that can determine the ID of a given partial request. */ - public CollectionBasedRequestTransformer(final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public CollectionBasedRequestTransformer( + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(collectionCollector, idFunction); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformer.java index 07846bd..0726f99 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformer.java @@ -25,10 +25,11 @@ public class CollectionBasedResponseTransformer, P, I> * Creates a new instance and defines how the {@link Collection} should be collected from a {@link java.util.stream.Stream}. * * @param collectionCollector The {@link Collector} we want to use to get a batch from a stream of elements. - * @param idFunction The transformation that can determine the Id of a given partial response. + * @param idFunction The transformation that can determine the ID of a given partial response. */ - public CollectionBasedResponseTransformer(final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public CollectionBasedResponseTransformer( + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(collectionCollector, idFunction); } @@ -36,12 +37,13 @@ public CollectionBasedResponseTransformer(final @NotNull Collector coll * Creates a new instance and defines how the {@link Collection} should be collected from a {@link java.util.stream.Stream}. * * @param collectionCollector The {@link Collector} we want to use to get a batch from a stream of elements. - * @param idFunction The transformation that can determine the Id of a given partial response. + * @param idFunction The transformation that can determine the ID of a given partial response. * @param nullIfEmpty Flag telling the implementation whether we want to use null in case of an empty {@link Collection}. */ - public CollectionBasedResponseTransformer(final @NotNull Collector collectionCollector, - final @NotNull Function idFunction, - final boolean nullIfEmpty) { + public CollectionBasedResponseTransformer( + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction, + final boolean nullIfEmpty) { super(collectionCollector, idFunction, nullIfEmpty); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformer.java index bd4c283..9a8f460 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformer.java @@ -12,7 +12,7 @@ /** * Abstract transformer intended to be used in cases when the batch request is a - * simple {@link Map} of the partial requests using the Id as key. + * simple {@link Map} of the partial requests using the ID as key. * * @param The {@link Map} type used for the batch. * @param

The type of the partial request payload. @@ -40,9 +40,10 @@ public MapBasedRequestTransformer(final @NotNull Supplier instanceSupplier) { * @param splitValueTransformer The Function we need to use when we split the batch for transforming * an Entry to a value in the partial request entry. */ - public MapBasedRequestTransformer(final @NotNull Collector, ?, C> mergeMapCollector, - final @NotNull Function, I> splitKeyTransformer, - final @NotNull Function, P> splitValueTransformer) { + public MapBasedRequestTransformer( + final @NotNull Collector, ?, C> mergeMapCollector, + final @NotNull Function, I> splitKeyTransformer, + final @NotNull Function, P> splitValueTransformer) { super(mergeMapCollector, splitKeyTransformer, splitValueTransformer, false); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformer.java index 4058c27..80cb1bd 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformer.java @@ -12,7 +12,7 @@ /** * Abstract transformer intended to be used in cases when the batch response is a - * simple {@link Map} of the partial responses using the Id as key. + * simple {@link Map} of the partial responses using the ID as key. * * @param The {@link Map} type used for the batch. * @param

The type of the partial response payload. @@ -40,10 +40,11 @@ public MapBasedResponseTransformer(final @NotNull Supplier instanceSupplier) * an Entry to a value in the partial response entry. * @param nullIfEmpty True is we need to return null in case we are merging an empty map. */ - public MapBasedResponseTransformer(final @NotNull Collector, ?, C> mergeMapCollector, - final @NotNull Function, I> splitKeyTransformer, - final @NotNull Function, P> splitValueTransformer, - final boolean nullIfEmpty) { + public MapBasedResponseTransformer( + final @NotNull Collector, ?, C> mergeMapCollector, + final @NotNull Function, I> splitKeyTransformer, + final @NotNull Function, P> splitValueTransformer, + final boolean nullIfEmpty) { super(mergeMapCollector, splitKeyTransformer, splitValueTransformer, nullIfEmpty); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformer.java index d5bb5d9..48f2483 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformer.java @@ -18,7 +18,7 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Collection} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public class WrappedCollectionBasedRequestTransformer, E, I> extends AbstractWrappedCollectionBasedTransformer @@ -26,36 +26,38 @@ public class WrappedCollectionBasedRequestTransformer /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public WrappedCollectionBasedRequestTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public WrappedCollectionBasedRequestTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(instanceSupplier, collectionReadFunction, collectionWriteBiFunction, collectionCollector, idFunction); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public WrappedCollectionBasedRequestTransformer(final @NotNull Function cloneFunction, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public WrappedCollectionBasedRequestTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(cloneFunction, collectionReadFunction, collectionWriteBiFunction, collectionCollector, idFunction); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformer.java index 0f23c4c..1c45c6d 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformer.java @@ -18,43 +18,45 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Collection} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public class WrappedCollectionBasedResponseTransformer, E, I> extends AbstractWrappedCollectionBasedTransformer implements BatchResponseTransformer { /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public WrappedCollectionBasedResponseTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public WrappedCollectionBasedResponseTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(instanceSupplier, collectionReadFunction, collectionWriteBiFunction, collectionCollector, idFunction); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param collectionReadFunction The function that can read the collection from a batch. * @param collectionWriteBiFunction The function that can write the collection into a batch. * @param collectionCollector The collector creating a new collection from the partial entities. - * @param idFunction The function that can convert an entity to the Id identifying it. + * @param idFunction The function that can convert an entity to the ID identifying it. */ - public WrappedCollectionBasedResponseTransformer(final @NotNull Function cloneFunction, - final @NotNull Function collectionReadFunction, - final @NotNull BiFunction collectionWriteBiFunction, - final @NotNull Collector collectionCollector, - final @NotNull Function idFunction) { + public WrappedCollectionBasedResponseTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function collectionReadFunction, + final @NotNull BiFunction collectionWriteBiFunction, + final @NotNull Collector collectionCollector, + final @NotNull Function idFunction) { super(cloneFunction, collectionReadFunction, collectionWriteBiFunction, collectionCollector, idFunction); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformer.java index 857027e..c1f499a 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformer.java @@ -17,39 +17,41 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Map} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public class WrappedMapBasedRequestTransformer, E, I> extends AbstractWrappedMapBasedTransformer implements BatchRequestTransformer { /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public WrappedMapBasedRequestTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public WrappedMapBasedRequestTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { super(instanceSupplier, mapReadFunction, mapWriteBiFunction, mapCollector); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public WrappedMapBasedRequestTransformer(final @NotNull Function cloneFunction, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public WrappedMapBasedRequestTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { super(cloneFunction, mapReadFunction, mapWriteBiFunction, mapCollector); } diff --git a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformer.java b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformer.java index 12cef12..4ae083e 100644 --- a/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformer.java +++ b/src/main/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformer.java @@ -17,39 +17,41 @@ * @param The type of the batch wrapper class. * @param The type of the {@link Map} holding the values we want to partition. * @param The type of the partial entities. - * @param The type of the Id we can use for partial entity identification. + * @param The type of the ID we can use for partial entity identification. */ public class WrappedMapBasedResponseTransformer, E, I> extends AbstractWrappedMapBasedTransformer implements BatchResponseTransformer { /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param instanceSupplier The {@link Supplier} we can use for getting a new empty batch instance. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public WrappedMapBasedResponseTransformer(final @NotNull Supplier instanceSupplier, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public WrappedMapBasedResponseTransformer( + final @NotNull Supplier instanceSupplier, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { super(instanceSupplier, mapReadFunction, mapWriteBiFunction, mapCollector); } /** - * Creates a new instance and sets all of the parameters we can use for customization. + * Creates a new instance and sets all the parameters we can use for customization. * * @param cloneFunction The function that can clone a batch. * @param mapReadFunction The function that can read the map from a batch. * @param mapWriteBiFunction The function that can write the map into a batch. * @param mapCollector The collector creating a new map from the partial entities. */ - public WrappedMapBasedResponseTransformer(final @NotNull Function cloneFunction, - final @NotNull Function mapReadFunction, - final @NotNull BiFunction mapWriteBiFunction, - final @NotNull Collector, ?, C> mapCollector) { + public WrappedMapBasedResponseTransformer( + final @NotNull Function cloneFunction, + final @NotNull Function mapReadFunction, + final @NotNull BiFunction mapWriteBiFunction, + final @NotNull Collector, ?, C> mapCollector) { super(cloneFunction, mapReadFunction, mapWriteBiFunction, mapCollector); } diff --git a/src/test/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategyTest.java b/src/test/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategyTest.java index 244db60..8e61ecf 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategyTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/core/CacheRefreshStrategyTest.java @@ -5,23 +5,11 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import java.util.Arrays; -import java.util.Collections; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; +import java.util.*; import java.util.stream.Stream; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.CACHE_ONLY; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.NEVER_CACHE; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.OPPORTUNISTIC; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.OPTIMISTIC; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.PESSIMISTIC; -import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.values; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static com.github.nagyesta.cacheonly.core.CacheRefreshStrategy.*; +import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.params.provider.Arguments.of; /** @@ -111,11 +99,12 @@ private static Stream invalidSelectItemProvider() { @ParameterizedTest @MethodSource("cacheUseProvider") void testAllowsCacheGetShouldReturnTheExpectedValueWhenCalled( - final CacheRefreshStrategy underTest, final boolean expected) { + final CacheRefreshStrategy underTest, + final boolean expected) { //given //when - final boolean actual = underTest.allowsCacheGet(); + final var actual = underTest.allowsCacheGet(); //then assertEquals(expected, actual); @@ -124,11 +113,12 @@ void testAllowsCacheGetShouldReturnTheExpectedValueWhenCalled( @ParameterizedTest @MethodSource("failOnMissProvider") void testShouldFailOnMissShouldReturnTheExpectedValueWhenCalled( - final CacheRefreshStrategy underTest, final boolean expected) { + final CacheRefreshStrategy underTest, + final boolean expected) { //given //when - final boolean actual = underTest.shouldFailOnMiss(); + final var actual = underTest.shouldFailOnMiss(); //then assertEquals(expected, actual); @@ -137,11 +127,12 @@ void testShouldFailOnMissShouldReturnTheExpectedValueWhenCalled( @ParameterizedTest @MethodSource("cacheUseProvider") void testAllowsCachePutShouldReturnTheExpectedValueWhenCalled( - final CacheRefreshStrategy underTest, final boolean expected) { + final CacheRefreshStrategy underTest, + final boolean expected) { //given //when - final boolean actual = underTest.allowsCachePut(); + final var actual = underTest.allowsCachePut(); //then assertEquals(expected, actual); @@ -151,12 +142,15 @@ void testAllowsCachePutShouldReturnTheExpectedValueWhenCalled( @MethodSource("validSelectItemProvider") void testSelectItemsForFetchShouldKeepTheExpectedItemsWhenCalledWithValidInput( final CacheRefreshStrategy underTest, - final Set allIds, final Set foundIds, final int partitionSize, - final SortedSet expectedMandatory, final int expectedAdditional) { + final Set allIds, + final Set foundIds, + final int partitionSize, + final SortedSet expectedMandatory, + final int expectedAdditional) { //given //when - final Set actual = underTest.selectItemsForFetch(allIds, foundIds, partitionSize); + final var actual = underTest.selectItemsForFetch(allIds, foundIds, partitionSize); //then final SortedSet common = new TreeSet<>(SetUtils.intersection(actual, expectedMandatory)); @@ -171,7 +165,9 @@ void testSelectItemsForFetchShouldKeepTheExpectedItemsWhenCalledWithValidInput( @MethodSource("invalidSelectItemProvider") void testSelectItemsForFetchShouldThrowExceptionWhenCalledWithInvalidInput( final CacheRefreshStrategy underTest, - final Set allIds, final Set foundIds, final int partitionSize) { + final Set allIds, + final Set foundIds, + final int partitionSize) { //given //when diff --git a/src/test/java/com/github/nagyesta/cacheonly/core/CommentCacheServiceTemplateIntegrationTest.java b/src/test/java/com/github/nagyesta/cacheonly/core/CommentCacheServiceTemplateIntegrationTest.java index 51fcd2b..370caaf 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/core/CommentCacheServiceTemplateIntegrationTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/core/CommentCacheServiceTemplateIntegrationTest.java @@ -10,33 +10,18 @@ import com.github.nagyesta.cacheonly.raw.exception.BatchServiceException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.UUID; +import java.util.*; import static com.github.nagyesta.cacheonly.example.replies.CommentContext.THREADS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = CommentContext.class) @@ -57,7 +42,7 @@ class CommentCacheServiceTemplateIntegrationTest { void testCallCacheableBatchServiceShouldWrapExceptionWhenExceptionCaught() { //given // create the test request - final ThreadRequest request = ThreadRequest.builder() + final var request = ThreadRequest.builder() .articleId(UUID.randomUUID()) .threadIds(Collections.singletonList(1L)) .build(); @@ -70,25 +55,26 @@ void testCallCacheableBatchServiceShouldWrapExceptionWhenExceptionCaught() { @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() throws BatchServiceException { + void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() + throws BatchServiceException { //given // create the test request - final List threadIds = Arrays.asList(1L, 2L, 3L, 4L); - final ThreadRequest request = ThreadRequest.builder() + final var threadIds = Arrays.asList(1L, 2L, 3L, 4L); + final var request = ThreadRequest.builder() .articleId(CommentService.NO_COMMENT) .threadIds(threadIds) .build(); //when - final CommentThreads actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNull(actual); // all items were tried from the cache and missed - final Cache cache = cacheManager.getCache(THREADS); - final InOrder inOrder = Mockito.inOrder(cache); + final var cache = cacheManager.getCache(THREADS); + final var inOrder = Mockito.inOrder(cache); threadIds.forEach(id -> inOrder.verify(cache).get( - eq(CommentService.NO_COMMENT.toString() + "_thread_" + id), + eq(CommentService.NO_COMMENT + "_thread_" + id), eq(CommentThreads.class))); // nothing is put into the cache as all of them are missed inOrder.verify(cache, never()).put(anyString(), any()); @@ -96,107 +82,110 @@ void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() throw @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() throws BatchServiceException, NotFoundException { + void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() + throws BatchServiceException, NotFoundException { //given // create the test request - final List threadIds = Arrays.asList(1L, 2L, 3L, 4L); - final ThreadRequest request = ThreadRequest.builder() + final var threadIds = Arrays.asList(1L, 2L, 3L, 4L); + final var request = ThreadRequest.builder() .articleId(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT) .threadIds(threadIds) .build(); - final CommentThreads expected = commentService.threadsOf(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT, new HashSet<>(threadIds)); + final var expected = commentService.threadsOf(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT, new HashSet<>(threadIds)); //when - final CommentThreads actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); assertEquals(2, actual.getThreads().size()); assertEquals(expected, actual); // all items were tried from the cache and missed - final Cache cache = cacheManager.getCache(THREADS); - final InOrder inOrder = Mockito.inOrder(cache); + final var cache = cacheManager.getCache(THREADS); + final var inOrder = Mockito.inOrder(cache); threadIds.forEach(id -> inOrder.verify(cache).get( - eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT.toString() + "_thread_" + id), + eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT + "_thread_" + id), eq(CommentThreads.class))); // only 1 and 3 are put into the cache as others are nulls - inOrder.verify(cache).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT.toString() + "_thread_1"), any()); - inOrder.verify(cache).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT.toString() + "_thread_3"), any()); - inOrder.verify(cache, never()).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT.toString() + "_thread_2"), any()); - inOrder.verify(cache, never()).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT.toString() + "_thread_4"), any()); + inOrder.verify(cache).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT + "_thread_1"), any()); + inOrder.verify(cache).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT + "_thread_3"), any()); + inOrder.verify(cache, never()).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT + "_thread_2"), any()); + inOrder.verify(cache, never()).put(eq(CommentService.AINT_NOBODY_GOT_TIME_FOR_THAT + "_thread_4"), any()); } @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() throws BatchServiceException, NotFoundException { + void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() + throws BatchServiceException, NotFoundException { //given // create the test request - final List threadIds = Collections.singletonList(1L); - final ThreadRequest request = ThreadRequest.builder() + final var threadIds = Collections.singletonList(1L); + final var request = ThreadRequest.builder() .articleId(CommentService.ARE_YOU_OUT_OF_QUOTA) .threadIds(threadIds) .build(); // fetch expected data - final CommentThreads expected = underTest.callBatchServiceAndPutAllToCache(request); + final var expected = underTest.callBatchServiceAndPutAllToCache(request); // verify it was just put into the cache - final Cache cache = cacheManager.getCache(THREADS); - verify(cache, never()).get(eq(CommentService.ARE_YOU_OUT_OF_QUOTA.toString() + "_thread_1"), eq(List.class)); - verify(cache).put(eq(CommentService.ARE_YOU_OUT_OF_QUOTA.toString() + "_thread_1"), any()); + final var cache = cacheManager.getCache(THREADS); + verify(cache, never()).get(eq(CommentService.ARE_YOU_OUT_OF_QUOTA + "_thread_1"), eq(List.class)); + verify(cache).put(eq(CommentService.ARE_YOU_OUT_OF_QUOTA + "_thread_1"), any()); reset(cache); // the real service is called this time - final CommentService spyService = batchServiceCaller.getCommentService(); + final var spyService = batchServiceCaller.getCommentService(); verify(spyService).threadsOf(eq(CommentService.ARE_YOU_OUT_OF_QUOTA), eq(Collections.singleton(1L))); reset(spyService); //when - final CommentThreads actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); assertEquals(1, actual.getThreads().size()); assertEquals(expected, actual); - // opportunistic processing will not call when all of the items are already cached - verify(cache).get(eq(CommentService.ARE_YOU_OUT_OF_QUOTA.toString() + "_thread_1"), eq(CommentThreads.class)); - verify(cache, never()).put(eq(CommentService.ARE_YOU_OUT_OF_QUOTA.toString() + "_thread_1"), any()); + // opportunistic processing will not call when all the items are already cached + verify(cache).get(eq(CommentService.ARE_YOU_OUT_OF_QUOTA + "_thread_1"), eq(CommentThreads.class)); + verify(cache, never()).put(eq(CommentService.ARE_YOU_OUT_OF_QUOTA + "_thread_1"), any()); // the real service is not called again verify(spyService, never()).threadsOf(eq(CommentService.ARE_YOU_OUT_OF_QUOTA), eq(Collections.singleton(1L))); } @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldUseRealServiceOnlyWhenSomeNotFoundInCache() throws BatchServiceException, NotFoundException { + void testCallCacheableBatchServiceShouldUseRealServiceOnlyWhenSomeNotFoundInCache() + throws BatchServiceException, NotFoundException { //given // warm-up cache - final ThreadRequest warmUpRequest = ThreadRequest.builder() + final var warmUpRequest = ThreadRequest.builder() .articleId(CommentService.CACHING_IS_NOT_ALWAYS_EASY).threadIds(Collections.singletonList(1L)).build(); underTest.callBatchServiceAndPutAllToCache(warmUpRequest); // verify it was just put into the cache - final Cache cache = cacheManager.getCache(THREADS); - verify(cache, never()).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_1"), eq(CommentThreads.class)); - verify(cache, atLeastOnce()).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_1"), any()); + final var cache = cacheManager.getCache(THREADS); + verify(cache, never()).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_1"), eq(CommentThreads.class)); + verify(cache, atLeastOnce()).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_1"), any()); reset(cache); // create the test request - final List threadIds = Arrays.asList(1L, 5L); - final ThreadRequest request = ThreadRequest.builder() + final var threadIds = Arrays.asList(1L, 5L); + final var request = ThreadRequest.builder() .articleId(CommentService.CACHING_IS_NOT_ALWAYS_EASY).threadIds(threadIds).build(); // fetch expected data - final CommentThreads expected = commentService.threadsOf(CommentService.CACHING_IS_NOT_ALWAYS_EASY, new HashSet<>(threadIds)); - final CommentService spyService = batchServiceCaller.getCommentService(); + final var expected = commentService.threadsOf(CommentService.CACHING_IS_NOT_ALWAYS_EASY, new HashSet<>(threadIds)); + final var spyService = batchServiceCaller.getCommentService(); verify(spyService).threadsOf(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY), eq(Collections.singleton(1L))); reset(spyService); //when - final CommentThreads actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); assertEquals(2, actual.getThreads().size()); assertEquals(expected, actual); // opportunistic processing will refresh the already cached value as well - verify(cache).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_1"), eq(CommentThreads.class)); - verify(cache).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_1"), any()); - verify(cache).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_5"), eq(CommentThreads.class)); - verify(cache).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY.toString() + "_thread_5"), any()); + verify(cache).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_1"), eq(CommentThreads.class)); + verify(cache).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_1"), any()); + verify(cache).get(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_5"), eq(CommentThreads.class)); + verify(cache).put(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY + "_thread_5"), any()); // only a single call will be made verify(spyService, never()).threadsOf(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY), eq(Collections.singleton(1L))); verify(spyService, never()).threadsOf(eq(CommentService.CACHING_IS_NOT_ALWAYS_EASY), eq(Collections.singleton(5L))); diff --git a/src/test/java/com/github/nagyesta/cacheonly/core/ParcelCacheServiceTemplateIntegrationTest.java b/src/test/java/com/github/nagyesta/cacheonly/core/ParcelCacheServiceTemplateIntegrationTest.java index 444af59..d35ef0d 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/core/ParcelCacheServiceTemplateIntegrationTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/core/ParcelCacheServiceTemplateIntegrationTest.java @@ -4,7 +4,6 @@ import com.github.nagyesta.cacheonly.example.parcel.ParcelCacheServiceTemplate; import com.github.nagyesta.cacheonly.example.parcel.ParcelContext; import com.github.nagyesta.cacheonly.example.parcel.raw.ParcelBatchServiceCaller; -import com.github.nagyesta.cacheonly.example.parcel.raw.ParcelService; import com.github.nagyesta.cacheonly.example.parcel.response.ParcelResponse; import com.github.nagyesta.cacheonly.raw.exception.BatchServiceException; import org.junit.jupiter.api.BeforeAll; @@ -23,13 +22,8 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = ParcelContext.class) @@ -70,19 +64,21 @@ private static Stream validInputProvider() { @ParameterizedTest @MethodSource("validInputProvider") void testCallCacheableBatchServiceShouldBeSplittingRequestsWhenItHasMoreItemsThanAllowed( - final List ids, final int expectedCalls) throws BatchServiceException { + final List ids, + final int expectedCalls) + throws BatchServiceException { //given // reset spy - final ParcelService spyService = batchServiceCaller.getParcelService(); + final var spyService = batchServiceCaller.getParcelService(); reset(spyService); // create the expected test response - final List expected = ids.stream() + final var expected = ids.stream() .sorted() .map(id -> new ParcelResponse(id, spyService.lookup(id))) .collect(Collectors.toList()); //when - final List actual = underTest.callCacheableBatchService(ids); + final var actual = underTest.callCacheableBatchService(ids); //then if (expectedCalls == 0) { diff --git a/src/test/java/com/github/nagyesta/cacheonly/core/StockCacheServiceTemplateIntegrationTest.java b/src/test/java/com/github/nagyesta/cacheonly/core/StockCacheServiceTemplateIntegrationTest.java index b6f3de0..6f20a8e 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/core/StockCacheServiceTemplateIntegrationTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/core/StockCacheServiceTemplateIntegrationTest.java @@ -7,33 +7,19 @@ import com.github.nagyesta.cacheonly.raw.exception.BatchServiceException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InOrder; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.math.BigDecimal; -import java.util.Arrays; -import java.util.Collections; -import java.util.Map; -import java.util.SortedMap; -import java.util.SortedSet; -import java.util.TreeSet; +import java.util.*; import static com.github.nagyesta.cacheonly.example.stock.StockContext.STOCKS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.verify; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.Mockito.*; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = StockContext.class) @@ -51,20 +37,21 @@ class StockCacheServiceTemplateIntegrationTest { @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() throws BatchServiceException { + void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() + throws BatchServiceException { //given // create the test request final SortedSet request = new TreeSet<>(Arrays.asList("A", "B", "C")); //when - final SortedMap actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); assertEquals(Collections.emptyMap(), actual); // all items were tried from the cache and missed - final Cache cache = cacheManager.getCache(STOCKS); - final InOrder inOrder = Mockito.inOrder(cache); + final var cache = cacheManager.getCache(STOCKS); + final var inOrder = Mockito.inOrder(cache); inOrder.verify(cache).get(eq("price_A"), eq(BigDecimal.class)); // pessimistic strategy aborts after first failure inOrder.verify(cache, never()).get(eq("price_B"), eq(BigDecimal.class)); @@ -75,14 +62,15 @@ void testCallCacheableBatchServiceShouldNotPutAnythingWhenNoResultsFound() throw @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() throws BatchServiceException { + void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() + throws BatchServiceException { //given // create the test request final SortedSet request = new TreeSet<>(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM, "UNKNOWN")); - final Map expected = stockService.lookupNoLimit(request); + final var expected = stockService.lookupNoLimit(request); //when - final SortedMap actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); @@ -90,9 +78,9 @@ void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() throws BatchS assertIterableEquals(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM), actual.keySet()); assertEquals(expected, actual); // all items were tried from the cache and missed - final Cache cache = cacheManager.getCache(STOCKS); - final StockService spyService = batchServiceCaller.getStockService(); - final InOrder inOrder = Mockito.inOrder(cache, spyService); + final var cache = cacheManager.getCache(STOCKS); + final var spyService = batchServiceCaller.getStockService(); + final var inOrder = Mockito.inOrder(cache, spyService); inOrder.verify(cache).get(eq("price_" + StockService.AAPL), eq(BigDecimal.class)); // pessimistic strategy aborts after first failure inOrder.verify(cache, never()).get(eq("price_" + StockService.AMD), eq(BigDecimal.class)); @@ -109,14 +97,15 @@ void testCallCacheableBatchServiceShouldCacheWhenResultsAreFound() throws BatchS @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() throws BatchServiceException { + void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() + throws BatchServiceException { //given // create the test request final SortedSet request = new TreeSet<>(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM)); final Map expected = underTest.callBatchServiceAndPutAllToCache(request); // verify that items where just put into cache - final Cache cache = cacheManager.getCache(STOCKS); - final StockService spyService = batchServiceCaller.getStockService(); + final var cache = cacheManager.getCache(STOCKS); + final var spyService = batchServiceCaller.getStockService(); verify(spyService).lookup(eq(new TreeSet<>(Arrays.asList(StockService.AAPL, StockService.EPAM)))); verify(spyService).lookup(eq(new TreeSet<>(Collections.singletonList(StockService.AMD)))); reset(spyService); @@ -126,7 +115,7 @@ void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() t reset(cache); //when - final SortedMap actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); @@ -134,7 +123,7 @@ void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() t assertIterableEquals(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM), actual.keySet()); assertEquals(expected, actual); // all items were tried from the cache and missed - final InOrder inOrder = Mockito.inOrder(cache, spyService); + final var inOrder = Mockito.inOrder(cache, spyService); inOrder.verify(cache).get(eq("price_" + StockService.AAPL), eq(BigDecimal.class)); inOrder.verify(cache).get(eq("price_" + StockService.EPAM), eq(BigDecimal.class)); inOrder.verify(cache).get(eq("price_" + StockService.AMD), eq(BigDecimal.class)); @@ -148,24 +137,25 @@ void testCallCacheableBatchServiceShouldNotUseRealServiceWhenAllFoundInCache() t @Test @DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD) - void testCallCacheableBatchServiceShouldUseRealServiceOnlyWhenSomeNotFoundInCache() throws BatchServiceException { + void testCallCacheableBatchServiceShouldUseRealServiceOnlyWhenSomeNotFoundInCache() + throws BatchServiceException { //given // create the warm-up request final SortedSet warmUpRequest = new TreeSet<>(Collections.singletonList(StockService.AAPL)); underTest.callBatchServiceAndPutAllToCache(warmUpRequest); // verify that items where just put into cache - final Cache cache = cacheManager.getCache(STOCKS); - final StockService spyService = batchServiceCaller.getStockService(); + final var cache = cacheManager.getCache(STOCKS); + final var spyService = batchServiceCaller.getStockService(); verify(spyService).lookup(eq(new TreeSet<>(Collections.singletonList(StockService.AAPL)))); reset(spyService); verify(cache).put(eq("price_" + StockService.AAPL), any()); reset(cache); // create the test request final SortedSet request = new TreeSet<>(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM)); - final Map expected = stockService.lookupNoLimit(request); + final var expected = stockService.lookupNoLimit(request); //when - final SortedMap actual = underTest.callCacheableBatchService(request); + final var actual = underTest.callCacheableBatchService(request); //then assertNotNull(actual); @@ -173,7 +163,7 @@ void testCallCacheableBatchServiceShouldUseRealServiceOnlyWhenSomeNotFoundInCach assertIterableEquals(Arrays.asList(StockService.AAPL, StockService.AMD, StockService.EPAM), actual.keySet()); assertEquals(expected, actual); // all items were tried from the cache and missed - final InOrder inOrder = Mockito.inOrder(cache, spyService); + final var inOrder = Mockito.inOrder(cache, spyService); inOrder.verify(cache).get(eq("price_" + StockService.AAPL), eq(BigDecimal.class)); inOrder.verify(cache).get(eq("price_" + StockService.EPAM), eq(BigDecimal.class)); // pessimistic strategy aborts after first failure diff --git a/src/test/java/com/github/nagyesta/cacheonly/core/UnstableCacheServiceTemplateTest.java b/src/test/java/com/github/nagyesta/cacheonly/core/UnstableCacheServiceTemplateTest.java index fb94007..69fc44a 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/core/UnstableCacheServiceTemplateTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/core/UnstableCacheServiceTemplateTest.java @@ -14,11 +14,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("checkstyle:MagicNumber") class UnstableCacheServiceTemplateTest { @@ -31,110 +27,110 @@ static void beforeAll() { @Test public void testExceptionsAreHandledWhenBothCacheAndOriginFails() { //given - final UnstableCacheServiceTemplate underTest = new UnstableCacheServiceTemplate(); - final BasicBatchServiceCallMetricCollector metricCollector = new BasicBatchServiceCallMetricCollector(); + final var underTest = new UnstableCacheServiceTemplate(); + final var metricCollector = new BasicBatchServiceCallMetricCollector(); underTest.setMetricsCollector(metricCollector); - final List input = Arrays.asList(0L, 1L, 2L, 3L, 4L); + final var input = Arrays.asList(0L, 1L, 2L, 3L, 4L); //when - final List actual = underTest.callCacheableBatchService(input); + final var actual = underTest.callCacheableBatchService(input); //then assertNull(actual); - assertEquals(metricCollector.getCacheGet(), 5); - assertEquals(metricCollector.getCacheMiss(), 5); - assertEquals(metricCollector.getCacheHit(), 0); - assertEquals(metricCollector.getPartitionCreated(), 1); - assertEquals(metricCollector.getPartitionFailed(), 0); - assertEquals(metricCollector.getPartitionSucceeded(), 1); + assertEquals(5, metricCollector.getCacheGet()); + assertEquals(5, metricCollector.getCacheMiss()); + assertEquals(0, metricCollector.getCacheHit()); + assertEquals(1, metricCollector.getPartitionCreated()); + assertEquals(0, metricCollector.getPartitionFailed()); + assertEquals(1, metricCollector.getPartitionSucceeded()); } @Test public void testExceptionsAreHandledWhenCalledWithEmptyList() { //given - final UnstableCacheServiceTemplate underTest = new UnstableCacheServiceTemplate(); - final BasicBatchServiceCallMetricCollector metricCollector = new BasicBatchServiceCallMetricCollector(); + final var underTest = new UnstableCacheServiceTemplate(); + final var metricCollector = new BasicBatchServiceCallMetricCollector(); underTest.setMetricsCollector(metricCollector); final List input = Collections.emptyList(); //when - final List actual = underTest.callCacheableBatchService(input); + final var actual = underTest.callCacheableBatchService(input); //then assertNull(actual); - assertEquals(metricCollector.getCacheGet(), 0); - assertEquals(metricCollector.getCacheMiss(), 0); - assertEquals(metricCollector.getCacheHit(), 0); - assertEquals(metricCollector.getPartitionCreated(), 0); - assertEquals(metricCollector.getPartitionFailed(), 0); - assertEquals(metricCollector.getPartitionSucceeded(), 0); + assertEquals(0, metricCollector.getCacheGet()); + assertEquals(0, metricCollector.getCacheMiss()); + assertEquals(0, metricCollector.getCacheHit()); + assertEquals(0, metricCollector.getPartitionCreated()); + assertEquals(0, metricCollector.getPartitionFailed()); + assertEquals(0, metricCollector.getPartitionSucceeded()); } @Test @Timeout(value = 60, unit = TimeUnit.MILLISECONDS) public void testExceptionsAreHandledWhenBothCacheAndOriginTimesOut() { //given - final UnstableCacheServiceTemplate underTest = new UnstableCacheServiceTemplate(); - final BasicBatchServiceCallMetricCollector metricCollector = new BasicBatchServiceCallMetricCollector(); + final var underTest = new UnstableCacheServiceTemplate(); + final var metricCollector = new BasicBatchServiceCallMetricCollector(); underTest.setMetricsCollector(metricCollector); - final List input = Arrays.asList(-40L, -31L, -32L, -33L, -44L); + final var input = Arrays.asList(-40L, -31L, -32L, -33L, -44L); //when assertThrows(BatchServiceException.class, () -> underTest.callCacheableBatchService(input)); //then + exception - assertEquals(metricCollector.getCacheGet(), 5); - assertEquals(metricCollector.getCacheMiss(), 5); - assertEquals(metricCollector.getCacheHit(), 0); - assertEquals(metricCollector.getPartitionCreated(), 1); - assertEquals(metricCollector.getPartitionFailed(), 1); - assertEquals(metricCollector.getPartitionSucceeded(), 0); + assertEquals(5, metricCollector.getCacheGet()); + assertEquals(5, metricCollector.getCacheMiss()); + assertEquals(0, metricCollector.getCacheHit()); + assertEquals(1, metricCollector.getPartitionCreated()); + assertEquals(1, metricCollector.getPartitionFailed()); + assertEquals(0, metricCollector.getPartitionSucceeded()); } @Test public void testExceptionsAreHandledWhenCallsResultErrors() { //given - final UnstableCacheServiceTemplate underTest = new UnstableCacheServiceTemplate(); - final BasicBatchServiceCallMetricCollector metricCollector = new BasicBatchServiceCallMetricCollector(); + final var underTest = new UnstableCacheServiceTemplate(); + final var metricCollector = new BasicBatchServiceCallMetricCollector(); underTest.setMetricsCollector(metricCollector); - final List input = Collections.singletonList(-15L); + final var input = Collections.singletonList(-15L); //when assertThrows(BatchServiceException.class, () -> underTest.callCacheableBatchService(input)); //then + exception - assertEquals(metricCollector.getCacheGet(), 1); - assertEquals(metricCollector.getCacheMiss(), 1); - assertEquals(metricCollector.getCacheHit(), 0); - assertEquals(metricCollector.getPartitionCreated(), 1); - assertEquals(metricCollector.getPartitionFailed(), 1); - assertEquals(metricCollector.getPartitionSucceeded(), 0); + assertEquals(1, metricCollector.getCacheGet()); + assertEquals(1, metricCollector.getCacheMiss()); + assertEquals(0, metricCollector.getCacheHit()); + assertEquals(1, metricCollector.getPartitionCreated()); + assertEquals(1, metricCollector.getPartitionFailed()); + assertEquals(0, metricCollector.getPartitionSucceeded()); } @Test public void testHappyCaseIsWorkingWhenFoundInCache() { //given - final UnstableCacheServiceTemplate underTest = new UnstableCacheServiceTemplate(); - final BasicBatchServiceCallMetricCollector metricCollector = new BasicBatchServiceCallMetricCollector(); + final var underTest = new UnstableCacheServiceTemplate(); + final var metricCollector = new BasicBatchServiceCallMetricCollector(); underTest.setMetricsCollector(metricCollector); - final List input = Collections.singletonList(19L); + final var input = Collections.singletonList(19L); //when - final List actual = underTest.callCacheableBatchService(input); + final var actual = underTest.callCacheableBatchService(input); //then assertNotNull(actual); assertIterableEquals(Collections.singletonList("19"), actual); - assertEquals(metricCollector.getCacheGet(), 1); - assertEquals(metricCollector.getCacheMiss(), 0); - assertEquals(metricCollector.getCacheHit(), 1); - assertEquals(metricCollector.getPartitionCreated(), 0); - assertEquals(metricCollector.getPartitionFailed(), 0); - assertEquals(metricCollector.getPartitionSucceeded(), 0); + assertEquals(1, metricCollector.getCacheGet()); + assertEquals(0, metricCollector.getCacheMiss()); + assertEquals(1, metricCollector.getCacheHit()); + assertEquals(0, metricCollector.getPartitionCreated()); + assertEquals(0, metricCollector.getPartitionFailed()); + assertEquals(0, metricCollector.getPartitionSucceeded()); } } diff --git a/src/test/java/com/github/nagyesta/cacheonly/entity/CacheKeyTest.java b/src/test/java/com/github/nagyesta/cacheonly/entity/CacheKeyTest.java index 6023f4d..613352e 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/entity/CacheKeyTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/entity/CacheKeyTest.java @@ -15,7 +15,7 @@ class CacheKeyTest { @SuppressWarnings({"UnnecessaryBoxing", "checkstyle:MagicNumber"}) private static Stream keyPairProvider() { - final CacheKey aCacheKey = new CacheKey<>(KEY_1, 1); + final var aCacheKey = new CacheKey<>(KEY_1, 1); return Stream.builder() .add(Arguments.of(aCacheKey, aCacheKey, true)) .add(Arguments.of(new CacheKey<>(KEY_1, 1), new CacheKey<>(KEY_2, 1), false)) @@ -27,11 +27,14 @@ private static Stream keyPairProvider() { @ParameterizedTest @MethodSource("keyPairProvider") - void testEqualsShouldCompareBothFieldsWhenCalled(final Object a, final Object b, final boolean expected) { + void testEqualsShouldCompareBothFieldsWhenCalled( + final Object a, + final Object b, + final boolean expected) { //given //when - final boolean actual = a.equals(b); + final var actual = a.equals(b); //then assertEquals(expected, actual); @@ -39,12 +42,15 @@ void testEqualsShouldCompareBothFieldsWhenCalled(final Object a, final Object b, @ParameterizedTest @MethodSource("keyPairProvider") - void testHashCodeShouldCompareBothFieldsWhenCalled(final Object a, final Object b, final boolean expected) { + void testHashCodeShouldCompareBothFieldsWhenCalled( + final Object a, + final Object b, + final boolean expected) { //given //when - final int hashA = a.hashCode(); - final int hashB = b.hashCode(); + final var hashA = a.hashCode(); + final var hashB = b.hashCode(); //then assertEquals(expected, hashA == hashB); diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/raw/ParcelService.java b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/raw/ParcelService.java index 8331f04..f3f25ed 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/raw/ParcelService.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/raw/ParcelService.java @@ -21,7 +21,7 @@ public List lookup(final List batchRequest) { } public ParcelStatus lookup(final String id) { - ParcelStatus result = ParcelStatus.NEW; + var result = ParcelStatus.NEW; if (id.startsWith("A")) { result = ParcelStatus.PICKED_UP; } else if (id.startsWith("B")) { diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/response/ParcelResponse.java b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/response/ParcelResponse.java index 649100d..0b5f836 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/response/ParcelResponse.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/response/ParcelResponse.java @@ -1,13 +1,4 @@ package com.github.nagyesta.cacheonly.example.parcel.response; -import lombok.AllArgsConstructor; -import lombok.Data; -import org.springframework.cache.annotation.EnableCaching; - -@Data -@AllArgsConstructor -@EnableCaching -public class ParcelResponse { - private String id; - private ParcelStatus status; +public record ParcelResponse(String id, ParcelStatus status) { } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelBatchResponseTransformer.java b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelBatchResponseTransformer.java index 9cc7d50..f5a9ab7 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelBatchResponseTransformer.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelBatchResponseTransformer.java @@ -16,12 +16,13 @@ public class ParcelBatchResponseTransformer extends CollectionBasedResponseTransformer, ParcelResponse, String> { public ParcelBatchResponseTransformer() { - super(Collectors.toList(), ParcelResponse::getId, true); + super(Collectors.toList(), ParcelResponse::id, true); } @Nullable @Override - public List mergeToBatchResponse(final @NotNull Map entityMap) { + public List mergeToBatchResponse( + final @NotNull Map entityMap) { return super.mergeToBatchResponse(new TreeMap<>(entityMap)); } } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelPartialCacheSupport.java b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelPartialCacheSupport.java index 7687c72..78f1972 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelPartialCacheSupport.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/parcel/transform/ParcelPartialCacheSupport.java @@ -5,6 +5,7 @@ import org.springframework.stereotype.Component; @Component -public class ParcelPartialCacheSupport extends NoOpPartialCacheSupport { +public class ParcelPartialCacheSupport + extends NoOpPartialCacheSupport { } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/replies/CommentContext.java b/src/test/java/com/github/nagyesta/cacheonly/example/replies/CommentContext.java index 9c20165..b9f3525 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/replies/CommentContext.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/replies/CommentContext.java @@ -24,7 +24,7 @@ public class CommentContext { @Bean public CacheManager cacheManager() { - final SimpleCacheManager cacheManager = new SimpleCacheManager(); + final var cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Collections.singletonList(spy(new ConcurrentMapCache(THREADS)))); return cacheManager; } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/replies/raw/CommentService.java b/src/test/java/com/github/nagyesta/cacheonly/example/replies/raw/CommentService.java index 75374c9..aa1c4df 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/replies/raw/CommentService.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/replies/raw/CommentService.java @@ -6,13 +6,7 @@ import org.springframework.stereotype.Service; import org.springframework.util.Assert; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import java.util.*; import java.util.stream.Collectors; @Service @@ -30,9 +24,7 @@ public class CommentService { private final Map> database; CommentService() { - final Map> map = new HashMap<>(); - map.put(NO_COMMENT, Collections.emptyList()); - map.put(CACHING_IS_NOT_ALWAYS_EASY, Collections.unmodifiableList(Arrays.asList( + this.database = Map.of(NO_COMMENT, Collections.emptyList(), CACHING_IS_NOT_ALWAYS_EASY, Collections.unmodifiableList(Arrays.asList( Comment.builder() .articleId(CACHING_IS_NOT_ALWAYS_EASY) .commentId(1L) @@ -79,8 +71,7 @@ public class CommentService { .author(S_SERIOUS) .message("I am looking for one too, could you send a link?") .build() - ))); - map.put(ARE_YOU_OUT_OF_QUOTA, Collections.unmodifiableList(Arrays.asList( + )), ARE_YOU_OUT_OF_QUOTA, Collections.unmodifiableList(Arrays.asList( Comment.builder() .articleId(ARE_YOU_OUT_OF_QUOTA) .commentId(1L) @@ -101,8 +92,7 @@ public class CommentService { .author(O_PEN) .message("It happens.") .build() - ))); - map.put(AINT_NOBODY_GOT_TIME_FOR_THAT, Collections.unmodifiableList(Arrays.asList( + )), AINT_NOBODY_GOT_TIME_FOR_THAT, Collections.unmodifiableList(Arrays.asList( Comment.builder() .articleId(AINT_NOBODY_GOT_TIME_FOR_THAT) .commentId(1L) @@ -130,20 +120,22 @@ public class CommentService { .message("LOL, more like third.") .build() ))); - this.database = Collections.unmodifiableMap(map); } @NotNull - public CommentThreads threadsOf(final @NotNull UUID article, final @NotNull Set threadIds) throws NotFoundException { + public CommentThreads threadsOf( + final @NotNull UUID article, + final @NotNull Set threadIds) + throws NotFoundException { Assert.isTrue(threadIds.size() <= 5, "Batch size is too large."); if (!database.containsKey(article)) { throw new NotFoundException(); } - final Set threadStarters = this.database.get(article).stream() + final var threadStarters = this.database.get(article).stream() .filter(comment -> comment.getThreadId() == null) .map(Comment::getCommentId) .collect(Collectors.toSet()); - final Map> threads = this.database.get(article).stream() + final var threads = this.database.get(article).stream() .filter(comment -> comment.getThreadId() != null) .filter(comment -> threadIds.contains(comment.getThreadId())) .collect(Collectors.groupingBy(Comment::getThreadId)); diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/replies/request/ThreadRequest.java b/src/test/java/com/github/nagyesta/cacheonly/example/replies/request/ThreadRequest.java index 0254fdf..315cbad 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/replies/request/ThreadRequest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/replies/request/ThreadRequest.java @@ -15,7 +15,9 @@ public class ThreadRequest { public ThreadRequest() { } - public ThreadRequest(final UUID articleId, final List threadIds) { + public ThreadRequest( + final UUID articleId, + final List threadIds) { this.articleId = articleId; this.threadIds = threadIds; } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentBatchBasedRequestTransformer.java b/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentBatchBasedRequestTransformer.java index 61542f9..1ef1910 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentBatchBasedRequestTransformer.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentBatchBasedRequestTransformer.java @@ -9,7 +9,8 @@ import java.util.stream.Collectors; @Component -public class CommentBatchBasedRequestTransformer extends WrappedCollectionBasedRequestTransformer, Long, Long> { +public class CommentBatchBasedRequestTransformer + extends WrappedCollectionBasedRequestTransformer, Long, Long> { public CommentBatchBasedRequestTransformer() { super(ThreadRequest::new, ThreadRequest::getThreadIds, (request, threadIds) -> { diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentPartialCacheSupport.java b/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentPartialCacheSupport.java index a577f26..d69e4ec 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentPartialCacheSupport.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/replies/transform/CommentPartialCacheSupport.java @@ -35,7 +35,7 @@ public Class getEntityClass() { @NotNull @Override public CacheKey toCacheKey(final @NotNull ThreadRequest partialRequest) { - final Long id = partialRequest.getThreadIds().get(0); + final var id = partialRequest.getThreadIds().get(0); return new CacheKey<>(partialRequest.getArticleId().toString() + "_thread_" + id, id); } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/stock/StockContext.java b/src/test/java/com/github/nagyesta/cacheonly/example/stock/StockContext.java index 478fa88..b7bf150 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/stock/StockContext.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/stock/StockContext.java @@ -24,7 +24,7 @@ public class StockContext { @Bean public CacheManager cacheManager() { - final SimpleCacheManager cacheManager = new SimpleCacheManager(); + final var cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Collections.singletonList(spy(new ConcurrentMapCache(STOCKS)))); return cacheManager; } diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/stock/raw/StockBatchServiceCaller.java b/src/test/java/com/github/nagyesta/cacheonly/example/stock/raw/StockBatchServiceCaller.java index 3074cfa..f4463d2 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/stock/raw/StockBatchServiceCaller.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/stock/raw/StockBatchServiceCaller.java @@ -41,7 +41,8 @@ public CacheRefreshStrategy refreshStrategy() { @NotNull @Override @SuppressWarnings("RedundantThrows") - public SortedMap callBatchService(final @NotNull SortedSet batchRequest) + public SortedMap callBatchService( + final @NotNull SortedSet batchRequest) throws BatchServiceException { // we call the service here return new TreeMap<>(stockService.lookup(batchRequest)); diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableCacheServiceTemplate.java b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableCacheServiceTemplate.java index 20a5ce3..e1436ca 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableCacheServiceTemplate.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableCacheServiceTemplate.java @@ -15,7 +15,7 @@ public class UnstableCacheServiceTemplate extends ConcurrentCacheServiceTemplate, List, Long, String, String, Long> { private static final BatchRequestTransformer, Long, Long> BATCH_REQUEST_TRANSFORMER = - new BatchRequestTransformer, Long, Long>() { + new BatchRequestTransformer<>() { @NotNull @Override public Map splitToPartialRequest(final @NotNull List batchRequest) { @@ -32,7 +32,7 @@ public List mergeToBatchRequest(final @NotNull Map requestMap) } }; private static final BatchResponseTransformer, String, Long> BATCH_RESPONSE_TRANSFORMER = - new BatchResponseTransformer, String, Long>() { + new BatchResponseTransformer<>() { @NotNull @Override public Map splitToPartialResponse(final @NotNull List batchResponse) { diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableConcurrentBatchServiceCaller.java b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableConcurrentBatchServiceCaller.java index 68770ed..9fc1432 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableConcurrentBatchServiceCaller.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstableConcurrentBatchServiceCaller.java @@ -38,9 +38,10 @@ public int maxPartitionSize() { @Nullable @Override - public List callBatchService(final @NotNull List batchRequest) throws BatchServiceException { + public List callBatchService(final @NotNull List batchRequest) + throws BatchServiceException { handleExceptionalCases(batchRequest); - final List result = batchRequest.stream() + final var result = batchRequest.stream() .filter(i -> i > 10) .map(String::valueOf) .collect(Collectors.toList()); @@ -54,9 +55,9 @@ public List callBatchService(final @NotNull List batchRequest) thr private void handleExceptionalCases(final @NotNull List batchRequest) { if (batchRequest.stream().anyMatch(i -> i < -30L)) { try { - final long start = System.currentTimeMillis(); + final var start = System.currentTimeMillis(); Thread.sleep(60); - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); log.trace("Took: {} ms", (end - start)); } catch (final InterruptedException e) { log.error(e.getMessage(), e); diff --git a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstablePartialCacheSupport.java b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstablePartialCacheSupport.java index ceac34d..518b503 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstablePartialCacheSupport.java +++ b/src/test/java/com/github/nagyesta/cacheonly/example/unstable/UnstablePartialCacheSupport.java @@ -52,21 +52,21 @@ public CacheManager getCacheManager() { @Override public String getFromCache(final @NotNull CacheKey key) { handleExceptionalCases(key); - if (key.getId() < 5 || key.getId() > 20) { + if (key.id() < 5 || key.id() > 20) { return null; } - return key.getKey(); + return key.key(); } private void handleExceptionalCases(final @NotNull CacheKey key) { - if (key.getId() == -15L) { + if (key.id() == -15L) { throw new IllegalStateException("Get failed."); } - if (key.getId() < -30) { + if (key.id() < -30) { try { - final long start = System.currentTimeMillis(); + final var start = System.currentTimeMillis(); Thread.sleep(60); - final long end = System.currentTimeMillis(); + final var end = System.currentTimeMillis(); log.trace("Took: {} ms", (end - start)); } catch (final InterruptedException e) { log.error(e.getMessage(), e); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/CollectionWrapper.java b/src/test/java/com/github/nagyesta/cacheonly/transform/CollectionWrapper.java index 5c5e34a..53f5498 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/CollectionWrapper.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/CollectionWrapper.java @@ -1,11 +1,15 @@ package com.github.nagyesta.cacheonly.transform; +import lombok.Getter; +import lombok.Setter; import org.apache.commons.collections4.CollectionUtils; import java.util.Collection; import java.util.Objects; import java.util.StringJoiner; +@Setter +@Getter public final class CollectionWrapper { private Collection collection; @@ -14,23 +18,14 @@ public CollectionWrapper(final Collection collection) { this.collection = collection; } - public Collection getCollection() { - return collection; - } - - public void setCollection(final Collection collection) { - this.collection = collection; - } - @Override public boolean equals(final Object o) { if (this == o) { return true; } - if (!(o instanceof CollectionWrapper)) { + if (!(o instanceof final CollectionWrapper that)) { return false; } - final CollectionWrapper that = (CollectionWrapper) o; return CollectionUtils.containsAll(this.collection, that.collection) && CollectionUtils.containsAll(that.collection, this.collection); } diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/MapWrapper.java b/src/test/java/com/github/nagyesta/cacheonly/transform/MapWrapper.java index 352d609..6f3c4ee 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/MapWrapper.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/MapWrapper.java @@ -1,9 +1,14 @@ package com.github.nagyesta.cacheonly.transform; +import lombok.Getter; +import lombok.Setter; + import java.util.Map; import java.util.Objects; import java.util.StringJoiner; +@Setter +@Getter public final class MapWrapper { private Map map; @@ -12,23 +17,14 @@ public MapWrapper(final Map map) { this.map = map; } - public Map getMap() { - return map; - } - - public void setMap(final Map map) { - this.map = map; - } - @Override public boolean equals(final Object o) { if (this == o) { return true; } - if (!(o instanceof MapWrapper)) { + if (!(o instanceof final MapWrapper that)) { return false; } - final MapWrapper that = (MapWrapper) o; return Objects.equals(map, that.map); } diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformerTest.java index 140e087..3c86b6d 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedRequestTransformerTest.java @@ -13,9 +13,7 @@ import java.util.stream.LongStream; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("checkstyle:MagicNumber") class CollectionBasedRequestTransformerTest { @@ -49,14 +47,15 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialRequestShouldSplitValidInput(final List input, - final Map expected) { + void testSplitToPartialRequestShouldSplitValidInput( + final List input, + final Map expected) { //given - final CollectionBasedRequestTransformer, String, Long> underTest = - new CollectionBasedRequestTransformer<>(Collectors.toList(), Long::parseLong); + final var underTest = + new CollectionBasedRequestTransformer, String, Long>(Collectors.toList(), Long::parseLong); //when - final Map actual = underTest.splitToPartialRequest(input); + final var actual = underTest.splitToPartialRequest(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -64,14 +63,16 @@ void testSplitToPartialRequestShouldSplitValidInput(final List input, @ParameterizedTest @MethodSource("mergeInputProvider") - void testMergeToBatchRequestShouldMergeValidInput(final Map input, - final List expected) { + void testMergeToBatchRequestShouldMergeValidInput( + final Map input, + final List expected) { //given - final CollectionBasedRequestTransformer, String, Long> underTest = - new CollectionBasedRequestTransformer<>(Collectors.toList(), Long::parseLong); + final var underTest = + new CollectionBasedRequestTransformer, String, Long>( + Collectors.toList(), Long::parseLong); //when - final List actual = underTest.mergeToBatchRequest(input); + final var actual = underTest.mergeToBatchRequest(input); //then assertNotNull(actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformerTest.java index 09c6eee..53ae70f 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/CollectionBasedResponseTransformerTest.java @@ -13,9 +13,7 @@ import java.util.stream.LongStream; import java.util.stream.Stream; -import static org.junit.jupiter.api.Assertions.assertIterableEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.*; @SuppressWarnings("checkstyle:MagicNumber") class CollectionBasedResponseTransformerTest { @@ -49,14 +47,16 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialResponseShouldSplitValidInput(final List input, - final Map expected) { + void testSplitToPartialResponseShouldSplitValidInput( + final List input, + final Map expected) { //given - final CollectionBasedResponseTransformer, String, Long> underTest = - new CollectionBasedResponseTransformer<>(Collectors.toList(), Long::parseLong); + final var underTest = + new CollectionBasedResponseTransformer, String, Long>( + Collectors.toList(), Long::parseLong); //when - final Map actual = underTest.splitToPartialResponse(input); + final var actual = underTest.splitToPartialResponse(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -64,14 +64,16 @@ void testSplitToPartialResponseShouldSplitValidInput(final List input, @ParameterizedTest @MethodSource("mergeInputProvider") - void testMergeToBatchResponseShouldMergeValidInput(final Map input, - final List expected) { + void testMergeToBatchResponseShouldMergeValidInput( + final Map input, + final List expected) { //given - final CollectionBasedResponseTransformer, String, Long> underTest = - new CollectionBasedResponseTransformer<>(Collectors.toList(), Long::parseLong, false); + final var underTest = + new CollectionBasedResponseTransformer, String, Long>( + Collectors.toList(), Long::parseLong, false); //when - final List actual = underTest.mergeToBatchResponse(input); + final var actual = underTest.mergeToBatchResponse(input); //then assertNotNull(actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformerTest.java index 5ce5e2d..ace573b 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedRequestTransformerTest.java @@ -46,14 +46,15 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialRequestShouldSplitValidInput(final SortedMap input, - final Map expected) { + void testSplitToPartialRequestShouldSplitValidInput( + final SortedMap input, + final Map expected) { //given - final MapBasedRequestTransformer, String, Long> underTest = - new MapBasedRequestTransformer<>(TreeMap::new); + final var underTest = + new MapBasedRequestTransformer, String, Long>(TreeMap::new); //when - final Map actual = underTest.splitToPartialRequest(input); + final var actual = underTest.splitToPartialRequest(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -61,15 +62,18 @@ void testSplitToPartialRequestShouldSplitValidInput(final SortedMap input, - final SortedMap expected) { + void testMergeToBatchRequestShouldMergeValidInput( + final Map input, + final SortedMap expected) { //given - final MapBasedRequestTransformer, String, Long> underTest = - new MapBasedRequestTransformer<>(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (T, U) -> T, TreeMap::new), - Map.Entry::getKey, Map.Entry::getValue); + final var underTest = + new MapBasedRequestTransformer, String, Long>( + Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (T, U) -> T, TreeMap::new), + Map.Entry::getKey, + Map.Entry::getValue); //when - final SortedMap actual = underTest.mergeToBatchRequest(input); + final var actual = underTest.mergeToBatchRequest(input); //then assertEquals(expected, actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformerTest.java index 828f134..09d79a1 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/MapBasedResponseTransformerTest.java @@ -46,14 +46,15 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialResponseShouldSplitValidInput(final SortedMap input, - final Map expected) { + void testSplitToPartialResponseShouldSplitValidInput( + final SortedMap input, + final Map expected) { //given - final MapBasedResponseTransformer, String, Long> underTest = - new MapBasedResponseTransformer<>(TreeMap::new); + final var underTest = + new MapBasedResponseTransformer, String, Long>(TreeMap::new); //when - final Map actual = underTest.splitToPartialResponse(input); + final var actual = underTest.splitToPartialResponse(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -61,15 +62,18 @@ void testSplitToPartialResponseShouldSplitValidInput(final SortedMap input, - final SortedMap expected) { + void testMergeToBatchResponseShouldMergeValidInput( + final Map input, + final SortedMap expected) { //given - final MapBasedResponseTransformer, String, Long> underTest = - new MapBasedResponseTransformer<>(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (T, U) -> T, TreeMap::new), - Map.Entry::getKey, Map.Entry::getValue, true); + final var underTest = + new MapBasedResponseTransformer, String, Long>( + Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (T, U) -> T, TreeMap::new), + Map.Entry::getKey, + Map.Entry::getValue, true); //when - final SortedMap actual = underTest.mergeToBatchResponse(input); + final var actual = underTest.mergeToBatchResponse(input); //then assertEquals(expected, actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformerTest.java index 21ee198..d2ec79c 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedRequestTransformerTest.java @@ -51,11 +51,13 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialRequestShouldSplitValidInput(final CollectionWrapper input, - final Map> expected) { + void testSplitToPartialRequestShouldSplitValidInput( + final CollectionWrapper input, + final Map> expected) { //given - final WrappedCollectionBasedRequestTransformer, Collection, String, Long> underTest = - new WrappedCollectionBasedRequestTransformer<>(() -> new CollectionWrapper<>(new ArrayList<>()), + final var underTest = + new WrappedCollectionBasedRequestTransformer, Collection, String, Long>( + () -> new CollectionWrapper<>(new ArrayList<>()), CollectionWrapper::getCollection, (wrapper, collection) -> { wrapper.setCollection(collection); @@ -63,7 +65,7 @@ void testSplitToPartialRequestShouldSplitValidInput(final CollectionWrapper> actual = underTest.splitToPartialRequest(input); + final var actual = underTest.splitToPartialRequest(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -71,11 +73,13 @@ void testSplitToPartialRequestShouldSplitValidInput(final CollectionWrapper> input, - final CollectionWrapper expected) { + void testMergeToBatchRequestShouldMergeValidInput( + final Map> input, + final CollectionWrapper expected) { //given - final WrappedCollectionBasedRequestTransformer, Collection, String, Long> underTest = - new WrappedCollectionBasedRequestTransformer<>(w -> new CollectionWrapper<>(new ArrayList<>()), + final var underTest = + new WrappedCollectionBasedRequestTransformer, Collection, String, Long>( + w -> new CollectionWrapper<>(new ArrayList<>()), CollectionWrapper::getCollection, (wrapper, collection) -> { wrapper.setCollection(collection); @@ -83,7 +87,7 @@ void testMergeToBatchRequestShouldMergeValidInput(final Map actual = underTest.mergeToBatchRequest(input); + final var actual = underTest.mergeToBatchRequest(input); //then assertEquals(expected, actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformerTest.java index a738fc3..bca6659 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedCollectionBasedResponseTransformerTest.java @@ -51,11 +51,13 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialResponseShouldSplitValidInput(final CollectionWrapper input, - final Map> expected) { + void testSplitToPartialResponseShouldSplitValidInput( + final CollectionWrapper input, + final Map> expected) { //given - final WrappedCollectionBasedResponseTransformer, Collection, String, Long> underTest = - new WrappedCollectionBasedResponseTransformer<>(() -> new CollectionWrapper<>(new ArrayList<>()), + final var underTest = + new WrappedCollectionBasedResponseTransformer, Collection, String, Long>( + () -> new CollectionWrapper<>(new ArrayList<>()), CollectionWrapper::getCollection, (wrapper, collection) -> { wrapper.setCollection(collection); @@ -63,7 +65,7 @@ void testSplitToPartialResponseShouldSplitValidInput(final CollectionWrapper> actual = underTest.splitToPartialResponse(input); + final var actual = underTest.splitToPartialResponse(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -71,11 +73,13 @@ void testSplitToPartialResponseShouldSplitValidInput(final CollectionWrapper> input, - final CollectionWrapper expected) { + void testMergeToBatchResponseShouldMergeValidInput( + final Map> input, + final CollectionWrapper expected) { //given - final WrappedCollectionBasedResponseTransformer, Collection, String, Long> underTest = - new WrappedCollectionBasedResponseTransformer<>(w -> new CollectionWrapper<>(new ArrayList<>()), + final var underTest = + new WrappedCollectionBasedResponseTransformer, Collection, String, Long>( + w -> new CollectionWrapper<>(new ArrayList<>()), CollectionWrapper::getCollection, (wrapper, collection) -> { wrapper.setCollection(collection); @@ -83,7 +87,7 @@ void testMergeToBatchResponseShouldMergeValidInput(final Map actual = underTest.mergeToBatchResponse(input); + final var actual = underTest.mergeToBatchResponse(input); //then assertEquals(expected, actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformerTest.java index b33b909..733e84a 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedRequestTransformerTest.java @@ -48,17 +48,19 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialRequestShouldSplitValidInput(final MapWrapper input, - final Map> expected) { + void testSplitToPartialRequestShouldSplitValidInput( + final MapWrapper input, + final Map> expected) { //given - final WrappedMapBasedRequestTransformer, Map, String, Long> underTest = - new WrappedMapBasedRequestTransformer<>(() -> new MapWrapper<>(new HashMap<>()), MapWrapper::getMap, (wrapper, map) -> { + final var underTest = + new WrappedMapBasedRequestTransformer, Map, String, Long>( + () -> new MapWrapper<>(new HashMap<>()), MapWrapper::getMap, (wrapper, map) -> { wrapper.setMap(map); return wrapper; }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //when - final Map> actual = underTest.splitToPartialRequest(input); + final var actual = underTest.splitToPartialRequest(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -66,17 +68,21 @@ void testSplitToPartialRequestShouldSplitValidInput(final MapWrapper> input, - final MapWrapper expected) { + void testMergeToBatchRequestShouldMergeValidInput( + final Map> input, + final MapWrapper expected) { //given - final WrappedMapBasedRequestTransformer, Map, String, Long> underTest = - new WrappedMapBasedRequestTransformer<>(w -> new MapWrapper<>(new HashMap<>()), MapWrapper::getMap, (wrapper, map) -> { - wrapper.setMap(map); - return wrapper; - }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + final var underTest = + new WrappedMapBasedRequestTransformer, Map, String, Long>( + w -> new MapWrapper<>(new HashMap<>()), + MapWrapper::getMap, + (wrapper, map) -> { + wrapper.setMap(map); + return wrapper; + }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //when - final MapWrapper actual = underTest.mergeToBatchRequest(input); + final var actual = underTest.mergeToBatchRequest(input); //then assertEquals(expected, actual); diff --git a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformerTest.java b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformerTest.java index 20ce450..5e51fb0 100644 --- a/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformerTest.java +++ b/src/test/java/com/github/nagyesta/cacheonly/transform/common/WrappedMapBasedResponseTransformerTest.java @@ -48,17 +48,21 @@ private static Stream mergeInputProvider() { @ParameterizedTest @MethodSource("splitInputProvider") - void testSplitToPartialResponseShouldSplitValidInput(final MapWrapper input, - final Map> expected) { + void testSplitToPartialResponseShouldSplitValidInput( + final MapWrapper input, + final Map> expected) { //given - final WrappedMapBasedResponseTransformer, Map, String, Long> underTest = - new WrappedMapBasedResponseTransformer<>(() -> new MapWrapper<>(new HashMap<>()), MapWrapper::getMap, (wrapper, map) -> { - wrapper.setMap(map); - return wrapper; - }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + final var underTest = + new WrappedMapBasedResponseTransformer, Map, String, Long>( + () -> new MapWrapper<>(new HashMap<>()), + MapWrapper::getMap, + (wrapper, map) -> { + wrapper.setMap(map); + return wrapper; + }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //when - final Map> actual = underTest.splitToPartialResponse(input); + final var actual = underTest.splitToPartialResponse(input); //then assertIterableEquals(expected.entrySet(), actual.entrySet()); @@ -66,17 +70,21 @@ void testSplitToPartialResponseShouldSplitValidInput(final MapWrapper> input, - final MapWrapper expected) { + void testMergeToBatchResponseShouldMergeValidInput( + final Map> input, + final MapWrapper expected) { //given - final WrappedMapBasedResponseTransformer, Map, String, Long> underTest = - new WrappedMapBasedResponseTransformer<>(w -> new MapWrapper<>(new HashMap<>()), MapWrapper::getMap, (wrapper, map) -> { - wrapper.setMap(map); - return wrapper; - }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + final var underTest = + new WrappedMapBasedResponseTransformer, Map, String, Long>( + w -> new MapWrapper<>(new HashMap<>()), + MapWrapper::getMap, + (wrapper, map) -> { + wrapper.setMap(map); + return wrapper; + }, Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); //when - final MapWrapper actual = underTest.mergeToBatchResponse(input); + final var actual = underTest.mergeToBatchResponse(input); //then assertEquals(expected, actual);