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