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