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