updated create task BB
[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                         throw new IllegalStateException(
731                                         "WorkflowAction was unable to verify if the instance name already exist in AAI.");
732                 }
733         }
734
735         protected String convertTypeFromPlural(String type) {
736                 if (!type.matches(supportedTypes)) {
737                         return type;
738                 } else {
739                         if (type.equals("serviceInstances")) {
740                                 return SERVICE;
741                         } else {
742                                 return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
743                         }
744                 }
745         }
746
747         protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
748                         String requestAction) {
749                 List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
750                 if (requestAction.equals(CREATEINSTANCE)) {
751                         for (ExecuteBuildingBlock ebb : orchFlows) {
752                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
753                                         String key = ebb.getBuildingBlock().getKey();
754                                         boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().getIsVirtualLink());
755                                         String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
756                                         sortedOrchFlows.add(ebb);
757                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
758                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
759                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
760                                                         sortedOrchFlows.add(ebb2);
761                                                         break;
762                                                 }
763                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
764                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
765                                                         sortedOrchFlows.add(ebb2);
766                                                         break;
767                                                 }
768                                         }
769                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
770                                                 if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
771                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
772                                                         sortedOrchFlows.add(ebb2);
773                                                         break;
774                                                 }
775                                                 if(isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")
776                                                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
777                                                         sortedOrchFlows.add(ebb2);
778                                                         break;
779                                                 }
780                                         }
781                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("CreateNetworkBB")
782                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("ActivateNetworkBB")) {
783                                         continue;
784                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
785                                         sortedOrchFlows.add(ebb);
786                                 }
787                         }
788                 } else if (requestAction.equals("deleteInstance")) {
789                         for (ExecuteBuildingBlock ebb : orchFlows) {
790                                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
791                                         sortedOrchFlows.add(ebb);
792                                         String key = ebb.getBuildingBlock().getKey();
793                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
794                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
795                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
796                                                         sortedOrchFlows.add(ebb2);
797                                                         break;
798                                                 }
799                                         }
800                                         for (ExecuteBuildingBlock ebb2 : orchFlows) {
801                                                 if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
802                                                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
803                                                         sortedOrchFlows.add(ebb2);
804                                                         break;
805                                                 }
806                                         }
807                                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
808                                                 || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
809                                         continue;
810                                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
811                                         sortedOrchFlows.add(ebb);
812                                 }
813                         }
814                 }
815                 return sortedOrchFlows;
816         }
817
818         protected List<ExecuteBuildingBlock> buildExecuteBuildingBlockList(List<OrchestrationFlow> orchFlows,
819                         List<Resource> resourceCounter, String requestId, String apiVersion, String resourceId, WorkflowType resourceType,
820                         String requestAction, boolean aLaCarte, String vnfType,
821                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails) {
822                 List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
823                 for (OrchestrationFlow orchFlow : orchFlows) {
824                         if (orchFlow.getFlowName().contains(SERVICE)) {
825                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
826                                         workflowResourceIds.setServiceInstanceId(resourceId);
827                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.SERVICE == x.getResourceType())
828                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
829                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
830                                 }
831                         } else if (orchFlow.getFlowName().contains(VNF)) {
832                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
833                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VNF == x.getResourceType())
834                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
835                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
836                                 }
837                         } else if (orchFlow.getFlowName().contains(NETWORK)
838                                         && !orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
839                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
840                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORK == x.getResourceType())
841                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
842                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
843                                 }
844                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
845                                         Resource resource = resourceCounter.stream().filter(x -> WorkflowType.VIRTUAL_LINK == x.getResourceType())
846                                                         .collect(Collectors.toList()).get(i);
847                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resource, apiVersion, resourceId,
848                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, true, resource.getVirtualLinkKey(), false));
849                                 }
850                         } else if (orchFlow.getFlowName().contains(VFMODULE)) {
851                                 List<Resource> vfModuleResourcesSorted = sortVfModulesByBaseFirst(resourceCounter.stream().filter(x -> WorkflowType.VFMODULE == x.getResourceType())
852                                                 .collect(Collectors.toList()));
853                                 for (int i = 0; i < vfModuleResourcesSorted.size(); i++) {
854                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, vfModuleResourcesSorted.get(i), apiVersion, resourceId,
855                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
856                                 }
857                         } else if (orchFlow.getFlowName().contains(VOLUMEGROUP)) {
858                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
859                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.VOLUMEGROUP == x.getResourceType())
860                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
861                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
862                                 }
863                         } else if (orchFlow.getFlowName().contains(NETWORKCOLLECTION)) {
864                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
865                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType())
866                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
867                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
868                                 }
869                         } else if (orchFlow.getFlowName().contains(CONFIGURATION)) {
870                                 for (int i = 0; i < resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType()).collect(Collectors.toList()).size(); i++) {
871                                         flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, resourceCounter.stream().filter(x -> WorkflowType.CONFIGURATION == x.getResourceType())
872                                                         .collect(Collectors.toList()).get(i), apiVersion, resourceId,
873                                                         requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, true));
874                                 }
875                         }else {
876                                 flowsToExecute.add(buildExecuteBuildingBlock(orchFlow, requestId, null, apiVersion, resourceId,
877                                                 requestAction, aLaCarte, vnfType, workflowResourceIds, requestDetails, false, null, false));
878                         }
879                 }
880                 return flowsToExecute;
881         }
882
883         protected ExecuteBuildingBlock buildExecuteBuildingBlock(OrchestrationFlow orchFlow, String requestId, Resource resource,
884                         String apiVersion, String resourceId, String requestAction, boolean aLaCarte, String vnfType,
885                         WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, boolean isVirtualLink, String virtualLinkKey, boolean isConfiguration) {
886                 ExecuteBuildingBlock executeBuildingBlock = new ExecuteBuildingBlock();
887                 BuildingBlock buildingBlock = new BuildingBlock();
888                 buildingBlock.setBpmnFlowName(orchFlow.getFlowName());
889                 buildingBlock.setMsoId(UUID.randomUUID().toString());
890                 if(resource == null){
891                         buildingBlock.setKey("");
892                 }else{
893                         buildingBlock.setKey(resource.getResourceId());
894                 }
895                 buildingBlock.setIsVirtualLink(isVirtualLink);
896                 buildingBlock.setVirtualLinkKey(virtualLinkKey);
897                 executeBuildingBlock.setApiVersion(apiVersion);
898                 executeBuildingBlock.setaLaCarte(aLaCarte);
899                 executeBuildingBlock.setRequestAction(requestAction);
900                 executeBuildingBlock.setResourceId(resourceId);
901                 executeBuildingBlock.setVnfType(vnfType);
902                 executeBuildingBlock.setWorkflowResourceIds(workflowResourceIds);
903                 executeBuildingBlock.setRequestId(requestId);
904                 executeBuildingBlock.setBuildingBlock(buildingBlock);
905                 executeBuildingBlock.setRequestDetails(requestDetails);
906                 if(isConfiguration){
907                         ConfigurationResourceKeys configurationResourceKeys = new ConfigurationResourceKeys();
908                         configurationResourceKeys.setCvnfcCustomizationUUID(resource.getCvnfModuleCustomizationId());
909                         configurationResourceKeys.setVfModuleCustomizationUUID(resource.getVfModuleCustomizationId());
910                         configurationResourceKeys.setVnfResourceCustomizationUUID(resource.getVnfCustomizationId());
911                         executeBuildingBlock.setConfigurationResourceKeys(configurationResourceKeys);
912                 }
913                 return executeBuildingBlock;
914         }
915
916         protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
917                         WorkflowType resourceName, boolean aLaCarte) {
918                 List<OrchestrationFlow> listToExecute = new ArrayList<>();
919                 NorthBoundRequest northBoundRequest = catalogDbClient
920                                 .getNorthBoundRequestByActionAndIsALaCarteAndRequestScope(requestAction, resourceName.toString(), aLaCarte);
921                 if(northBoundRequest == null){
922                         if(aLaCarte){
923                                 buildAndThrowException(execution,"The request: ALaCarte " + resourceName + " " + requestAction + " is not supported by GR_API.");
924                         }else{
925                                 buildAndThrowException(execution,"The request: Macro " + resourceName + " " + requestAction + " is not supported by GR_API.");
926                         }
927                 } else {
928                 if(northBoundRequest.getIsToplevelflow()!=null){
929                         execution.setVariable(G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
930                 }
931                 List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
932                 if (flows == null)
933                         flows = new ArrayList<>();
934                 for (OrchestrationFlow flow : flows) {
935                         if (!flow.getFlowName().contains("BB")) {
936                                 List<OrchestrationFlow> macroQueryFlows = catalogDbClient
937                                                 .getOrchestrationFlowByAction(flow.getFlowName());
938                                 for (OrchestrationFlow macroFlow : macroQueryFlows) {
939                                         listToExecute.add(macroFlow);
940                                 }
941                         } else {
942                                 listToExecute.add(flow);
943                         }
944                 }
945                 }
946                 return listToExecute;
947         }
948
949         protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
950                 msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),
951                                 MsoLogger.ErrorCode.UnknownError, msg, ex);
952                 execution.setVariable("WorkflowActionErrorMessage", msg);
953                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
954         }
955
956         protected void buildAndThrowException(DelegateExecution execution, String msg) {
957                 msoLogger.error(msg);
958                 execution.setVariable("WorkflowActionErrorMessage", msg);
959                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
960         }
961         
962         public void handleRuntimeException (DelegateExecution execution){
963                 StringBuffer wfeExpMsg = new StringBuffer("Runtime error ");
964                 String runtimeErrorMessage = null;
965                 try{
966                         String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
967                         if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
968                                 wfeExpMsg = wfeExpMsg.append(": ").append(javaExpMsg);
969                         }
970                         runtimeErrorMessage = wfeExpMsg.toString();
971                         msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, runtimeErrorMessage, "BPMN", MsoLogger.getServiceName(),
972                                         MsoLogger.ErrorCode.UnknownError, runtimeErrorMessage);
973                         execution.setVariable("WorkflowActionErrorMessage", runtimeErrorMessage);
974                 } catch (Exception e){
975                         //if runtime message was mulformed
976                         runtimeErrorMessage = "Runtime error";
977                 }
978                 exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
979         }
980 }