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