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