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