Merge "Fixed issues in AN NSSMF for allocate flow & added timeDelay in QueryJobStatus"
[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  * Modifications Copyright (c) 2021 Nokia
10  * ================================================================================
11  * Modifications Copyright (c) 2020 Tech Mahindra
12  * ================================================================================
13  * Licensed under the Apache License, Version 2.0 (the "License");
14  * you may not use this file except in compliance with the License.
15  * You may obtain a copy of the License at
16  *
17  *      http://www.apache.org/licenses/LICENSE-2.0
18  *
19  * Unless required by applicable law or agreed to in writing, software
20  * distributed under the License is distributed on an "AS IS" BASIS,
21  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22  * See the License for the specific language governing permissions and
23  * limitations under the License.
24  * ============LICENSE_END=========================================================
25  */
26
27 package org.onap.so.bpmn.infrastructure.workflow.tasks;
28
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import java.io.IOException;
32 import org.apache.commons.lang3.SerializationUtils;
33 import org.camunda.bpm.engine.delegate.DelegateExecution;
34 import org.javatuples.Pair;
35 import org.onap.aai.domain.yang.Relationship;
36 import org.onap.aai.domain.yang.ServiceInstance;
37 import org.onap.aai.domain.yang.Vnfc;
38 import org.onap.aai.domain.yang.VolumeGroup;
39 import org.onap.aai.domain.yang.VpnBinding;
40 import org.onap.aaiclient.client.aai.AAICommonObjectMapperProvider;
41 import org.onap.aaiclient.client.aai.AAIObjectName;
42 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper;
43 import org.onap.aaiclient.client.aai.entities.Relationships;
44 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri;
45 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory;
46 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder;
47 import org.onap.aaiclient.client.generated.fluentbuilders.AAIFluentTypeBuilder.Types;
48 import org.onap.so.bpmn.common.BBConstants;
49 import org.onap.so.bpmn.infrastructure.workflow.tasks.excpetion.VnfcMultipleRelationshipException;
50 import org.onap.so.bpmn.infrastructure.workflow.tasks.utils.WorkflowResourceIdsUtils;
51 import org.onap.so.bpmn.servicedecomposition.bbobjects.Configuration;
52 import org.onap.so.bpmn.servicedecomposition.bbobjects.VfModule;
53 import org.onap.so.bpmn.servicedecomposition.entities.ExecuteBuildingBlock;
54 import org.onap.so.bpmn.servicedecomposition.entities.WorkflowResourceIds;
55 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetup;
56 import org.onap.so.bpmn.servicedecomposition.tasks.BBInputSetupUtils;
57 import org.onap.so.client.exception.ExceptionBuilder;
58 import org.onap.so.client.orchestration.AAIConfigurationResources;
59 import org.onap.so.client.orchestration.AAIEntityNotFoundException;
60 import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization;
61 import org.onap.so.db.catalog.beans.CollectionResourceCustomization;
62 import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization;
63 import org.onap.so.db.catalog.beans.InstanceGroup;
64 import org.onap.so.db.catalog.beans.VfModuleCustomization;
65 import org.onap.so.db.catalog.beans.macro.NorthBoundRequest;
66 import org.onap.so.db.catalog.beans.macro.OrchestrationFlow;
67 import org.onap.so.db.catalog.client.CatalogDbClient;
68 import org.onap.so.serviceinstancebeans.CloudConfiguration;
69 import org.onap.so.serviceinstancebeans.ModelInfo;
70 import org.onap.so.serviceinstancebeans.ModelType;
71 import org.onap.so.serviceinstancebeans.RelatedInstance;
72 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
73 import org.onap.so.serviceinstancebeans.RequestDetails;
74 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.springframework.beans.factory.annotation.Autowired;
78 import org.springframework.core.env.Environment;
79 import org.springframework.stereotype.Component;
80 import org.springframework.util.CollectionUtils;
81 import java.util.ArrayList;
82 import java.util.Arrays;
83 import java.util.Comparator;
84 import java.util.List;
85 import java.util.Map;
86 import java.util.Optional;
87 import java.util.UUID;
88 import java.util.regex.Matcher;
89 import java.util.regex.Pattern;
90 import java.util.stream.Collectors;
91 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.ASSIGNINSTANCE;
92 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.CONTROLLER;
93 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.CREATE_INSTANCE;
94 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.FABRIC_CONFIGURATION;
95 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.NETWORKCOLLECTION;
96 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.REPLACEINSTANCE;
97 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.REPLACEINSTANCERETAINASSIGNMENTS;
98 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.SERVICE;
99 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.USER_PARAM_SERVICE;
100 import static org.onap.so.bpmn.infrastructure.workflow.tasks.WorkflowActionConstants.WORKFLOW_ACTION_ERROR_MESSAGE;
101
102 @Component
103 public class WorkflowAction {
104
105     private static final Logger logger = LoggerFactory.getLogger(WorkflowAction.class);
106
107     private static final String SERVICE_INSTANCES = "serviceInstances";
108     private static final String VF_MODULES = "vfModules";
109     private static final String VNF_TYPE = "vnfType";
110     private static final String CONFIGURATION = "Configuration";
111     private static final String SUPPORTEDTYPES =
112             "vnfs|vfModules|networks|networkCollections|volumeGroups|serviceInstances|instanceGroups";
113     private static final String HOMINGSOLUTION = "Homing_Solution";
114     private static final String SERVICE_TYPE_TRANSPORT = "TRANSPORT";
115     private static final String SERVICE_TYPE_BONDING = "BONDING";
116     private static final String CLOUD_OWNER = "DEFAULT";
117     private static final String CREATENETWORKBB = "CreateNetworkBB";
118     private static final String ACTIVATENETWORKBB = "ActivateNetworkBB";
119     private static final String VOLUMEGROUP_DELETE_PATTERN = "(Un|De)(.*)Volume(.*)";
120     private static final String VOLUMEGROUP_CREATE_PATTERN = "(A|C)(.*)Volume(.*)";
121     private static final String DEFAULT_CLOUD_OWNER = "org.onap.so.cloud-owner";
122     private static final String HOMING = "homing";
123
124     @Autowired
125     protected BBInputSetup bbInputSetup;
126     @Autowired
127     protected BBInputSetupUtils bbInputSetupUtils;
128     @Autowired
129     private ExceptionBuilder exceptionBuilder;
130     @Autowired
131     private CatalogDbClient catalogDbClient;
132     @Autowired
133     private AAIConfigurationResources aaiConfigurationResources;
134     @Autowired
135     private WorkflowActionExtractResourcesAAI workflowActionUtils;
136     @Autowired
137     private VrfValidation vrfValidation;
138     @Autowired
139     private Environment environment;
140     @Autowired
141     private UserParamsServiceTraversal userParamsServiceTraversal;
142     @Autowired
143     private AaiResourceIdValidator aaiResourceIdValidator;
144     @Autowired
145     private ExecuteBuildingBlockBuilder executeBuildingBlockBuilder;
146
147     public void setBbInputSetupUtils(BBInputSetupUtils bbInputSetupUtils) {
148         this.bbInputSetupUtils = bbInputSetupUtils;
149     }
150
151     public void setBbInputSetup(BBInputSetup bbInputSetup) {
152         this.bbInputSetup = bbInputSetup;
153     }
154
155     public void selectExecutionList(DelegateExecution execution) throws Exception {
156         try {
157             fillExecutionDefault(execution);
158             final String bpmnRequest = (String) execution.getVariable(BBConstants.G_BPMN_REQUEST);
159             ServiceInstancesRequest sIRequest =
160                     new ObjectMapper().readValue(bpmnRequest, ServiceInstancesRequest.class);
161
162             final String requestId = (String) execution.getVariable(BBConstants.G_REQUEST_ID);
163
164             String uri = (String) execution.getVariable(BBConstants.G_URI);
165             boolean isResume = isUriResume(uri);
166
167             final boolean isALaCarte = (boolean) execution.getVariable(BBConstants.G_ALACARTE);
168             Resource resource = getResource(bbInputSetupUtils, isResume, isALaCarte, uri, requestId);
169
170             WorkflowResourceIds workflowResourceIds = populateResourceIdsFromApiHandler(execution);
171             RequestDetails requestDetails = sIRequest.getRequestDetails();
172             String requestAction = (String) execution.getVariable(BBConstants.G_ACTION);
173             String resourceId = getResourceId(resource, requestAction, requestDetails, workflowResourceIds);
174             WorkflowType resourceType = resource.getResourceType();
175
176             String serviceInstanceId = getServiceInstanceId(execution, resourceId, resourceType);
177
178             fillExecution(execution, requestDetails.getRequestInfo().getSuppressRollback(), resourceId, resourceType);
179             List<ExecuteBuildingBlock> flowsToExecute;
180             if (isRequestMacroServiceResume(isALaCarte, resourceType, requestAction, serviceInstanceId)) {
181                 String errorMessage = "Could not resume Macro flow. Error loading execution path.";
182                 flowsToExecute = loadExecuteBuildingBlocks(execution, requestId, errorMessage);
183             } else if (isALaCarte && isResume) {
184                 String errorMessage =
185                         "Could not resume request with request Id: " + requestId + ". No flowsToExecute was found";
186                 flowsToExecute = loadExecuteBuildingBlocks(execution, requestId, errorMessage);
187             } else {
188                 String vnfType = (String) execution.getVariable(VNF_TYPE);
189                 String cloudOwner = getCloudOwner(requestDetails.getCloudConfiguration());
190                 List<OrchestrationFlow> orchFlows =
191                         (List<OrchestrationFlow>) execution.getVariable(BBConstants.G_ORCHESTRATION_FLOW);
192                 final String apiVersion = (String) execution.getVariable(BBConstants.G_APIVERSION);
193                 final String serviceType =
194                         Optional.ofNullable((String) execution.getVariable(BBConstants.G_SERVICE_TYPE)).orElse("");
195                 if (isALaCarte) {
196                     flowsToExecute = loadExecuteBuildingBlocksForAlaCarte(orchFlows, execution, requestAction,
197                             resourceType, cloudOwner, serviceType, sIRequest, requestId, workflowResourceIds,
198                             requestDetails, resourceId, vnfType, apiVersion);
199                 } else {
200                     flowsToExecute = loadExecuteBuildingBlocksForMacro(sIRequest, resourceType, requestAction,
201                             execution, serviceInstanceId, resourceId, workflowResourceIds, orchFlows, cloudOwner,
202                             serviceType, requestId, apiVersion, vnfType, requestDetails);
203                 }
204             }
205             // If the user set "Homing_Solution" to "none", disable homing, else if "Homing_Solution" is specified,
206             // enable it.
207             List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
208             if (sIRequest.getRequestDetails().getRequestParameters() != null && userParams != null) {
209                 for (Map<String, Object> params : userParams) {
210                     if (params.containsKey(HOMINGSOLUTION)) {
211                         execution.setVariable(HOMING, !"none".equals(params.get(HOMINGSOLUTION)));
212                     }
213                 }
214             }
215
216             if (CollectionUtils.isEmpty(flowsToExecute)) {
217                 throw new IllegalStateException("Macro did not come up with a valid execution path.");
218             }
219
220             List<String> flowNames = new ArrayList<>();
221             logger.info("List of BuildingBlocks to execute:");
222
223             flowsToExecute.forEach(ebb -> {
224                 logger.info(ebb.getBuildingBlock().getBpmnFlowName());
225                 flowNames.add(ebb.getBuildingBlock().getBpmnFlowName());
226             });
227
228             if (!isResume) {
229                 bbInputSetupUtils.persistFlowExecutionPath(requestId, flowsToExecute);
230             }
231             setExecutionVariables(execution, flowsToExecute, flowNames);
232
233         } catch (Exception ex) {
234             if (!(execution.hasVariable("WorkflowException")
235                     || execution.hasVariable("WorkflowExceptionExceptionMessage"))) {
236                 buildAndThrowException(execution, "Exception while setting execution list. ", ex);
237             } else {
238                 throw ex;
239             }
240         }
241     }
242
243     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocksForAlaCarte(List<OrchestrationFlow> orchFlows,
244             DelegateExecution execution, String requestAction, WorkflowType resourceType, String cloudOwner,
245             String serviceType, ServiceInstancesRequest sIRequest, String requestId,
246             WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails, String resourceId, String vnfType,
247             String apiVersion) throws Exception {
248         List<ExecuteBuildingBlock> flowsToExecute = new ArrayList<>();
249         if (orchFlows == null || orchFlows.isEmpty()) {
250             orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, true, cloudOwner,
251                     serviceType);
252         }
253         Resource resourceKey = getResourceKey(sIRequest, resourceType);
254
255         ReplaceInstanceRelatedInformation replaceInfo = new ReplaceInstanceRelatedInformation();
256         if ((requestAction.equalsIgnoreCase(REPLACEINSTANCE)
257                 || requestAction.equalsIgnoreCase(REPLACEINSTANCERETAINASSIGNMENTS))
258                 && resourceType.equals(WorkflowType.VFMODULE)) {
259             logger.debug("Build a BB list for replacing BB modules");
260             ConfigBuildingBlocksDataObject cbbdo = createConfigBuildingBlocksDataObject(execution, sIRequest, requestId,
261                     workflowResourceIds, requestDetails, requestAction, resourceId, vnfType, orchFlows, apiVersion,
262                     resourceKey, replaceInfo);
263             orchFlows = getVfModuleReplaceBuildingBlocks(cbbdo);
264
265             createBuildingBlocksForOrchFlows(execution, sIRequest, requestId, workflowResourceIds, requestDetails,
266                     requestAction, resourceId, flowsToExecute, vnfType, orchFlows, apiVersion, resourceKey,
267                     replaceInfo);
268         } else {
269             if (isConfiguration(orchFlows) && !requestAction.equalsIgnoreCase(CREATE_INSTANCE)) {
270                 addConfigBuildingBlocksToFlowsToExecuteList(execution, sIRequest, requestId, workflowResourceIds,
271                         requestDetails, requestAction, resourceId, flowsToExecute, vnfType, apiVersion, resourceKey,
272                         replaceInfo, orchFlows);
273             }
274             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().contains(FABRIC_CONFIGURATION))
275                     .collect(Collectors.toList());
276
277             for (OrchestrationFlow orchFlow : orchFlows) {
278                 ExecuteBuildingBlock ebb = executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, requestId,
279                         resourceKey, apiVersion, resourceId, requestAction, true, vnfType, workflowResourceIds,
280                         requestDetails, false, null, null, false, replaceInfo);
281                 flowsToExecute.add(ebb);
282             }
283         }
284         return flowsToExecute;
285     }
286
287     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocksForMacro(ServiceInstancesRequest sIRequest,
288             WorkflowType resourceType, String requestAction, DelegateExecution execution, String serviceInstanceId,
289             String resourceId, WorkflowResourceIds workflowResourceIds, List<OrchestrationFlow> orchFlows,
290             String cloudOwner, String serviceType, String requestId, String apiVersion, String vnfType,
291             RequestDetails requestDetails) throws IOException, VrfBondingServiceException {
292         List<ExecuteBuildingBlock> flowsToExecute;
293         boolean containsService = false;
294         List<Resource> resourceList = new ArrayList<>();
295         List<Pair<WorkflowType, String>> aaiResourceIds = new ArrayList<>();
296         List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
297         if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(ASSIGNINSTANCE)) {
298             // SERVICE-MACRO-ASSIGN will always get user params with a
299             // service.
300
301             if (userParams != null) {
302                 containsService = isContainsService(sIRequest);
303                 if (containsService) {
304                     resourceList = userParamsServiceTraversal.getResourceListFromUserParams(execution, userParams,
305                             serviceInstanceId, requestAction);
306                 }
307             } else {
308                 buildAndThrowException(execution,
309                         "Service-Macro-Assign request details must contain user params with a service");
310             }
311         } else if (resourceType == WorkflowType.SERVICE && requestAction.equalsIgnoreCase(CREATE_INSTANCE)) {
312             // SERVICE-MACRO-CREATE will get user params with a service,
313             // a service with a network, a service with a
314             // network collection, OR an empty service.
315             // If user params is just a service or null and macro
316             // queries the SI and finds a VNF, macro fails.
317
318             if (userParams != null) {
319                 containsService = isContainsService(sIRequest);
320             }
321             if (containsService) {
322                 resourceList = userParamsServiceTraversal.getResourceListFromUserParams(execution, userParams,
323                         serviceInstanceId, requestAction);
324             }
325             if (!foundRelated(resourceList)) {
326                 traverseCatalogDbService(execution, sIRequest, resourceList, aaiResourceIds);
327             }
328         } else if (resourceType == WorkflowType.SERVICE && ("activateInstance".equalsIgnoreCase(requestAction)
329                 || "unassignInstance".equalsIgnoreCase(requestAction)
330                 || "deleteInstance".equalsIgnoreCase(requestAction)
331                 || requestAction.equalsIgnoreCase("activate" + FABRIC_CONFIGURATION))) {
332             // SERVICE-MACRO-ACTIVATE, SERVICE-MACRO-UNASSIGN, and
333             // SERVICE-MACRO-DELETE
334             // Will never get user params with service, macro will have
335             // to query the SI in AAI to find related instances.
336             traverseAAIService(execution, resourceList, resourceId, aaiResourceIds);
337         } else if (resourceType == WorkflowType.SERVICE && "deactivateInstance".equalsIgnoreCase(requestAction)) {
338             resourceList.add(new Resource(WorkflowType.SERVICE, "", false));
339         } else if (resourceType == WorkflowType.VNF && (REPLACEINSTANCE.equalsIgnoreCase(requestAction)
340                 || ("recreateInstance".equalsIgnoreCase(requestAction)))) {
341             traverseAAIVnf(execution, resourceList, workflowResourceIds.getServiceInstanceId(),
342                     workflowResourceIds.getVnfId(), aaiResourceIds);
343         } else if (resourceType == WorkflowType.VNF && "updateInstance".equalsIgnoreCase(requestAction)) {
344             customTraverseAAIVnf(execution, resourceList, workflowResourceIds.getServiceInstanceId(),
345                     workflowResourceIds.getVnfId(), aaiResourceIds);
346         } else {
347             buildAndThrowException(execution, "Current Macro Request is not supported");
348         }
349         StringBuilder foundObjects = new StringBuilder();
350         for (WorkflowType type : WorkflowType.values()) {
351             foundObjects.append(type).append(" - ")
352                     .append((int) resourceList.stream().filter(x -> type.equals(x.getResourceType())).count())
353                     .append("    ");
354         }
355         logger.info("Found {}", foundObjects);
356
357         if (orchFlows == null || orchFlows.isEmpty()) {
358             orchFlows = queryNorthBoundRequestCatalogDb(execution, requestAction, resourceType, false, cloudOwner,
359                     serviceType);
360         }
361         boolean vnfReplace = false;
362         if (resourceType.equals(WorkflowType.VNF) && (REPLACEINSTANCE.equalsIgnoreCase(requestAction)
363                 || REPLACEINSTANCERETAINASSIGNMENTS.equalsIgnoreCase(requestAction))) {
364             vnfReplace = true;
365         }
366         flowsToExecute = executeBuildingBlockBuilder.buildExecuteBuildingBlockList(orchFlows, resourceList, requestId,
367                 apiVersion, resourceId, requestAction, vnfType, workflowResourceIds, requestDetails, vnfReplace);
368         if (isNetworkCollectionInTheResourceList(resourceList)) {
369             logger.info("Sorting for Vlan Tagging");
370             flowsToExecute = sortExecutionPathByObjectForVlanTagging(flowsToExecute, requestAction);
371         }
372         // By default, enable homing at VNF level for CREATE_INSTANCE and ASSIGNINSTANCE
373         if (resourceType == WorkflowType.SERVICE
374                 && (requestAction.equals(CREATE_INSTANCE) || requestAction.equals(ASSIGNINSTANCE))
375                 && resourceList.stream().anyMatch(x -> WorkflowType.VNF.equals(x.getResourceType()))) {
376             execution.setVariable(HOMING, true);
377             execution.setVariable("calledHoming", false);
378         }
379         if (resourceType == WorkflowType.SERVICE && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE)
380                 || requestAction.equalsIgnoreCase(CREATE_INSTANCE))) {
381             generateResourceIds(flowsToExecute, resourceList, serviceInstanceId);
382         } else {
383             updateResourceIdsFromAAITraversal(flowsToExecute, resourceList, aaiResourceIds, serviceInstanceId);
384         }
385         return flowsToExecute;
386     }
387
388     private void setExecutionVariables(DelegateExecution execution, List<ExecuteBuildingBlock> flowsToExecute,
389             List<String> flowNames) {
390         execution.setVariable("flowNames", flowNames);
391         execution.setVariable(BBConstants.G_CURRENT_SEQUENCE, 0);
392         execution.setVariable("retryCount", 0);
393         execution.setVariable("isRollback", false);
394         execution.setVariable("flowsToExecute", flowsToExecute);
395         execution.setVariable("isRollbackComplete", false);
396     }
397
398     private boolean isContainsService(ServiceInstancesRequest sIRequest) {
399         boolean containsService;
400         List<Map<String, Object>> userParams = sIRequest.getRequestDetails().getRequestParameters().getUserParams();
401         containsService = userParams.stream().anyMatch(param -> param.containsKey(USER_PARAM_SERVICE));
402         return containsService;
403     }
404
405
406
407     private List<ExecuteBuildingBlock> loadExecuteBuildingBlocks(DelegateExecution execution, String requestId,
408             String errorMessage) {
409         List<ExecuteBuildingBlock> flowsToExecute;
410         flowsToExecute = bbInputSetupUtils.loadOriginalFlowExecutionPath(requestId);
411         if (flowsToExecute == null) {
412             buildAndThrowException(execution, errorMessage);
413         }
414         return flowsToExecute;
415     }
416
417     private ConfigBuildingBlocksDataObject createConfigBuildingBlocksDataObject(DelegateExecution execution,
418             ServiceInstancesRequest sIRequest, String requestId, WorkflowResourceIds workflowResourceIds,
419             RequestDetails requestDetails, String requestAction, String resourceId, String vnfType,
420             List<OrchestrationFlow> orchFlows, String apiVersion, Resource resourceKey,
421             ReplaceInstanceRelatedInformation replaceInfo) {
422
423         return new ConfigBuildingBlocksDataObject().setsIRequest(sIRequest).setOrchFlows(orchFlows)
424                 .setRequestId(requestId).setResourceKey(resourceKey).setApiVersion(apiVersion).setResourceId(resourceId)
425                 .setRequestAction(requestAction).setaLaCarte(true).setVnfType(vnfType)
426                 .setWorkflowResourceIds(workflowResourceIds).setRequestDetails(requestDetails).setExecution(execution)
427                 .setReplaceInformation(replaceInfo);
428     }
429
430     private void createBuildingBlocksForOrchFlows(DelegateExecution execution, ServiceInstancesRequest sIRequest,
431             String requestId, WorkflowResourceIds workflowResourceIds, RequestDetails requestDetails,
432             String requestAction, String resourceId, List<ExecuteBuildingBlock> flowsToExecute, String vnfType,
433             List<OrchestrationFlow> orchFlows, String apiVersion, Resource resourceKey,
434             ReplaceInstanceRelatedInformation replaceInfo) throws Exception {
435
436         for (OrchestrationFlow orchFlow : orchFlows) {
437             if (orchFlow.getFlowName().contains(CONFIGURATION)) {
438                 List<OrchestrationFlow> configOrchFlows = new ArrayList<>();
439                 configOrchFlows.add(orchFlow);
440                 addConfigBuildingBlocksToFlowsToExecuteList(execution, sIRequest, requestId, workflowResourceIds,
441                         requestDetails, requestAction, resourceId, flowsToExecute, vnfType, apiVersion, resourceKey,
442                         replaceInfo, configOrchFlows);
443             } else {
444                 ExecuteBuildingBlock ebb = executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, requestId,
445                         resourceKey, apiVersion, resourceId, requestAction, true, vnfType, workflowResourceIds,
446                         requestDetails, false, null, null, false, replaceInfo);
447                 flowsToExecute.add(ebb);
448             }
449         }
450     }
451
452     private void addConfigBuildingBlocksToFlowsToExecuteList(DelegateExecution execution,
453             ServiceInstancesRequest sIRequest, String requestId, WorkflowResourceIds workflowResourceIds,
454             RequestDetails requestDetails, String requestAction, String resourceId,
455             List<ExecuteBuildingBlock> flowsToExecute, String vnfType, String apiVersion, Resource resourceKey,
456             ReplaceInstanceRelatedInformation replaceInfo, List<OrchestrationFlow> configOrchFlows) throws Exception {
457
458         ConfigBuildingBlocksDataObject cbbdo = createConfigBuildingBlocksDataObject(execution, sIRequest, requestId,
459                 workflowResourceIds, requestDetails, requestAction, resourceId, vnfType, configOrchFlows, apiVersion,
460                 resourceKey, replaceInfo);
461         List<ExecuteBuildingBlock> configBuildingBlocks = getConfigBuildingBlocks(cbbdo);
462         flowsToExecute.addAll(configBuildingBlocks);
463     }
464
465     private Resource getResourceKey(ServiceInstancesRequest sIRequest, WorkflowType resourceType) {
466         String resourceId = "";
467         ModelInfo modelInfo = sIRequest.getRequestDetails().getModelInfo();
468         if (modelInfo != null) {
469             if (modelInfo.getModelType().equals(ModelType.service)) {
470                 resourceId = modelInfo.getModelVersionId();
471             } else {
472                 resourceId = modelInfo.getModelCustomizationId();
473             }
474         }
475         return new Resource(resourceType, resourceId, true);
476     }
477
478     private String getCloudOwner(CloudConfiguration cloudConfiguration) {
479         if (cloudConfiguration != null && cloudConfiguration.getCloudOwner() != null) {
480             return cloudConfiguration.getCloudOwner();
481         }
482         logger.warn("cloud owner value not found in request details, it will be set as default");
483         return environment.getProperty(DEFAULT_CLOUD_OWNER);
484     }
485
486     protected <T> List<T> getRelatedResourcesInVfModule(String vnfId, String vfModuleId, Class<T> resultClass,
487             AAIObjectName name) {
488         List<T> vnfcs = new ArrayList<>();
489         AAIResourceUri uri =
490                 AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().genericVnf(vnfId).vfModule(vfModuleId));
491         AAIResultWrapper vfModuleResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
492         Optional<Relationships> relationshipsOp = vfModuleResultsWrapper.getRelationships();
493         if (relationshipsOp.isEmpty()) {
494             logger.debug("No relationships were found for vfModule in AAI");
495         } else {
496             Relationships relationships = relationshipsOp.get();
497             List<AAIResultWrapper> vnfcResultWrappers = relationships.getByType(name);
498             for (AAIResultWrapper vnfcResultWrapper : vnfcResultWrappers) {
499                 Optional<T> vnfcOp = vnfcResultWrapper.asBean(resultClass);
500                 vnfcOp.ifPresent(vnfcs::add);
501             }
502         }
503         return vnfcs;
504     }
505
506     protected <T> T getRelatedResourcesInVnfc(Vnfc vnfc, Class<T> resultClass, AAIObjectName name)
507             throws VnfcMultipleRelationshipException {
508         T configuration = null;
509         AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIFluentTypeBuilder.network().vnfc(vnfc.getVnfcName()));
510         AAIResultWrapper vnfcResultsWrapper = bbInputSetupUtils.getAAIResourceDepthOne(uri);
511         Optional<Relationships> relationshipsOp = vnfcResultsWrapper.getRelationships();
512         if (relationshipsOp.isEmpty()) {
513             logger.debug("No relationships were found for VNFC in AAI");
514         } else {
515             Relationships relationships = relationshipsOp.get();
516             List<AAIResultWrapper> configurationResultWrappers =
517                     this.getResultWrappersFromRelationships(relationships, name);
518             if (configurationResultWrappers.size() > 1) {
519                 throw new VnfcMultipleRelationshipException(vnfc.getVnfcName());
520             }
521             if (!configurationResultWrappers.isEmpty()) {
522                 Optional<T> configurationOp = configurationResultWrappers.get(0).asBean(resultClass);
523                 if (configurationOp.isPresent()) {
524                     configuration = configurationOp.get();
525                 }
526             }
527         }
528         return configuration;
529     }
530
531     protected List<AAIResultWrapper> getResultWrappersFromRelationships(Relationships relationships,
532             AAIObjectName name) {
533         return relationships.getByType(name);
534     }
535
536     protected boolean isConfiguration(List<OrchestrationFlow> orchFlows) {
537         for (OrchestrationFlow flow : orchFlows) {
538             if (flow.getFlowName().contains(CONFIGURATION) && !"ConfigurationScaleOutBB".equals(flow.getFlowName())) {
539                 return true;
540             }
541         }
542         return false;
543     }
544
545     protected List<ExecuteBuildingBlock> getConfigBuildingBlocks(ConfigBuildingBlocksDataObject dataObj)
546             throws AAIEntityNotFoundException, VnfcMultipleRelationshipException {
547
548         List<ExecuteBuildingBlock> flowsToExecuteConfigs = new ArrayList<>();
549         List<OrchestrationFlow> result = dataObj.getOrchFlows().stream()
550                 .filter(item -> item.getFlowName().contains(FABRIC_CONFIGURATION)).collect(Collectors.toList());
551         String vnfId = dataObj.getWorkflowResourceIds().getVnfId();
552         String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId();
553
554         String vnfCustomizationUUID = bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
555         String vfModuleCustomizationUUID;
556         org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
557
558         if (aaiVfModule == null) {
559             logger.error("No matching VfModule is found in Generic-Vnf in AAI for vnfId: {} and vfModuleId : {}", vnfId,
560                     vfModuleId);
561             throw new AAIEntityNotFoundException("No matching VfModule is found in Generic-Vnf in AAI for vnfId: "
562                     + vnfId + " and vfModuleId : " + vfModuleId);
563         } else {
564             vfModuleCustomizationUUID = aaiVfModule.getModelCustomizationId();
565         }
566         String replaceVfModuleCustomizationUUID = "";
567         String replaceVnfModuleCustomizationUUID = "";
568         boolean isReplace = false;
569         if (dataObj.getRequestAction().equalsIgnoreCase("replaceInstance")
570                 || dataObj.getRequestAction().equalsIgnoreCase("replaceInstanceRetainAssignments")) {
571             for (RelatedInstanceList relatedInstList : dataObj.getRequestDetails().getRelatedInstanceList()) {
572                 RelatedInstance relatedInstance = relatedInstList.getRelatedInstance();
573                 if (relatedInstance.getModelInfo().getModelType().equals(ModelType.vnf)) {
574                     replaceVnfModuleCustomizationUUID = relatedInstance.getModelInfo().getModelCustomizationId();
575                 }
576             }
577             replaceVfModuleCustomizationUUID = dataObj.getRequestDetails().getModelInfo().getModelCustomizationId();
578             isReplace = true;
579         }
580
581         List<org.onap.aai.domain.yang.Vnfc> vnfcs =
582                 getRelatedResourcesInVfModule(vnfId, vfModuleId, org.onap.aai.domain.yang.Vnfc.class, Types.VNFC);
583         for (org.onap.aai.domain.yang.Vnfc vnfc : vnfcs) {
584             WorkflowResourceIds workflowIdsCopy = SerializationUtils.clone(dataObj.getWorkflowResourceIds());
585             org.onap.aai.domain.yang.Configuration configuration =
586                     getRelatedResourcesInVnfc(vnfc, org.onap.aai.domain.yang.Configuration.class, Types.CONFIGURATION);
587             if (configuration == null) {
588                 logger.warn(String.format("No configuration found for VNFC %s in AAI", vnfc.getVnfcName()));
589                 continue;
590             }
591             workflowIdsCopy.setConfigurationId(configuration.getConfigurationId());
592             for (OrchestrationFlow orchFlow : result) {
593                 if (!isReplace || (isReplace && (orchFlow.getFlowName().contains("Delete")))) {
594                     if (!isReplace) {
595                         dataObj.getResourceKey().setVfModuleCustomizationId(vfModuleCustomizationUUID);
596                         dataObj.getResourceKey().setVnfCustomizationId(vnfCustomizationUUID);
597                     } else {
598                         if (orchFlow.getFlowName().contains("Delete")) {
599                             dataObj.getResourceKey().setVfModuleCustomizationId(vfModuleCustomizationUUID);
600                             dataObj.getResourceKey().setVnfCustomizationId(vnfCustomizationUUID);
601                         } else {
602                             dataObj.getResourceKey().setVfModuleCustomizationId(replaceVfModuleCustomizationUUID);
603                             dataObj.getResourceKey().setVnfCustomizationId(replaceVnfModuleCustomizationUUID);
604                         }
605                     }
606                     dataObj.getResourceKey().setCvnfModuleCustomizationId(vnfc.getModelCustomizationId());
607                     String vnfcName = vnfc.getVnfcName();
608                     if (vnfcName == null || vnfcName.isEmpty()) {
609                         buildAndThrowException(dataObj.getExecution(), "Exception in create execution list "
610                                 + ": VnfcName does not exist or is null while there is a configuration for the vfModule",
611                                 new Exception("Vnfc and Configuration do not match"));
612                     }
613                     ExecuteBuildingBlock ebb =
614                             executeBuildingBlockBuilder.buildExecuteBuildingBlock(orchFlow, dataObj.getRequestId(),
615                                     dataObj.getResourceKey(), dataObj.getApiVersion(), dataObj.getResourceId(),
616                                     dataObj.getRequestAction(), dataObj.isaLaCarte(), dataObj.getVnfType(),
617                                     workflowIdsCopy, dataObj.getRequestDetails(), false, null, vnfcName, true, null);
618                     flowsToExecuteConfigs.add(ebb);
619                 }
620             }
621         }
622         return flowsToExecuteConfigs;
623     }
624
625     protected void buildAndThrowException(DelegateExecution execution, String msg) {
626         logger.error(msg);
627         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg);
628         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg);
629     }
630
631     protected void buildAndThrowException(DelegateExecution execution, String msg, Exception ex) {
632         logger.error(msg, ex);
633         execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, msg + ex.getMessage());
634         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, msg + ex.getMessage());
635     }
636
637     protected List<OrchestrationFlow> getVfModuleReplaceBuildingBlocks(ConfigBuildingBlocksDataObject dataObj)
638             throws Exception {
639
640         String vnfId = dataObj.getWorkflowResourceIds().getVnfId();
641         String vfModuleId = dataObj.getWorkflowResourceIds().getVfModuleId();
642
643         logger.debug("BUILDING REPLACE LIST");
644
645         boolean volumeGroupExisted = false;
646         boolean volumeGroupWillExist = false;
647         boolean keepVolumeGroup = false;
648
649         boolean rebuildVolumeGroups = false;
650         if (dataObj.getRequestDetails().getRequestParameters() != null
651                 && dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups() != null) {
652             rebuildVolumeGroups = dataObj.getRequestDetails().getRequestParameters().getRebuildVolumeGroups();
653         }
654         String volumeGroupName = "";
655         Optional<VolumeGroup> volumeGroupFromVfModule =
656                 bbInputSetupUtils.getRelatedVolumeGroupFromVfModule(vnfId, vfModuleId);
657         if (volumeGroupFromVfModule.isPresent()) {
658             String volumeGroupId = volumeGroupFromVfModule.get().getVolumeGroupId();
659             volumeGroupName = volumeGroupFromVfModule.get().getVolumeGroupName();
660             logger.debug("Volume group id of the existing volume group is: {}", volumeGroupId);
661             volumeGroupExisted = true;
662             dataObj.getWorkflowResourceIds().setVolumeGroupId(volumeGroupId);
663             dataObj.getReplaceInformation().setOldVolumeGroupName(volumeGroupName);
664         }
665
666         List<OrchestrationFlow> orchFlows = dataObj.getOrchFlows();
667         VfModuleCustomization vfModuleCustomization = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(
668                 dataObj.getRequestDetails().getModelInfo().getModelCustomizationUuid());
669         if (vfModuleCustomization != null && vfModuleCustomization.getVfModule() != null
670                 && vfModuleCustomization.getVfModule().getVolumeHeatTemplate() != null
671                 && vfModuleCustomization.getVolumeHeatEnv() != null) {
672             volumeGroupWillExist = true;
673             if (!volumeGroupExisted) {
674                 String newVolumeGroupId = UUID.randomUUID().toString();
675                 dataObj.getWorkflowResourceIds().setVolumeGroupId(newVolumeGroupId);
676                 dataObj.getReplaceInformation().setOldVolumeGroupName(volumeGroupName);
677                 logger.debug("newVolumeGroupId: {}", newVolumeGroupId);
678             }
679         }
680
681         if (volumeGroupExisted && volumeGroupWillExist && !rebuildVolumeGroups) {
682             keepVolumeGroup = true;
683         }
684
685         if (!volumeGroupExisted || keepVolumeGroup) {
686             logger.debug("Filtering out deletion of volume groups");
687             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_DELETE_PATTERN))
688                     .collect(Collectors.toList());
689         }
690         if (!volumeGroupWillExist || keepVolumeGroup) {
691             logger.debug("Filtering out creation of volume groups");
692             orchFlows = orchFlows.stream().filter(item -> !item.getFlowName().matches(VOLUMEGROUP_CREATE_PATTERN))
693                     .collect(Collectors.toList());
694         }
695
696         return orchFlows;
697     }
698
699
700
701     private void updateResourceIdsFromAAITraversal(List<ExecuteBuildingBlock> flowsToExecute,
702             List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds, String serviceInstanceId) {
703         for (Pair<WorkflowType, String> pair : aaiResourceIds) {
704             logger.debug("{}, {}", pair.getValue0(), pair.getValue1());
705         }
706
707         Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE))
708                 .forEach(type -> resourceList.stream().filter(resource -> type.equals(resource.getResourceType()))
709                         .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(),
710                                 retrieveAAIResourceId(aaiResourceIds, type), null, serviceInstanceId)));
711     }
712
713     private String retrieveAAIResourceId(List<Pair<WorkflowType, String>> aaiResourceIds, WorkflowType resource) {
714         String id = null;
715         for (int i = 0; i < aaiResourceIds.size(); i++) {
716             if (aaiResourceIds.get(i).getValue0() == resource) {
717                 id = aaiResourceIds.get(i).getValue1();
718                 aaiResourceIds.remove(i);
719                 break;
720             }
721         }
722         return id;
723     }
724
725     private void generateResourceIds(List<ExecuteBuildingBlock> flowsToExecute, List<Resource> resourceList,
726             String serviceInstanceId) {
727         Arrays.stream(WorkflowType.values()).filter(type -> !type.equals(WorkflowType.SERVICE))
728                 .forEach(type -> resourceList.stream().filter(resource -> type.equals(resource.getResourceType()))
729                         .forEach(resource -> updateWorkflowResourceIds(flowsToExecute, type, resource.getResourceId(),
730                                 null, resource.getVirtualLinkKey(), serviceInstanceId)));
731     }
732
733     protected void updateWorkflowResourceIds(List<ExecuteBuildingBlock> flowsToExecute, WorkflowType resourceType,
734             String key, String id, String virtualLinkKey, String serviceInstanceId) {
735         String resourceId = id;
736         if (resourceId == null) {
737             resourceId = UUID.randomUUID().toString();
738         }
739         for (ExecuteBuildingBlock ebb : flowsToExecute) {
740             if (key != null && key.equalsIgnoreCase(ebb.getBuildingBlock().getKey()) && (ebb.getBuildingBlock()
741                     .getBpmnFlowName().contains(resourceType.toString())
742                     || (ebb.getBuildingBlock().getBpmnFlowName().contains(CONTROLLER)
743                             && ebb.getBuildingBlock().getBpmnScope().equalsIgnoreCase(resourceType.toString())))) {
744                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
745                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
746                 WorkflowResourceIdsUtils.setResourceIdByWorkflowType(workflowResourceIds, resourceType, resourceId);
747                 ebb.setWorkflowResourceIds(workflowResourceIds);
748             }
749             if (virtualLinkKey != null && ebb.getBuildingBlock().isVirtualLink()
750                     && virtualLinkKey.equalsIgnoreCase(ebb.getBuildingBlock().getVirtualLinkKey())) {
751                 WorkflowResourceIds workflowResourceIds = new WorkflowResourceIds();
752                 workflowResourceIds.setServiceInstanceId(serviceInstanceId);
753                 workflowResourceIds.setNetworkId(resourceId);
754                 ebb.setWorkflowResourceIds(workflowResourceIds);
755             }
756         }
757     }
758
759     protected CollectionResourceCustomization findCatalogNetworkCollection(DelegateExecution execution,
760             org.onap.so.db.catalog.beans.Service service) {
761         CollectionResourceCustomization networkCollection = null;
762         int count = 0;
763         for (CollectionResourceCustomization collectionCust : service.getCollectionResourceCustomizations()) {
764             if (catalogDbClient.getNetworkCollectionResourceCustomizationByID(
765                     collectionCust.getModelCustomizationUUID()) != null) {
766                 networkCollection = collectionCust;
767                 count++;
768             }
769         }
770         if (count == 0) {
771             return null;
772         } else if (count > 1) {
773             buildAndThrowException(execution,
774                     "Found multiple Network Collections in the Service model, only one per Service is supported.");
775         }
776         return networkCollection;
777     }
778
779     protected void traverseCatalogDbService(DelegateExecution execution, ServiceInstancesRequest sIRequest,
780             List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds)
781             throws JsonProcessingException, VrfBondingServiceException {
782         String modelUUID = sIRequest.getRequestDetails().getModelInfo().getModelVersionId();
783         org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(modelUUID);
784
785         if (service == null) {
786             buildAndThrowException(execution, "Could not find the service model in catalog db.");
787         } else {
788             resourceList.add(new Resource(WorkflowType.SERVICE, service.getModelUUID(), false));
789             RelatedInstance relatedVpnBinding =
790                     bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.vpnBinding);
791             RelatedInstance relatedLocalNetwork =
792                     bbInputSetupUtils.getRelatedInstanceByType(sIRequest.getRequestDetails(), ModelType.network);
793
794             if (relatedVpnBinding != null && relatedLocalNetwork != null) {
795                 traverseVrfConfiguration(aaiResourceIds, resourceList, service, relatedVpnBinding, relatedLocalNetwork);
796             } else {
797                 traverseNetworkCollection(execution, resourceList, service);
798             }
799         }
800     }
801
802     protected void traverseVrfConfiguration(List<Pair<WorkflowType, String>> aaiResourceIds,
803             List<Resource> resourceList, org.onap.so.db.catalog.beans.Service service,
804             RelatedInstance relatedVpnBinding, RelatedInstance relatedLocalNetwork)
805             throws VrfBondingServiceException, JsonProcessingException {
806         org.onap.aai.domain.yang.L3Network aaiLocalNetwork =
807                 bbInputSetupUtils.getAAIL3Network(relatedLocalNetwork.getInstanceId());
808         vrfValidation.vrfServiceValidation(service);
809         vrfValidation.vrfCatalogDbChecks(service);
810         vrfValidation.aaiVpnBindingValidation(relatedVpnBinding.getInstanceId(),
811                 bbInputSetupUtils.getAAIVpnBinding(relatedVpnBinding.getInstanceId()));
812         vrfValidation.aaiNetworkValidation(relatedLocalNetwork.getInstanceId(), aaiLocalNetwork);
813         vrfValidation.aaiSubnetValidation(aaiLocalNetwork);
814         vrfValidation.aaiAggregateRouteValidation(aaiLocalNetwork);
815         vrfValidation.aaiRouteTargetValidation(aaiLocalNetwork);
816         String existingAAIVrfConfiguration = getExistingAAIVrfConfiguration(relatedVpnBinding, aaiLocalNetwork);
817         if (existingAAIVrfConfiguration != null) {
818             aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, existingAAIVrfConfiguration));
819         }
820         resourceList.add(new Resource(WorkflowType.CONFIGURATION,
821                 service.getConfigurationCustomizations().get(0).getModelCustomizationUUID(), false));
822
823     }
824
825     protected String getExistingAAIVrfConfiguration(RelatedInstance relatedVpnBinding,
826             org.onap.aai.domain.yang.L3Network aaiLocalNetwork)
827             throws JsonProcessingException, VrfBondingServiceException {
828         Optional<Relationships> relationshipsOp = new AAIResultWrapper(
829                 new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiLocalNetwork)).getRelationships();
830         if (relationshipsOp.isPresent()) {
831             List<AAIResultWrapper> configurationsRelatedToLocalNetwork =
832                     relationshipsOp.get().getByType(Types.CONFIGURATION);
833             if (configurationsRelatedToLocalNetwork.size() > 1) {
834                 throw new VrfBondingServiceException(
835                         "Network: " + aaiLocalNetwork.getNetworkId() + " has more than 1 configuration related to it");
836             }
837             if (configurationsRelatedToLocalNetwork.size() == 1) {
838                 AAIResultWrapper configWrapper = configurationsRelatedToLocalNetwork.get(0);
839                 Optional<Configuration> relatedConfiguration = configWrapper.asBean(Configuration.class);
840                 if (relatedConfiguration.isPresent() && vrfConfigurationAlreadyExists(relatedVpnBinding,
841                         relatedConfiguration.get(), configWrapper)) {
842                     return relatedConfiguration.get().getConfigurationId();
843                 }
844             }
845         }
846         return null;
847     }
848
849     protected boolean vrfConfigurationAlreadyExists(RelatedInstance relatedVpnBinding, Configuration vrfConfiguration,
850             AAIResultWrapper configWrapper) throws VrfBondingServiceException {
851         if ("VRF-ENTRY".equalsIgnoreCase(vrfConfiguration.getConfigurationType())) {
852             Optional<Relationships> relationshipsConfigOp = configWrapper.getRelationships();
853             if (relationshipsConfigOp.isPresent()) {
854                 Optional<VpnBinding> relatedInfraVpnBindingOp =
855                         workflowActionUtils.extractRelationshipsVpnBinding(relationshipsConfigOp.get());
856                 if (relatedInfraVpnBindingOp.isPresent()) {
857                     VpnBinding relatedInfraVpnBinding = relatedInfraVpnBindingOp.get();
858                     if (!relatedInfraVpnBinding.getVpnId().equalsIgnoreCase(relatedVpnBinding.getInstanceId())) {
859                         throw new VrfBondingServiceException("Configuration: " + vrfConfiguration.getConfigurationId()
860                                 + " is not connected to the same vpn binding id provided in request: "
861                                 + relatedVpnBinding.getInstanceId());
862                     } else {
863                         return true;
864                     }
865                 }
866             }
867         }
868         return false;
869     }
870
871     protected void traverseNetworkCollection(DelegateExecution execution, List<Resource> resourceList,
872             org.onap.so.db.catalog.beans.Service service) {
873         if (isVnfCustomizationsInTheService(service)) {
874             buildAndThrowException(execution,
875                     "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");
876         }
877         if (isPnfCustomizationsInTheService(service)) {
878             buildAndThrowException(execution,
879                     "Cannot orchestrate Service-Macro-Create without user params with a pnf. Please update ASDC model for new macro orchestration support or add service_recipe records to route to old macro flows");
880         }
881         List<CollectionResourceCustomization> customizations = service.getCollectionResourceCustomizations();
882         if (customizations.isEmpty()) {
883             logger.debug("No Collections found. CollectionResourceCustomization list is empty.");
884         } else {
885             CollectionResourceCustomization collectionResourceCustomization =
886                     findCatalogNetworkCollection(execution, service);
887             traverseNetworkCollectionResourceCustomization(resourceList, collectionResourceCustomization);
888         }
889         traverseNetworkCollectionCustomization(resourceList, service);
890     }
891
892     private void traverseNetworkCollectionResourceCustomization(List<Resource> resourceList,
893             CollectionResourceCustomization collectionResourceCustomization) {
894         if (collectionResourceCustomizationShouldNotBeProcessed(resourceList, collectionResourceCustomization))
895             return;
896         int minNetworks = 0;
897         org.onap.so.db.catalog.beans.InstanceGroup instanceGroup =
898                 collectionResourceCustomization.getCollectionResource().getInstanceGroup();
899         CollectionResourceInstanceGroupCustomization collectionInstCust = null;
900         if (!instanceGroup.getCollectionInstanceGroupCustomizations().isEmpty()) {
901             for (CollectionResourceInstanceGroupCustomization collectionInstanceGroupTemp : instanceGroup
902                     .getCollectionInstanceGroupCustomizations()) {
903                 if (collectionInstanceGroupTemp.getModelCustomizationUUID()
904                         .equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
905                     collectionInstCust = collectionInstanceGroupTemp;
906                     break;
907                 }
908             }
909             if (interfaceNetworkQuantityIsAvailableInCollection(collectionInstCust)) {
910                 minNetworks = collectionInstCust.getSubInterfaceNetworkQuantity();
911             }
912         }
913         logger.debug("minNetworks: {}", minNetworks);
914         CollectionNetworkResourceCustomization collectionNetworkResourceCust =
915                 getCollectionNetworkResourceCustomization(collectionResourceCustomization, instanceGroup);
916         for (int i = 0; i < minNetworks; i++) {
917             if (collectionNetworkResourceCust != null) {
918                 Resource resource = new Resource(WorkflowType.VIRTUAL_LINK,
919                         collectionNetworkResourceCust.getModelCustomizationUUID(), false);
920                 resource.setVirtualLinkKey(Integer.toString(i));
921                 resourceList.add(resource);
922             }
923         }
924     }
925
926     private CollectionNetworkResourceCustomization getCollectionNetworkResourceCustomization(
927             CollectionResourceCustomization collectionResourceCustomization, InstanceGroup instanceGroup) {
928         CollectionNetworkResourceCustomization collectionNetworkResourceCust = null;
929         for (CollectionNetworkResourceCustomization collectionNetworkTemp : instanceGroup
930                 .getCollectionNetworkResourceCustomizations()) {
931             if (collectionNetworkTemp.getNetworkResourceCustomization().getModelCustomizationUUID()
932                     .equalsIgnoreCase(collectionResourceCustomization.getModelCustomizationUUID())) {
933                 collectionNetworkResourceCust = collectionNetworkTemp;
934                 break;
935             }
936         }
937         return collectionNetworkResourceCust;
938     }
939
940     private boolean collectionResourceCustomizationShouldNotBeProcessed(List<Resource> resourceList,
941             CollectionResourceCustomization collectionResourceCustomization) {
942         if (collectionResourceCustomization == null) {
943             logger.debug("No Network Collection Customization found");
944             return true;
945         }
946         resourceList.add(new Resource(WorkflowType.NETWORKCOLLECTION,
947                 collectionResourceCustomization.getModelCustomizationUUID(), false));
948         logger.debug("Found a network collection");
949         if (collectionResourceCustomization.getCollectionResource() == null) {
950             logger.debug("No Network Collection found. collectionResource is null");
951             return true;
952         }
953         if (collectionResourceCustomization.getCollectionResource().getInstanceGroup() == null) {
954             logger.debug("No Instance Group found for network collection.");
955             return true;
956         }
957         String toscaNodeType =
958                 collectionResourceCustomization.getCollectionResource().getInstanceGroup().getToscaNodeType();
959         if (!toscaNodeTypeHasNetworkCollection(toscaNodeType)) {
960             logger.debug("Instance Group tosca node type does not contain NetworkCollection:  {}", toscaNodeType);
961             return true;
962         }
963         return false;
964     }
965
966     private boolean interfaceNetworkQuantityIsAvailableInCollection(
967             CollectionResourceInstanceGroupCustomization collectionInstCust) {
968         return collectionInstCust != null && collectionInstCust.getSubInterfaceNetworkQuantity() != null;
969     }
970
971     private boolean toscaNodeTypeHasNetworkCollection(String toscaNodeType) {
972         return toscaNodeType != null && toscaNodeType.contains(NETWORKCOLLECTION);
973     }
974
975     private void traverseNetworkCollectionCustomization(List<Resource> resourceList,
976             org.onap.so.db.catalog.beans.Service service) {
977         if (isNetworkCollectionInTheResourceList(resourceList)) {
978             return;
979         }
980         if (service.getNetworkCustomizations() == null) {
981             logger.debug("No networks were found on this service model");
982             return;
983         }
984         for (int i = 0; i < service.getNetworkCustomizations().size(); i++) {
985             resourceList.add(new Resource(WorkflowType.NETWORK,
986                     service.getNetworkCustomizations().get(i).getModelCustomizationUUID(), false));
987         }
988     }
989
990     private boolean isNetworkCollectionInTheResourceList(List<Resource> resourceList) {
991         return resourceList.stream().anyMatch(x -> WorkflowType.NETWORKCOLLECTION == x.getResourceType());
992     }
993
994     private boolean isVnfCustomizationsInTheService(org.onap.so.db.catalog.beans.Service service) {
995         return !(service.getVnfCustomizations() == null || service.getVnfCustomizations().isEmpty());
996     }
997
998     private boolean isPnfCustomizationsInTheService(org.onap.so.db.catalog.beans.Service service) {
999         return !(service.getPnfCustomizations() == null || service.getPnfCustomizations().isEmpty());
1000     }
1001
1002     protected void traverseAAIService(DelegateExecution execution, List<Resource> resourceList, String resourceId,
1003             List<Pair<WorkflowType, String>> aaiResourceIds) {
1004         try {
1005             ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(resourceId);
1006             org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
1007                     bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
1008             resourceList.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false));
1009             traverseServiceInstanceMSOVnfs(resourceList, aaiResourceIds, serviceInstanceMSO);
1010             traverseServiceInstanceMSOPnfs(resourceList, aaiResourceIds, serviceInstanceMSO);
1011             if (serviceInstanceMSO.getNetworks() != null) {
1012                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.L3Network network : serviceInstanceMSO
1013                         .getNetworks()) {
1014                     aaiResourceIds.add(new Pair<>(WorkflowType.NETWORK, network.getNetworkId()));
1015                     resourceList.add(new Resource(WorkflowType.NETWORK, network.getNetworkId(), false));
1016                 }
1017             }
1018             if (serviceInstanceMSO.getCollection() != null) {
1019                 logger.debug("found networkcollection");
1020                 aaiResourceIds
1021                         .add(new Pair<>(WorkflowType.NETWORKCOLLECTION, serviceInstanceMSO.getCollection().getId()));
1022                 resourceList.add(new Resource(WorkflowType.NETWORKCOLLECTION,
1023                         serviceInstanceMSO.getCollection().getId(), false));
1024             }
1025             if (serviceInstanceMSO.getConfigurations() != null) {
1026                 for (Configuration config : serviceInstanceMSO.getConfigurations()) {
1027                     Optional<org.onap.aai.domain.yang.Configuration> aaiConfig =
1028                             aaiConfigurationResources.getConfiguration(config.getConfigurationId());
1029                     if (aaiConfig.isPresent() && aaiConfig.get().getRelationshipList() != null) {
1030                         for (Relationship relationship : aaiConfig.get().getRelationshipList().getRelationship()) {
1031                             if (relationship.getRelatedTo().contains("vnfc")
1032                                     || relationship.getRelatedTo().contains("vpn-binding")) {
1033                                 aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, config.getConfigurationId()));
1034                                 resourceList.add(
1035                                         new Resource(WorkflowType.CONFIGURATION, config.getConfigurationId(), false));
1036                                 break;
1037                             }
1038                         }
1039                     }
1040                 }
1041             }
1042         } catch (Exception ex) {
1043             logger.error("Exception in traverseAAIService", ex);
1044             buildAndThrowException(execution,
1045                     "Could not find existing Service Instance or related Instances to execute the request on.");
1046         }
1047     }
1048
1049     private void traverseServiceInstanceMSOVnfs(List<Resource> resourceList,
1050             List<Pair<WorkflowType, String>> aaiResourceIds,
1051             org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO) {
1052         if (serviceInstanceMSO.getVnfs() == null) {
1053             return;
1054         }
1055         for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) {
1056             aaiResourceIds.add(new Pair<>(WorkflowType.VNF, vnf.getVnfId()));
1057             resourceList.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false));
1058             traverseVnfModules(resourceList, aaiResourceIds, vnf);
1059             if (vnf.getVolumeGroups() != null) {
1060                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf.getVolumeGroups()) {
1061                     aaiResourceIds.add(new Pair<>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
1062                     resourceList.add(new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false));
1063                 }
1064             }
1065         }
1066     }
1067
1068     private void traverseServiceInstanceMSOPnfs(List<Resource> resourceList,
1069             List<Pair<WorkflowType, String>> aaiResourceIds,
1070             org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO) {
1071         if (serviceInstanceMSO.getPnfs() == null) {
1072             return;
1073         }
1074         for (org.onap.so.bpmn.servicedecomposition.bbobjects.Pnf pnf : serviceInstanceMSO.getPnfs()) {
1075             aaiResourceIds.add(new Pair<>(WorkflowType.PNF, pnf.getPnfId()));
1076             resourceList.add(new Resource(WorkflowType.PNF, pnf.getPnfId(), false));
1077         }
1078     }
1079
1080     private void traverseVnfModules(List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds,
1081             org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf) {
1082         if (vnf.getVfModules() == null) {
1083             return;
1084         }
1085         for (VfModule vfModule : vnf.getVfModules()) {
1086             aaiResourceIds.add(new Pair<>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
1087             Resource resource = new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false);
1088             resource.setBaseVfModule(vfModule.getModelInfoVfModule().getIsBaseBoolean());
1089             resourceList.add(resource);
1090         }
1091     }
1092
1093     private void traverseAAIVnf(DelegateExecution execution, List<Resource> resourceList, String serviceId,
1094             String vnfId, List<Pair<WorkflowType, String>> aaiResourceIds) {
1095         try {
1096             ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
1097             org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
1098                     bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
1099             resourceList.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false));
1100             if (serviceInstanceMSO.getVnfs() != null) {
1101                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) {
1102                     if (vnf.getVnfId().equals(vnfId)) {
1103                         aaiResourceIds.add(new Pair<>(WorkflowType.VNF, vnf.getVnfId()));
1104                         resourceList.add(new Resource(WorkflowType.VNF, vnf.getVnfId(), false));
1105                         if (vnf.getVfModules() != null) {
1106                             for (VfModule vfModule : vnf.getVfModules()) {
1107                                 aaiResourceIds.add(new Pair<>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
1108                                 resourceList.add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false));
1109                                 findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(),
1110                                         resourceList, aaiResourceIds);
1111                             }
1112                         }
1113                         if (vnf.getVolumeGroups() != null) {
1114                             for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
1115                                     .getVolumeGroups()) {
1116                                 aaiResourceIds
1117                                         .add(new Pair<>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
1118                                 resourceList.add(
1119                                         new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false));
1120                             }
1121                         }
1122                         break;
1123                     }
1124                 }
1125             }
1126         } catch (Exception ex) {
1127             logger.error("Exception in traverseAAIVnf", ex);
1128             buildAndThrowException(execution,
1129                     "Could not find existing Vnf or related Instances to execute the request on.");
1130         }
1131     }
1132
1133     private void customTraverseAAIVnf(DelegateExecution execution, List<Resource> resourceList, String serviceId,
1134             String vnfId, List<Pair<WorkflowType, String>> aaiResourceIds) {
1135         try {
1136             ServiceInstance serviceInstanceAAI = bbInputSetupUtils.getAAIServiceInstanceById(serviceId);
1137             org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance serviceInstanceMSO =
1138                     bbInputSetup.getExistingServiceInstance(serviceInstanceAAI);
1139             resourceList.add(new Resource(WorkflowType.SERVICE, serviceInstanceMSO.getServiceInstanceId(), false));
1140             if (serviceInstanceMSO.getVnfs() != null) {
1141                 for (org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf vnf : serviceInstanceMSO.getVnfs()) {
1142                     if (vnf.getVnfId().equals(vnfId)) {
1143                         aaiResourceIds.add(new Pair<>(WorkflowType.VNF, vnf.getVnfId()));
1144
1145                         String vnfCustomizationUUID =
1146                                 bbInputSetupUtils.getAAIGenericVnf(vnfId).getModelCustomizationId();
1147                         resourceList.add(new Resource(WorkflowType.VNF, vnfCustomizationUUID, false));
1148
1149                         if (vnf.getVfModules() != null) {
1150                             for (VfModule vfModule : vnf.getVfModules()) {
1151                                 aaiResourceIds.add(new Pair<>(WorkflowType.VFMODULE, vfModule.getVfModuleId()));
1152                                 resourceList.add(new Resource(WorkflowType.VFMODULE, vfModule.getVfModuleId(), false));
1153                                 findConfigurationsInsideVfModule(execution, vnf.getVnfId(), vfModule.getVfModuleId(),
1154                                         resourceList, aaiResourceIds);
1155                             }
1156                         }
1157                         if (vnf.getVolumeGroups() != null) {
1158                             for (org.onap.so.bpmn.servicedecomposition.bbobjects.VolumeGroup volumeGroup : vnf
1159                                     .getVolumeGroups()) {
1160                                 aaiResourceIds
1161                                         .add(new Pair<>(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId()));
1162                                 resourceList.add(
1163                                         new Resource(WorkflowType.VOLUMEGROUP, volumeGroup.getVolumeGroupId(), false));
1164                             }
1165                         }
1166                         break;
1167                     }
1168                 }
1169             }
1170         } catch (Exception ex) {
1171             logger.error("Exception in customTraverseAAIVnf", ex);
1172             buildAndThrowException(execution,
1173                     "Could not find existing Vnf or related Instances to execute the request on.");
1174         }
1175
1176     }
1177
1178     private void findConfigurationsInsideVfModule(DelegateExecution execution, String vnfId, String vfModuleId,
1179             List<Resource> resourceList, List<Pair<WorkflowType, String>> aaiResourceIds) {
1180         try {
1181             org.onap.aai.domain.yang.VfModule aaiVfModule = bbInputSetupUtils.getAAIVfModule(vnfId, vfModuleId);
1182             AAIResultWrapper vfModuleWrapper = new AAIResultWrapper(
1183                     new AAICommonObjectMapperProvider().getMapper().writeValueAsString(aaiVfModule));
1184             Optional<Relationships> relationshipsOp;
1185             relationshipsOp = vfModuleWrapper.getRelationships();
1186             if (relationshipsOp.isPresent()) {
1187                 relationshipsOp = workflowActionUtils.extractRelationshipsVnfc(relationshipsOp.get());
1188                 if (relationshipsOp.isPresent()) {
1189                     Optional<Configuration> config =
1190                             workflowActionUtils.extractRelationshipsConfiguration(relationshipsOp.get());
1191                     if (config.isPresent()) {
1192                         aaiResourceIds.add(new Pair<>(WorkflowType.CONFIGURATION, config.get().getConfigurationId()));
1193                         resourceList.add(
1194                                 new Resource(WorkflowType.CONFIGURATION, config.get().getConfigurationId(), false));
1195                     }
1196                 }
1197             }
1198         } catch (Exception ex) {
1199             logger.error("Exception in findConfigurationsInsideVfModule", ex);
1200             buildAndThrowException(execution, "Failed to find Configuration object from the vfModule.");
1201         }
1202     }
1203
1204     protected WorkflowResourceIds populateResourceIdsFromApiHandler(DelegateExecution execution) {
1205         return WorkflowResourceIdsUtils.getWorkflowResourceIdsFromExecution(execution);
1206     }
1207
1208     protected Resource extractResourceIdAndTypeFromUri(String uri) {
1209         Pattern patt = Pattern.compile("[vV]\\d+.*?(?:(?:/(?<type>" + SUPPORTEDTYPES
1210                 + ")(?:/(?<id>[^/]+))?)(?:/(?<action>[^/]+))?(?:/resume)?)?$");
1211         Matcher m = patt.matcher(uri);
1212         boolean generated = false;
1213
1214         if (m.find()) {
1215             logger.debug("found match on {} : {} ", uri, m);
1216             String type = m.group("type");
1217             String id = m.group("id");
1218             String action = m.group("action");
1219             if (type == null) {
1220                 throw new IllegalArgumentException("Uri could not be parsed. No type found. " + uri);
1221             }
1222             if (action == null) {
1223                 if (type.equals(SERVICE_INSTANCES) && (id == null || "assign".equals(id))) {
1224                     id = UUID.randomUUID().toString();
1225                     generated = true;
1226                 } else if (type.equals(VF_MODULES) && "scaleOut".equals(id)) {
1227                     id = UUID.randomUUID().toString();
1228                     generated = true;
1229                 }
1230             } else {
1231                 if (action.matches(SUPPORTEDTYPES)) {
1232                     id = UUID.randomUUID().toString();
1233                     generated = true;
1234                     type = action;
1235                 }
1236             }
1237             return new Resource(WorkflowType.fromString(convertTypeFromPlural(type)), id, generated);
1238         } else {
1239             throw new IllegalArgumentException("Uri could not be parsed: " + uri);
1240         }
1241     }
1242
1243     protected String convertTypeFromPlural(String type) {
1244         if (!type.matches(SUPPORTEDTYPES)) {
1245             return type;
1246         } else {
1247             if (type.equals(SERVICE_INSTANCES)) {
1248                 return SERVICE;
1249             } else {
1250                 return type.substring(0, 1).toUpperCase() + type.substring(1, type.length() - 1);
1251             }
1252         }
1253     }
1254
1255     protected List<ExecuteBuildingBlock> sortExecutionPathByObjectForVlanTagging(List<ExecuteBuildingBlock> orchFlows,
1256             String requestAction) {
1257         List<ExecuteBuildingBlock> sortedOrchFlows = new ArrayList<>();
1258         if (requestAction.equals(CREATE_INSTANCE)) {
1259             for (ExecuteBuildingBlock ebb : orchFlows) {
1260                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("AssignNetworkBB")) {
1261                     String key = ebb.getBuildingBlock().getKey();
1262                     boolean isVirtualLink = Boolean.TRUE.equals(ebb.getBuildingBlock().isVirtualLink());
1263                     String virtualLinkKey = ebb.getBuildingBlock().getVirtualLinkKey();
1264                     sortedOrchFlows.add(ebb);
1265                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
1266                         if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
1267                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
1268                             sortedOrchFlows.add(ebb2);
1269                             break;
1270                         }
1271                         if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
1272                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
1273                             sortedOrchFlows.add(ebb2);
1274                             break;
1275                         }
1276                     }
1277                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
1278                         if (!isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)
1279                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
1280                             sortedOrchFlows.add(ebb2);
1281                             break;
1282                         }
1283                         if (isVirtualLink && ebb2.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)
1284                                 && ebb2.getBuildingBlock().getVirtualLinkKey().equalsIgnoreCase(virtualLinkKey)) {
1285                             sortedOrchFlows.add(ebb2);
1286                             break;
1287                         }
1288                     }
1289                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals(CREATENETWORKBB)
1290                         || ebb.getBuildingBlock().getBpmnFlowName().equals(ACTIVATENETWORKBB)) {
1291                     continue;
1292                 } else if (!"".equals(ebb.getBuildingBlock().getBpmnFlowName())) {
1293                     sortedOrchFlows.add(ebb);
1294                 }
1295             }
1296         } else if (requestAction.equals("deleteInstance")) {
1297             for (ExecuteBuildingBlock ebb : orchFlows) {
1298                 if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeactivateNetworkBB")) {
1299                     sortedOrchFlows.add(ebb);
1300                     String key = ebb.getBuildingBlock().getKey();
1301                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
1302                         if (ebb2.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
1303                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
1304                             sortedOrchFlows.add(ebb2);
1305                             break;
1306                         }
1307                     }
1308                     for (ExecuteBuildingBlock ebb2 : orchFlows) {
1309                         if (ebb2.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")
1310                                 && ebb2.getBuildingBlock().getKey().equalsIgnoreCase(key)) {
1311                             sortedOrchFlows.add(ebb2);
1312                             break;
1313                         }
1314                     }
1315                 } else if (ebb.getBuildingBlock().getBpmnFlowName().equals("DeleteNetworkBB")
1316                         || ebb.getBuildingBlock().getBpmnFlowName().equals("UnassignNetworkBB")) {
1317                     continue;
1318                 } else if (!ebb.getBuildingBlock().getBpmnFlowName().equals("")) {
1319                     sortedOrchFlows.add(ebb);
1320                 }
1321             }
1322         }
1323         return sortedOrchFlows;
1324     }
1325
1326     protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
1327             WorkflowType resourceName, boolean aLaCarte, String cloudOwner) {
1328         return this.queryNorthBoundRequestCatalogDb(execution, requestAction, resourceName, aLaCarte, cloudOwner, "");
1329     }
1330
1331     protected List<OrchestrationFlow> queryNorthBoundRequestCatalogDb(DelegateExecution execution, String requestAction,
1332             WorkflowType resourceName, boolean aLaCarte, String cloudOwner, String serviceType) {
1333         List<OrchestrationFlow> listToExecute = new ArrayList<>();
1334         NorthBoundRequest northBoundRequest;
1335         if (serviceType.equalsIgnoreCase(SERVICE_TYPE_TRANSPORT)
1336                 || serviceType.equalsIgnoreCase(SERVICE_TYPE_BONDING)) {
1337             northBoundRequest =
1338                     catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwnerAndServiceType(
1339                             requestAction, resourceName.toString(), aLaCarte, cloudOwner, serviceType);
1340         } else {
1341             northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
1342                     requestAction, resourceName.toString(), aLaCarte, cloudOwner);
1343         }
1344         if (northBoundRequest == null) {
1345             northBoundRequest = catalogDbClient.getNorthBoundRequestByActionAndIsALaCarteAndRequestScopeAndCloudOwner(
1346                     requestAction, resourceName.toString(), aLaCarte, CLOUD_OWNER);
1347         }
1348         if (northBoundRequest == null) {
1349             buildAndThrowException(execution, String.format("The request: %s %s %s is not supported by GR_API.",
1350                     (aLaCarte ? "AlaCarte" : "Macro"), resourceName, requestAction));
1351         } else {
1352             if (northBoundRequest.getIsToplevelflow() != null) {
1353                 execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, northBoundRequest.getIsToplevelflow());
1354             }
1355             List<OrchestrationFlow> flows = northBoundRequest.getOrchestrationFlowList();
1356             if (flows == null) {
1357                 flows = new ArrayList<>();
1358             } else {
1359                 flows.sort(Comparator.comparingInt(OrchestrationFlow::getSequenceNumber));
1360             }
1361             for (OrchestrationFlow flow : flows) {
1362                 if (!flow.getFlowName().contains("BB") && !flow.getFlowName().contains("Activity")) {
1363                     List<OrchestrationFlow> macroQueryFlows =
1364                             catalogDbClient.getOrchestrationFlowByAction(flow.getFlowName());
1365                     listToExecute.addAll(macroQueryFlows);
1366                 } else {
1367                     listToExecute.add(flow);
1368                 }
1369             }
1370         }
1371         return listToExecute;
1372     }
1373
1374     public void handleRuntimeException(DelegateExecution execution) {
1375         StringBuilder wfeExpMsg = new StringBuilder("Runtime error ");
1376         String runtimeErrorMessage;
1377         try {
1378             String javaExpMsg = (String) execution.getVariable("BPMN_javaExpMsg");
1379             if (javaExpMsg != null && !javaExpMsg.isEmpty()) {
1380                 wfeExpMsg.append(": ").append(javaExpMsg);
1381             }
1382             runtimeErrorMessage = wfeExpMsg.toString();
1383             logger.error(runtimeErrorMessage);
1384             execution.setVariable(WORKFLOW_ACTION_ERROR_MESSAGE, runtimeErrorMessage);
1385         } catch (Exception e) {
1386             logger.error("Runtime error", e);
1387             // if runtime message was mulformed
1388             runtimeErrorMessage = "Runtime error";
1389         }
1390         exceptionBuilder.buildAndThrowWorkflowException(execution, 7000, runtimeErrorMessage);
1391     }
1392
1393     protected boolean isUriResume(String uri) {
1394         return uri.endsWith("/resume");
1395     }
1396
1397     protected boolean isRequestMacroServiceResume(boolean aLaCarte, WorkflowType resourceType, String requestAction,
1398             String serviceInstanceId) {
1399         return (!aLaCarte && resourceType == WorkflowType.SERVICE
1400                 && (requestAction.equalsIgnoreCase(ASSIGNINSTANCE) || requestAction.equalsIgnoreCase(CREATE_INSTANCE))
1401                 && (serviceInstanceId != null && serviceInstanceId.trim().length() > 1)
1402                 && (bbInputSetupUtils.getAAIServiceInstanceById(serviceInstanceId) != null));
1403     }
1404
1405     protected boolean foundRelated(List<Resource> resourceList) {
1406         return (containsWorkflowType(resourceList, WorkflowType.VNF)
1407                 || containsWorkflowType(resourceList, WorkflowType.PNF)
1408                 || containsWorkflowType(resourceList, WorkflowType.NETWORK)
1409                 || containsWorkflowType(resourceList, WorkflowType.NETWORKCOLLECTION));
1410     }
1411
1412     protected boolean containsWorkflowType(List<Resource> resourceList, WorkflowType workflowType) {
1413         return resourceList.stream().anyMatch(resource -> resource.getResourceType().equals(workflowType));
1414     }
1415
1416     private void fillExecutionDefault(DelegateExecution execution) {
1417         execution.setVariable("sentSyncResponse", false);
1418         execution.setVariable(HOMING, false);
1419         execution.setVariable("calledHoming", false);
1420         execution.setVariable(BBConstants.G_ISTOPLEVELFLOW, true);
1421     }
1422
1423     private void fillExecution(DelegateExecution execution, boolean suppressRollback, String resourceId,
1424             WorkflowType resourceType) {
1425         execution.setVariable("suppressRollback", suppressRollback);
1426         execution.setVariable("resourceId", resourceId);
1427         execution.setVariable("resourceType", resourceType);
1428         execution.setVariable("resourceName", resourceType.toString());
1429     }
1430
1431     private Resource getResource(BBInputSetupUtils bbInputSetupUtils, boolean isResume, boolean alaCarte, String uri,
1432             String requestId) {
1433         if (!alaCarte && isResume) {
1434             logger.debug("replacing URI {}", uri);
1435             uri = bbInputSetupUtils.loadOriginalInfraActiveRequestById(requestId).getRequestUrl();
1436             logger.debug("for RESUME with original value {}", uri);
1437         }
1438         return extractResourceIdAndTypeFromUri(uri);
1439     }
1440
1441     private String getResourceId(Resource resource, String requestAction, RequestDetails requestDetails,
1442             WorkflowResourceIds workflowResourceIds) throws Exception {
1443         if (resource.isGenerated() && requestAction.equalsIgnoreCase("createInstance")
1444                 && requestDetails.getRequestInfo().getInstanceName() != null) {
1445             return aaiResourceIdValidator.validateResourceIdInAAI(resource.getResourceId(), resource.getResourceType(),
1446                     requestDetails.getRequestInfo().getInstanceName(), requestDetails, workflowResourceIds);
1447         } else {
1448             return resource.getResourceId();
1449         }
1450     }
1451
1452     private String getServiceInstanceId(DelegateExecution execution, String resourceId, WorkflowType resourceType) {
1453         String serviceInstanceId = (String) execution.getVariable("serviceInstanceId");
1454         if ((serviceInstanceId == null || serviceInstanceId.isEmpty()) && WorkflowType.SERVICE.equals(resourceType)) {
1455             serviceInstanceId = resourceId;
1456         }
1457         return serviceInstanceId;
1458     }
1459
1460 }