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