Adding rest service for so monitoring
[so.git] / mso-api-handlers / mso-requests-db / 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 java.sql.Timestamp;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.LinkedList;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Map.Entry;
35 import java.util.concurrent.TimeUnit;
36
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
47 import org.onap.so.db.request.beans.InfraActiveRequests;
48 import org.onap.so.logger.MsoLogger;
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 MsoLogger msoLogger =
65             MsoLogger.getMsoLogger(MsoLogger.Catalog.GENERAL, 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         msoLogger.debug("Execute query on infra active request table");
118
119         List<InfraActiveRequests> results = new ArrayList<InfraActiveRequests>();
120
121         try {
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         } finally {
128             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
129                     "Successfully", "RequestDB", "getInfraActiveRequest", null);
130         }
131         return results;
132     }
133
134     /*
135      * (non-Javadoc)
136      * 
137      * @see
138      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java.
139      * lang.String)
140      */
141     @Override
142     public InfraActiveRequests getRequestFromInfraActive(final String requestId) {
143         final long startTime = System.currentTimeMillis();
144         msoLogger.debug("Get request " + requestId + " from InfraActiveRequests DB");
145
146         InfraActiveRequests ar = null;
147         try {
148             final Query query = entityManager.createQuery(
149                     "from InfraActiveRequests where requestId = :requestId OR clientRequestId = :requestId");
150             query.setParameter(REQUEST_ID, requestId);
151             ar = this.getSingleResult(query);
152         } finally {
153
154             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
155                     "Successfully", "InfraRequestDB", "getRequestFromInfraActive", null);
156         }
157         return ar;
158     }
159
160     /*
161      * (non-Javadoc)
162      * 
163      * @see
164      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkInstanceNameDuplicate(java.
165      * util.HashMap, java.lang.String, java.lang.String)
166      */
167     @Override
168     public InfraActiveRequests checkInstanceNameDuplicate(final HashMap<String, String> instanceIdMap,
169             final String instanceName, final String requestScope) {
170
171         final List<Predicate> predicates = new LinkedList<>();
172         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
173         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
174         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
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
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         InfraActiveRequests infraActiveRequests = null;
241
242         if (dupList != null && !dupList.isEmpty()) {
243             infraActiveRequests = dupList.get(0);
244         }
245
246         return infraActiveRequests;
247     }
248
249     /*
250      * (non-Javadoc)
251      * 
252      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
253      * getOrchestrationFiltersFromInfraActive(java.util.Map)
254      */
255     @Override
256     public List<InfraActiveRequests> getOrchestrationFiltersFromInfraActive(
257             final Map<String, List<String>> orchestrationMap) {
258
259
260         final List<Predicate> predicates = new LinkedList<>();
261         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
262         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
263         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
264         for (final Map.Entry<String, List<String>> entry : orchestrationMap.entrySet()) {
265             String mapKey = entry.getKey();
266             if ("serviceInstanceId".equalsIgnoreCase(mapKey)) {
267                 mapKey = "serviceInstanceId";
268             } else if ("serviceInstanceName".equalsIgnoreCase(mapKey)) {
269                 mapKey = "serviceInstanceName";
270             } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) {
271                 mapKey = "vnfId";
272             } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) {
273                 mapKey = "vnfName";
274             } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) {
275                 mapKey = "vfModuleId";
276             } else if ("vfModuleInstanceName".equalsIgnoreCase(mapKey)) {
277                 mapKey = "vfModuleName";
278             } else if ("volumeGroupInstanceId".equalsIgnoreCase(mapKey)) {
279                 mapKey = "volumeGroupId";
280             } else if ("volumeGroupInstanceName".equalsIgnoreCase(mapKey)) {
281                 mapKey = "volumeGroupName";
282             } else if ("networkInstanceId".equalsIgnoreCase(mapKey)) {
283                 mapKey = "networkId";
284             } else if ("networkInstanceName".equalsIgnoreCase(mapKey)) {
285                 mapKey = "networkName";
286             } else if (mapKey.equalsIgnoreCase("configurationInstanceId")) {
287                 mapKey = "configurationId";
288             } else if (mapKey.equalsIgnoreCase("configurationInstanceName")) {
289                 mapKey = "configurationName";
290             } else if ("lcpCloudRegionId".equalsIgnoreCase(mapKey)) {
291                 mapKey = "aicCloudRegion";
292             } else if ("tenantId".equalsIgnoreCase(mapKey)) {
293                 mapKey = "tenantId";
294             } else if ("modelType".equalsIgnoreCase(mapKey)) {
295                 mapKey = "requestScope";
296             } else if ("requestorId".equalsIgnoreCase(mapKey)) {
297                 mapKey = "requestorId";
298             } else if ("requestExecutionDate".equalsIgnoreCase(mapKey)) {
299                 mapKey = "startTime";
300             }
301
302             final String propertyValue = entry.getValue().get(1);
303             if ("startTime".equals(mapKey)) {
304                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
305                 try {
306                     final Date thisDate = format.parse(propertyValue);
307                     final Timestamp minTime = new Timestamp(thisDate.getTime());
308                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
309
310                     if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
311                         predicates.add(cb.or(cb.lessThan(tableRoot.get(mapKey), minTime),
312                                 cb.greaterThanOrEqualTo(tableRoot.get(mapKey), maxTime)));
313                     } else {
314                         predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
315                     }
316                 } catch (final Exception e) {
317                     msoLogger.debug("Exception in getOrchestrationFiltersFromInfraActive(): + " + e.getMessage(), e);
318                     return null;
319                 }
320             } else if ("DOES_NOT_EQUAL".equalsIgnoreCase(entry.getValue().get(0))) {
321                 predicates.add(cb.notEqual(tableRoot.get(mapKey), propertyValue));
322             } else {
323                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
324             }
325
326         }
327
328         final Order order = cb.asc(tableRoot.get(START_TIME));
329
330         return executeInfraQuery(crit, predicates, order);
331     }
332
333     // Added this method for Tenant Isolation project ( 1802-295491a) to query the mso_requests DB
334     // (infra_active_requests table) for operationalEnvId and OperationalEnvName
335     /*
336      * (non-Javadoc)
337      * 
338      * @see org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#
339      * getCloudOrchestrationFiltersFromInfraActive(java.util.Map)
340      */
341     @Override
342     public List<InfraActiveRequests> getCloudOrchestrationFiltersFromInfraActive(
343             final Map<String, String> orchestrationMap) {
344         final List<Predicate> predicates = new LinkedList<>();
345         final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
346         final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
347         final Root<InfraActiveRequests> tableRoot = crit.from(InfraActiveRequests.class);
348
349         // Add criteria on OperationalEnvironment RequestScope when requestorId is only specified in
350         // the filter
351         // as the same requestorId can also match on different API methods
352         final String resourceType = orchestrationMap.get("resourceType");
353         if (resourceType == null) {
354             predicates.add(cb.equal(tableRoot.get("requestScope"), "operationalEnvironment"));
355         }
356
357         for (final Map.Entry<String, String> entry : orchestrationMap.entrySet()) {
358             String mapKey = entry.getKey();
359             if (mapKey.equalsIgnoreCase("requestorId")) {
360                 mapKey = "requestorId";
361             } else if (mapKey.equalsIgnoreCase("requestExecutionDate")) {
362                 mapKey = "startTime";
363             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentId")) {
364                 mapKey = "operationalEnvId";
365             } else if (mapKey.equalsIgnoreCase("operationalEnvironmentName")) {
366                 mapKey = "operationalEnvName";
367             } else if (mapKey.equalsIgnoreCase("resourceType")) {
368                 mapKey = "requestScope";
369             }
370
371             final String propertyValue = entry.getValue();
372             if (mapKey.equals("startTime")) {
373                 final SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
374                 try {
375                     final Date thisDate = format.parse(propertyValue);
376                     final Timestamp minTime = new Timestamp(thisDate.getTime());
377                     final Timestamp maxTime = new Timestamp(thisDate.getTime() + TimeUnit.DAYS.toMillis(1));
378
379                     predicates.add(cb.between(tableRoot.get(mapKey), minTime, maxTime));
380                 } catch (final Exception e) {
381                     msoLogger.debug("Exception in getCloudOrchestrationFiltersFromInfraActive(): + " + e.getMessage());
382                     return null;
383                 }
384             } else {
385                 predicates.add(cb.equal(tableRoot.get(mapKey), propertyValue));
386             }
387         }
388
389         final Order order = cb.asc(tableRoot.get(START_TIME));
390         return executeInfraQuery(crit, predicates, order);
391     }
392
393     /*
394      * (non-Javadoc)
395      * 
396      * @see
397      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestListFromInfraActive(java
398      * .lang.String, java.lang.String, java.lang.String)
399      */
400     @Override
401     public List<InfraActiveRequests> getRequestListFromInfraActive(final String queryAttributeName,
402             final String queryValue, final String requestType) {
403         msoLogger.debug("Get list of infra requests from DB with " + queryAttributeName + " = " + queryValue);
404
405
406         try {
407             final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
408             final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
409             final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
410             final Predicate isEqual = cb.equal(candidateRoot.get(queryAttributeName), queryValue);
411             final Predicate equalRequestType = cb.equal(candidateRoot.get(REQUEST_TYPE), requestType);
412             final Predicate isNull = cb.isNull(candidateRoot.get(REQUEST_TYPE));
413             final Predicate orClause = cb.or(equalRequestType, isNull);
414             final Order orderDesc = cb.desc(candidateRoot.get(START_TIME));
415             final Order orderAsc = cb.asc(candidateRoot.get(SOURCE));
416             crit.where(cb.and(isEqual, orClause)).orderBy(orderDesc, orderAsc);
417
418             final List<InfraActiveRequests> arList = entityManager.createQuery(crit).getResultList();
419             if (arList != null && !arList.isEmpty()) {
420                 return arList;
421             }
422         } catch (final Exception exception) {
423             msoLogger.error("Unable to execute query", exception);
424         }
425         return Collections.emptyList();
426     }
427
428
429     /*
430      * (non-Javadoc)
431      * 
432      * @see
433      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#getRequestFromInfraActive(java.
434      * lang.String, java.lang.String)
435      */
436     @Override
437     public InfraActiveRequests getRequestFromInfraActive(final String requestId, final String requestType) {
438         final long startTime = System.currentTimeMillis();
439         msoLogger.debug("Get infra request from DB with id " + requestId);
440
441         InfraActiveRequests ar = null;
442         try {
443             final Query query = entityManager.createQuery(
444                     "from InfraActiveRequests where (requestId = :requestId OR clientRequestId = :requestId) and requestType = :requestType");
445             query.setParameter(REQUEST_ID, requestId);
446             query.setParameter(REQUEST_TYPE, requestType);
447             ar = this.getSingleResult(query);
448         } finally {
449             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
450                     "Successfully", "RequestDB", "getRequestFromInfraActive", null);
451         }
452         return ar;
453     }
454
455
456     /*
457      * (non-Javadoc)
458      * 
459      * @see
460      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfName(java.lang.
461      * String, java.lang.String, java.lang.String)
462      */
463     @Override
464     public InfraActiveRequests checkDuplicateByVnfName(final String vnfName, final String action,
465             final String requestType) {
466
467         final long startTime = System.currentTimeMillis();
468         msoLogger.debug("Get infra request from DB for VNF " + vnfName + " and action " + action + " and requestType "
469                 + requestType);
470
471         InfraActiveRequests ar = null;
472         try {
473             final Query query = entityManager.createQuery(
474                     "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");
475             query.setParameter("vnfName", vnfName);
476             query.setParameter("action", action);
477             query.setParameter(REQUEST_TYPE, requestType);
478             @SuppressWarnings("unchecked")
479             final List<InfraActiveRequests> results = query.getResultList();
480             if (!results.isEmpty()) {
481                 ar = results.get(0);
482             }
483         } finally {
484             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
485                     "Successfully", "RequestDB", "checkDuplicateByVnfName", null);
486         }
487
488         return ar;
489     }
490
491     /*
492      * (non-Javadoc)
493      * 
494      * @see
495      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkDuplicateByVnfId(java.lang.
496      * String, java.lang.String, java.lang.String)
497      */
498     @Override
499     public InfraActiveRequests checkDuplicateByVnfId(final String vnfId, final String action,
500             final String requestType) {
501
502         final long startTime = System.currentTimeMillis();
503         msoLogger.debug("Get list of infra requests from DB for VNF " + vnfId + " and action " + action);
504
505         InfraActiveRequests ar = null;
506         try {
507             final Query query = entityManager.createQuery(
508                     "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");
509             query.setParameter("vnfId", vnfId);
510             query.setParameter("action", action);
511             query.setParameter(REQUEST_TYPE, requestType);
512             @SuppressWarnings("unchecked")
513             final List<InfraActiveRequests> results = query.getResultList();
514             if (!results.isEmpty()) {
515                 ar = results.get(0);
516             }
517         } finally {
518             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
519                     "Successfully", "RequestDB", "checkDuplicateByVnfId", null);
520         }
521
522         return ar;
523     }
524
525     /*
526      * (non-Javadoc)
527      * 
528      * @see
529      * org.onap.so.requestsdb.InfraActiveRequestsRepositoryCustom#checkVnfIdStatus(java.lang.String)
530      */
531     @Override
532     public InfraActiveRequests checkVnfIdStatus(final String operationalEnvironmentId) {
533         final long startTime = System.currentTimeMillis();
534         msoLogger.debug("Get Infra request from DB for OperationalEnvironmentId " + operationalEnvironmentId);
535
536         InfraActiveRequests ar = null;
537         try {
538             final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
539             final CriteriaQuery<InfraActiveRequests> crit = cb.createQuery(InfraActiveRequests.class);
540             final Root<InfraActiveRequests> candidateRoot = crit.from(InfraActiveRequests.class);
541             final Predicate operationalEnvEq =
542                     cb.equal(candidateRoot.get("operationalEnvId"), operationalEnvironmentId);
543             final Predicate requestStatusNotEq = cb.notEqual(candidateRoot.get(REQUEST_STATUS), "COMPLETE");
544             final Predicate actionEq = cb.equal(candidateRoot.get("action"), "create");
545             final Order startTimeOrder = cb.desc(candidateRoot.get("startTime"));
546             crit.select(candidateRoot);
547             crit.where(cb.and(operationalEnvEq, requestStatusNotEq, actionEq));
548             crit.orderBy(startTimeOrder);
549             final TypedQuery<InfraActiveRequests> query = entityManager.createQuery(crit);
550             final List<InfraActiveRequests> results = query.getResultList();
551             if (!results.isEmpty()) {
552                 ar = results.get(0);
553             }
554         } finally {
555             msoLogger.recordMetricEvent(startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
556                     "Successfully", "RequestDB", "checkDuplicateByVnfName", null);
557         }
558
559         return ar;
560     }
561
562     protected <T> T getSingleResult(final Query query) {
563         query.setMaxResults(1);
564         final List<T> list = query.getResultList();
565         if (list == null || list.isEmpty()) {
566             return null;
567         } else if (list.size() == 1) {
568             return list.get(0);
569         } else {
570             throw new NonUniqueResultException();
571         }
572
573     }
574
575     @Override
576     public List<InfraActiveRequests> getInfraActiveRequests(final Map<String, String[]> filters, final long startTime,
577             final long endTime, final Integer maxResult) {
578         if (filters == null) {
579             return Collections.emptyList();
580         }
581         try {
582             final CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
583             final CriteriaQuery<InfraActiveRequests> criteriaQuery =
584                     criteriaBuilder.createQuery(InfraActiveRequests.class);
585             final Root<InfraActiveRequests> tableRoot = criteriaQuery.from(InfraActiveRequests.class);
586             final List<Predicate> predicates = getPredicates(filters, criteriaBuilder, tableRoot);
587
588             final Timestamp minTime = new Timestamp(startTime);
589             final Timestamp maxTime = new Timestamp(endTime);
590             predicates.add(criteriaBuilder.greaterThanOrEqualTo(tableRoot.get(START_TIME), minTime));
591             predicates.add(criteriaBuilder.lessThanOrEqualTo(tableRoot.get(END_TIME), maxTime));
592
593             criteriaQuery.where(criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])));
594             if (maxResult != null) {
595                 return entityManager.createQuery(criteriaQuery).setMaxResults(maxResult).getResultList();
596             }
597             return entityManager.createQuery(criteriaQuery).getResultList();
598         } catch (final Exception exception) {
599             msoLogger.error("Unable to execute query using filters: " + filters, exception);
600             return Collections.emptyList();
601         }
602     }
603
604     private List<Predicate> getPredicates(final Map<String, String[]> filters, final CriteriaBuilder criteriaBuilder,
605             final Root<InfraActiveRequests> tableRoot) {
606         final List<Predicate> predicates = new LinkedList<>();
607         for (final Entry<String, String[]> entry : filters.entrySet()) {
608             final String[] params = entry.getValue();
609             if (VALID_COLUMNS.contains(entry.getKey()) && params.length == 2) {
610                 final QueryOperationType operationType = QueryOperationType.getQueryOperationType(params[0]);
611                 final Predicate predicate =
612                         operationType.getPredicate(criteriaBuilder, tableRoot, entry.getKey(), params[1]);
613                 predicates.add(predicate);
614             }
615         }
616         return predicates;
617     }
618 }