Merge "asdc process vf resource into db bug fix"
[so.git] / bpmn / so-bpmn-tasks / src / main / java / org / onap / so / bpmn / infrastructure / workflow / tasks / WorkflowAction.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.bpmn.infrastructure.workflow.tasks;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.UUID;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33 import java.util.stream.Collectors;
34
35 import org.camunda.bpm.engine.delegate.DelegateExecution;
36 import org.javatuples.Pair;
37 import org.slf4j.LoggerFactory;
38 import org.onap.aai.domain.yang.GenericVnf;
39 import org.onap.aai.domain.yang.L3Network;
40 import org.onap.aai.domain.yang.Relationship;
41 import org.onap.aai.domain.yang.ServiceInstance;
42 import org.onap.aai.domain.yang.VolumeGroup;
43 import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
44 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
45 import org.onap.so.bpmn.servicedecomposition.entities.BuildingBlock;
46 import org.onap.so.bpmn.servicedecomposition.entities.ConfigurationResourceKeys;
47 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
48 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
49 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup;
50 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
51 import org.onap.so.bpmn.infrastructure.workflow.tasks.Resource;
52 import org.onap.so.client.aai.AAICommonObjectMapperProvider;
53 import org.onap.so.client.aai.entities.AAIResultWrapper;
54 import org.onap.so.client.aai.entities.Relationships;
55 import org.onap.so.client.exception.ExceptionBuilder;
56 import org.onap.so.client.orchestration.AAIConfigurationResources;
57 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
58 import org.onap.so.db.catalog.beans.CollectionResourceCustomization;
59 import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
60 import org.onap.so.db.catalog.beans.CvnfcCustomization;
61 import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization;
62 import org.onap.so.db.catalog.beans.VfModuleCustomization;
63 import org.onap.so.db.catalog.beans.VnfVfmoduleCvnfcConfigurationCustomization;
64 import org.onap.so.db.catalog.beans.macro.NorthBoundRequest;
65 import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
66 import org.onap.so.db.catalog.client.CatalogDbClient;
67 import org.onap.so.logger.MsoLogger;
68 import org.onap.so.serviceinstancebeans.ModelInfo;
69 import org.onap.so.serviceinstancebeans.ModelType;
70 import org.onap.so.serviceinstancebeans.Networks;
71 import org.onap.so.serviceinstancebeans.RequestDetails;
72 import org.onap.so.serviceinstancebeans.Service;
73 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
74 import org.onap.so.serviceinstancebeans.VfModules;
75 import org.onap.so.serviceinstancebeans.Vnfs;
76 import org.slf4j.Logger;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.core.env.Environment;
79 import org.springframework.stereotype.Component;
80
81 import com.fasterxml.jackson.databind.ObjectMapper;
82
83 @Component
84 public class WorkflowAction {
85
86         private static final String WORKFLOW_ACTION_ERROR_MESSAGE = "WorkflowActionErrorMessage";
87         private static final String SERVICE_INSTANCES = "serviceInstances";
88         private static final String VF_MODULES = "vfModules";
89         private static final String WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI = "WorkflowAction was unable to verify if the instance name already exist in AAI.";
90         private static final String G_ORCHESTRATION_FLOW = "gOrchestrationFlow";
91         private static final String G_ACTION = "requestAction";
92         private static final String G_CURRENT_SEQUENCE = "gCurrentSequence";
93         private static final String G_REQUEST_ID = "mso-request-id";
94         private static final String G_BPMN_REQUEST = "bpmnRequest";
95         private static final String G_ALACARTE = "aLaCarte";
96         private static final String G_APIVERSION = "apiVersion";
97         private static final String G_URI = "requestUri";
98         private static final String G_ISTOPLEVELFLOW = "isTopLevelFlow";
99         private static final String VNF_TYPE = "vnfType";
100         private static final String SERVICE = "Service";
101         private static final String VNF = "Vnf";
102         private static final String VFMODULE = "VfModule";
103         private static final String VOLUMEGROUP = "VolumeGroup";
104         private static final String NETWORK = "Network";
105         private static final String NETWORKCOLLECTION = "NetworkCollection";
106         private static final String CONFIGURATION = "Configuration";
107         private static final String ASSIGNINSTANCE = "assignInstance";
108         private static final String CREATEINSTANCE = "createInstance";
109         private static final String USERPARAMSERVICE = "service";
110         private static final String supportedTypes = "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances";
111         private static final String HOMINGSOLUTION = "Homing_Solution";
112         private static final String FABRIC_CONFIGURATION = "FabricConfiguration";       
113         private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
114         
115         @Autowired
116         protected BBInputSetup bbInputSetup;
117         @Autowired
118         protected BBInputSetupUtils bbInputSetupUtils;
119         @Autowired
120         private ExceptionBuilder exceptionBuilder;
121         @Autowired
122         private CatalogDbClient catalogDbClient;
123         @Autowired
124         private AAIConfigurationResources aaiConfigurationResources;
125         @Autowired
126         private WorkflowActionExtractResourcesAAI workflowActionUtils;
127
128         @Autowired
129         private Environment environment;
130         private String defaultCloudOwner = "org.onap.so.cloud-owner";
131
132         public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
133                 this.bbInputSetupUtils = bbInputSetupUtils;
134         }
135
136         public void setBbInputSetup(BBInputSetup bbInputSetup) {
137                 this.bbInputSetup = bbInputSetup;
138         }
139
140         public void selectExecutionList(DelegateExecution execution) throws Exception {
141                 final String requestAction = (String) execution.getVariable(G_ACTION);
142                 final String requestId = (String) execution.getVariable(G_REQUEST_ID);
143                 final String bpmnRequest = (String) execution.getVariable(G_BPMN_REQUEST);
144                 final boolean aLaCarte = (boolean) execution.getVariable(G_ALACARTE);
145                 final String apiVersion = (String) execution.getVariable(G_APIVERSION);
146                 final String uri = (String) execution.getVariable(G_URI);
147                 final String vnfType = (String) execution.getVariable(VNF_TYPE);
148                 String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
149                 List<OrchestrationFlow> orchFlows = (List<OrchestrationFlow>) execution.getVariable(G_ORCHESTRATION_FLOW);
150                 List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
151                 WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
152                 List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
153                 List<Resource> resourceCounter = new ArrayList<>();
154                 execution.setVariable("sentSyncResponse", false);
155                 execution.setVariable("homing", false);
156                 execution.setVariable("calledHoming", false);
157
158                 try {
159                         ObjectMapper mapper = new ObjectMapper();
160                         execution.setVariable(G_ISTOPLEVELFLOW, true);
161                         ServiceInstancesRequest sIRequest = mapper.readValue(bpmnRequest, ServiceInstancesRequest.class);
162                         RequestDetails requestDetails = sIRequest.getRequestDetails();
163                         String cloudOwner = "";
164                         try{
165                                 cloudOwner = requestDetails.getCloudConfiguration().getCloudOwner();
166                         } catch (Exception ex) {
167                                 cloudOwner = environment.getProperty(defaultCloudOwner);
168                         }
169                         Resource resource = extractResourceIdAndTypeFromUri(uri);
170                         WorkflowType resourceType = resource.getResourceType();
171                         execution.setVariable("resourceName", resourceType.toString());
172                         String resourceId = "";
173                         if (resource.isGenerated()) {
174                                 resourceId = validateResourceIdInAAI(resource.getResourceId(), resourceType,
175                                                 sIRequest.getRequestDetails().getRequestInfo().getInstanceName(), sIRequest.getRequestDetails(),
176                                                 workflowResourceIds);
177                         } else {
178                                 resourceId = resource.getResourceId();
179                         }
180                         if((serviceInstanceId == null || serviceInstanceId.equals("")) && resourceType == WorkflowType.SERVICE){
181                                 serviceInstanceId = resourceId;
182                         }
183                         execution.setVariable("resourceId", resourceId);
184                         execution.setVariable("resourceType", resourceType);
185
186                         if (aLaCarte) {
187                                 if (orchFlows == null || orchFlows.isEmpty()) {
188                                         orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner);
189                                 }
190                                 orchFlows = filterOrchFlows(orchFlows, resourceType, execution);
191                                 String key = "";
192                                 ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
193                                 if(modelInfo.getModelType().equals(ModelType.service)) {
194                                         key = modelInfo.getModelVersionId();
195                                 } else {
196                                         key = modelInfo.getModelCustomizationId();
197                                 }
198                                 Resource resourceKey = new Resource(resourceType, key, aLaCarte);
199                                 for (OrchestrationFlow orchFlow : orchFlows) {
200                                         ExecuteBuildingBlock ebb = buildExecuteBuildingBlock(orchFlow, requestId, resourceKey, apiVersion, resourceId,
201                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false);
202                                         flowsToExecute.add(ebb);
203                                 }
204                         } else {
205                                 boolean foundRelated = false;
206                                 boolean containsService = false;
207                                 if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) {
208                                         // SERVICE-MACRO-ASSIGN will always get user params with a
209                                         // service.
210                                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
211                                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
212                                                                 .getUserParams();
213                                                 for (Map<String, Object> params : userParams) {
214                                                         if (params.containsKey(USERPARAMSERVICE)) {
215                                                                 containsService = true;
216                                                         }
217                                                 }
218                                                 if (containsService) {
219                                                         traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
220                                                 }
221                                         } else {
222                                                 buildAndThrowException(execution,
223                                                                 "Service-Macro-Assign request details must contain user params with a service");
224                                         }
225                                 } else if (resourceType == WorkflowType.SERVICE
226                                                 && requestAction.equalsIgnoreCase(CREATEINSTANCE)) {
227                                         // SERVICE-MACRO-CREATE will get user params with a service,
228                                         // a service with a network, a service with a
229                                         // networkcollection, OR an empty service.
230                                         // If user params is just a service or null and macro
231                                         // queries the SI and finds a VNF, macro fails.
232
233                                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
234                                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters()
235                                                                 .getUserParams();
236                                                 for (Map<String, Object> params : userParams) {
237                                                         if (params.containsKey(USERPARAMSERVICE)) {
238                                                                 containsService = true;
239                                                         }
240                                                 }
241                                         }
242                                         if (containsService) {
243                                                 foundRelated = traverseUserParamsService(execution, resourceCounter, sIRequest, requestAction);
244                                         }
245                                         if (!foundRelated) {
246                                                 traverseCatalogDbService(execution, sIRequest, resourceCounter);
247                                         }
248                                 } else if (resourceType == WorkflowType.SERVICE
249                                                 && (requestAction.equalsIgnoreCase("activateInstance")
250                                                                 || requestAction.equalsIgnoreCase("unassignInstance")
251                                                                 || requestAction.equalsIgnoreCase("deleteInstance")
252                                                                 || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) {
253                                         // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and
254                                         // SERVICE-MACRO-DELETE
255                                         // Will never get user params with service, macro will have
256                                         // to query the SI in AAI to find related instances.
257                                         traverseAAIService(execution, resourceCounter, resourceId, aaiResourceIds);
258                                 } else if (resourceType == WorkflowType.SERVICE
259                                                 && requestAction.equalsIgnoreCase("deactivateInstance")) {
260                                         resourceCounter.add(new Resource(WorkflowType.SERVICE,"",false));
261                                 } else if (resourceType == WorkflowType.VNF && (requestAction.equalsIgnoreCase("replaceInstance") || (requestAction.equalsIgnoreCase("recreateInstance")))) {
262                                         traverseAAIVnf(execution, resourceCounter, workflowResourceIds.getServiceInstanceId(), workflowResourceIds.getVnfId(), aaiResourceIds);
263                                 } else {
264                                         buildAndThrowException(execution, "Current Macro Request is not supported");
265                                 }
266                                 String foundObjects = "";
267                                 for(WorkflowType type : WorkflowType.values()){
268                                         foundObjects = foundObjects + type + " - " + resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList()).size() + "    ";
269                                 }
270                                 logger.info("Found {}", foundObjects);
271
272                                 if (orchFlows == null || orchFlows.isEmpty()) {
273                                         orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, aLaCarte, cloudOwner);
274                                 }
275                                 flowsToExecute = buildExecuteBuildingBlockList(orchFlows, resourceCounter, requestId, apiVersion, resourceId,
276                                                 resourceType, requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails);
277                                 if (!resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
278                                         logger.info("Sorting for Vlan Tagging");
279                                         flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
280                                 }
281                                 // By default, enable homing at VNF level for CREATEINSTANCE and ASSIGNINSTANCE
282                                 if (resourceType == WorkflowType.SERVICE
283                                         && (requestAction.equals(CREATEINSTANCE) || requestAction.equals(ASSIGNINSTANCE))
284                                         && !resourceCounter.stream().filter(x -> WorkflowType.VNF.equals(x.getResourceType())).collect(Collectors.toList()).isEmpty()) {
285                                         execution.setVariable("homing", true);
286                                         execution.setVariable("calledHoming", false);
287                                 }
288                                 if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE) || requestAction.equalsIgnoreCase(CREATEINSTANCE))){
289                                         generateResourceIds(flowsToExecute, resourceCounter, serviceInstanceId);
290                                 }else{
291                                         updateResourceIdsFromAAITraversal(flowsToExecute, resourceCounter, aaiResourceIds, serviceInstanceId);
292                                 }
293                         }
294
295                         // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified, enable it.
296                         if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
297                                 List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
298                                 for (Map<String, Object> params : userParams) {
299                                         if (params.containsKey(HOMINGSOLUTION)) {
300                                                 if (params.get(HOMINGSOLUTION).equals("none")) {
301                                                         execution.setVariable("homing", false);
302                                                 } else {
303                                                         execution.setVariable("homing", true);
304                                                 }
305                                         }
306                                 }
307                         }
308
309                         if (flowsToExecute.isEmpty()) {
310                                 throw new IllegalStateException("Macro did not come up with a valid execution path.");
311                         }
312
313                         logger.info("List of BuildingBlocks to execute:");
314                         for (ExecuteBuildingBlock ebb : flowsToExecute) {
315                                 logger.info(ebb.getBuildingBlock().getBpmnFlowName());
316                         }
317
318                         execution.setVariable(G_CURRENT_SEQUENCE, 0);
319                         execution.setVariable("retryCount", 0);
320                         execution.setVariable("isRollback", false);
321                         execution.setVariable("flowsToExecute", flowsToExecute);
322                         execution.setVariable("isRollbackComplete", false);
323
324                 } catch (Exception ex) {
325                         buildAndThrowException(execution, "Exception in create execution list " + ex.getMessage(), ex);
326                 }
327         }
328
329         protected List<Resource> sortVfModulesByBaseFirst(List<Resource> vfModuleResources) {
330                 int count = 0;
331                 for(Resource resource : vfModuleResources){
332                         if(resource.isBaseVfModule()){
333                                 Collections.swap(vfModuleResources, 0, count);
334                                 break;
335                 }
336                         count++;
337                 }
338                 return vfModuleResources;
339         }
340
341         private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
342                         List<Resource> resourceCounter, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
343                 for(Pair<WorkflowType,String> pair : aaiResourceIds){
344                         logger.debug(pair.getValue0() + ", " + pair.getValue1());
345                 }
346                 
347                 Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
348                         List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
349                         for(int i = 0; i < resources.size(); i++){
350                                 updateWorkflowResourceIds(flowsToExecute, type, resources.get(i).getResourceId(), retrieveAAIResourceId(aaiResourceIds,type), null, serviceInstanceId);
351                 }
352                 });
353         }
354
355         private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource){
356                 String id = null;
357                 for(int i = 0; i<aaiResourceIds.size();i++){
358                         if(aaiResourceIds.get(i).getValue0() == resource){
359                                 id = aaiResourceIds.get(i).getValue1();
360                                 aaiResourceIds.remove(i);
361                                 break;
362                         }
363                 }
364                 return id;
365         }
366         private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceCounter, String serviceInstanceId) {
367                 Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE)).forEach(type -> {
368                         List<Resource> resources = resourceCounter.stream().filter(x -> type.equals(x.getResourceType())).collect(Collectors.toList());
369                         for(int i = 0; i < resources.size(); i++){
370                                 Resource resource = resourceCounter.stream().filter(x -> type.equals(x.getResourceType()))
371                                                 .collect(Collectors.toList()).get(i);
372                                 updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(), null, resource.getVirtualLinkKey(),serviceInstanceId);
373                         }
374                 });
375         }       
376         
377         protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resource, String key, String id, String virtualLinkKey, String serviceInstanceId){
378                 String resourceId = id;
379                 if(resourceId==null){
380                         resourceId = UUID.randomUUID().toString();
381                 }
382                 for(ExecuteBuildingBlock ebb : flowsToExecute){
383                         if(key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey()) && ebb.getBuildingBlock().getBpmnFlowName().contains(resource.toString())){
384                                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
385                                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
386                                 if(resource == WorkflowType.VNF){
387                                         workflowResourceIds.setVnfId(resourceId);
388                                 }else if(resource == WorkflowType.VFMODULE){
389                                         workflowResourceIds.setVfModuleId(resourceId);
390                                 }else if(resource == WorkflowType.VOLUMEGROUP){
391                                         workflowResourceIds.setVolumeGroupId(resourceId);
392                                 }else if(resource == WorkflowType.NETWORK){
393                                         workflowResourceIds.setNetworkId(resourceId);
394                                 }else if(resource == WorkflowType.NETWORKCOLLECTION){
395                                         workflowResourceIds.setNetworkCollectionId(resourceId);
396                                 }else if(resource == WorkflowType.CONFIGURATION){
397                                         workflowResourceIds.setConfigurationId(resourceId);
398                                 }
399                                 ebb.setWorkflowResourceIds(workflowResourceIds);
400                         }
401                         if(virtualLinkKey != null && ebb.getBuildingBlock().getIsVirtualLink() 
402                                         && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
403                                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
404                                 workflowResourceIds.setNetworkId(resourceId);
405                                 ebb.setWorkflowResourceIds(workflowResourceIds);
406                         }
407                 }
408         }
409
410         protected CollectionResourceCustomization findCatalogNetworkCollection(DelegateExecution execution, org.onap.so.db.catalog.beans.Service service) {
411                 CollectionResourceCustomization networkCollection = null;
412                 int count = 0;
413                 for(CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()){
414                         if(catalogDbClient.getNetworkCollectionResourceCustomizationByID(collectionCust.getModelCustomizationUUID()) 
415                                         instanceof NetworkCollectionResourceCustomization) {
416                                 networkCollection = collectionCust;
417                                 count++;
418                         }
419                 }
420                 if(count == 0){
421                         return null;
422                 }else if(count > 1) {
423                         buildAndThrowException(execution, "Found multiple Network Collections in the Service model, only one per Service is supported.");
424                 }
425                 return networkCollection;
426         }
427         
428         protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest,
429                         List<Resource> resourceCounter) {
430                 String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId();
431                 org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID);
432                 if (service == null) {
433                         buildAndThrowException(execution, "Could not find the service model in catalog db.");
434                 } else {
435                         resourceCounter.add(new Resource(WorkflowType.SERVICE,service.getModelUUID(),false));
436                         if (service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty()) {
437                                 List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
438                                 if(customizations.isEmpty()) {
439                                         logger.debug("No Collections found. CollectionResourceCustomization list is empty.");
440                                 }else{
441                                         CollectionResourceCustomization collectionResourceCustomization = findCatalogNetworkCollection(execution, service);
442                                         if(collectionResourceCustomization!=null){
443                                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,collectionResourceCustomization.getModelCustomizationUUID(),false));
444                                                 logger.debug("Found a network collection");
445                                                 if(collectionResourceCustomization.getCollectionResource()!=null){
446                                                         if(collectionResourceCustomization.getCollectionResource().getInstanceGroup() != null){
447                                                                 String toscaNodeType = collectionResourceCustomization.getCollectionResource().getInstanceGroup().getToscaNodeType();
448                                                                 if (toscaNodeType != null && toscaNodeType.contains("NetworkCollection")) {
449                                                                         int minNetworks = 0;
450                                                                         org.onap.so.db.catalog.beans.InstanceGroup instanceGroup = collectionResourceCustomization.getCollectionResource().getInstanceGroup();
451                                                                         CollectionResourceInstanceGroupCustomization collectionInstCust = null;
452                                                                         if(!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) {
453                                                                                 for(CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup.getCollectionInstanceGroupCustomizations()) {
454                                                                                         if(collectionInstanceGroupTemp.getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
455                                                                                                 collectionInstCust = collectionInstanceGroupTemp;
456                                                                                                 break;
457                                                                                         }
458                                                                                 }
459                                                                                 if(collectionInstCust != null && collectionInstCust.getSubInterfaceNetworkQuantity() != null) {
460                                                                                         minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity();
461                                                                                 }
462                                                                         }
463                                                                         logger.debug("minNetworks: {}" , minNetworks);
464                                                                         CollectionNetworkResourceCustomization collectionNetworkResourceCust = null;
465                                                                         for(CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup.getCollectionNetworkResourceCustomizations()) {
466                                                                                 if(collectionNetworkTemp.getNetworkResourceCustomization().getModelCustomizationUUID().equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
467                                                                                         collectionNetworkResourceCust = collectionNetworkTemp;
468                                                                                         break;
469                                                                                 }
470                                                                         }
471                                                                         for (int i = 0; i < minNetworks; i++) {
472                                                                                 if(collectionNetworkResourceCust != null && collectionInstCust != null) {
473                                                                                         Resource resource = new Resource(WorkflowType.VIRTUAL_LINK,collectionNetworkResourceCust.getModelCustomizationUUID(),false);
474                                                                                         resource.setVirtualLinkKey(Integer.toString(i));
475                                                                                         resourceCounter.add(resource);
476                                                                                 }
477                                                                         }
478                                                                 } else {
479                                                                         logger.debug("Instance Group tosca node type does not contain NetworkCollection:  {}" , toscaNodeType);
480                                                                 }
481                                                         }else{
482                                                                 logger.debug("No Instance Group found for network collection.");
483                                                         }
484                                                 }else{
485                                                         logger.debug("No Network Collection found. collectionResource is null");
486                                                 }
487                                         } else {
488                                                 logger.debug("No Network Collection Customization found");
489                                         }
490                                 }
491                                 if (resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).isEmpty()) {
492                                         if (service.getNetworkCustomizations() == null) {
493                                                 logger.debug("No networks were found on this service model");
494                                         } else {
495                                                 for (int i = 0; i < service.getNetworkCustomizations().size(); i++) {
496                                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,service.getNetworkCustomizations().get(i).getModelCustomizationUUID(),false));
497                                                 }
498                                         }
499                                 }
500                         } else {
501                                 buildAndThrowException(execution,
502                                                 "Cannot orchestrate Service-Macro-Create without user params with a vnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows");
503                         }
504                 }
505         }
506
507         protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceCounter, String resourceId, List<Pair<WorkflowType, String>> aaiResourceIds) {
508                 try {
509                         ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
510                         org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
511                                         .getExistingServiceInstance(serviceInstanceAAI);
512                         resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
513                         if (serviceInstanceMSO.getVnfs() != null) {
514                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
515                                                 .getVnfs()) {
516                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
517                                         resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
518                                         if (vnf.getVfModules() != null) {
519                                                 for (VfModule vfModule : vnf.getVfModules()) {
520                                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
521                                                         resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));
522                                                 }
523                                         }
524                                         if (vnf.getVolumeGroups() != null) {
525                                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
526                                                                 .getVolumeGroups()) {
527                                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
528                                                         resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
529                                                 }
530                                         }
531                                 }
532                         }
533                         if (serviceInstanceMSO.getNetworks() != null) {
534                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO
535                                                 .getNetworks()) {
536                                         aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORK, network.getNetworkId()));
537                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getNetworkId(),false));
538                                 }
539                         }
540                         if (serviceInstanceMSO.getCollection() != null) {
541                                 logger.debug("found networkcollection");
542                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId()));
543                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,serviceInstanceMSO.getCollection().getId(),false));
544                         }
545                         if (serviceInstanceMSO.getConfigurations() !=null) {
546                                 for(Configuration config : serviceInstanceMSO.getConfigurations()){
547                                         Optional<org.onap.aai.domain.yang.Configuration> aaiConfig = aaiConfigurationResources.getConfiguration(config.getConfigurationId());
548                                         if(aaiConfig.isPresent() && aaiConfig.get().getRelationshipList()!=null){
549                                                 for(Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()){
550                                                         if(relationship.getRelatedTo().contains("vnfc")){
551                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.getConfigurationId()));
552                                                                 resourceCounter.add(new Resource(WorkflowType.CONFIGURATION,config.getConfigurationId(),false));
553                                                                 break;
554                                                         }
555                                                 }
556                                         }
557                                 }
558                         }
559                 } catch (Exception ex) {
560                         buildAndThrowException(execution,
561                                         "Could not find existing Service Instance or related Instances to execute the request on.");
562                 }
563         }
564
565         private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceCounter, String serviceId, String vnfId,
566                         List<Pair<WorkflowType, String>> aaiResourceIds) {
567                 try{
568                         ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
569                         org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO = bbInputSetup
570                                         .getExistingServiceInstance(serviceInstanceAAI);
571                         resourceCounter.add(new Resource(WorkflowType.SERVICE,serviceInstanceMSO.getServiceInstanceId(),false));
572                         if (serviceInstanceMSO.getVnfs() != null) {
573                                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO
574                                                 .getVnfs()) {
575                                         if(vnf.getVnfId().equals(vnfId)){
576                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VNF, vnf.getVnfId()));
577                                                 resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getVnfId(),false));
578                                                 if (vnf.getVfModules() != null) {
579                                                         for (VfModule vfModule : vnf.getVfModules()) {
580                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
581                                                                 resourceCounter.add(new Resource(WorkflowType.VFMODULE,vfModule.getVfModuleId(),false));        
582                                                                 findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(), resourceCounter, aaiResourceIds);
583                                                         }
584                                                 }
585                                                 if (vnf.getVolumeGroups() != null) {
586                                                         for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
587                                                                         .getVolumeGroups()) {
588                                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
589                                                                 resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,volumeGroup.getVolumeGroupId(),false));
590                                                         }
591                                                 }
592                                                 break;
593                                         }
594                                 }
595                         }
596                 } catch (Exception ex) {
597                         buildAndThrowException(execution,
598                                         "Could not find existing Vnf or related Instances to execute the request on.");
599                 }
600         }
601
602         private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId, List<Resource> resourceCounter, 
603                         List<Pair<WorkflowType, String>> aaiResourceIds) {
604                 try{
605                         org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
606                         AAIResultWrapper vfModuleWrapper = new AAIResultWrapper(
607                                         new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVfModule));
608                         Optional<Relationships> relationshipsOp;
609                         relationshipsOp = vfModuleWrapper.getRelationships();
610                         if(relationshipsOp.isPresent()) {
611                                 relationshipsOp = workflowActionUtils.extractRelationshipsVnfc(relationshipsOp.get());
612                                 if(relationshipsOp.isPresent()){
613                                         Optional<Configuration> config = workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get());
614                                         if(config.isPresent()){
615                                                 aaiResourceIds.add(new Pair<WorkflowType, String>(WorkflowType.CONFIGURATION, config.get().getConfigurationId()));
616                                                 resourceCounter.add(new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false));
617                                         }
618                                 }
619                         }
620                 }catch (Exception ex){
621                         buildAndThrowException(execution,
622                                         "Failed to find Configuration object from the vfModule.");
623                 }
624         }
625         
626         protected boolean traverseUserParamsService(DelegateExecution execution, List<Resource> resourceCounter,
627                         ServiceInstancesRequest sIRequest, String requestAction)
628                         throws IOException {
629                 boolean foundRelated = false;
630                 boolean foundVfModuleOrVG = false;
631                 String vnfCustomizationUUID = "";
632                 String vfModuleCustomizationUUID = "";
633                 if (sIRequest.getRequestDetails().getRequestParameters().getUserParams() != null) {
634                         List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
635                         for (Map<String, Object> params : userParams) {
636                                 if (params.containsKey(USERPARAMSERVICE)) {
637                                         ObjectMapper obj = new ObjectMapper();
638                                         String input = obj.writeValueAsString(params.get(USERPARAMSERVICE));
639                                         Service validate = obj.readValue(input, Service.class);
640                                         resourceCounter.add(new Resource(WorkflowType.SERVICE,validate.getModelInfo().getModelVersionId(),false));
641                                         if (validate.getResources().getVnfs() != null) {
642                                                 for (Vnfs vnf : validate.getResources().getVnfs()) {
643                                                         resourceCounter.add(new Resource(WorkflowType.VNF,vnf.getModelInfo().getModelCustomizationId(),false));
644                                                         foundRelated = true;
645                                                         if(vnf.getModelInfo()!=null && vnf.getModelInfo().getModelCustomizationUuid()!=null){
646                                                                 vnfCustomizationUUID = vnf.getModelInfo().getModelCustomizationUuid();
647                                                         }
648                                                         if (vnf.getVfModules() != null) {
649                                                                 for (VfModules vfModule : vnf.getVfModules()) {
650                                                                         VfModuleCustomization vfModuleCustomization = catalogDbClient
651                                                                                         .getVfModuleCustomizationByModelCuztomizationUUID(
652                                                                                                         vfModule.getModelInfo().getModelCustomizationUuid());
653                                                                         if (vfModuleCustomization != null) {
654
655                                                                                 if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null && vfModuleCustomization.getVolumeHeatEnv() != null) {
656                                                                                         resourceCounter.add(new Resource(WorkflowType.VOLUMEGROUP,vfModuleCustomization.getModelCustomizationUUID(),false));
657                                                                                         foundRelated = true;
658                                                                                         foundVfModuleOrVG = true;
659                                                                                 }
660
661                                                                                 if(vfModuleCustomization.getVfModule() != null && vfModuleCustomization.getVfModule().getModuleHeatTemplate() != null && vfModuleCustomization.getHeatEnvironment() != null){
662                                                                                         foundRelated = true;
663                                                                                         foundVfModuleOrVG = true;
664                                                                                         Resource resource = new Resource(WorkflowType.VFMODULE,vfModuleCustomization.getModelCustomizationUUID(),false);
665                                                                                         if(vfModuleCustomization.getVfModule().getIsBase()!=null && vfModuleCustomization.getVfModule().getIsBase()){
666                                                                                                 resource.setBaseVfModule(true);
667                                                                                         }else{
668                                                                                                 resource.setBaseVfModule(false);
669                                                                                         }
670                                                                                         resourceCounter.add(resource);
671                                                                                         if(vfModule.getModelInfo()!=null && vfModule.getModelInfo().getModelCustomizationUuid()!=null){
672                                                                                                 vfModuleCustomizationUUID = vfModule.getModelInfo().getModelCustomizationUuid();
673                                                                                         }
674                                                                                         if(!vnfCustomizationUUID.equals("")&&!vfModuleCustomizationUUID.equals("")){
675                                                                                                 List<String> configs = traverseCatalogDbForConfiguration(vnfCustomizationUUID,vfModuleCustomizationUUID);
676                                                                                                 for(String config : configs){
677                                                                                                         Resource configResource = new Resource(WorkflowType.CONFIGURATION,config,false);
678                                                                                                         resource.setVnfCustomizationId(vnf.getModelInfo().getModelCustomizationId());
679                                                                                                         resource.setVfModuleCustomizationId(vfModule.getModelInfo().getModelCustomizationId());
680                                                                                                         resourceCounter.add(configResource);
681                                                                                                 }
682                                                                                         }
683                                                                                 }
684                                                                                 if(!foundVfModuleOrVG){
685                                                                                         buildAndThrowException(execution, "Could not determine if vfModule was a vfModule or volume group. Heat template and Heat env are null");
686                                                                                 }
687                                                                         }
688                                                                 }
689                                                         }
690                                                 }
691                                         }
692                                         if (validate.getResources().getNetworks() != null) {
693                                                 for (Networks network : validate.getResources().getNetworks()) {
694                                                         resourceCounter.add(new Resource(WorkflowType.NETWORK,network.getModelInfo().getModelCustomizationId(),false));
695                                                         foundRelated = true;
696                                                 }
697                                                 if (requestAction.equals(CREATEINSTANCE)) {
698                                                         String networkColCustId = queryCatalogDBforNetworkCollection(execution, sIRequest);
699                                                         if (networkColCustId != null) {
700                                                                 resourceCounter.add(new Resource(WorkflowType.NETWORKCOLLECTION,networkColCustId,false));
701                                                                 foundRelated = true;
702                                                         }
703                                                 }
704                                         }
705                                         break;
706                                 }
707                         }
708                 }
709                 return foundRelated;
710         }
711         
712
713         protected List<String> traverseCatalogDbForConfiguration(String vnfCustomizationUUID, String vfModuleCustomizationUUID) {
714                 List<String> configurations = new ArrayList<>();
715                 try{
716                         List<CvnfcCustomization> cvnfcCustomizations = catalogDbClient.getCvnfcCustomizationByVnfCustomizationUUIDAndVfModuleCustomizationUUID(vnfCustomizationUUID, vfModuleCustomizationUUID);
717                         for(CvnfcCustomization cvnfc : cvnfcCustomizations){
718                                 for(VnfVfmoduleCvnfcConfigurationCustomization customization : cvnfc.getVnfVfmoduleCvnfcConfigurationCustomization()){
719                                         if(customization.getConfigurationResource().getToscaNodeType().contains(FABRIC_CONFIGURATION)){
720                                                 configurations.add(customization.getConfigurationResource().getModelUUID());
721                                         }
722                                 }
723                         }
724                         logger.debug("found {} configurations" , configurations.size() );
725                         return configurations;
726                 } catch (Exception ex){
727                         logger.error("Error in finding configurations", ex);
728                         return configurations;
729                 }
730         }
731
732         protected String queryCatalogDBforNetworkCollection(DelegateExecution execution, ServiceInstancesRequest sIRequest) {
733                 org.onap.so.db.catalog.beans.Service service = catalogDbClient
734                                 .getServiceByID(sIRequest.getRequestDetails().getModelInfo().getModelVersionId());
735                 if (service != null) {
736                         CollectionResourceCustomization networkCollection = this.findCatalogNetworkCollection(execution, service);
737                         if(networkCollection != null) {
738                                 return networkCollection.getModelCustomizationUUID();
739                         }
740                 }
741                 return null;
742         }
743
744         protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
745                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
746                 workflowResourceIds.setServiceInstanceId((String) execution.getVariable("serviceInstanceId"));
747                 workflowResourceIds.setNetworkId((String) execution.getVariable("networkId"));
748                 workflowResourceIds.setVfModuleId((String) execution.getVariable("vfModuleId"));
749                 workflowResourceIds.setVnfId((String) execution.getVariable("vnfId"));
750                 workflowResourceIds.setVolumeGroupId((String) execution.getVariable("volumeGroupId"));
751                 return workflowResourceIds;
752         }
753
754         protected Resource extractResourceIdAndTypeFromUri(String uri) {
755             Pattern patt = Pattern.compile(
756                     "[vV]\\d+.*?(?:(?:/(?<type>" + supportedTypes + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?)?$");
757             Matcher m = patt.matcher(uri);
758             Boolean generated = false;
759
760             if (m.find()) {
761                 logger.debug("found match on {} : {} " , uri ,  m);
762                 String type = m.group("type");
763                 String id = m.group("id");
764                 String action = m.group("action");
765                 if (type == null) {
766                     throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
767                 }
768                 if (action == null) {
769                     if (type.equals(SERVICE_INSTANCES) && (id == null || id.equals("assign"))) {
770                         id = UUID.randomUUID().toString();
771                         generated = true;
772                     }else if (type.equals(VF_MODULES) && id.equals("scaleOut")) {
773                         id = UUID.randomUUID().toString();
774                         generated = true;
775                     }
776                 } else {
777                     if (action.matches(supportedTypes)) {
778                         id = UUID.randomUUID().toString();
779                         generated = true;
780                         type = action;
781                     }
782                 }
783                 return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated);
784             } else {
785                 throw new IllegalArgumentException("Uri could not be parsed: " + uri);
786             }
787         }
788
789         protected String validateResourceIdInAAI(String generatedResourceId, WorkflowType type, String instanceName,
790                         RequestDetails reqDetails, WorkflowResourceIds workflowResourceIds) throws Exception {
791                 try {
792                         if ("SERVICE".equalsIgnoreCase(type.toString())) {
793                                 String globalCustomerId = reqDetails.getSubscriberInfo().getGlobalSubscriberId();
794                                 String serviceType = reqDetails.getRequestParameters().getSubscriptionServiceType();
795                                 if (instanceName != null) {
796                                         Optional<ServiceInstance> serviceInstanceAAI = bbInputSetupUtils
797                                                         .getAAIServiceInstanceByName(globalCustomerId, serviceType, instanceName);
798                                         if (serviceInstanceAAI.isPresent()) {
799                                                 return serviceInstanceAAI.get().getServiceInstanceId();
800                                         }
801                                 }
802                         } else if ("NETWORK".equalsIgnoreCase(type.toString())) {
803                                 Optional<L3Network> network = bbInputSetupUtils.getRelatedNetworkByNameFromServiceInstance(
804                                                 workflowResourceIds.getServiceInstanceId(), instanceName);
805                                 if (network.isPresent()) {
806                                         return network.get().getNetworkId();
807                                 }
808                         } else if ("VNF".equalsIgnoreCase(type.toString())) {
809                                 Optional<GenericVnf> vnf = bbInputSetupUtils.getRelatedVnfByNameFromServiceInstance(
810                                                 workflowResourceIds.getServiceInstanceId(), instanceName);
811                                 if (vnf.isPresent()) {
812                                         return vnf.get().getVnfId();
813                                 }
814                         } else if ("VFMODULE".equalsIgnoreCase(type.toString())) {
815                                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
816                                 if (vnf != null && vnf.getVfModules() != null) {
817                                         for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
818                                                 if (vfModule.getVfModuleName().equalsIgnoreCase(instanceName)) {
819                                                         return vfModule.getVfModuleId();
820                                                 }
821                                         }
822                                 }
823                         } else if ("VOLUMEGROUP".equalsIgnoreCase(type.toString())) {
824                                 Optional<VolumeGroup> volumeGroup = bbInputSetupUtils
825                                                 .getRelatedVolumeGroupByNameFromVnf(workflowResourceIds.getVnfId(), instanceName);
826                                 if (volumeGroup.isPresent()) {
827                                         return volumeGroup.get().getVolumeGroupId();
828                                 }
829                                 GenericVnf vnf = bbInputSetupUtils.getAAIGenericVnf(workflowResourceIds.getVnfId());
830                                 if (vnf != null && vnf.getVfModules() != null) {
831                                         for (org.onap.aai.domain.yang.VfModule vfModule : vnf.getVfModules().getVfModule()) {
832                                                 Optional<VolumeGroup> volumeGroupFromVfModule = bbInputSetupUtils
833                                                                 .getRelatedVolumeGroupByNameFromVfModule(vnf.getVnfId(), vfModule.getVfModuleId(), instanceName);
834                                                 if (volumeGroupFromVfModule.isPresent()) {
835                                                         return volumeGroupFromVfModule.get().getVolumeGroupId();
836                                                 }
837                                         }
838                                 }
839                         }
840                         return generatedResourceId;
841                 } catch (Exception ex) {
842                         logger.error(WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI, ex);
843                         throw new IllegalStateException(
844                                         WORKFLOW_ACTION_WAS_UNABLE_TO_VERIFY_IF_THE_INSTANCE_NAME_ALREADY_EXIST_IN_AAI);
845                 }
846         }
847
848         protected String convertTypeFromPlural(String type) {
849                 if (!type.matches(supportedTypes)) {
850                         return type;
851                 } else {
852                         if (type.equals(SERVICE_INSTANCES)) {
853                                 return SERVICE;
854                         } else {
855                                 return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
856                         }
857                 }
858         }
859
860         protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
861                         String requestAction) {
862                 List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
863                 if (requestAction.equals(CREATEINSTANCE)) {
864                         for (ExecuteBuildingBlock ebb : orchFlows) {
865                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
866                                         String key = ebb.getBuildingBlock().getKey();
867                                         boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().getIsVirtualLink());
868                                         String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
869                                         sortedOrchFlows.add(ebb);
870                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
871                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
872                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
873                                                         sortedOrchFlows.add(ebb2);
874                                                         break;
875                                                 }
876                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
877                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
878                                                         sortedOrchFlows.add(ebb2);
879                                                         break;
880                                                 }
881                                         }
882                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
883                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
884                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
885                                                         sortedOrchFlows.add(ebb2);
886                                                         break;
887                                                 }
888                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
889                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
890                                                         sortedOrchFlows.add(ebb2);
891                                                         break;
892                                                 }
893                                         }
894                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
895                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")) {
896                                         continue;
897                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
898                                         sortedOrchFlows.add(ebb);
899                                 }
900                         }
901                 } else if (requestAction.equals("deleteInstance")) {
902                         for (ExecuteBuildingBlock ebb : orchFlows) {
903                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
904                                         sortedOrchFlows.add(ebb);
905                                         String key = ebb.getBuildingBlock().getKey();
906                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
907                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
908                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
909                                                         sortedOrchFlows.add(ebb2);
910                                                         break;
911                                                 }
912                                         }
913                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
914                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
915                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
916                                                         sortedOrchFlows.add(ebb2);
917                                                         break;
918                                                 }
919                                         }
920                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
921                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
922                                         continue;
923                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
924                                         sortedOrchFlows.add(ebb);
925                                 }
926                         }
927                 }
928                 return sortedOrchFlows;
929         }
930
931         protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows,
932                         List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId, WorkflowType resourceType,
933                         String requestAction, boolean aLaCarte, String vnfType,
934                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails) {
935                 List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
936                 for (OrchestrationFlow orchFlow : orchFlows) {
937                         if (orchFlow.getFlowName().contains(SERVICE)) {
938                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
939                                         workflowResourceIds.setServiceInstanceId(resourceId);
940                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
941                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
942                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
943                                 }
944                         } else if (orchFlow.getFlowName().contains(VNF)) {
945                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
946                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
947                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
948                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
949                                 }
950                         } else if (orchFlow.getFlowName().contains(NETWORK)
951                                         && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
952                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
953                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
954                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
955                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
956                                 }
957                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
958                                         Resource resource = resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType())
959                                                         .collect(Collectors.toList()).get(i);
960                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId,
961                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true, resource.getVirtualLinkKey(), false));
962                                 }
963                         } else if (orchFlow.getFlowName().contains(VFMODULE)) {
964                                 List<Resource> vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream().filter(x -> WorkflowType.VFMODULE == x.getResourceType())
965                                                 .collect(Collectors.toList()));
966                                 for (int i = 0; i < vfModuleResourcesSorted.size(); i++) {
967                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i), apiVersion, resourceId,
968                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
969                                 }
970                         } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) {
971                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
972                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType())
973                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
974                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
975                                 }
976                         } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
977                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
978                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
979                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
980                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
981                                 }
982                         } else if (orchFlow.getFlowName().contains(CONFIGURATION)) {
983                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
984                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType())
985                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
986                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, true));
987                                 }
988                         }else {
989                                 flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId,
990                                                 requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
991                         }
992                 }
993                 return flowsToExecute;
994         }
995
996         protected ExecuteBuildingBlock buildExecuteBuildingBlock(OrchestrationFlow orchFlow, String requestId, Resource resource,
997                         String apiVersion, String resourceId, String requestAction, boolean aLaCarte, String vnfType,
998                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) {
999                 ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
1000                 BuildingBlock buildingBlock = new BuildingBlock();
1001                 buildingBlock.setBpmnFlowName(orchFlow.getFlowName());
1002                 buildingBlock.setMsoId(UUID.randomUUID().toString());
1003                 if(resource == null){
1004                         buildingBlock.setKey("");
1005                 }else{
1006                         buildingBlock.setKey(resource.getResourceId());
1007                 }
1008                 buildingBlock.setIsVirtualLink(isVirtualLink);
1009                 buildingBlock.setVirtualLinkKey(virtualLinkKey);
1010                 executeBuildingBlock.setApiVersion(apiVersion);
1011                 executeBuildingBlock.setaLaCarte(aLaCarte);
1012                 executeBuildingBlock.setRequestAction(requestAction);
1013                 executeBuildingBlock.setResourceId(resourceId);
1014                 executeBuildingBlock.setVnfType(vnfType);
1015                 executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
1016                 executeBuildingBlock.setRequestId(requestId);
1017                 executeBuildingBlock.setBuildingBlock(buildingBlock);
1018                 executeBuildingBlock.setRequestDetails(requestDetails);
1019                 if(isConfiguration){
1020                         ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
1021                         configurationResourceKeys.setCvnfcCustomizationUUID(resource.getCvnfModuleCustomizationId());
1022                         configurationResourceKeys.setVfModuleCustomizationUUID(resource.getVfModuleCustomizationId());
1023                         configurationResourceKeys.setVnfResourceCustomizationUUID(resource.getVnfCustomizationId());
1024                         executeBuildingBlock.setConfigurationResourceKeys(configurationResourceKeys);
1025                 }
1026                 return executeBuildingBlock;
1027         }
1028
1029         protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
1030                         WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
1031                 List<OrchestrationFlow> listToExecute = new ArrayList<>();
1032                 NorthBoundRequest northBoundRequest = catalogDbClient
1033                                 .getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(requestAction, resourceName.toString(), aLaCarte, cloudOwner);
1034                 if(northBoundRequest == null){
1035                         if(aLaCarte){
1036                                 buildAndThrowException(execution,"The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API.");
1037                         }else{
1038                                 buildAndThrowException(execution,"The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API.");
1039                         }
1040                 } else {
1041                 if(northBoundRequest.getIsToplevelflow()!=null){
1042                         execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
1043                 }
1044                 List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
1045                 if (flows == null)
1046                         flows = new ArrayList<>();
1047                 for (OrchestrationFlow flow : flows) {
1048                         if (!flow.getFlowName().contains("BB")) {
1049                                 List<OrchestrationFlow> macroQueryFlows = catalogDbClient
1050                                                 .getOrchestrationFlowByAction(flow.getFlowName());
1051                                 for (OrchestrationFlow macroFlow : macroQueryFlows) {
1052                                         listToExecute.add(macroFlow);
1053                                 }
1054                         } else {
1055                                 listToExecute.add(flow);
1056                         }
1057                 }
1058                 }
1059                 return listToExecute;
1060         }
1061         
1062         protected List<OrchestrationFlow> filterOrchFlows(List<OrchestrationFlow> orchFlows, WorkflowType resourceType, DelegateExecution execution) {
1063                 List<OrchestrationFlow> result = new ArrayList<>(orchFlows);
1064                 if (resourceType.equals(WorkflowType.VFMODULE)) {
1065                         List<String> fabricCustomizations = traverseCatalogDbForConfiguration((String)execution.getVariable("vnfId"), (String)execution.getVariable("vfModuleId"));
1066                         if (fabricCustomizations.isEmpty()) {
1067                                 result = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
1068                         }
1069                 }
1070                 return result;
1071         }
1072
1073         protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
1074                 logger.error(msg, ex);
1075                 execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
1076                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
1077         }
1078
1079         protected void buildAndThrowException(DelegateExecution execution, String msg) {
1080                 logger.error(msg);
1081                 execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
1082                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
1083         }
1084         
1085         public void handleRuntimeException (DelegateExecution execution){
1086                 StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
1087                 String runtimeErrorMessage = null;
1088                 try{
1089                         String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
1090                         if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
1091                                 wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg);
1092                         }
1093                         runtimeErrorMessage = wfeExpMsg.toString();
1094                         logger.error(runtimeErrorMessage);
1095                         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
1096                 } catch (Exception e){
1097                         logger.error("Runtime error", e);
1098                         //if runtime message was mulformed
1099                         runtimeErrorMessage = "Runtime error";
1100                 }
1101                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
1102         }
1103 }