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