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