1. Project Clover database Wed Jan 17 2024 23:40:18 CST
  2. Package org.europa.together.application

File GenericHbmDAO.java

 

Coverage histogram

../../../../img/srcFileCovDistChart10.png
0% of files have more coverage

Code metrics

34
80
12
1
250
214
31
0.39
6.67
12
2.58

Classes

Class Line # Actions
GenericHbmDAO 37 80 0% 31 0
1.0100%
 

Contributing tests

This file is covered by 63 tests. .

Source view

1    package org.europa.together.application;
2   
3    import java.io.Serializable;
4    import java.lang.reflect.ParameterizedType;
5    import java.util.ArrayList;
6    import java.util.List;
7    import java.util.Map;
8    import jakarta.persistence.EntityManager;
9    import jakarta.persistence.PersistenceContext;
10    import jakarta.persistence.criteria.CriteriaBuilder;
11    import jakarta.persistence.criteria.CriteriaQuery;
12    import jakarta.persistence.criteria.Predicate;
13    import jakarta.persistence.criteria.Root;
14    import java.sql.Timestamp;
15    import java.util.Date;
16    import org.europa.together.business.GenericDAO;
17    import org.europa.together.business.JsonTools;
18    import org.europa.together.business.Logger;
19    import org.europa.together.domain.LogLevel;
20    import org.europa.together.domain.JpaPagination;
21    import org.europa.together.exceptions.DAOException;
22    import org.europa.together.exceptions.JsonProcessingException;
23    import org.europa.together.utils.StringUtils;
24    import org.springframework.beans.factory.annotation.Autowired;
25    import org.springframework.stereotype.Repository;
26    import org.springframework.transaction.annotation.Transactional;
27   
28    /**
29    * Abstract implementation of Domain Access Object (DAO) Pattern.
30    *
31    * @param <T> as template.
32    * @param <PK> as PrimaryKey
33    */
34    @SuppressWarnings("unchecked")
35    @Repository
36    @Transactional
 
