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