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