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