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