From 40acbcd6ac93b4fd0623fe57a9e19cd34bb1f64a Mon Sep 17 00:00:00 2001 From: Joern Muehlencord Date: Sat, 22 Jun 2019 01:00:56 +0200 Subject: [PATCH] introduced CommonAbstractController and StandardController --- .../shared/db/AbstractController.java | 253 +-------------- .../shared/db/CommonAbstractController.java | 297 ++++++++++++++++++ .../shared/db/StandardController.java | 77 +++++ 3 files changed, 381 insertions(+), 246 deletions(-) create mode 100644 db/src/main/java/de/muehlencord/shared/db/CommonAbstractController.java create mode 100644 db/src/main/java/de/muehlencord/shared/db/StandardController.java diff --git a/db/src/main/java/de/muehlencord/shared/db/AbstractController.java b/db/src/main/java/de/muehlencord/shared/db/AbstractController.java index b6baec5..8617c7d 100644 --- a/db/src/main/java/de/muehlencord/shared/db/AbstractController.java +++ b/db/src/main/java/de/muehlencord/shared/db/AbstractController.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 Joern Muehlencord . + * Copyright 2016 Joern Muehlencord * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,44 +15,28 @@ */ package de.muehlencord.shared.db; -import de.muehlencord.shared.util.DateUtil; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.Map; import javax.ejb.Lock; import javax.ejb.LockType; -import javax.ejb.TransactionAttribute; -import javax.ejb.TransactionAttributeType; -import javax.inject.Inject; import javax.persistence.EntityGraph; -import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Order; -import javax.persistence.criteria.Path; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; -import javax.persistence.metamodel.IdentifiableType; -import javax.persistence.metamodel.Metamodel; -import javax.persistence.metamodel.SingularAttribute; -import javax.transaction.Transactional; -import org.apache.commons.lang3.StringUtils; /** * * @author Joern Muehlencord * @param */ -public abstract class AbstractController { - - @Inject - @ApplicationPU - protected EntityManager em; +public abstract class AbstractController extends CommonAbstractController { private final Class entityClass; @@ -60,215 +44,16 @@ public abstract class AbstractController { this.entityClass = clazz; } - protected Predicate getFilterCondition(CriteriaBuilder cb, Root root, Map filters) { - return getFilterCondition(cb, root, filters, null); - } - - protected Predicate getFilterCondition(CriteriaBuilder cb, Root root, Map filters, Map excludeFilters) { - Predicate filterCondition = null; - filterCondition = getFilterCondition(filterCondition, cb, root, filters, true); - filterCondition = getFilterCondition(filterCondition, cb, root, excludeFilters, false); - return filterCondition; - } - - protected Predicate addFilterCondition(CriteriaBuilder cb, Predicate filterCondition, Predicate addCondition) { - if (addCondition == null) { - return filterCondition; - } - if (filterCondition == null) { - filterCondition = addCondition; - } else { - filterCondition = cb.and(filterCondition, addCondition); - } - return filterCondition; - } /** - * extends the given filterCondition by the addtional filters - * - * @param filterCondition the current filter condition - * @param cb the criteria builder to use - * @param root the root of the object to search for - * @param filters the filters to apply - * @param include if set to true, the filter is used as include filter - * (equals, in). If set to false, the filter is inverted and used as exclude - * filter (not equals, not in etc) - * @return + * * general find methods *** */ - protected Predicate getFilterCondition(Predicate filterCondition, CriteriaBuilder cb, Root root, Map filters, boolean include) { - String wildCard = "%"; - if (filters != null) { - for (Map.Entry filter : filters.entrySet()) { - if (!"".equals(filter.getValue())) { - Path path = getPathElement(root, filter); - - // check for differnt types - // 1st String, either from Enum Status or from other free text string - if (filter.getValue() == null) { - Predicate predicate; - if (include) { - predicate = cb.isNull(path); - } else { - predicate = cb.isNotNull(path); - } - filterCondition = addFilterCondition(cb, filterCondition, predicate); - } else if (String.class.equals(filter.getValue().getClass())) { - switch (filter.getKey()) { - default: - String filterValue = filter.getValue().toString(); - Predicate predicate; - if (filterValue.equals("{NULL}")) { - if (include) { - predicate = cb.isNull(path); - } else { - predicate = cb.isNotNull(path); - } - } else { - filterValue = filterValue.trim(); - filterValue = filterValue.replace("?", "_"); - filterValue = filterValue.replace("*", "%"); - - String[] values = filterValue.split("\\s+"); // split by whitespaces - Predicate[] partSearchPredicates = new Predicate[values.length]; - for (int i = 0; i < values.length; i++) { - String value = wildCard + values[i] + wildCard; - if (include) { - partSearchPredicates[i] = cb.like(cb.upper(path), value.toUpperCase(Locale.US), '\\'); - } else { - partSearchPredicates[i] = cb.notLike(cb.upper(path), value.toUpperCase(Locale.US), '\\'); - } - } - predicate = cb.and(partSearchPredicates); // all parts must be available - } - filterCondition = addFilterCondition(cb, filterCondition, predicate); - } - } // 2nd for arrays, received from e.g. project selections - else if (filter.getValue().getClass().isArray()) { - Predicate condition = null; - Object[] values = (Object[]) filter.getValue(); - if (values.length > 0) { - for (Object value : values) { - if (include) { - Predicate equalPredicate = cb.equal(path, value); - if (condition == null) { - condition = equalPredicate; - } else { - condition = cb.or(condition, equalPredicate); - } - } else { - Predicate equalPredicate = cb.notEqual(path, value); - if (condition == null) { - condition = equalPredicate; - } else { - condition = cb.and(condition, equalPredicate); - } - } - } - filterCondition = addFilterCondition(cb, filterCondition, condition); - } - } else { // at last object comparison - if (include) { - filterCondition = addFilterCondition(cb, filterCondition, cb.equal(path, filter.getValue())); - } else { - filterCondition = addFilterCondition(cb, filterCondition, cb.notEqual(path, filter.getValue())); - } - } - } - } - } - return filterCondition; - } - - private Path getPathElement(Root root, Map.Entry filter) { - String[] pathElements = StringUtils.split(filter.getKey(), '.'); - Path path = null; - for (String element : pathElements) { - if (path == null) { - path = root.get(element); - } else { - path = path.get(element); - } - } - return path; - } - - public Audit applyAuditChanges(Audit audit, boolean onCreate, String changedBy) throws ControllerException { - if (audit == null) { - audit = new Audit(); - } - if (onCreate) { - audit.setCreatedBy(changedBy); - audit.setCreatedOn(DateUtil.getCurrentTimeInUTC()); - } - audit.setLastUpdatedBy(changedBy); - audit.setLastUpdatedOn(DateUtil.getCurrentTimeInUTC()); - - return audit; - } - - public T attach(T entity) { - return em.merge(entity); - } - - @TransactionAttribute(TransactionAttributeType.REQUIRED) - @Transactional - @Lock(LockType.WRITE) - public T create(T entity, String createdBy) throws ControllerException { - if (Auditable.class.isAssignableFrom(entity.getClass())) { - Audit audit = ((Auditable) entity).getAudit(); - ((Auditable) entity).setAudit(applyAuditChanges(audit, true, createdBy)); - } - if (EndDateable.class.isAssignableFrom(entity.getClass())) { - EndDateable endDateable = (EndDateable) entity; - endDateable.setValidFrom(DateUtil.getCurrentTimeInUTC()); - } - em.persist(entity); - return entity; - } - - @TransactionAttribute(TransactionAttributeType.REQUIRED) - @Transactional - @Lock(LockType.WRITE) - public T update(T entity, String updatedBy) throws ControllerException { - T currentEntity = attach(entity); - T newEntity = EntityUtil.cloneToNewEntity(currentEntity); - if (Auditable.class.isAssignableFrom(entity.getClass())) { - Audit audit = ((Auditable) entity).getAudit(); - ((Auditable) entity).setAudit(applyAuditChanges(audit, false, updatedBy)); - } - - if (EndDateable.class.isAssignableFrom(entity.getClass())) { - // end date existing entity - EndDateable endDateable = (EndDateable) entity; - endDateable.setValidTo(DateUtil.getCurrentTimeInUTC()); - em.merge(entity); - // and create new entity instead - - return create(newEntity, updatedBy); - } else { - // if it is not enddatable, just update it (already done above) - // and save it - return em.merge(entity); - } - } - - @TransactionAttribute(TransactionAttributeType.REQUIRED) - @Transactional - @Lock(LockType.WRITE) - public void delete(T entity, String deletedBy) throws ControllerException { - // if the entity is endDateable just set the validToDate to now intead of executing the deletion - if (EndDateable.class.isAssignableFrom(entity.getClass())) { - update(entity, deletedBy); - } else { - em.remove(attach(entity)); - } - } - + @Lock(LockType.READ) public T find(Object id) { return em.find(entityClass, id); - } - + } + @Lock(LockType.READ) public T find(Object id, String... subGraphItems) { EntityGraph graph = this.em.createEntityGraph(entityClass); @@ -323,30 +108,6 @@ public abstract class AbstractController { return query.getResultList(); } + - /** - * returns null, if the list is empty or null itself. Returns the one - * element if there is exactly one element in the list. Otherwise an - * exception is thrown - * - * @param resultList - * @return - * @throws ControllerException - */ - public T ensureSingleElement(List resultList) throws ControllerException { - if ((resultList == null) || (resultList.isEmpty())) { - return null; - } - if (resultList.size() > 1) { - throw new ControllerException(ControllerException.CAUSE_TOO_MANY_ROWS, "More than one element found in list - expected exactly one"); - } - return resultList.get(0); - } - - private SingularAttribute getIdAttribute() { - Metamodel m = em.getEntityManagerFactory().getMetamodel(); - IdentifiableType of = (IdentifiableType) m.managedType(entityClass); -// of.getDeclaredId(entityClass).getJavaMember(). - return of.getId(of.getIdType().getJavaType()); - } } diff --git a/db/src/main/java/de/muehlencord/shared/db/CommonAbstractController.java b/db/src/main/java/de/muehlencord/shared/db/CommonAbstractController.java new file mode 100644 index 0000000..2dae84b --- /dev/null +++ b/db/src/main/java/de/muehlencord/shared/db/CommonAbstractController.java @@ -0,0 +1,297 @@ +/* + * Copyright 2019 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.db; + +import de.muehlencord.shared.util.DateUtil; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import javax.ejb.Lock; +import javax.ejb.LockType; +import javax.ejb.TransactionAttribute; +import javax.ejb.TransactionAttributeType; +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Path; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; +import javax.transaction.Transactional; +import org.apache.commons.lang3.StringUtils; + +/** + * + * @author joern.muehlencord + */ +public abstract class CommonAbstractController { + + @Inject + @ApplicationPU + protected EntityManager em; + + @Lock(LockType.READ) + public List findAll(Class entityClass) { + return findAll(entityClass, new ArrayList<>()); + } + + @Lock(LockType.READ) + public List findAll(Class entityClass, String... orderFields) { + return findAll(entityClass, Arrays.asList(orderFields)); + } + + @Lock(LockType.READ) + public List findAll(Class entityClass, List orderFields) { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery criteria = cb.createQuery(entityClass); + + final Root r = criteria.from(entityClass); + + List orderList = new ArrayList<>(); + orderFields.stream().forEachOrdered(field -> orderList.add(cb.asc(r.get(field)))); + final TypedQuery query = em.createQuery(criteria.orderBy(orderList)); + + return query.getResultList(); + } + + /* **** standard crud options *** */ + public Audit applyAuditChanges(Audit audit, boolean onCreate, String changedBy) throws ControllerException { + if (audit == null) { + audit = new Audit(); + } + if (onCreate) { + audit.setCreatedBy(changedBy); + audit.setCreatedOn(DateUtil.getCurrentTimeInUTC()); + } + audit.setLastUpdatedBy(changedBy); + audit.setLastUpdatedOn(DateUtil.getCurrentTimeInUTC()); + + return audit; + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + @Transactional + @Lock(LockType.WRITE) + public T create(T entity, String createdBy) throws ControllerException { + if (Auditable.class.isAssignableFrom(entity.getClass())) { + Audit audit = ((Auditable) entity).getAudit(); + ((Auditable) entity).setAudit(applyAuditChanges(audit, true, createdBy)); + } + if (EndDateable.class.isAssignableFrom(entity.getClass())) { + EndDateable endDateable = (EndDateable) entity; + endDateable.setValidFrom(DateUtil.getCurrentTimeInUTC()); + } + em.persist(entity); + return entity; + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + @Transactional + @Lock(LockType.WRITE) + public T update(T entity, String updatedBy) throws ControllerException { + T currentEntity = attach(entity); + T newEntity = EntityUtil.cloneToNewEntity(currentEntity); + if (Auditable.class.isAssignableFrom(entity.getClass())) { + Audit audit = ((Auditable) entity).getAudit(); + ((Auditable) entity).setAudit(applyAuditChanges(audit, false, updatedBy)); + } + + if (EndDateable.class.isAssignableFrom(entity.getClass())) { + // end date existing entity + EndDateable endDateable = (EndDateable) entity; + endDateable.setValidTo(DateUtil.getCurrentTimeInUTC()); + em.merge(entity); + // and create new entity instead + + return create(newEntity, updatedBy); + } else { + // if it is not enddatable, just update it (already done above) + // and save it + return em.merge(entity); + } + } + + @TransactionAttribute(TransactionAttributeType.REQUIRED) + @Transactional + @Lock(LockType.WRITE) + public void delete(T entity, String deletedBy) throws ControllerException { + // if the entity is endDateable just set the validToDate to now intead of executing the deletion + if (EndDateable.class.isAssignableFrom(entity.getClass())) { + update(entity, deletedBy); + } else { + em.remove(attach(entity)); + } + } + + public T attach(T entity) { + return em.merge(entity); + } + + + /* *** filter methods *** */ + protected Predicate getFilterCondition(CriteriaBuilder cb, Root root, Map filters) { + return getFilterCondition(cb, root, filters, null); + } + + protected Predicate getFilterCondition(CriteriaBuilder cb, Root root, Map filters, Map excludeFilters) { + Predicate filterCondition = null; + filterCondition = getFilterCondition(filterCondition, cb, root, filters, true); + filterCondition = getFilterCondition(filterCondition, cb, root, excludeFilters, false); + return filterCondition; + } + + /** + * extends the given filterCondition by the addtional filters + * + * @param filterCondition the current filter condition + * @param cb the criteria builder to use + * @param root the root of the object to search for + * @param filters the filters to apply + * @param include if set to true, the filter is used as include filter (equals, in). If set to false, the filter is inverted and used as exclude filter (not equals, not in etc) + * @return + */ + protected Predicate getFilterCondition(Predicate filterCondition, CriteriaBuilder cb, Root root, Map filters, boolean include) { + String wildCard = "%"; + if (filters != null) { + for (Map.Entry filter : filters.entrySet()) { + if (!"".equals(filter.getValue())) { + Path path = getPathElement(root, filter); + + // check for differnt types + // 1st String, either from Enum Status or from other free text string + if (filter.getValue() == null) { + Predicate predicate; + if (include) { + predicate = cb.isNull(path); + } else { + predicate = cb.isNotNull(path); + } + filterCondition = addFilterCondition(cb, filterCondition, predicate); + } else if (String.class.equals(filter.getValue().getClass())) { + switch (filter.getKey()) { + default: + String filterValue = filter.getValue().toString(); + Predicate predicate; + if (filterValue.equals("{NULL}")) { + if (include) { + predicate = cb.isNull(path); + } else { + predicate = cb.isNotNull(path); + } + } else { + filterValue = filterValue.trim(); + filterValue = filterValue.replace("?", "_"); + filterValue = filterValue.replace("*", "%"); + + String[] values = filterValue.split("\\s+"); // split by whitespaces + Predicate[] partSearchPredicates = new Predicate[values.length]; + for (int i = 0; i < values.length; i++) { + String value = wildCard + values[i] + wildCard; + if (include) { + partSearchPredicates[i] = cb.like(cb.upper(path), value.toUpperCase(Locale.US), '\\'); + } else { + partSearchPredicates[i] = cb.notLike(cb.upper(path), value.toUpperCase(Locale.US), '\\'); + } + } + predicate = cb.and(partSearchPredicates); // all parts must be available + } + filterCondition = addFilterCondition(cb, filterCondition, predicate); + } + } // 2nd for arrays, received from e.g. project selections + else if (filter.getValue().getClass().isArray()) { + Predicate condition = null; + Object[] values = (Object[]) filter.getValue(); + if (values.length > 0) { + for (Object value : values) { + if (include) { + Predicate equalPredicate = cb.equal(path, value); + if (condition == null) { + condition = equalPredicate; + } else { + condition = cb.or(condition, equalPredicate); + } + } else { + Predicate equalPredicate = cb.notEqual(path, value); + if (condition == null) { + condition = equalPredicate; + } else { + condition = cb.and(condition, equalPredicate); + } + } + } + filterCondition = addFilterCondition(cb, filterCondition, condition); + } + } else { // at last object comparison + if (include) { + filterCondition = addFilterCondition(cb, filterCondition, cb.equal(path, filter.getValue())); + } else { + filterCondition = addFilterCondition(cb, filterCondition, cb.notEqual(path, filter.getValue())); + } + } + } + } + } + return filterCondition; + } + + protected Predicate addFilterCondition(CriteriaBuilder cb, Predicate filterCondition, Predicate addCondition) { + if (addCondition == null) { + return filterCondition; + } + if (filterCondition == null) { + filterCondition = addCondition; + } else { + filterCondition = cb.and(filterCondition, addCondition); + } + return filterCondition; + } + + private Path getPathElement(Root root, Map.Entry filter) { + String[] pathElements = StringUtils.split(filter.getKey(), '.'); + Path path = null; + for (String element : pathElements) { + if (path == null) { + path = root.get(element); + } else { + path = path.get(element); + } + } + return path; + } + + /** + * returns null, if the list is empty or null itself. Returns the one element if there is exactly one element in the list. Otherwise an exception is thrown + * + * @param resultList + * @return + * @throws ControllerException + */ + public T ensureSingleElement(List resultList) throws ControllerException { + if ((resultList == null) || (resultList.isEmpty())) { + return null; + } + if (resultList.size() > 1) { + throw new ControllerException(ControllerException.CAUSE_TOO_MANY_ROWS, "More than one element found in list - expected exactly one"); + } + return resultList.get(0); + } + +} diff --git a/db/src/main/java/de/muehlencord/shared/db/StandardController.java b/db/src/main/java/de/muehlencord/shared/db/StandardController.java new file mode 100644 index 0000000..a45f404 --- /dev/null +++ b/db/src/main/java/de/muehlencord/shared/db/StandardController.java @@ -0,0 +1,77 @@ +/* + * Copyright 2019 joern.muehlencord. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.muehlencord.shared.db; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.ejb.Lock; +import javax.ejb.LockType; +import javax.ejb.Stateless; +import javax.persistence.EntityGraph; +import javax.persistence.TypedQuery; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Order; +import javax.persistence.criteria.Predicate; +import javax.persistence.criteria.Root; + +/** + * + * @author joern.muehlencord + */ +@Stateless +public class StandardController extends CommonAbstractController { + + @Lock(LockType.READ) + public T find(Class clazz, Object id) { + return em.find(clazz, id); + } + + @Lock(LockType.READ) + public T find(Class clazz, Object id, String... subGraphItems) { + EntityGraph graph = this.em.createEntityGraph(clazz); + for (String subGraphItem : subGraphItems) { + graph.addSubgraph(subGraphItem); + } + + Map hints = new HashMap<>(); + hints.put("javax.persistence.loadgraph", graph); + + T entity = (T) em.find(clazz, id, hints); + return entity; + } + + @Lock(LockType.READ) + public List find(Class clazz, Map filters, List orderFields) { + final CriteriaBuilder cb = em.getCriteriaBuilder(); + final CriteriaQuery criteria = cb.createQuery(clazz); + + final Root r = criteria.from(clazz); + Predicate filterCondition = getFilterCondition(cb, r, filters); + if (filterCondition != null) { + criteria.where(filterCondition); + } + List orderList = new ArrayList<>(); + orderFields.stream().forEachOrdered(field -> orderList.add(cb.asc(r.get(field)))); + final TypedQuery query = em.createQuery(criteria.orderBy(orderList)); + + return query.getResultList(); + } + +}