introduced CommonAbstractController and StandardController

This commit is contained in:
Joern Muehlencord
2019-06-22 01:00:56 +02:00
parent ab2a0e2301
commit 40acbcd6ac
3 changed files with 381 additions and 246 deletions

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2016 Joern Muehlencord <joern at muehlencord.de>. * Copyright 2016 Joern Muehlencord
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -15,44 +15,28 @@
*/ */
package de.muehlencord.shared.db; package de.muehlencord.shared.db;
import de.muehlencord.shared.util.DateUtil;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Locale;
import java.util.Map; import java.util.Map;
import javax.ejb.Lock; import javax.ejb.Lock;
import javax.ejb.LockType; import javax.ejb.LockType;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityGraph; import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery; import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Order; import javax.persistence.criteria.Order;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root; 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 <joern at muehlencord.de> * @author Joern Muehlencord <joern at muehlencord.de>
* @param <T> * @param <T>
*/ */
public abstract class AbstractController<T extends Serializable> { public abstract class AbstractController<T extends Serializable> extends CommonAbstractController {
@Inject
@ApplicationPU
protected EntityManager em;
private final Class<T> entityClass; private final Class<T> entityClass;
@ -60,209 +44,10 @@ public abstract class AbstractController<T extends Serializable> {
this.entityClass = clazz; this.entityClass = clazz;
} }
protected Predicate getFilterCondition(CriteriaBuilder cb, Root<T> root, Map<String, Object> filters) {
return getFilterCondition(cb, root, filters, null);
}
protected Predicate getFilterCondition(CriteriaBuilder cb, Root<T> root, Map<String, Object> filters, Map<String, Object> 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 * * general find methods ***
*
* @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<T> root, Map<String, Object> filters, boolean include) {
String wildCard = "%";
if (filters != null) {
for (Map.Entry<String, Object> filter : filters.entrySet()) {
if (!"".equals(filter.getValue())) {
Path<String> 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<String> getPathElement(Root<T> root, Map.Entry<String, Object> filter) {
String[] pathElements = StringUtils.split(filter.getKey(), '.');
Path<String> 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) @Lock(LockType.READ)
public T find(Object id) { public T find(Object id) {
@ -324,29 +109,5 @@ public abstract class AbstractController<T extends Serializable> {
return query.getResultList(); 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<T> 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 <T> SingularAttribute<? super T, ?> getIdAttribute() {
Metamodel m = em.getEntityManagerFactory().getMetamodel();
IdentifiableType<T> of = (IdentifiableType<T>) m.managedType(entityClass);
// of.getDeclaredId(entityClass).getJavaMember().
return of.getId(of.getIdType().getJavaType());
}
} }

View File

@ -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 <T> List<T> findAll(Class<T> entityClass) {
return findAll(entityClass, new ArrayList<>());
}
@Lock(LockType.READ)
public <T> List<T> findAll(Class<T> entityClass, String... orderFields) {
return findAll(entityClass, Arrays.asList(orderFields));
}
@Lock(LockType.READ)
public <T> List<T> findAll(Class<T> entityClass, List<String> orderFields) {
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<T> criteria = cb.createQuery(entityClass);
final Root<T> r = criteria.from(entityClass);
List<Order> orderList = new ArrayList<>();
orderFields.stream().forEachOrdered(field -> orderList.add(cb.asc(r.get(field))));
final TypedQuery<T> 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> 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 extends Serializable> 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 <T extends Serializable> 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 extends Serializable> T attach(T entity) {
return em.merge(entity);
}
/* *** filter methods *** */
protected <T extends Serializable> Predicate getFilterCondition(CriteriaBuilder cb, Root<T> root, Map<String, Object> filters) {
return getFilterCondition(cb, root, filters, null);
}
protected <T extends Serializable> Predicate getFilterCondition(CriteriaBuilder cb, Root<T> root, Map<String, Object> filters, Map<String, Object> 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 <T extends Serializable> Predicate getFilterCondition(Predicate filterCondition, CriteriaBuilder cb, Root<T> root, Map<String, Object> filters, boolean include) {
String wildCard = "%";
if (filters != null) {
for (Map.Entry<String, Object> filter : filters.entrySet()) {
if (!"".equals(filter.getValue())) {
Path<String> 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 <T extends Serializable> Path<String> getPathElement(Root<T> root, Map.Entry<String, Object> filter) {
String[] pathElements = StringUtils.split(filter.getKey(), '.');
Path<String> 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> T ensureSingleElement(List<T> 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);
}
}

View File

@ -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 extends Serializable> T find(Class<T> clazz, Object id) {
return em.find(clazz, id);
}
@Lock(LockType.READ)
public <T extends Serializable> T find(Class<T> 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 <T extends Serializable> List<T> find(Class<T> clazz, Map<String, Object> filters, List<String> orderFields) {
final CriteriaBuilder cb = em.getCriteriaBuilder();
final CriteriaQuery<T> criteria = cb.createQuery(clazz);
final Root<T> r = criteria.from(clazz);
Predicate filterCondition = getFilterCondition(cb, r, filters);
if (filterCondition != null) {
criteria.where(filterCondition);
}
List<Order> orderList = new ArrayList<>();
orderFields.stream().forEachOrdered(field -> orderList.add(cb.asc(r.get(field))));
final TypedQuery<T> query = em.createQuery(criteria.orderBy(orderList));
return query.getResultList();
}
}