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