Replaced all tabs with spaces in java and pom.xml
[so.git] / mso-api-handlers / mso-requests-db-repositories / src / main / java / org / onap / so / db / request / data / repository / InfraActiveRequestsRepositoryImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.db.request.data.repository;
24
25 import java.sql.Timestamp;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.concurrent.TimeUnit;
37 import javax.persistence.EntityManager;
38 import javax.persistence.NonUniqueResultException;
39 import javax.persistence.Query;
40 import javax.persistence.TypedQuery;
41 import javax.persistence.criteria.CriteriaBuilder;
42 import javax.persistence.criteria.CriteriaQuery;
43 import javax.persistence.criteria.Order;
44 import javax.persistence.criteria.Predicate;
45 import javax.persistence.criteria.Root;
46 import org.onap.so.db.request.beans.InfraActiveRequests;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.beans.factory.annotation.Qualifier;
51 import org.springframework.stereotype.Repository;
52 import org.springframework.transaction.annotation.Transactional;
53
54
55 @Repository
56 @Transactional(readOnly = true)
57 public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRepositoryCustom {
58
59
60     @Qualifier("requestEntityManagerFactory")
61     @Autowired
62     private EntityManager entityManager;
63
64     protected static Logger logger = LoggerFactory.getLogger(InfraActiveRequestsRepositoryImpl.class);
65
66     protected static final String REQUEST_STATUS = "requestStatus";
67     protected static final String SOURCE = "source";
68     protected static final String START_TIME = "startTime";
69     protected static final String END_TIME = "endTime";
70     protected static final String REQUEST_TYPE = "requestType";
71     protected static final String SERVICE_INSTANCE_ID = "serviceInstanceId";
72     protected static final String SERVICE_INSTANCE_NAME = "serviceInstanceName";
73     protected static final String VNF_INSTANCE_NAME = "vnfName";
74     protected static final String VNF_INSTANCE_ID = "vnfId";
75     protected static final String VOLUME_GROUP_INSTANCE_NAME = "volumeGroupName";
76     protected static final String VOLUME_GROUP_INSTANCE_ID = "volumeGroupId";
77     protected static final String VFMODULE_INSTANCE_NAME = "vfModuleName";
78     protected static final String VFMODULE_INSTANCE_ID = "vfModuleId";
79     protected static final String NETWORK_INSTANCE_NAME = "networkName";
80     protected static final String CONFIGURATION_INSTANCE_ID = "configurationId";
81     protected static final String CONFIGURATION_INSTANCE_NAME = "configurationName";
82     protected static final String OPERATIONAL_ENV_ID = "operationalEnvId";
83     protected static final String OPERATIONAL_ENV_NAME = "operationalEnvName";
84     protected static final String NETWORK_INSTANCE_ID = "networkId";
85     protected static final String GLOBAL_SUBSCRIBER_ID = "globalSubscriberId";
86     protected static final String SERVICE_NAME_VERSION_ID = "serviceNameVersionId";
87     protected static final String SERVICE_ID = "serviceId";
88     protected static final String SERVICE_VERSION = "serviceVersion";
89     protected static final String REQUEST_ID = "requestId";
90     protected static final String REQUESTOR_ID = "requestorId";
91     protected static final String ACTION = "action";
92
93     private static final List<String> VALID_COLUMNS =
94             Arrays.asList(REQUEST_ID, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, ACTION, REQUEST_STATUS);
95
96
97     /*
98      * (non-Javadoc)
99      * 
100      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#healthCheck()
101      */
102     @Override
103     public boolean healthCheck() {
104
105         final Query query = entityManager.createNativeQuery(" show tables ");
106
107         final List<?> list = query.getResultList();
108
109         return true;
110     }
111
112     private List<InfraActiveRequests> executeInfraQuery(final CriteriaQuery<InfraActiveRequests> crit,
113             final List<Predicate> predicates, final Order order) {
114
115         final long startTime = System.currentTimeMillis();
116         logger.debug("Execute query on infra active request table");
117
118         List<InfraActiveRequests> results = new ArrayList<InfraActiveRequests>();
119
120         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
121         crit.where(cb.and(predicates.toArray(new Predicate[0])));
122         crit.orderBy(order);
123         results = entityManager.createQuery(crit).getResultList();
124
125         return results;
126     }
127
128     /*
129      * (non-Javadoc)
130      * 
131      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String)
132      */
133     @Override
134     public InfraActiveRequests getRequestFromInfraActive(final String requestId) {
135         final long startTime = System.currentTimeMillis();
136         logger.debug("Get request {} from InfraActiveRequests DB", requestId);
137
138         InfraActiveRequests ar = null;
139         final Query query = entityManager
140                 .createQuery("from InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
141         query.setParameter(REQUEST_ID, requestId);
142         ar = this.getSingleResult(query);
143         return ar;
144     }
145
146     /*
147      * (non-Javadoc)
148      * 
149      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkInstanceNameDuplicate(java. util.HashMap,
150      * java.lang.String, java.lang.String)
151      */
152     @Override
153     public InfraActiveRequests checkInstanceNameDuplicate(final HashMap<String, String> instanceIdMap,
154             final String instanceName, final String requestScope) {
155
156         final List<Predicate> predicates = new LinkedList<>();
157         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
158         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
159         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
160         InfraActiveRequests infraActiveRequests = null;
161
162         if (instanceName != null && !instanceName.equals("")) {
163
164             if ("service".equals(requestScope)) {
165                 predicates.add(cb.equal(tableRoot.get(SERVICE_INSTANCE_NAME), instanceName));
166             } else if ("vnf".equals(requestScope)) {
167                 predicates.add(cb.equal(tableRoot.get(VNF_INSTANCE_NAME), instanceName));
168             } else if ("volumeGroup".equals(requestScope)) {
169                 predicates.add(cb.equal(tableRoot.get(VOLUME_GROUP_INSTANCE_NAME), instanceName));
170             } else if ("vfModule".equals(requestScope)) {
171                 predicates.add(cb.equal(tableRoot.get(VFMODULE_INSTANCE_NAME), instanceName));
172             } else if ("network".equals(requestScope)) {
173                 predicates.add(cb.equal(tableRoot.get(NETWORK_INSTANCE_NAME), instanceName));
174             } else if (requestScope.equals("configuration")) {
175                 predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_NAME), instanceName));
176             } else if (requestScope.equals("operationalEnvironment")) {
177                 predicates.add(cb.equal(tableRoot.get(OPERATIONAL_ENV_NAME), instanceName));
178             }
179
180         } else {
181             if (instanceIdMap != null) {
182                 if ("service".equals(requestScope) && instanceIdMap.get("serviceInstanceId") != null) {
183                     predicates
184                             .add(cb.equal(tableRoot.get(SERVICE_INSTANCE_ID), instanceIdMap.get("serviceInstanceId")));
185                 }
186
187                 if ("vnf".equals(requestScope) && instanceIdMap.get("vnfInstanceId") != null) {
188                     predicates.add(cb.equal(tableRoot.get(VNF_INSTANCE_ID), instanceIdMap.get("vnfInstanceId")));
189                 }
190
191                 if ("vfModule".equals(requestScope) && instanceIdMap.get("vfModuleInstanceId") != null) {
192                     predicates.add(
193                             cb.equal(tableRoot.get(VFMODULE_INSTANCE_ID), instanceIdMap.get("vfModuleInstanceId")));
194                 }
195
196                 if ("volumeGroup".equals(requestScope) && instanceIdMap.get("volumeGroupInstanceId") != null) {
197                     predicates.add(cb.equal(tableRoot.get(VOLUME_GROUP_INSTANCE_ID),
198                             instanceIdMap.get("volumeGroupInstanceId")));
199                 }
200
201                 if ("network".equals(requestScope) && instanceIdMap.get("networkInstanceId") != null) {
202                     predicates
203                             .add(cb.equal(tableRoot.get(NETWORK_INSTANCE_ID), instanceIdMap.get("networkInstanceId")));
204                 }
205
206                 if (requestScope.equals("configuration") && instanceIdMap.get("configurationInstanceId") != null) {
207                     predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_ID),
208                             instanceIdMap.get("configurationInstanceId")));
209                 }
210
211                 if (requestScope.equals("operationalEnvironment")
212                         && instanceIdMap.get("operationalEnvironmentId") != null) {
213                     predicates.add(
214                             cb.equal(tableRoot.get(OPERATIONAL_ENV_ID), instanceIdMap.get("operationalEnvironmentId")));
215                 }
216             }
217         }
218         if (!predicates.isEmpty()) {
219             predicates.add(tableRoot.get(REQUEST_STATUS)
220                     .in(Arrays.asList("PENDING", "IN_PROGRESS", "TIMEOUT", "PENDING_MANUAL_TASK")));
221
222             final Order order = cb.desc(tableRoot.get(START_TIME));
223
224             final List<InfraActiveRequests> dupList = executeInfraQuery(crit, predicates, order);
225
226             if (dupList != null && !dupList.isEmpty()) {
227                 infraActiveRequests = dupList.get(0);
228             }
229         }
230
231         return infraActiveRequests;
232     }
233
234     /*
235      * (non-Javadoc)
236      * 
237      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
238      * getOrchestrationFiltersFromInfraActive(java.util.Map)
239      */
240     @Override
241     public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(
242             final Map<String, List<String>> orchestrationMap) {
243
244
245         final List<Predicate> predicates = new LinkedList<>();
246         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
247         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
248         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
249         for (final Map.Entry<String, List<String>> entry : orchestrationMap.entrySet()) {
250             String mapKey = entry.getKey();
251             if ("serviceInstanceId".equalsIgnoreCase(mapKey)) {
252                 mapKey = "serviceInstanceId";
253             } else if ("serviceInstanceName".equalsIgnoreCase(mapKey)) {
254                 mapKey = "serviceInstanceName";
255             } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) {
256                 mapKey = "vnfId";
257             } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) {
258                 mapKey = "vnfName";
259             } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) {
260                 mapKey = "vfModuleId";
261             } else if ("vfModuleInstanceName".equalsIgnoreCase(mapKey)) {
262                 mapKey = "vfModuleName";
263             } else if ("volumeGroupInstanceId".equalsIgnoreCase(mapKey)) {
264                 mapKey = "volumeGroupId";
265             } else if ("volumeGroupInstanceName".equalsIgnoreCase(mapKey)) {
266                 mapKey = "volumeGroupName";
267             } else if ("networkInstanceId".equalsIgnoreCase(mapKey)) {
268                 mapKey = "networkId";
269             } else if ("networkInstanceName".equalsIgnoreCase(mapKey)) {
270                 mapKey = "networkName";
271             } else if (mapKey.equalsIgnoreCase("configurationInstanceId")) {
272                 mapKey = "configurationId";
273             } else if (mapKey.equalsIgnoreCase("configurationInstanceName")) {
274                 mapKey = "configurationName";
275             } else if ("lcpCloudRegionId".equalsIgnoreCase(mapKey)) {
276                 mapKey = "aicCloudRegion";
277             } else if ("tenantId".equalsIgnoreCase(mapKey)) {
278                 mapKey = "tenantId";
279             } else if ("modelType".equalsIgnoreCase(mapKey)) {
280                 mapKey = "requestScope";
281             } else if ("requestorId".equalsIgnoreCase(mapKey)) {
282                 mapKey = "requestorId";
283             } else if ("requestExecutionDate".equalsIgnoreCase(mapKey)) {
284                 mapKey = "startTime";
285             }
286
287             final String propertyValue = entry.getValue().get(1);
288             if ("startTime".equals(mapKey)) {
289                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
290                 try {
291                     final Date thisDate = format.parse(propertyValue);
292                     final Timestamp minTime = new Timestamp(thisDate.getTime());
293                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
294
295                     if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
296                         predicates.add(cb.or(cb.lessThan(tableRoot.get(mapKey), minTime),
297                                 cb.greaterThanOrEqualTo(tableRoot.get(mapKey), maxTime)));
298                     } else {
299                         predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
300                     }
301                 } catch (final Exception e) {
302                     logger.debug("Exception in getOrchestrationFiltersFromInfraActive(): {}", e.getMessage(), e);
303                     return null;
304                 }
305             } else if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
306                 predicates.add(cb.notEqual(tableRoot.get(mapKey), propertyValue));
307             } else {
308                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
309             }
310
311         }
312
313         final Order order = cb.asc(tableRoot.get(START_TIME));
314
315         return executeInfraQuery(crit, predicates, order);
316     }
317
318     // Added this method for Tenant Isolation project ( 1802-295491a) to query the mso_requests DB
319     // (infra_active_requests table) for operationalEnvId and OperationalEnvName
320     /*
321      * (non-Javadoc)
322      * 
323      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
324      * getCloudOrchestrationFiltersFromInfraActive(java.util.Map)
325      */
326     @Override
327     public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(
328             final Map<String, String> orchestrationMap) {
329         final List<Predicate> predicates = new LinkedList<>();
330         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
331         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
332         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
333
334         // Add criteria on OperationalEnvironment RequestScope when requestorId is only specified in
335         // the filter
336         // as the same requestorId can also match on different API methods
337         final String resourceType = orchestrationMap.get("resourceType");
338         if (resourceType == null) {
339             predicates.add(cb.equal(tableRoot.get("requestScope"), "operationalEnvironment"));
340         }
341
342         for (final Map.Entry<String, String> entry : orchestrationMap.entrySet()) {
343             String mapKey = entry.getKey();
344             if (mapKey.equalsIgnoreCase("requestorId")) {
345                 mapKey = "requestorId";
346             } else if (mapKey.equalsIgnoreCase("requestExecutionDate")) {
347                 mapKey = "startTime";
348             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentId")) {
349                 mapKey = "operationalEnvId";
350             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentName")) {
351                 mapKey = "operationalEnvName";
352             } else if (mapKey.equalsIgnoreCase("resourceType")) {
353                 mapKey = "requestScope";
354             }
355
356             final String propertyValue = entry.getValue();
357             if (mapKey.equals("startTime")) {
358                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
359                 try {
360                     final Date thisDate = format.parse(propertyValue);
361                     final Timestamp minTime = new Timestamp(thisDate.getTime());
362                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
363
364                     predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
365                 } catch (final Exception e) {
366                     logger.debug("Exception in getCloudOrchestrationFiltersFromInfraActive(): {}", e.getMessage());
367                     return null;
368                 }
369             } else {
370                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
371             }
372         }
373
374         final Order order = cb.asc(tableRoot.get(START_TIME));
375         return executeInfraQuery(crit, predicates, order);
376     }
377
378     /*
379      * (non-Javadoc)
380      * 
381      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestListFromInfraActive(java .lang.String,
382      * java.lang.String, java.lang.String)
383      */
384     @Override
385     public List<InfraActiveRequests> getRequestListFromInfraActive(final String queryAttributeName,
386             final String queryValue, final String requestType) {
387         logger.debug("Get list of infra requests from DB with {} = {}", queryAttributeName, queryValue);
388
389
390         try {
391             final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
392             final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
393             final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
394             final Predicate isEqual = cb.equal(candidateRoot.get(queryAttributeName), queryValue);
395             final Predicate equalRequestType = cb.equal(candidateRoot.get(REQUEST_TYPE), requestType);
396             final Predicate isNull = cb.isNull(candidateRoot.get(REQUEST_TYPE));
397             final Predicate orClause = cb.or(equalRequestType, isNull);
398             final Order orderDesc = cb.desc(candidateRoot.get(START_TIME));
399             final Order orderAsc = cb.asc(candidateRoot.get(SOURCE));
400             crit.where(cb.and(isEqual, orClause)).orderBy(orderDesc, orderAsc);
401
402             final List<InfraActiveRequests> arList = entityManager.createQuery(crit).getResultList();
403             if (arList != null && !arList.isEmpty()) {
404                 return arList;
405             }
406         } catch (final Exception exception) {
407             logger.error("Unable to execute query", exception);
408         }
409         return Collections.emptyList();
410     }
411
412
413     /*
414      * (non-Javadoc)
415      * 
416      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String,
417      * java.lang.String)
418      */
419     @Override
420     public InfraActiveRequests getRequestFromInfraActive(final String requestId, final String requestType) {
421         final long startTime = System.currentTimeMillis();
422         logger.debug("Get infra request from DB with id {}", requestId);
423
424         InfraActiveRequests ar = null;
425
426         final Query query = entityManager.createQuery(
427                 "from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType");
428         query.setParameter(REQUEST_ID, requestId);
429         query.setParameter(REQUEST_TYPE, requestType);
430         ar = this.getSingleResult(query);
431         return ar;
432     }
433
434
435     /*
436      * (non-Javadoc)
437      * 
438      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfName(java.lang. String,
439      * java.lang.String, java.lang.String)
440      */
441     @Override
442     public InfraActiveRequests checkDuplicateByVnfName(final String vnfName, final String action,
443             final String requestType) {
444
445         final long startTime = System.currentTimeMillis();
446         logger.debug("Get infra request from DB for VNF {} and action {} and requestType {}", vnfName, action,
447                 requestType);
448
449         InfraActiveRequests ar = null;
450
451         final Query query = entityManager.createQuery(
452                 "from InfraActiveRequests where vnfName = :vnfName and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
453         query.setParameter("vnfName", vnfName);
454         query.setParameter("action", action);
455         query.setParameter(REQUEST_TYPE, requestType);
456         @SuppressWarnings("unchecked")
457         final List<InfraActiveRequests> results = query.getResultList();
458         if (!results.isEmpty()) {
459             ar = results.get(0);
460         }
461
462         return ar;
463     }
464
465     /*
466      * (non-Javadoc)
467      * 
468      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfId(java.lang. String,
469      * java.lang.String, java.lang.String)
470      */
471     @Override
472     public InfraActiveRequests checkDuplicateByVnfId(final String vnfId, final String action,
473             final String requestType) {
474
475         final long startTime = System.currentTimeMillis();
476         logger.debug("Get list of infra requests from DB for VNF {} and action {}", vnfId, action);
477
478         InfraActiveRequests ar = null;
479
480         final Query query = entityManager.createQuery(
481                 "from InfraActiveRequests where vnfId = :vnfId and action = :action and (requestStatus = 'PENDING' or requestStatus = 'IN_PROGRESS' or requestStatus = 'TIMEOUT' or requestStatus = 'PENDING_MANUAL_TASK') and requestType = :requestType ORDER BY startTime DESC");
482         query.setParameter("vnfId", vnfId);
483         query.setParameter("action", action);
484         query.setParameter(REQUEST_TYPE, requestType);
485         @SuppressWarnings("unchecked")
486         final List<InfraActiveRequests> results = query.getResultList();
487         if (!results.isEmpty()) {
488             ar = results.get(0);
489         }
490
491         return ar;
492     }
493
494     /*
495      * (non-Javadoc)
496      * 
497      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkVnfIdStatus(java.lang.String)
498      */
499     @Override
500     public InfraActiveRequests checkVnfIdStatus(final String operationalEnvironmentId) {
501         final long startTime = System.currentTimeMillis();
502         logger.debug("Get Infra request from DB for OperationalEnvironmentId {}", operationalEnvironmentId);
503
504         InfraActiveRequests ar = null;
505
506         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
507         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
508         final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
509         final Predicate operationalEnvEq = cb.equal(candidateRoot.get("operationalEnvId"), operationalEnvironmentId);
510         final Predicate requestStatusNotEq = cb.notEqual(candidateRoot.get(REQUEST_STATUS), "COMPLETE");
511         final Predicate actionEq = cb.equal(candidateRoot.get("action"), "create");
512         final Order startTimeOrder = cb.desc(candidateRoot.get("startTime"));
513         crit.select(candidateRoot);
514         crit.where(cb.and(operationalEnvEq, requestStatusNotEq, actionEq));
515         crit.orderBy(startTimeOrder);
516         final TypedQuery<InfraActiveRequests> query = entityManager.createQuery(crit);
517         final List<InfraActiveRequests> results = query.getResultList();
518         if (!results.isEmpty()) {
519             ar = results.get(0);
520         }
521
522         return ar;
523     }
524
525     protected <T> T getSingleResult(final Query query) {
526         query.setMaxResults(1);
527         final List<T> list = query.getResultList();
528         if (list == null || list.isEmpty()) {
529             return null;
530         } else if (list.size() == 1) {
531             return list.get(0);
532         } else {
533             throw new NonUniqueResultException();
534         }
535
536     }
537
538     @Override
539     public List<InfraActiveRequests> getInfraActiveRequests(final Map<String, String[]> filters, final long startTime,
540             final long endTime, final Integer maxResult) {
541         if (filters == null) {
542             return Collections.emptyList();
543         }
544         try {
545             final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
546
547             final CriteriaQuery<InfraActiveRequests> criteriaQuery =
548                     criteriaBuilder.createQuery(InfraActiveRequests.class);
549             final Root<InfraActiveRequests> tableRoot = criteriaQuery.from(InfraActiveRequests.class);
550             final List<Predicate> predicates = getPredicates(filters, criteriaBuilder, tableRoot);
551
552             final Timestamp minTime = new Timestamp(startTime);
553             final Timestamp maxTime = new Timestamp(endTime);
554             final Predicate basePredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
555             final Predicate additionalPredicate =
556                     criteriaBuilder.and(criteriaBuilder.greaterThanOrEqualTo(tableRoot.get(START_TIME), minTime),
557                             criteriaBuilder.or(tableRoot.get(END_TIME).isNull(),
558                                     criteriaBuilder.lessThanOrEqualTo(tableRoot.get(END_TIME), maxTime)));
559
560             criteriaQuery.where(criteriaBuilder.and(basePredicate, additionalPredicate));
561             if (maxResult != null) {
562                 return entityManager.createQuery(criteriaQuery).setMaxResults(maxResult).getResultList();
563             }
564             return entityManager.createQuery(criteriaQuery).getResultList();
565         } catch (final Exception exception) {
566             logger.error("Unable to execute query using filters: {}", filters, exception);
567             return Collections.emptyList();
568         }
569     }
570
571     protected List<Predicate> getPredicates(final Map<String, String[]> filters, final CriteriaBuilder criteriaBuilder,
572             final Root<InfraActiveRequests> tableRoot) {
573         final List<Predicate> predicates = new LinkedList<>();
574         for (final Entry<String, String[]> entry : filters.entrySet()) {
575             final String[] params = entry.getValue();
576             if (VALID_COLUMNS.contains(entry.getKey()) && params.length == 2) {
577                 final QueryOperationType operationType = QueryOperationType.getQueryOperationType(params[0]);
578                 final Predicate predicate =
579                         operationType.getPredicate(criteriaBuilder, tableRoot, entry.getKey(), params[1]);
580                 predicates.add(predicate);
581             }
582         }
583         return predicates;
584     }
585 }