From 173989cf702f212e376d0be4a49450289c4a06a0 Mon Sep 17 00:00:00 2001 From: Javier Godoy <11554739+javier-godoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 19:12:55 -0300 Subject: [PATCH 1/4] docs: document QuerySpec methods --- .../com/appjars/saturn/model/QuerySpec.java | 47 +++++++++++++++++-- 1 file changed, 44 insertions(+), 3 deletions(-) diff --git a/commons-model/src/main/java/com/appjars/saturn/model/QuerySpec.java b/commons-model/src/main/java/com/appjars/saturn/model/QuerySpec.java index 93d5629..0f3325e 100644 --- a/commons-model/src/main/java/com/appjars/saturn/model/QuerySpec.java +++ b/commons-model/src/main/java/com/appjars/saturn/model/QuerySpec.java @@ -26,26 +26,29 @@ import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; - +import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; -@Getter -@Setter public class QuerySpec { public enum Order { ASC, DESC; } + @Getter + @Setter private String[] returnedAttributes; + @Getter + @Setter private Map orders; private Integer firstResult; private Integer maxResult; + @Getter private final Collection constraints = new ArrayList<>(); public void addOrder(String property, Order order) { @@ -80,4 +83,42 @@ public String toString() { return buffer.toString(); } + /** + * Return the position of the first result to retrieve. + * @return the position of the first result to retrieve (numbered from 0) or null. + * @see {@link #setFirstResult(Integer)} + */ + public Integer getFirstResult() { + return firstResult; + } + + /** + * Return the maximum number of results to retrieve. + * @return the maximum number of results to retrieve, or null. + */ + public Integer getMaxResult() { + return maxResult; + } + + /** + * Set the position of the first result to retrieve. + * @param startPosition position of the first result, + * numbered from 0 (may be null) + * @return the same query instance + * @throws IllegalArgumentException if the argument is negative + */ + public void setFirstResult(Integer firstResult) { + if (firstResult!=null && firstResult<0) throw new IllegalArgumentException(); + this.firstResult = firstResult; + } + + /** + * Set the maximum number of results to retrieve. + * @param maxResult maximum number of results to retrieve (may be null) + * @throws IllegalArgumentException if the argument is negative + */ + public void setMaxResult(Integer maxResult) { + if (maxResult!=null && maxResult<0) throw new IllegalArgumentException(); + this.maxResult = maxResult; + } } From a480b6860768b436f941c1b6fe5edf2f32c11d72 Mon Sep 17 00:00:00 2001 From: Javier Godoy <11554739+javier-godoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 19:14:22 -0300 Subject: [PATCH 2/4] feat: add constructor to ConstraintTransformerJpaImpl --- .../saturn/dao/jpa/ConstraintTransformerJpaImpl.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/commons-data-impl/src/main/java/com/appjars/saturn/dao/jpa/ConstraintTransformerJpaImpl.java b/commons-data-impl/src/main/java/com/appjars/saturn/dao/jpa/ConstraintTransformerJpaImpl.java index acacf84..b2af05b 100644 --- a/commons-data-impl/src/main/java/com/appjars/saturn/dao/jpa/ConstraintTransformerJpaImpl.java +++ b/commons-data-impl/src/main/java/com/appjars/saturn/dao/jpa/ConstraintTransformerJpaImpl.java @@ -41,11 +41,17 @@ import com.appjars.saturn.model.constraints.AttributeRelationalConstraint; import com.appjars.saturn.model.constraints.NegatedConstraint; import com.appjars.saturn.model.constraints.RelationalConstraint; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +@RequiredArgsConstructor public class ConstraintTransformerJpaImpl extends ConstraintTransformer { + @NonNull private final CriteriaBuilder criteriaBuilder; - private From root; + + @NonNull + private final From root; public ConstraintTransformerJpaImpl(EntityManager em, From root) { this.criteriaBuilder = em.getCriteriaBuilder(); From 1142921f0ebbafc5791c37b38dbddb897d6a0fcb Mon Sep 17 00:00:00 2001 From: Javier Godoy <11554739+javier-godoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 19:52:42 -0300 Subject: [PATCH 3/4] feat: improve ConstraintBuilder API --- .../com/appjars/saturn/model/Constraint.java | 6 + .../saturn/model/ConstraintBuilder.java | 146 +++++++++++++----- 2 files changed, 117 insertions(+), 35 deletions(-) diff --git a/commons-model/src/main/java/com/appjars/saturn/model/Constraint.java b/commons-model/src/main/java/com/appjars/saturn/model/Constraint.java index 83afb0c..3b78706 100644 --- a/commons-model/src/main/java/com/appjars/saturn/model/Constraint.java +++ b/commons-model/src/main/java/com/appjars/saturn/model/Constraint.java @@ -19,6 +19,12 @@ */ package com.appjars.saturn.model; +import com.appjars.saturn.model.constraints.NegatedConstraint; + public interface Constraint { + default Constraint not() { + return new NegatedConstraint(this); + } + } diff --git a/commons-model/src/main/java/com/appjars/saturn/model/ConstraintBuilder.java b/commons-model/src/main/java/com/appjars/saturn/model/ConstraintBuilder.java index 2d94000..e8c7ffc 100644 --- a/commons-model/src/main/java/com/appjars/saturn/model/ConstraintBuilder.java +++ b/commons-model/src/main/java/com/appjars/saturn/model/ConstraintBuilder.java @@ -20,7 +20,8 @@ package com.appjars.saturn.model; import java.util.Collection; - +import java.util.stream.Collectors; +import java.util.stream.Stream; import com.appjars.saturn.model.constraints.AttributeBetweenConstraint; import com.appjars.saturn.model.constraints.AttributeILikeConstraint; import com.appjars.saturn.model.constraints.AttributeInConstraint; @@ -29,41 +30,116 @@ import com.appjars.saturn.model.constraints.AttributeRelationalConstraint; import com.appjars.saturn.model.constraints.NegatedConstraint; import com.appjars.saturn.model.constraints.RelationalConstraint; +import lombok.AccessLevel; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; -import lombok.experimental.UtilityClass; - -@UtilityClass +@RequiredArgsConstructor(access = AccessLevel.PROTECTED) public class ConstraintBuilder { - public Constraint not(Constraint c) { - return new NegatedConstraint(c); - } - - public Constraint equal(String attribute, Object value) { - return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.EQ); - } - - public Constraint notEqual(String attribute, Object value) { - return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.NE); - } - - public > Constraint between(String attribute, T lower, T upper) { - return new AttributeBetweenConstraint(attribute, lower, upper); - } - - public Constraint like(String attribute, String pattern) { - return new AttributeLikeConstraint(attribute, pattern); - } - - public Constraint in(String attribute, Collection values) { - return new AttributeInConstraint(attribute, values); - } - - public Constraint isNull(String attribute) { - return new AttributeNullConstraint(attribute); - } - - public Constraint iLike(String attribute, String pattern) { - return new AttributeILikeConstraint(attribute, pattern); - } + public static ConstraintBuilder of(String attribute0, String... attributes) { + String attribute = Stream.concat(Stream.of(attribute0), Stream.of(attributes)).collect(Collectors.joining(".")); + return new ConstraintBuilder(attribute); + } + + @NonNull + private final String attribute; + + /** + * @deprecated Use {@link Constraint#not()} + */ + @Deprecated + public static Constraint not(Constraint c) { + return new NegatedConstraint(c); + } + + /** @deprecated Use {@link #equal(String)} */ + @Deprecated + public static Constraint equal(String attribute, Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.EQ); + } + + /** @deprecated Use {@link #notEqual(String)} */ + @Deprecated + public static Constraint notEqual(String attribute, Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.NE); + } + + /** @deprecated Use {@link #between(String)} */ + @Deprecated + public > Constraint between(String attribute, T lower, T upper) { + return new AttributeBetweenConstraint(attribute, lower, upper); + } + + /** @deprecated Use {@link #like(String)} */ + @Deprecated + public static Constraint like(String attribute, String pattern) { + return new AttributeLikeConstraint(attribute, pattern); + } + + /** @deprecated Use {@link #in(String)} */ + @Deprecated + public static Constraint in(String attribute, Collection values) { + return new AttributeInConstraint(attribute, values); + } + + /** @deprecated Use {@link #isNull(String)} */ + @Deprecated + public static Constraint isNull(String attribute) { + return new AttributeNullConstraint(attribute); + } + + /** @deprecated Use {@link #iLike(String)} */ + @Deprecated + public static Constraint iLike(String attribute, String pattern) { + return new AttributeILikeConstraint(attribute, pattern); + } + + public Constraint equal(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.EQ); + } + + public Constraint notEqual(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.NE); + } + + public Constraint lessThan(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.LT); + } + + public Constraint greaterThan(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.GT); + } + + public Constraint greaterOrEqualThan(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.GE); + } + + public Constraint lessOrEqualThan(Object value) { + return new AttributeRelationalConstraint(attribute, value, RelationalConstraint.LE); + } + + public > Constraint between(T lower, T upper) { + return new AttributeBetweenConstraint(attribute, lower, upper); + } + + public Constraint like(String pattern) { + return new AttributeLikeConstraint(attribute, pattern); + } + + public Constraint in(Collection values) { + return new AttributeInConstraint(attribute, values); + } + + public Constraint isNull() { + return new AttributeNullConstraint(attribute); + } + public Constraint isNotNull() { + return ConstraintBuilder.not(new AttributeNullConstraint(attribute)); + } + + public Constraint iLike(String pattern) { + return new AttributeILikeConstraint(attribute, pattern); + } + } From 01d4a355216e9412ba8e328853973fe271718ba0 Mon Sep 17 00:00:00 2001 From: Javier Godoy <11554739+javier-godoy@users.noreply.github.com> Date: Tue, 12 Apr 2022 22:01:15 -0300 Subject: [PATCH 4/4] feat: add support for spring-data repositories --- commons-business-spring-impl/LICENSE.txt | 201 ++++++++++++++++++ commons-business-spring-impl/pom.xml | 42 ++++ .../service/ConstraintSpecification.java | 34 +++ .../saturn/service/JpaCrudService.java | 149 +++++++++++++ pom.xml | 1 + 5 files changed, 427 insertions(+) create mode 100644 commons-business-spring-impl/LICENSE.txt create mode 100644 commons-business-spring-impl/pom.xml create mode 100644 commons-business-spring-impl/src/main/java/com/appjars/saturn/service/ConstraintSpecification.java create mode 100644 commons-business-spring-impl/src/main/java/com/appjars/saturn/service/JpaCrudService.java diff --git a/commons-business-spring-impl/LICENSE.txt b/commons-business-spring-impl/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/commons-business-spring-impl/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/commons-business-spring-impl/pom.xml b/commons-business-spring-impl/pom.xml new file mode 100644 index 0000000..b3fbaf8 --- /dev/null +++ b/commons-business-spring-impl/pom.xml @@ -0,0 +1,42 @@ + + + 4.0.0 + + + com.appjars.saturn.backend + commons-backend + 1.2.0-SNAPSHOT + + + commons-business-spring-impl + Commons Backend - Business Implementation (Spring Data) + + + + com.appjars.saturn.backend + commons-business-impl + ${project.version} + + + com.appjars.saturn.backend + commons-data-impl + ${project.version} + + + org.projectlombok + lombok + provided + + + javax.persistence + javax.persistence-api + + + org.springframework.data + spring-data-jpa + 2.6.3 + + + + diff --git a/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/ConstraintSpecification.java b/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/ConstraintSpecification.java new file mode 100644 index 0000000..5d45dae --- /dev/null +++ b/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/ConstraintSpecification.java @@ -0,0 +1,34 @@ +package com.appjars.saturn.service; + +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.lang.NonNull; +import com.appjars.saturn.dao.jpa.ConstraintTransformerJpaImpl; +import com.appjars.saturn.model.Constraint; +import com.appjars.saturn.model.QuerySpec; +import lombok.AccessLevel; +import lombok.RequiredArgsConstructor; + +@SuppressWarnings("serial") +@RequiredArgsConstructor(access = AccessLevel.PRIVATE) +final class ConstraintSpecification implements Specification { + + @NonNull + private final Constraint constraint; + + private static Specification newInstance(Constraint constraint) { + return new ConstraintSpecification<>(constraint); + } + + @Override + public javax.persistence.criteria.Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder criteriaBuilder) { + return new ConstraintTransformerJpaImpl(criteriaBuilder, root).apply(constraint); + } + + static Specification buildSpecification(QuerySpec querySpec) { + return querySpec.getConstraints().stream().map(ConstraintSpecification::newInstance).reduce(Specification::and).orElse(null); + } + +} diff --git a/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/JpaCrudService.java b/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/JpaCrudService.java new file mode 100644 index 0000000..ff52f0b --- /dev/null +++ b/commons-business-spring-impl/src/main/java/com/appjars/saturn/service/JpaCrudService.java @@ -0,0 +1,149 @@ +package com.appjars.saturn.service; + +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; + +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.jpa.domain.Specification; +import org.springframework.data.jpa.repository.JpaSpecificationExecutor; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.util.Streamable; + +import com.appjars.saturn.model.ErrorDescription; +import com.appjars.saturn.model.QuerySpec; +import com.appjars.saturn.service.CrudService; +import com.appjars.saturn.service.validation.CreationValidator; +import com.appjars.saturn.service.validation.DeletionValidator; +import com.appjars.saturn.service.validation.UpdateValidator; +import com.appjars.saturn.validation.CreationValidationException; +import com.appjars.saturn.validation.DeletionValidationException; +import com.appjars.saturn.validation.UpdateValidationException; +import com.appjars.saturn.validation.ValidationException; +import com.appjars.saturn.validation.ValidationSupport; +import com.appjars.saturn.validation.Validator; + +public abstract class JpaCrudService implements CrudService { + + protected abstract CrudRepository getCrudRepository(); + + protected abstract JpaSpecificationExecutor getExecutor(); + + protected Specification buildSpecification(QuerySpec spec) { + return ConstraintSpecification.buildSpecification(spec); + } + + protected abstract K getId(T entity); + + private Sort buildSort(QuerySpec filter) { + if (filter.getOrders()==null || filter.getOrders().isEmpty()) { + return Sort.unsorted(); + } else { + return Sort.by(filter.getOrders().entrySet().stream().map(e->{ + switch (e.getValue()) { + case ASC: + return Sort.Order.asc(e.getKey()); + case DESC: + return Sort.Order.desc(e.getKey()); + } + throw new AssertionError(); + }).collect(Collectors.toList())); + } + } + + private Pageable buildPageable(QuerySpec filter) { + if (filter.getMaxResult()==null) { + throw new IllegalArgumentException("QuerySpec is not pageable"); + } + + int firstResult = Optional.ofNullable(filter.getFirstResult()).orElse(0); + int firstPage = firstResult/filter.getMaxResult(); + if (firstResult%filter.getMaxResult() !=0) { + throw new IllegalArgumentException("QuerySpec is not pageable"); + } + + Sort sort = buildSort(filter); + return PageRequest.of(firstPage, filter.getMaxResult(), sort); + } + + @Override + public Optional findById(K id) { + return getCrudRepository().findById(id); + } + + @Override + public List findAll() { + return Streamable.of(getCrudRepository().findAll()).toList(); + } + + @Override + public List filter(QuerySpec filter) { + if (filter.getFirstResult()==null && filter.getMaxResult()==null) { + return getExecutor().findAll(buildSpecification(filter), buildSort(filter)); + } else if (filter.getMaxResult().equals(0)) { + return Collections.emptyList(); + } else { + return getExecutor().findAll(buildSpecification(filter), buildPageable(filter)).toList(); + } + } + + @Override + public long count(QuerySpec filter) { + return getExecutor().count(buildSpecification(filter)); + } + + private List> getValidators(@SuppressWarnings("rawtypes") Class validatorType) { + if (this instanceof ValidationSupport) { + @SuppressWarnings("unchecked") + List> validators = ((ValidationSupport)this).getValidators(validatorType); + return validators; + } else { + return Collections.emptyList(); + } + } + + private void validate(@SuppressWarnings("rawtypes") Class validatorType, T entity, Function,ValidationException> newException) { + List> validators = getValidators(validatorType); + if (!validators.isEmpty()) { + List errors = validators.stream().flatMap(val->val.validate(entity).stream()).collect(Collectors.toList()); + if (!errors.isEmpty()) { + throw newException.apply(errors); + } + } + } + + @Override + public K save(T entity) { + validate(CreationValidator.class, entity, CreationValidationException::new); + return getId(getCrudRepository().save(entity)); + } + + @Override + public void update(T entity) { + validate(UpdateValidator.class, entity, UpdateValidationException::new); + getCrudRepository().save(entity); + } + + @Override + public void delete(T entity) { + validate(DeletionValidator.class, entity, DeletionValidationException::new); + getCrudRepository().delete(entity); + } + + @Override + public void deleteById(K id) { + if (getValidators(DeletionValidator.class).isEmpty()) { + getCrudRepository().deleteById(id); + } else { + findById(id).ifPresent(entity->{ + validate(DeletionValidator.class, entity, DeletionValidationException::new); + getCrudRepository().delete(entity); + }); + } + } + +} diff --git a/pom.xml b/pom.xml index fa368df..dc9082f 100644 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,7 @@ commons-data-impl commons-business commons-business-impl + commons-business-spring-impl commons-model