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