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