Merge "update scheduled tasks to have mdc setup"
[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     protected static final String OPENV = "operationalEnvironment";
93
94     private static final List<String> VALID_COLUMNS =
95             Arrays.asList(REQUEST_ID, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, ACTION, REQUEST_STATUS,
96                     VFMODULE_INSTANCE_ID, VNF_INSTANCE_ID, NETWORK_INSTANCE_ID, VOLUME_GROUP_INSTANCE_ID);
97
98
99     /*
100      * (non-Javadoc)
101      * 
102      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#healthCheck()
103      */
104     @Override
105     public boolean healthCheck() {
106
107         final Query query = entityManager.createNativeQuery(" show tables ");
108
109         final List<?> list = query.getResultList();
110
111         return true;
112     }
113
114     private List<InfraActiveRequests> executeInfraQuery(final CriteriaQuery<InfraActiveRequests> crit,
115             final List<Predicate> predicates, final Order order) {
116
117         logger.debug("Execute query on infra active request table");
118
119         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
120         crit.where(cb.and(predicates.toArray(new Predicate[0])));
121         crit.orderBy(order);
122
123         return entityManager.createQuery(crit).getResultList();
124     }
125
126     /*
127      * (non-Javadoc)
128      * 
129      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String)
130      */
131     @Override
132     public InfraActiveRequests getRequestFromInfraActive(final String requestId) {
133         logger.debug("Get request {} from InfraActiveRequests DB", requestId);
134
135         final Query query = entityManager
136                 .createQuery("from InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
137         query.setParameter(REQUEST_ID, requestId);
138         return this.getSingleResult(query);
139     }
140
141     /*
142      * (non-Javadoc)
143      * 
144      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkInstanceNameDuplicate(java. util.HashMap,
145      * java.lang.String, java.lang.String)
146      */
147     @Override
148     public InfraActiveRequests checkInstanceNameDuplicate(final Map<String, String> instanceIdMap,
149             final String instanceName, final String requestScope) {
150
151         final List<Predicate> predicates = new LinkedList<>();
152         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
153         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
154         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
155         InfraActiveRequests infraActiveRequests = null;
156
157         if (instanceName != null && !instanceName.equals("")) {
158
159             if ("service".equals(requestScope)) {
160                 predicates.add(cb.equal(tableRoot.get(SERVICE_INSTANCE_NAME), instanceName));
161             } else if ("vnf".equals(requestScope)) {
162                 predicates.add(cb.equal(tableRoot.get(VNF_INSTANCE_NAME), instanceName));
163             } else if ("volumeGroup".equals(requestScope)) {
164                 predicates.add(cb.equal(tableRoot.get(VOLUME_GROUP_INSTANCE_NAME), instanceName));
165             } else if ("vfModule".equals(requestScope)) {
166                 predicates.add(cb.equal(tableRoot.get(VFMODULE_INSTANCE_NAME), instanceName));
167             } else if ("network".equals(requestScope)) {
168                 predicates.add(cb.equal(tableRoot.get(NETWORK_INSTANCE_NAME), instanceName));
169             } else if (requestScope.equals("configuration")) {
170                 predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_NAME), instanceName));
171             } else if (requestScope.equals(OPENV)) {
172                 predicates.add(cb.equal(tableRoot.get(OPERATIONAL_ENV_NAME), instanceName));
173             }
174
175         } else {
176             if (instanceIdMap != null) {
177                 if ("service".equals(requestScope) && instanceIdMap.get(SERVICE_INSTANCE_ID) != null) {
178                     predicates
179                             .add(cb.equal(tableRoot.get(SERVICE_INSTANCE_ID), instanceIdMap.get("serviceInstanceId")));
180                 }
181
182                 if ("vnf".equals(requestScope) && instanceIdMap.get("vnfInstanceId") != null) {
183                     predicates.add(cb.equal(tableRoot.get(VNF_INSTANCE_ID), instanceIdMap.get("vnfInstanceId")));
184                 }
185
186                 if ("vfModule".equals(requestScope) && instanceIdMap.get("vfModuleInstanceId") != null) {
187                     predicates.add(
188                             cb.equal(tableRoot.get(VFMODULE_INSTANCE_ID), instanceIdMap.get("vfModuleInstanceId")));
189                 }
190
191                 if ("volumeGroup".equals(requestScope) && instanceIdMap.get("volumeGroupInstanceId") != null) {
192                     predicates.add(cb.equal(tableRoot.get(VOLUME_GROUP_INSTANCE_ID),
193                             instanceIdMap.get("volumeGroupInstanceId")));
194                 }
195
196                 if ("network".equals(requestScope) && instanceIdMap.get("networkInstanceId") != null) {
197                     predicates
198                             .add(cb.equal(tableRoot.get(NETWORK_INSTANCE_ID), instanceIdMap.get("networkInstanceId")));
199                 }
200
201                 if (requestScope.equals("configuration") && instanceIdMap.get("configurationInstanceId") != null) {
202                     predicates.add(cb.equal(tableRoot.get(CONFIGURATION_INSTANCE_ID),
203                             instanceIdMap.get("configurationInstanceId")));
204                 }
205
206                 if (requestScope.equals(OPENV) && instanceIdMap.get("operationalEnvironmentId") != null) {
207                     predicates.add(
208                             cb.equal(tableRoot.get(OPERATIONAL_ENV_ID), instanceIdMap.get("operationalEnvironmentId")));
209                 }
210             }
211         }
212         if (!predicates.isEmpty()) {
213             predicates.add(tableRoot.get(REQUEST_STATUS)
214                     .in(Arrays.asList("PENDING", "IN_PROGRESS", "TIMEOUT", "PENDING_MANUAL_TASK")));
215
216             final Order order = cb.desc(tableRoot.get(START_TIME));
217
218             final List<InfraActiveRequests> dupList = executeInfraQuery(crit, predicates, order);
219
220             if (dupList != null && !dupList.isEmpty()) {
221                 infraActiveRequests = dupList.get(0);
222             }
223         }
224
225         return infraActiveRequests;
226     }
227
228     /*
229      * (non-Javadoc)
230      * 
231      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
232      * getOrchestrationFiltersFromInfraActive(java.util.Map)
233      */
234     @Override
235     public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(
236             final Map<String, List<String>> orchestrationMap) {
237
238         final List<Predicate> predicates = new LinkedList<>();
239         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
240         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
241         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
242         for (final Map.Entry<String, List<String>> entry : orchestrationMap.entrySet()) {
243             String mapKey = entry.getKey();
244             if ("serviceInstanceId".equalsIgnoreCase(mapKey)) {
245                 mapKey = "serviceInstanceId";
246             } else if ("serviceInstanceName".equalsIgnoreCase(mapKey)) {
247                 mapKey = "serviceInstanceName";
248             } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) {
249                 mapKey = "vnfId";
250             } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) {
251                 mapKey = "vnfName";
252             } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) {
253                 mapKey = "vfModuleId";
254             } else if ("vfModuleInstanceName".equalsIgnoreCase(mapKey)) {
255                 mapKey = "vfModuleName";
256             } else if ("volumeGroupInstanceId".equalsIgnoreCase(mapKey)) {
257                 mapKey = "volumeGroupId";
258             } else if ("volumeGroupInstanceName".equalsIgnoreCase(mapKey)) {
259                 mapKey = "volumeGroupName";
260             } else if ("networkInstanceId".equalsIgnoreCase(mapKey)) {
261                 mapKey = "networkId";
262             } else if ("networkInstanceName".equalsIgnoreCase(mapKey)) {
263                 mapKey = "networkName";
264             } else if (mapKey.equalsIgnoreCase("configurationInstanceId")) {
265                 mapKey = "configurationId";
266             } else if (mapKey.equalsIgnoreCase("configurationInstanceName")) {
267                 mapKey = "configurationName";
268             } else if ("lcpCloudRegionId".equalsIgnoreCase(mapKey)) {
269                 mapKey = "aicCloudRegion";
270             } else if ("tenantId".equalsIgnoreCase(mapKey)) {
271                 mapKey = "tenantId";
272             } else if ("modelType".equalsIgnoreCase(mapKey)) {
273                 mapKey = "requestScope";
274             } else if ("requestorId".equalsIgnoreCase(mapKey)) {
275                 mapKey = "requestorId";
276             } else if ("requestExecutionDate".equalsIgnoreCase(mapKey)) {
277                 mapKey = "startTime";
278             }
279
280             final String propertyValue = entry.getValue().get(1);
281             if ("startTime".equals(mapKey)) {
282                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
283                 try {
284                     final Date thisDate = format.parse(propertyValue);
285                     final Timestamp minTime = new Timestamp(thisDate.getTime());
286                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
287
288                     if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
289                         predicates.add(cb.or(cb.lessThan(tableRoot.get(mapKey), minTime),
290                                 cb.greaterThanOrEqualTo(tableRoot.get(mapKey), maxTime)));
291                     } else {
292                         predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
293                     }
294                 } catch (final Exception e) {
295                     logger.debug("Exception in getOrchestrationFiltersFromInfraActive(): {}", e.getMessage(), e);
296                     return null;
297                 }
298             } else if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
299                 predicates.add(cb.notEqual(tableRoot.get(mapKey), propertyValue));
300             } else {
301                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
302             }
303
304         }
305
306         final Order order = cb.asc(tableRoot.get(START_TIME));
307
308         return executeInfraQuery(crit, predicates, order);
309     }
310
311     // Added this method for Tenant Isolation project ( 1802-295491a) to query the mso_requests DB
312     // (infra_active_requests table) for operationalEnvId and OperationalEnvName
313     /*
314      * (non-Javadoc)
315      * 
316      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
317      * getCloudOrchestrationFiltersFromInfraActive(java.util.Map)
318      */
319     @Override
320     public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(
321             final Map<String, String> orchestrationMap) {
322         final List<Predicate> predicates = new LinkedList<>();
323         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
324         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
325         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
326
327         // Add criteria on OperationalEnvironment RequestScope when requestorId is only specified in
328         // the filter
329         // as the same requestorId can also match on different API methods
330         final String resourceType = orchestrationMap.get("resourceType");
331         if (resourceType == null) {
332             predicates.add(cb.equal(tableRoot.get("requestScope"), OPENV));
333         }
334
335         for (final Map.Entry<String, String> entry : orchestrationMap.entrySet()) {
336             String mapKey = entry.getKey();
337             if (mapKey.equalsIgnoreCase("requestorId")) {
338                 mapKey = "requestorId";
339             } else if (mapKey.equalsIgnoreCase("requestExecutionDate")) {
340                 mapKey = "startTime";
341             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentId")) {
342                 mapKey = "operationalEnvId";
343             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentName")) {
344                 mapKey = "operationalEnvName";
345             } else if (mapKey.equalsIgnoreCase("resourceType")) {
346                 mapKey = "requestScope";
347             }
348
349             final String propertyValue = entry.getValue();
350             if (mapKey.equals("startTime")) {
351                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
352                 try {
353                     final Date thisDate = format.parse(propertyValue);
354                     final Timestamp minTime = new Timestamp(thisDate.getTime());
355                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
356
357                     predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
358                 } catch (final Exception e) {
359                     logger.debug("Exception in getCloudOrchestrationFiltersFromInfraActive(): {}", e.getMessage());
360                     return null;
361                 }
362             } else {
363                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
364             }
365         }
366
367         final Order order = cb.asc(tableRoot.get(START_TIME));
368         return executeInfraQuery(crit, predicates, order);
369     }
370
371     /*
372      * (non-Javadoc)
373      * 
374      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestListFromInfraActive(java .lang.String,
375      * java.lang.String, java.lang.String)
376      */
377     @Override
378     public List<InfraActiveRequests> getRequestListFromInfraActive(final String queryAttributeName,
379             final String queryValue, final String requestType) {
380         logger.debug("Get list of infra requests from DB with {} = {}", queryAttributeName, queryValue);
381
382
383         try {
384             final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
385             final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
386             final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
387             final Predicate isEqual = cb.equal(candidateRoot.get(queryAttributeName), queryValue);
388             final Predicate equalRequestType = cb.equal(candidateRoot.get(REQUEST_TYPE), requestType);
389             final Predicate isNull = cb.isNull(candidateRoot.get(REQUEST_TYPE));
390             final Predicate orClause = cb.or(equalRequestType, isNull);
391             final Order orderDesc = cb.desc(candidateRoot.get(START_TIME));
392             final Order orderAsc = cb.asc(candidateRoot.get(SOURCE));
393             crit.where(cb.and(isEqual, orClause)).orderBy(orderDesc, orderAsc);
394
395             final List<InfraActiveRequests> arList = entityManager.createQuery(crit).getResultList();
396             if (arList != null && !arList.isEmpty()) {
397                 return arList;
398             }
399         } catch (final Exception exception) {
400             logger.error("Unable to execute query", exception);
401         }
402         return Collections.emptyList();
403     }
404
405
406     /*
407      * (non-Javadoc)
408      * 
409      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java. lang.String,
410      * java.lang.String)
411      */
412     @Override
413     public InfraActiveRequests getRequestFromInfraActive(final String requestId, final String requestType) {
414         logger.debug("Get infra request from DB with id {}", requestId);
415
416         final Query query = entityManager.createQuery(
417                 "from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType");
418         query.setParameter(REQUEST_ID, requestId);
419         query.setParameter(REQUEST_TYPE, requestType);
420         return this.getSingleResult(query);
421     }
422
423
424     /*
425      * (non-Javadoc)
426      * 
427      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfName(java.lang. String,
428      * java.lang.String, java.lang.String)
429      */
430     @Override
431     public InfraActiveRequests checkDuplicateByVnfName(final String vnfName, final String action,
432             final String requestType) {
433
434         logger.debug("Get infra request from DB for VNF {} and action {} and requestType {}", vnfName, action,
435                 requestType);
436
437         InfraActiveRequests ar = null;
438
439         final Query query = entityManager.createQuery(
440                 "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");
441         query.setParameter("vnfName", vnfName);
442         query.setParameter("action", action);
443         query.setParameter(REQUEST_TYPE, requestType);
444         @SuppressWarnings("unchecked")
445         final List<InfraActiveRequests> results = query.getResultList();
446         if (!results.isEmpty()) {
447             ar = results.get(0);
448         }
449
450         return ar;
451     }
452
453     /*
454      * (non-Javadoc)
455      * 
456      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfId(java.lang. String,
457      * java.lang.String, java.lang.String)
458      */
459     @Override
460     public InfraActiveRequests checkDuplicateByVnfId(final String vnfId, final String action,
461             final String requestType) {
462
463         logger.debug("Get list of infra requests from DB for VNF {} and action {}", vnfId, action);
464
465         InfraActiveRequests ar = null;
466
467         final Query query = entityManager.createQuery(
468                 "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");
469         query.setParameter("vnfId", vnfId);
470         query.setParameter("action", action);
471         query.setParameter(REQUEST_TYPE, requestType);
472         @SuppressWarnings("unchecked")
473         final List<InfraActiveRequests> results = query.getResultList();
474         if (!results.isEmpty()) {
475             ar = results.get(0);
476         }
477
478         return ar;
479     }
480
481     /*
482      * (non-Javadoc)
483      * 
484      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkVnfIdStatus(java.lang.String)
485      */
486     @Override
487     public InfraActiveRequests checkVnfIdStatus(final String operationalEnvironmentId) {
488         logger.debug("Get Infra request from DB for OperationalEnvironmentId {}", operationalEnvironmentId);
489
490         InfraActiveRequests ar = null;
491
492         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
493         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
494         final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
495         final Predicate operationalEnvEq = cb.equal(candidateRoot.get("operationalEnvId"), operationalEnvironmentId);
496         final Predicate requestStatusNotEq = cb.notEqual(candidateRoot.get(REQUEST_STATUS), "COMPLETE");
497         final Predicate actionEq = cb.equal(candidateRoot.get("action"), "create");
498         final Order startTimeOrder = cb.desc(candidateRoot.get("startTime"));
499         crit.select(candidateRoot);
500         crit.where(cb.and(operationalEnvEq, requestStatusNotEq, actionEq));
501         crit.orderBy(startTimeOrder);
502         final TypedQuery<InfraActiveRequests> query = entityManager.createQuery(crit);
503         final List<InfraActiveRequests> results = query.getResultList();
504         if (!results.isEmpty()) {
505             ar = results.get(0);
506         }
507
508         return ar;
509     }
510
511     protected <T> T getSingleResult(final Query query) {
512         query.setMaxResults(1);
513         final List<T> list = query.getResultList();
514         if (list == null || list.isEmpty()) {
515             return null;
516         } else if (list.size() == 1) {
517             return list.get(0);
518         } else {
519             throw new NonUniqueResultException();
520         }
521
522     }
523
524     @Override
525     public List<InfraActiveRequests> getInfraActiveRequests(final Map<String, String[]> filters, final long startTime,
526             final long endTime, final Integer maxResult) {
527         if (filters == null) {
528             return Collections.emptyList();
529         }
530         try {
531             final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
532
533             final CriteriaQuery<InfraActiveRequests> criteriaQuery =
534                     criteriaBuilder.createQuery(InfraActiveRequests.class);
535             final Root<InfraActiveRequests> tableRoot = criteriaQuery.from(InfraActiveRequests.class);
536             final List<Predicate> predicates = getPredicates(filters, criteriaBuilder, tableRoot);
537
538             final Timestamp minTime = new Timestamp(startTime);
539             final Timestamp maxTime = new Timestamp(endTime);
540             final Predicate basePredicate = criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
541             final Predicate additionalPredicate =
542                     criteriaBuilder.and(criteriaBuilder.greaterThanOrEqualTo(tableRoot.get(START_TIME), minTime),
543                             criteriaBuilder.or(tableRoot.get(END_TIME).isNull(),
544                                     criteriaBuilder.lessThanOrEqualTo(tableRoot.get(END_TIME), maxTime)));
545
546             criteriaQuery.where(criteriaBuilder.and(basePredicate, additionalPredicate));
547             if (maxResult != null) {
548                 return entityManager.createQuery(criteriaQuery).setMaxResults(maxResult).getResultList();
549             }
550             return entityManager.createQuery(criteriaQuery).getResultList();
551         } catch (final Exception exception) {
552             logger.error("Unable to execute query using filters: {}", filters, exception);
553             return Collections.emptyList();
554         }
555     }
556
557     protected List<Predicate> getPredicates(final Map<String, String[]> filters, final CriteriaBuilder criteriaBuilder,
558             final Root<InfraActiveRequests> tableRoot) {
559         final List<Predicate> predicates = new LinkedList<>();
560         for (final Entry<String, String[]> entry : filters.entrySet()) {
561             final String[] params = entry.getValue();
562             if (VALID_COLUMNS.contains(entry.getKey()) && params.length == 2) {
563                 final QueryOperationType operationType = QueryOperationType.getQueryOperationType(params[0]);
564                 final Predicate predicate =
565                         operationType.getPredicate(criteriaBuilder, tableRoot, entry.getKey(), params[1]);
566                 predicates.add(predicate);
567             }
568         }
569         return predicates;
570     }
571 }