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