diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6d1af1e..f4a8c4c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,7 +22,7 @@ jobs: key: gradle-cache restore-keys: gradle-cache - name: Publish to Maven Central - run: ./gradlew assemble publishAggregatedPublicationToCentralPortal + run: ./gradlew assemble nmcpPublishAggregatedPublicationToCentralPortal env: MAVEN_CENTRAL_USERNAME: ${{ secrets.MAVEN_CENTRAL_USERNAME }} MAVEN_CENTRAL_PASSWORD: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..def2c40 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,51 @@ +# Changelog + +## 2.0.0 - 2026-08-30 + +- Updated Kotlin from 1.9.x to 2.4.10 +- Updated Spring Boot from 3.2.3 to 4.1.1 +- Updated Gradle from 8.4 to 9.7.1 +- Updated Dokka from 1.9.20 to 2.2.0 +- Updated Detekt from 1.23.6 to 2.0.0-alpha.6 +- Updated SonarQube plugin from 4.4.1.3373 to 7.4.0.8496 +- Updated NMCP from 0.0.7 to 1.6.1 +- Updated Foojay Toolchain Resolver from 0.5.0 to 1.0.0 +- Updated JUnit from 5.10.2 to 5.14.4 +- Updated MockK from 1.13.10 to 1.14.11 +- Updated Jakarta Persistence API from 3.1.0 to 3.2.0 +- Updated ANTLR from 4.13.1 to 4.13.2 +- Updated Spring Dependency Management from 1.1.4 to 1.1.7 +- Added standalone Hibernate example application + +### Breaking changes + +- New requirements: + - Java 17+ + - Kotlin 2.x (K2 compiler) if your project is using Kotlin + - Spring Boot 4.x if your project is using Spring Boot +- Contract/API changes: + - `DynamicQueryRepository` now has a `T : Any` bound (nullable type arguments are no longer allowed) + - `DynamicQuerySpecificationAdapter` now has a `T : Any` bound + - `ScopeDownSupplier` now has a `T : Any` bound + - Removed `DynamicQueryRepository.delete(DynamicQuerySpecification?)` and + `delete(DynamicQuerySpecification?, ScopeDownSupplier)` (Spring Data API changes no longer allows a Dynamic Query + to be used in a delete and/or update operation) + +## 1.1.0 - 2024-02-25 + +- Improved Maven publication metadata +- Minor fixes + +## 1.0.0 - 2024-02-25 + +- Initial release +- DSL grammar and parser (ANTLR-based) +- JPA Specification APIs +- Spring Boot autoconfiguration, Data JPA, and Web modules +- Detekt and SonarQube integration +- Maven Central publication support +- GitHub Actions CI/CD +- Attribute references and transformation operations in DSL +- Path conversion APIs +- Enum type value parsing +- Spring Boot example application diff --git a/build.gradle.kts b/build.gradle.kts index 3b8da27..e3ebf03 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,26 +1,25 @@ -import org.jetbrains.dokka.gradle.DokkaTask - plugins { - val kotlinVersion = "1.9.23" - val dokkaVersion = "1.9.20" - val sonarqubeVersion = "4.4.1.3373" - val detektVersion = "1.23.6" - val nmcpVersion = "0.0.7" - val springBootVersion = "3.2.3" - val springDependencyManagementVersion = "1.1.4" + val kotlinVersion = "2.4.10" + val dokkaVersion = "2.2.0" + val sonarqubeVersion = "7.4.0.8496" + val detektVersion = "2.0.0-alpha.6" + val nmcpVersion = "1.6.1" + val springBootVersion = "4.1.1" + val springDependencyManagementVersion = "1.1.7" `maven-publish` `java-library` jacoco signing - kotlin("jvm") version "1.9.10" + kotlin("jvm") version kotlinVersion kotlin("plugin.spring") version kotlinVersion apply false kotlin("plugin.jpa") version kotlinVersion apply false id("org.sonarqube") version sonarqubeVersion - id("io.gitlab.arturbosch.detekt") version detektVersion + id("dev.detekt") version detektVersion id("com.gradleup.nmcp") version nmcpVersion + id("com.gradleup.nmcp.aggregation") version nmcpVersion id("org.jetbrains.dokka") version dokkaVersion apply false id("org.springframework.boot") version springBootVersion apply false id("io.spring.dependency-management") version springDependencyManagementVersion apply false @@ -28,7 +27,7 @@ plugins { allprojects { group = "br.com.dillmann.dynamicquery" - version = "1.1.0" + version = "2.0.0" repositories { mavenCentral() @@ -43,17 +42,17 @@ allprojects { } } -gradle.rootProject { - nmcp { - publishAggregation { - subprojects.forEach { - project(":${it.name}") - } +nmcpAggregation { + centralPortal { + username = providers.environmentVariable("MAVEN_CENTRAL_USERNAME") + password = providers.environmentVariable("MAVEN_CENTRAL_PASSWORD") + publishingType = "USER_MANAGED" + } +} - username = providers.environmentVariable("MAVEN_CENTRAL_USERNAME") - password = providers.environmentVariable("MAVEN_CENTRAL_PASSWORD") - publicationType = "USER_MANAGED" - } +dependencies { + subprojects.forEach { + nmcpAggregation(project(":${it.name}")) } } @@ -63,7 +62,7 @@ subprojects { apply(plugin = "java-library") apply(plugin = "signing") apply(plugin = "jacoco") - apply(plugin = "io.gitlab.arturbosch.detekt") + apply(plugin = "dev.detekt") apply(plugin = "org.sonarqube") apply(plugin = "org.jetbrains.dokka") apply(plugin = "com.gradleup.nmcp") @@ -73,11 +72,11 @@ subprojects { testImplementation("org.jetbrains.kotlin:kotlin-test") // MockK - val mockkVersion: String by project + val mockkVersion = project.property("mockkVersion") testImplementation("io.mockk:mockk:$mockkVersion") // JUnit - val junitVersion: String by project + val junitVersion = project.property("junitVersion") testImplementation("org.junit.jupiter:junit-jupiter:$junitVersion") testRuntimeOnly("org.junit.platform:junit-platform-launcher") } @@ -98,12 +97,11 @@ subprojects { } } - create("dokkaJavadocJar") { - val dokkaJavadoc = getByName("dokkaJavadoc") as DokkaTask - dependsOn(dokkaJavadoc) + register("dokkaJavadocJar") { + dependsOn("dokkaGenerate") archiveClassifier = "javadoc" - from(dokkaJavadoc.outputDirectory) + from(rootProject.layout.buildDirectory.dir("dokka/javadoc")) } afterEvaluate { @@ -122,7 +120,7 @@ subprojects { kotlin { jvmToolchain(17) compilerOptions { - freeCompilerArgs.add("-Xjvm-default=all") + freeCompilerArgs.add("-jvm-default=no-compatibility") } } @@ -130,10 +128,6 @@ subprojects { withSourcesJar() } - nmcp { - publishAllPublications {} - } - signing { val signingKey = providers.environmentVariable("MAVEN_CENTRAL_SIGNING_KEY") val signingSecret = providers.environmentVariable("MAVEN_CENTRAL_SIGNING_SECRET") diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 72f3133..6eae35c 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -1,44 +1,17 @@ -build: - maxIssues: 0 - excludeCorrectable: false - weights: - complexity: 2 - LongParameterList: 1 - style: 1 - comments: 1 - config: validation: true warningsAsErrors: false - checkExhaustiveness: false - excludes: '' - -processors: - active: true - exclude: - - 'DetektProgressListener' - -console-reports: - active: true - exclude: - - 'ProjectStatisticsReport' - - 'ComplexityReport' - - 'NotificationReport' - - 'FindingsReport' - - 'FileBasedFindingsReport' - -output-reports: - active: true + excludes: [] comments: active: true AbsentOrWrongFileLicense: active: false - licenseTemplateFile: 'license.template' + licenseTemplate: 'license.template' licenseTemplateIsRegex: false - CommentOverPrivateFunction: + DocumentationOverPrivateFunction: active: false - CommentOverPrivateProperty: + DocumentationOverPrivateProperty: active: false DeprecatedBlockTag: active: false @@ -55,7 +28,7 @@ comments: allowParamOnConstructorProperties: false UndocumentedPublicClass: active: true - excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**', '**/specification/parameter/operation/OperationParameterType.kt', '**/specification/predicate/PredicateType.kt', '**/specification/group/LogicalOperatorType.kt'] searchInNestedClass: true searchInInnerClass: true searchInInnerObject: true @@ -67,26 +40,20 @@ comments: searchProtectedFunction: true UndocumentedPublicProperty: active: true - excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] + excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**', '**/specification/parameter/operation/OperationParameterType.kt', '**/specification/predicate/PredicateType.kt'] searchProtectedProperty: false complexity: active: true - CognitiveComplexMethod: - active: false - threshold: 15 ComplexCondition: active: true - threshold: 4 + allowedConditions: 4 ComplexInterface: active: false - threshold: 10 - includeStaticDeclarations: false - includePrivateDeclarations: false - ignoreOverloaded: false + allowedDefinitions: 10 CyclomaticComplexMethod: active: true - threshold: 25 + allowedComplexity: 25 ignoreSingleWhenExpression: true ignoreSimpleWhenEntries: true ignoreNestingFunctions: false @@ -107,32 +74,28 @@ complexity: ignoredLabels: [] LargeClass: active: true - threshold: 600 + allowedLines: 600 LongMethod: active: true - threshold: 60 + allowedLines: 60 excludes: - '**/test/**' LongParameterList: active: true - functionThreshold: 6 - constructorThreshold: 7 + allowedFunctionParameters: 6 + allowedConstructorParameters: 7 ignoreDefaultParameters: false ignoreDataClasses: true ignoreAnnotatedParameter: [] MethodOverloading: active: false - threshold: 6 - NamedArguments: - active: true - threshold: 3 - ignoreArgumentsMatchingNames: false + allowedOverloads: 6 NestedBlockDepth: active: true - threshold: 4 + allowedDepth: 4 NestedScopeFunctions: active: false - threshold: 1 + allowedDepth: 1 functions: - 'kotlin.apply' - 'kotlin.run' @@ -144,18 +107,18 @@ complexity: StringLiteralDuplication: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] - threshold: 3 + allowedDuplications: 3 ignoreAnnotation: true - excludeStringsWithLessThan5Characters: true + allowedWithLengthLessThan: 5 ignoreStringsRegex: '$^' TooManyFunctions: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] - thresholdInFiles: 20 - thresholdInClasses: 20 - thresholdInInterfaces: 20 - thresholdInObjects: 20 - thresholdInEnums: 20 + allowedFunctionsPerFile: 20 + allowedFunctionsPerClass: 20 + allowedFunctionsPerInterface: 20 + allowedFunctionsPerObject: 20 + allowedFunctionsPerEnum: 20 ignoreDeprecated: true ignorePrivate: false ignoreOverridden: false @@ -205,7 +168,7 @@ empty-blocks: active: true EmptyInitBlock: active: true - EmptyKtFile: + EmptyKotlinFile: active: true EmptySecondaryConstructor: active: true @@ -306,10 +269,10 @@ naming: ForbiddenClassName: active: false forbiddenName: [] - FunctionMaxLength: + FunctionNameMaxLength: active: false maximumFunctionNameLength: 30 - FunctionMinLength: + FunctionNameMinLength: active: true minimumFunctionNameLength: 3 FunctionNaming: @@ -369,7 +332,7 @@ performance: active: true CouldBeSequence: active: true - threshold: 3 + allowedOperations: 3 ForEachOnRange: active: true excludes: ['**/test/**', '**/androidTest/**', '**/commonTest/**', '**/jvmTest/**', '**/androidUnitTest/**', '**/androidInstrumentedTest/**', '**/jsTest/**', '**/iosTest/**'] @@ -567,8 +530,7 @@ style: allowedPatterns: '' ForbiddenImport: active: false - imports: [] - forbiddenPatterns: '' + allowedImports: [] ForbiddenMethodCall: active: true methods: @@ -625,7 +587,7 @@ style: excludeImportStatements: true excludeCommentStatements: false excludeRawStrings: true - MayBeConst: + MayBeConstant: active: true ModifierOrder: active: true @@ -651,15 +613,13 @@ style: active: true OptionalUnit: active: true - PreferToOverPairSyntax: - active: false ProtectedMemberInFinalClass: active: true RedundantExplicitType: active: true RedundantHigherOrderMapUsage: active: true - RedundantVisibilityModifierRule: + RedundantVisibilityModifier: active: true ReturnCount: active: false @@ -673,7 +633,7 @@ style: active: true SerialVersionUIDInSerializableClass: active: true - SpacingBetweenPackageAndImports: + SpacingAfterPackageAndImports: active: true StringShouldBeRawString: active: false @@ -694,10 +654,6 @@ style: active: false acceptableLength: 4 allowNonStandardGrouping: false - UnnecessaryAbstractClass: - active: true - UnnecessaryAnnotationUseSiteTarget: - active: false UnnecessaryApply: active: true UnnecessaryBackticks: @@ -715,16 +671,16 @@ style: UnnecessaryParentheses: active: true allowForUnclearPrecedence: false - UntilInsteadOfRangeTo: + RangeUntilInsteadOfRangeTo: active: false - UnusedImports: + UnusedImport: active: true UnusedParameter: active: true allowedNames: 'ignored|expected' UnusedPrivateClass: active: true - UnusedPrivateMember: + UnusedPrivateFunction: active: true allowedNames: '' UnusedPrivateProperty: diff --git a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/AndGroupSpecificationUnitTests.kt b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/AndGroupSpecificationUnitTests.kt index 899b87e..d27698f 100644 --- a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/AndGroupSpecificationUnitTests.kt +++ b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/AndGroupSpecificationUnitTests.kt @@ -28,7 +28,7 @@ class AndGroupSpecificationUnitTests { fun setUp() { every { leftSpecification.toPredicate(any(), any(), any()) } returns leftPredicate every { rightSpecification.toPredicate(any(), any(), any()) } returns rightPredicate - every { builder.and(any>(), any>()) } returns andPredicate + every { builder.and(*anyVararg()) } returns andPredicate } @Test @@ -48,9 +48,7 @@ class AndGroupSpecificationUnitTests { // validation assertEquals(andPredicate, result) - verify { - builder.and(leftPredicate as Expression, rightPredicate as Expression) - } + verify { builder.and(leftPredicate, rightPredicate) } } } diff --git a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/OrGroupSpecificationUnitTests.kt b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/OrGroupSpecificationUnitTests.kt index d2fd672..bdcde9a 100644 --- a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/OrGroupSpecificationUnitTests.kt +++ b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/group/OrGroupSpecificationUnitTests.kt @@ -28,7 +28,7 @@ class OrGroupSpecificationUnitTests { fun setUp() { every { leftSpecification.toPredicate(any(), any(), any()) } returns leftPredicate every { rightSpecification.toPredicate(any(), any(), any()) } returns rightPredicate - every { builder.or(any>(), any>()) } returns orPredicate + every { builder.or(*anyVararg()) } returns orPredicate } @Test @@ -48,9 +48,7 @@ class OrGroupSpecificationUnitTests { // validation assertEquals(orPredicate, result) - verify { - builder.or(leftPredicate as Expression, rightPredicate as Expression) - } + verify { builder.or(leftPredicate, rightPredicate) } } } diff --git a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/parameter/literal/LiteralParameterUnitTests.kt b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/parameter/literal/LiteralParameterUnitTests.kt index e11245e..ff66b6f 100644 --- a/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/parameter/literal/LiteralParameterUnitTests.kt +++ b/dynamic-query-specification/src/test/kotlin/br/com/dillmann/dynamicquery/specification/parameter/literal/LiteralParameterUnitTests.kt @@ -59,7 +59,7 @@ class LiteralParameterUnitTests { // validation assertEquals(result, literalExpression) verify { builder.literal(value) } - verify { ValueParsers.parse(any(), any()) wasNot Called } + verify(exactly = 0) { ValueParsers.parse(any(), any()) } } @Test diff --git a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepository.kt b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepository.kt index be879de..bc3b856 100644 --- a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepository.kt +++ b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepository.kt @@ -15,7 +15,7 @@ import java.util.* * @param T Generic type of the entity */ @NoRepositoryBean -interface DynamicQueryRepository : JpaSpecificationExecutor { +interface DynamicQueryRepository : JpaSpecificationExecutor { /** * Queries and returns a single result using provided [Specification] @@ -160,26 +160,4 @@ interface DynamicQueryRepository : JpaSpecificationExecutor { */ fun exists(specification: DynamicQuerySpecification?, scopeDownSupplier: ScopeDownSupplier): Boolean = exists(specification.toSpringSpecification(scopeDownSupplier)) - - /** - * Deletes any records that matches the provided [Specification] - * - * @param specification Dynamic Query's specification with the query predicates. If null is supplied, an empty - * predicate will be used with no query restrictions. - */ - fun delete(specification: DynamicQuerySpecification?): Long = - delete(specification.toSpringSpecification()) - - /** - * Deletes any records that matches the provided [Specification] and a scope-down supplied conditions, - * which allows a set of fixed conditions to be placed on top of the dynamic ones - * - * @param specification Dynamic Query's specification with the query predicates. If null is supplied, an empty - * predicate will be used with no query restrictions. - * @param scopeDownSupplier Specification transformer able to customize the generated [Specification] from the - * Dynamic Query's predicates. Please note that the supplier provided [Specification] will be used as-is, and - * is your responsibility to link (with an and/or expression) your query conditions with the Dynamic Query's ones. - */ - fun delete(specification: DynamicQuerySpecification?, scopeDownSupplier: ScopeDownSupplier): Long = - delete(specification.toSpringSpecification(scopeDownSupplier)) } diff --git a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationAdapter.kt b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationAdapter.kt index cc49032..5f9f72c 100644 --- a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationAdapter.kt +++ b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationAdapter.kt @@ -13,7 +13,7 @@ import org.springframework.data.jpa.domain.Specification * @param T Generic type of the specification's target entity * @param delegate Dynamic Query's specification to be adapted to the [Specification] */ -class DynamicQuerySpecificationAdapter(private val delegate: DynamicQuerySpecification): Specification { +class DynamicQuerySpecificationAdapter(private val delegate: DynamicQuerySpecification): Specification { /** * Produces a JPA-compliant predicate using the given criteria. Every call will be delegated to the adapted diff --git a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationExtensions.kt b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationExtensions.kt index 322d946..a716018 100644 --- a/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationExtensions.kt +++ b/dynamic-query-spring-boot-data-jpa/src/main/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQuerySpecificationExtensions.kt @@ -9,19 +9,19 @@ import org.springframework.data.jpa.domain.Specification * * @param T Generic type of the specification's target entity */ -fun DynamicQuerySpecification?.toSpringSpecification(): Specification = +fun DynamicQuerySpecification?.toSpringSpecification(): Specification = if (this != null) DynamicQuerySpecificationAdapter(this) else Specification.where { _, query, _ -> query.restriction } /** * Extension function for the [DynamicQuerySpecification] able to convert the instance to a Spring Data [Specification] * and apply additional predicates. If called on a null receiver/context, an empty [Specification] (with no query - * restrictions) will be used as the argument for the [scopeDownSupplier]. + * restrictions) will be used as the argument for the [supplier]. * * @param T Generic type of the specification's target entity - * @param scopeDownSupplier Specification transformer able to customize the generated [Specification] from the + * @param supplier Specification transformer able to customize the generated [Specification] from the * Dynamic Query's predicates. Please note that the supplier provided [Specification] will be used as-is, and * is your responsibility to link (with an and/or expression) your query conditions with the Dynamic Query's ones. */ -fun DynamicQuerySpecification?.toSpringSpecification(scopeDownSupplier: ScopeDownSupplier): Specification = - scopeDownSupplier(toSpringSpecification()) +fun DynamicQuerySpecification?.toSpringSpecification(supplier: ScopeDownSupplier): Specification = + supplier(toSpringSpecification()) diff --git a/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepositoryUnitTests.kt b/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepositoryUnitTests.kt index 0e3593b..163ce8b 100644 --- a/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepositoryUnitTests.kt +++ b/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/DynamicQueryRepositoryUnitTests.kt @@ -12,6 +12,7 @@ import org.junit.jupiter.api.Test import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort +import org.springframework.data.jpa.domain.DeleteSpecification import org.springframework.data.jpa.domain.Specification import java.util.* import kotlin.reflect.KFunction @@ -26,7 +27,7 @@ class DynamicQueryRepositoryUnitTests { private val findOneMock: (Specification) -> Optional = mockk() private val countMock: (Specification) -> Long = mockk() private val existsMock: (Specification) -> Boolean = mockk() - private val deleteMock: (Specification) -> Long = mockk() + private val deleteMock: (DeleteSpecification) -> Long = mockk() private val scopeDownSupplier: (Specification) -> Specification = mockk() private val specification: DynamicQuerySpecification = mockk() private val page: Pageable = mockk() @@ -194,24 +195,4 @@ class DynamicQueryRepositoryUnitTests { verify { specification.toSpringSpecification(scopeDownSupplier) } verify { existsMock(any>()) } } - - @Test - fun `delete without a scope-down customizer should convert the specification and delegate the execution to the Spring Data`() { - // execution - repository.delete(specification) - - // validation - verify { specification.toSpringSpecification() } - verify { deleteMock(any>()) } - } - - @Test - fun `delete with a scope-down customizer should convert the specification and delegate the execution to the Spring Data`() { - // execution - repository.delete(specification, scopeDownSupplier) - - // validation - verify { specification.toSpringSpecification(scopeDownSupplier) } - verify { deleteMock(any>()) } - } } diff --git a/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/artifacts/DynamicQueryRepositoryTestArtifact.kt b/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/artifacts/DynamicQueryRepositoryTestArtifact.kt index 636e177..112b283 100644 --- a/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/artifacts/DynamicQueryRepositoryTestArtifact.kt +++ b/dynamic-query-spring-boot-data-jpa/src/test/kotlin/br/com/dillmann/dynamicquery/springboot/datajpa/artifacts/DynamicQueryRepositoryTestArtifact.kt @@ -4,9 +4,10 @@ import br.com.dillmann.dynamicquery.springboot.datajpa.DynamicQueryRepository import org.springframework.data.domain.Page import org.springframework.data.domain.Pageable import org.springframework.data.domain.Sort +import org.springframework.data.jpa.domain.DeleteSpecification import org.springframework.data.jpa.domain.Specification +import org.springframework.data.jpa.domain.UpdateSpecification import org.springframework.data.jpa.repository.JpaSpecificationExecutor -import org.springframework.data.repository.query.FluentQuery import java.util.* import java.util.function.Function @@ -20,7 +21,7 @@ class DynamicQueryRepositoryTestArtifact( private val findOneDelegate: (Specification) -> Optional, private val countDelegate: (Specification) -> Long, private val existsDelegate: (Specification) -> Boolean, - private val deleteDelegate: (Specification) -> Long, + private val deleteDelegate: (DeleteSpecification) -> Long, ): DynamicQueryRepository { override fun findAll(specification: Specification): List = @@ -29,6 +30,9 @@ class DynamicQueryRepositoryTestArtifact( override fun findAll(specification: Specification, pageable: Pageable): Page = findAllPageDelegate(specification, pageable) + override fun findAll(specification: Specification, countSpec: Specification, pageable: Pageable): Page = + findAllPageDelegate(specification, pageable) + override fun findAll(specification: Specification, sort: Sort): List = findAllListDelegate(specification, sort) @@ -41,11 +45,14 @@ class DynamicQueryRepositoryTestArtifact( override fun exists(specification: Specification): Boolean = existsDelegate(specification) - override fun delete(specification: Specification): Long = + override fun delete(specification: DeleteSpecification): Long = deleteDelegate(specification) - override fun findBy( + override fun update(specification: UpdateSpecification): Long = + error("Not supported") + + override fun findBy( specification: Specification, - queryFunction: Function, R> + queryFunction: Function, R> ): R = error("Not supported") } diff --git a/dynamic-query/src/main/kotlin/br/com/dillmann/dynamicquery/DynamicQueryCompiler.kt b/dynamic-query/src/main/kotlin/br/com/dillmann/dynamicquery/DynamicQueryCompiler.kt index 9cfd72c..1016b14 100644 --- a/dynamic-query/src/main/kotlin/br/com/dillmann/dynamicquery/DynamicQueryCompiler.kt +++ b/dynamic-query/src/main/kotlin/br/com/dillmann/dynamicquery/DynamicQueryCompiler.kt @@ -66,7 +66,7 @@ object DynamicQueryCompiler { val currentPredicate = compile(child) leftSpecification = if (leftSpecification == null) currentPredicate - else compileLogicalOperator(logicalOperatorNode!!, leftSpecification!!, currentPredicate) + else compileLogicalOperator(logicalOperatorNode!!, leftSpecification, currentPredicate) } } diff --git a/examples/spring-boot-example/build.gradle b/examples/spring-boot-example/build.gradle index 52cd84d..b2b37d3 100644 --- a/examples/spring-boot-example/build.gradle +++ b/examples/spring-boot-example/build.gradle @@ -1,7 +1,7 @@ plugins { id 'java' - id 'org.springframework.boot' version '3.2.3' - id 'io.spring.dependency-management' version '1.1.4' + id 'org.springframework.boot' version '4.1.1' + id 'io.spring.dependency-management' version '1.1.7' } group = 'br.com.dillmann.dynamicquery.examples' @@ -21,6 +21,6 @@ dependencies { implementation 'org.flywaydb:flyway-core' implementation 'com.h2database:h2' - implementation 'br.com.dillmann.dynamicquery:dynamic-query-spring-boot-data-jpa:1.1.0' - implementation 'br.com.dillmann.dynamicquery:dynamic-query-spring-boot-web:1.1.0' + implementation 'br.com.dillmann.dynamicquery:dynamic-query-spring-boot-data-jpa:2.0.0' + implementation 'br.com.dillmann.dynamicquery:dynamic-query-spring-boot-web:2.0.0' } diff --git a/examples/spring-boot-example/gradle/wrapper/gradle-wrapper.properties b/examples/spring-boot-example/gradle/wrapper/gradle-wrapper.properties index 97f9ad6..2becd66 100644 --- a/examples/spring-boot-example/gradle/wrapper/gradle-wrapper.properties +++ b/examples/spring-boot-example/gradle/wrapper/gradle-wrapper.properties @@ -16,7 +16,7 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/examples/standalone-hibernate-example/README.md b/examples/standalone-hibernate-example/README.md new file mode 100644 index 0000000..f582785 --- /dev/null +++ b/examples/standalone-hibernate-example/README.md @@ -0,0 +1,26 @@ +# Standalone Hibernate example for the Dynamic Query + +This source code is a simple example of the integration and use of the Dynamic Query for JPA in a standalone +Hibernate-based project (or other JPA-compliant ORM). Only note that this is only a simple example, it isn't good +enough to be used as a template for new projects. + +Some key files to check out in this source: +- `ProductGroupHttpHandler`: Simple example on how to use the `DynamicQuery.parse()` API to parse a query string + and apply it as a JPA Criteria predicate +- `ProductHttpHandler`: More advanced use of the `DynamicQuery` with a simple example on how to apply fixed query + conditions on top of the Dynamic Query ones +- `Application`: Sets up a JDK `HttpServer` and wires everything together + +To get started with the demo, just execute `./gradlew run` on the command line and make some requests. The source +code uses an embedded H2 in-memory database with some pre-filled data. + +Some request examples: + +- [GET /product-groups?query=like(description, "Fruit%")](http://localhost:8080/product-groups?query=like%28description%2C%20%22Fruit%25%22%29) + to return only the product groups whose description starts with "Fruit" +- [GET /products?query=lessThan(unitPrice, 1)](http://localhost:8080/products?query=lessThan%28unitPrice%2C%201%29) + to retrieve the active products with a unit price less than 1 +- [GET /products?query=like(description, "B%")](http://localhost:8080/products?query=like%28description%2C%20%22B%25%22%29) + to retrieve the active products whose description starts with "B" +- [GET /products?query=equals(productGroup.id, 1)](http://localhost:8080/products?query=equals%28productGroup.id%2C%201%29) + to retrieve the active products belonging to product group 1 diff --git a/examples/standalone-hibernate-example/build.gradle b/examples/standalone-hibernate-example/build.gradle new file mode 100644 index 0000000..68bf948 --- /dev/null +++ b/examples/standalone-hibernate-example/build.gradle @@ -0,0 +1,28 @@ +plugins { + id 'java' + id 'application' + id 'org.hibernate.orm' version '7.0.0.Final' +} + +group = 'br.com.dillmann.dynamicquery.examples' +version = '0.0.1-SNAPSHOT' + +application { + mainClass = 'br.com.dillmann.dynamicquery.examples.hibernate.Application' +} + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.hibernate.orm:hibernate-core' + implementation 'com.h2database:h2:2.4.240' + implementation 'tools.jackson.core:jackson-databind:3.1.5' + + implementation 'br.com.dillmann.dynamicquery:dynamic-query:2.0.0' +} diff --git a/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.jar b/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.properties b/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2becd66 --- /dev/null +++ b/examples/standalone-hibernate-example/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,23 @@ +# +# Copyright 2012-2024 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/examples/standalone-hibernate-example/gradlew b/examples/standalone-hibernate-example/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/examples/standalone-hibernate-example/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/examples/standalone-hibernate-example/gradlew.bat b/examples/standalone-hibernate-example/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/examples/standalone-hibernate-example/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/standalone-hibernate-example/settings.gradle b/examples/standalone-hibernate-example/settings.gradle new file mode 100644 index 0000000..0f9474f --- /dev/null +++ b/examples/standalone-hibernate-example/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'standalone-hibernate-example' diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/AbstractHttpHandler.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/AbstractHttpHandler.java new file mode 100644 index 0000000..7997194 --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/AbstractHttpHandler.java @@ -0,0 +1,92 @@ +package br.com.dillmann.dynamicquery.examples.hibernate; + +import br.com.dillmann.dynamicquery.DynamicQuery; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import jakarta.persistence.EntityManager; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; +import tools.jackson.databind.json.JsonMapper; + +import java.io.IOException; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class AbstractHttpHandler implements HttpHandler { + private final JsonMapper jsonMapper = JsonMapper.builder().build(); + private final Class entityClass; + private final EntityManager entityManager; + + protected AbstractHttpHandler(final EntityManager entityManager, final Class entityClass) { + this.entityManager = entityManager; + this.entityClass = entityClass; + } + + protected Predicate staticPredicate( + final Root root, + final CriteriaQuery query, + final CriteriaBuilder builder + ) { + return null; + } + + @Override + public void handle(final HttpExchange exchange) throws IOException { + if (!"GET".equals(exchange.getRequestMethod())) { + exchange.sendResponseHeaders(405, -1); + return; + } + + final var params = parseQuery(exchange.getRequestURI().getRawQuery()); + final var queryExpression = params.get("query"); + + final var builder = entityManager.getCriteriaBuilder(); + final CriteriaQuery criteriaQuery = builder.createQuery(entityClass); + final Root root = criteriaQuery.from(entityClass); + + final var staticPredicate = staticPredicate(root, criteriaQuery, builder); + + if (queryExpression != null && !queryExpression.isBlank()) { + final var specification = DynamicQuery.parse(queryExpression); + final var dynamicPredicate = specification.toPredicate(root, criteriaQuery, builder); + final var finalPredicate = staticPredicate == null + ? dynamicPredicate + : builder.and(staticPredicate, dynamicPredicate); + + criteriaQuery.where(finalPredicate); + } else if (staticPredicate != null) { + criteriaQuery.where(staticPredicate); + } + + final var results = entityManager.createQuery(criteriaQuery).getResultList(); + final var responseBytes = jsonMapper.writeValueAsBytes(results); + + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, responseBytes.length); + try (final var os = exchange.getResponseBody()) { + os.write(responseBytes); + } + } + + private Map parseQuery(final String query) { + final var params = new LinkedHashMap(); + if (query == null || query.isBlank()) { + return params; + } + + for (final var param : query.split("&")) { + final var entry = param.split("=", 2); + final var key = URLDecoder.decode(entry[0], StandardCharsets.UTF_8); + final var value = entry.length > 1 + ? URLDecoder.decode(entry[1], StandardCharsets.UTF_8) + : null; + params.put(key, value); + } + + return params; + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/Application.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/Application.java new file mode 100644 index 0000000..74b2a7f --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/Application.java @@ -0,0 +1,26 @@ +package br.com.dillmann.dynamicquery.examples.hibernate; + +import br.com.dillmann.dynamicquery.examples.hibernate.product.ProductHttpHandler; +import br.com.dillmann.dynamicquery.examples.hibernate.productgroup.ProductGroupHttpHandler; +import com.sun.net.httpserver.HttpServer; + +import java.net.InetSocketAddress; + +public class Application { + + private static final int PORT = 8080; + + public static void main(final String[] args) throws Exception { + final var persistenceFactory = new PersistenceFactory(); + final var entityManager = persistenceFactory.getEntityManager(); + + final var server = HttpServer.create(new InetSocketAddress(PORT), 0); + server.createContext("/product-groups", new ProductGroupHttpHandler(entityManager)); + server.createContext("/products", new ProductHttpHandler(entityManager)); + + Runtime.getRuntime().addShutdownHook(new Thread(persistenceFactory::close)); + + server.start(); + System.out.println("Server started on port " + PORT); + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/PersistenceFactory.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/PersistenceFactory.java new file mode 100644 index 0000000..e5cd1ee --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/PersistenceFactory.java @@ -0,0 +1,60 @@ +package br.com.dillmann.dynamicquery.examples.hibernate; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.EntityManagerFactory; +import jakarta.persistence.Persistence; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +public class PersistenceFactory { + private final EntityManagerFactory delegate; + private final EntityManager entityManager; + + public PersistenceFactory() { + delegate = Persistence.createEntityManagerFactory("example"); + entityManager = delegate.createEntityManager(); + + entityManager.getTransaction().begin(); + seedData(); + entityManager.getTransaction().commit(); + } + + public EntityManager getEntityManager() { + return entityManager; + } + + public void close() { + entityManager.close(); + delegate.close(); + } + + private void seedData() { + try ( + final var stream = getClass().getResourceAsStream("/init.sql"); + final var reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)) + ) { + final var statementBuilder = new StringBuilder(); + String line; + + while ((line = reader.readLine()) != null) { + final var trimmed = line.trim(); + if (trimmed.isEmpty() || trimmed.startsWith("--")) { + continue; + } + + statementBuilder.append(line).append("\n"); + if (trimmed.endsWith(";")) { + entityManager.createNativeQuery(statementBuilder.toString()).executeUpdate(); + statementBuilder.setLength(0); + } + } + + if (!statementBuilder.isEmpty()) { + entityManager.createNativeQuery(statementBuilder.toString()).executeUpdate(); + } + } catch (final Exception e) { + throw new RuntimeException(e); + } + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/Product.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/Product.java new file mode 100644 index 0000000..6f9c5a6 --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/Product.java @@ -0,0 +1,68 @@ +package br.com.dillmann.dynamicquery.examples.hibernate.product; + +import br.com.dillmann.dynamicquery.examples.hibernate.productgroup.ProductGroup; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; + +import java.math.BigDecimal; + +@Entity +@Table(name = "product") +public class Product { + + @Id + private Integer id; + private String description; + private boolean active; + + @Column(name = "unit_price") + private BigDecimal unitPrice; + + @ManyToOne + @JoinColumn(name = "product_group_id") + private ProductGroup productGroup; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public boolean isActive() { + return active; + } + + public void setActive(boolean active) { + this.active = active; + } + + public BigDecimal getUnitPrice() { + return unitPrice; + } + + public void setUnitPrice(BigDecimal unitPrice) { + this.unitPrice = unitPrice; + } + + public ProductGroup getProductGroup() { + return productGroup; + } + + public void setProductGroup(ProductGroup productGroup) { + this.productGroup = productGroup; + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/ProductHttpHandler.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/ProductHttpHandler.java new file mode 100644 index 0000000..2a87a48 --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/product/ProductHttpHandler.java @@ -0,0 +1,24 @@ +package br.com.dillmann.dynamicquery.examples.hibernate.product; + +import br.com.dillmann.dynamicquery.examples.hibernate.AbstractHttpHandler; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.criteria.CriteriaBuilder; +import jakarta.persistence.criteria.CriteriaQuery; +import jakarta.persistence.criteria.Predicate; +import jakarta.persistence.criteria.Root; + +public class ProductHttpHandler extends AbstractHttpHandler { + public ProductHttpHandler(final EntityManager entityManager) { + super(entityManager, Product.class); + } + + @Override + protected Predicate staticPredicate( + final Root root, + final CriteriaQuery query, + final CriteriaBuilder builder + ) { + return builder.equal(root.get("active"), true); + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroup.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroup.java new file mode 100644 index 0000000..8b3d90b --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroup.java @@ -0,0 +1,30 @@ +package br.com.dillmann.dynamicquery.examples.hibernate.productgroup; + +import jakarta.persistence.Entity; +import jakarta.persistence.Id; +import jakarta.persistence.Table; + +@Entity +@Table(name = "product_group") +public class ProductGroup { + + @Id + private Integer id; + private String description; + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } +} diff --git a/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroupHttpHandler.java b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroupHttpHandler.java new file mode 100644 index 0000000..db834ef --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/java/br/com/dillmann/dynamicquery/examples/hibernate/productgroup/ProductGroupHttpHandler.java @@ -0,0 +1,10 @@ +package br.com.dillmann.dynamicquery.examples.hibernate.productgroup; + +import br.com.dillmann.dynamicquery.examples.hibernate.AbstractHttpHandler; +import jakarta.persistence.EntityManager; + +public class ProductGroupHttpHandler extends AbstractHttpHandler { + public ProductGroupHttpHandler(final EntityManager entityManager) { + super(entityManager, ProductGroup.class); + } +} diff --git a/examples/standalone-hibernate-example/src/main/resources/META-INF/persistence.xml b/examples/standalone-hibernate-example/src/main/resources/META-INF/persistence.xml new file mode 100644 index 0000000..8196501 --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,21 @@ + + + + org.hibernate.jpa.HibernatePersistenceProvider + + br.com.dillmann.dynamicquery.examples.hibernate.product.Product + br.com.dillmann.dynamicquery.examples.hibernate.productgroup.ProductGroup + + + + + + + + + + + diff --git a/examples/standalone-hibernate-example/src/main/resources/init.sql b/examples/standalone-hibernate-example/src/main/resources/init.sql new file mode 100644 index 0000000..8b3ec2b --- /dev/null +++ b/examples/standalone-hibernate-example/src/main/resources/init.sql @@ -0,0 +1,30 @@ +CREATE TABLE product_group ( + id INT NOT NULL PRIMARY KEY, + description VARCHAR(255) NOT NULL +); + +CREATE TABLE product ( + id INT NOT NULL PRIMARY KEY, + active BOOLEAN NOT NULL, + description VARCHAR(255) NOT NULL, + product_group_id INT NOT NULL, + unit_price NUMERIC(10, 2) NOT NULL, + CONSTRAINT product_product_group_fk FOREIGN KEY (product_group_id) REFERENCES product_group (id) +); + +INSERT INTO product_group (id, description) +VALUES (1, 'Fruits'), + (2, 'Dairy'), + (3, 'Meat'), + (4, 'Beverages'), + (5, 'Vegetables'); + +INSERT INTO product (id, active, description, product_group_id, unit_price) +VALUES (1, true, 'Apple', 1, 0.25), + (2, true, 'Banana', 1, 0.33), + (3, true, 'Potato', 5, 0.20), + (4, true, 'Onion', 5, 1.32), + (5, true, 'Butter', 2, 1.99), + (6, true, 'Chicken', 3, 1.99), + (7, true, 'Bacon', 3, 2.95), + (8, true, 'Orange', 5, 0.65); diff --git a/gradle.properties b/gradle.properties index 89823a9..6403dd9 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,7 +1,9 @@ kotlin.code.style=official +org.jetbrains.dokka.experimental.gradle.pluginMode=V2EnabledWithHelpers systemProp.sonar.gradle.skipCompile=true -kotlinVersion=1.9.10 -junitVersion=5.10.2 -mockkVersion=1.13.10 -jakartaPersistenceApiVersion=3.1.0 -antlrVersion=4.13.1 + +kotlinVersion=2.4.10 +junitVersion=5.14.4 +mockkVersion=1.14.11 +jakartaPersistenceApiVersion=3.2.0 +antlrVersion=4.13.2 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 98de593..e8fb6cb 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ #Sun Feb 25 18:35:06 BRT 2024 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/settings.gradle.kts b/settings.gradle.kts index 0215822..d93cbcd 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,5 +1,5 @@ plugins { - id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0" + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" } rootProject.name = "dynamicquery"