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