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