37    public abstract class GenericHbmDAO<T, PK extends Serializable>
38    implements GenericDAO<T, PK> {
39   
40    private static final long serialVersionUID = 2L;
41    private static final Logger LOGGER = new LogbackLogger(GenericHbmDAO.class);
42   
43    /**
44    * JPA Entity Manager for Transactions.
45    */
46    @PersistenceContext
47    @SuppressWarnings("checkstyle:visibilitymodifier")
48    public transient EntityManager mainEntityManagerFactory;
49   
50    @Autowired
51    private JsonTools<T> jsonTools;
52   
53    private final Class<T> genericType;
54   
55    /**
56    * Constructor.
57    */
 
58  2 toggle public GenericHbmDAO() {
59  2 ParameterizedType clazz = (ParameterizedType) getClass().getGenericSuperclass();
60  2 genericType = (Class<T>) clazz.getActualTypeArguments()[0];
61  2 LOGGER.log("instance class", LogLevel.INFO);
62    }
63   
 
64  4 toggle @Override
65    public boolean create(final T object) {
66  4 boolean success = false;
67  4 if (object != null) {
68  3 mainEntityManagerFactory.persist(object);
69  3 success = true;
70    }
71  4 return success;
72    }
73   
 
74  3 toggle @Override
75    public void delete(final PK id)
76    throws DAOException {
77  3 T foundObject = find(id);
78  2 if (foundObject != null) {
79  1 mainEntityManagerFactory.remove(foundObject);
80    } else {
81  1 throw new DAOException("delete:" + id.toString());
82    }
83    }
84   
 
85  21 toggle @Override
86    public void update(final PK id, final T object)
87    throws DAOException {
88  20 if (object != null && this.find(id) != null) {
89  16 mainEntityManagerFactory.merge(object);
90  16 LOGGER.log("DAO (" + object.getClass().getSimpleName() + ") update",
91    LogLevel.TRACE);
92    } else {
93  4 String message = "update faild. -> ";
94  4 if (id != null) {
95  3 message += id.toString();
96    }
97  4 if (object != null) {
98  2 message += " : " + object.toString();
99    }
100  4 throw new DAOException(message);
101    }
102    }
103   
 
104  1 toggle @Override
105    @Transactional(readOnly = true)
106    public long countAllElements() {
107  1 CriteriaBuilder builder = mainEntityManagerFactory.getCriteriaBuilder();
108  1 CriteriaQuery<T> query = builder.createQuery(genericType);
109    // create Criteria
110  1 query.from(genericType);
111  1 return mainEntityManagerFactory.createQuery(query).getResultList().size();
112    }
113   
 
114  47 toggle @Override
115    @Transactional(readOnly = true)
116    public List<T> listAllElements(final JpaPagination pivotElement) {
117  47 LOGGER.log("GenericDAO: " + pivotElement.toString(), LogLevel.DEBUG);
118  47 CriteriaBuilder builder = mainEntityManagerFactory.getCriteriaBuilder();
119  47 CriteriaQuery<T> query = builder.createQuery(genericType);
120  47 Root<T> root = query.from(genericType);
121  47 int limit = pivotElement.getPageSize();
122    // skip pagination
123  47 int countedResults = mainEntityManagerFactory.createQuery(query).getResultList().size();
124  47 if (limit == 0 || limit >= countedResults) {
125  36 limit = countedResults;
126    }
127    // order the result set
128  47 if (pivotElement.getSorting().equals(JpaPagination.ORDER_ASC)) {
129  44 query.orderBy(builder.asc(root.get(pivotElement.getPrimaryKey())));
130    } else {
131  3 query.orderBy(builder.desc(root.get(pivotElement.getPrimaryKey())));
132    }
133  47 if (!StringUtils.isEmpty(pivotElement.getAdditionalOrdering())) {
134  5 query.orderBy(builder.asc(root.get(pivotElement.getAdditionalOrdering())));
135    }
136    // put everything together
137  47 List<Predicate> filters = calculatePredicates(builder, root, pivotElement);
138  47 if (!filters.isEmpty()) {
139  40 query.where(filters.toArray(new Predicate[filters.size()]));
140    }
141  47 List<T> results = mainEntityManagerFactory.createQuery(query)
142    .setMaxResults(limit).getResultList();
143  47 return results;
144    }
145   
 
146  2 toggle @Override
147    @Transactional(readOnly = true)
148    public PK getPrimaryKeyOfObject(final T object) {
149  2 PK returnVal = null;
150  2 if (object != null) {
151  1 returnVal = (PK) mainEntityManagerFactory.getEntityManagerFactory()
152    .getPersistenceUnitUtil().getIdentifier(object);
153  1 LOGGER.log("DAO (" + object.getClass().getSimpleName() + ") IDX="
154    + returnVal, LogLevel.TRACE);
155    } else {
156  1 LOGGER.log("getPrimaryKeyOfObject() : Object is null.", LogLevel.WARN);
157    }
158  2 return returnVal;
159    }
160   
 
161  1 toggle @Override
162    public String serializeAsJson(final T object)
163    throws JsonProcessingException {
164  1 return jsonTools.serializeAsJsonObject(object);
165    }
166   
 
167  1 toggle @Override
168    public T deserializeJsonAsObject(final String json, final Class<T> object)
169    throws JsonProcessingException, ClassNotFoundException {
170  1 return jsonTools.deserializeJsonAsObject(json, object);
171    }
172   
 
173  1 toggle @Override
174    public List<T> deserializeJsonAsList(final String json)
175    throws JsonProcessingException, ClassNotFoundException {
176  1 return jsonTools.deserializeJsonAsList(json);
177    }
178   
 
179  44 toggle @Override
180    @Transactional(readOnly = true)
181    public T find(final PK id) {
182  44 T retVal = mainEntityManagerFactory.find(genericType, id);
183  41 return retVal;
184    }
185   
186    //### ######################################################################
 
187  47 toggle private List<Predicate> calculatePredicates(final CriteriaBuilder builder, final Root<T> root,
188    final JpaPagination pivotElement) {
189  47 List<Predicate> filters = new ArrayList<>();
190    // get the break element
191  47 if (!StringUtils.isEmpty(pivotElement.getPageBreak())) {
192  9 if (pivotElement.getPaging().equals(JpaPagination.PAGING_FOREWARD)) {
193  8 filters.add(builder.greaterThanOrEqualTo(root.get(pivotElement.getPrimaryKey()),
194    pivotElement.getPageBreak()
195    ));
196    } else {
197  1 filters.add(builder.lessThanOrEqualTo(root.get(pivotElement.getPrimaryKey()),
198    pivotElement.getPageBreak()
199    ));
200    }
201    }
202  47 if (!pivotElement.getFilterStringCriteria().isEmpty()) {
203  32 for (Map.Entry<String, String> entry
204    : pivotElement.getFilterStringCriteria().entrySet()) {
205  84 filters.add(
206    builder.equal(root.get(entry.getKey()), entry.getValue()));
207    }
208    } else {
209  15 LOGGER.log("No String based filters are set.", LogLevel.DEBUG);
210    }
211  47 if (!pivotElement.getFilterBooleanCriteria().isEmpty()) {
212  3 for (Map.Entry<String, Boolean> entry
213    : pivotElement.getFilterBooleanCriteria().entrySet()) {
214  3 filters.add(
215    builder.equal(root.get(entry.getKey()), entry.getValue()));
216    }
217    } else {
218  44 LOGGER.log("No Boolean based filters are set.", LogLevel.DEBUG);
219    }
220  47 if (!pivotElement.getFilterIntegerCriteria().isEmpty()) {
221  2 for (Map.Entry<String, Integer> entry
222    : pivotElement.getFilterIntegerCriteria().entrySet()) {
223  2 filters.add(
224    builder.equal(root.get(entry.getKey()), entry.getValue()));
225    }
226    } else {
227  45 LOGGER.log("No Integer based filters are set.", LogLevel.DEBUG);
228    }
229  47 if (!pivotElement.getFilterFloatCriteria().isEmpty()) {
230  2 for (Map.Entry<String, Float> entry
231    : pivotElement.getFilterFloatCriteria().entrySet()) {
232  2 filters.add(
233    builder.equal(root.get(entry.getKey()), entry.getValue()));
234    }
235    } else {
236  45 LOGGER.log("No Integer based filters are set.", LogLevel.DEBUG);
237    }
238  47 if (!pivotElement.getFilterDateCriteria().isEmpty()) {
239  2 for (Map.Entry<String, Date> entry
240    : pivotElement.getFilterDateCriteria().entrySet()) {
241  2 filters.add(
242    builder.equal(root.get(entry.getKey()),
243    Timestamp.from(entry.getValue().toInstant())));
244    }
245    } else {
246  45 LOGGER.log("No Date based filters are set.", LogLevel.DEBUG);
247    }
248  47 return filters;
249    }
250    }