Merge "Bug fix for Multi-result row data order"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / RequestHandlerUtils.java
index dc38d4e..0c6ad0b 100644 (file)
@@ -56,13 +56,22 @@ import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
 import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
 import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
 import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
+import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
 import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException;
 import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler;
 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
 import org.onap.so.constants.Status;
+import org.onap.so.db.catalog.beans.NetworkResource;
+import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
+import org.onap.so.db.catalog.beans.Recipe;
+import org.onap.so.db.catalog.beans.ServiceRecipe;
 import org.onap.so.db.catalog.beans.VfModule;
+import org.onap.so.db.catalog.beans.VfModuleCustomization;
+import org.onap.so.db.catalog.beans.VnfRecipe;
+import org.onap.so.db.catalog.beans.VnfResource;
+import org.onap.so.db.catalog.beans.VnfResourceCustomization;
 import org.onap.so.db.catalog.client.CatalogDbClient;
 import org.onap.so.db.request.beans.InfraActiveRequests;
 import org.onap.so.db.request.client.RequestsDbClient;
@@ -70,13 +79,19 @@ import org.onap.so.exceptions.ValidationException;
 import org.onap.so.logger.ErrorCode;
 import org.onap.so.logger.LogConstants;
 import org.onap.so.logger.MessageEnum;
+import org.onap.so.serviceinstancebeans.CloudConfiguration;
 import org.onap.so.serviceinstancebeans.ModelInfo;
 import org.onap.so.serviceinstancebeans.ModelType;
+import org.onap.so.serviceinstancebeans.Networks;
 import org.onap.so.serviceinstancebeans.RelatedInstance;
 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
+import org.onap.so.serviceinstancebeans.RequestDetails;
 import org.onap.so.serviceinstancebeans.RequestParameters;
+import org.onap.so.serviceinstancebeans.Service;
 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
+import org.onap.so.serviceinstancebeans.VfModules;
+import org.onap.so.serviceinstancebeans.Vnfs;
 import org.onap.so.utils.UUIDChecker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -94,7 +109,9 @@ public class RequestHandlerUtils extends AbstractRestHandler {
 
     private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
 
-    private static final String SAVE_TO_DB = "save instance to db";
+    protected static final String SAVE_TO_DB = "save instance to db";
+    private static final String NAME = "name";
+    private static final String VALUE = "value";
 
     @Autowired
     private Environment env;
@@ -102,9 +119,6 @@ public class RequestHandlerUtils extends AbstractRestHandler {
     @Autowired
     private RequestClientFactory reqClientFactory;
 
-    @Autowired
-    private RequestsDbClient infraActiveRequestsClient;
-
     @Autowired
     private ResponseBuilder builder;
 
@@ -119,13 +133,14 @@ public class RequestHandlerUtils extends AbstractRestHandler {
 
     public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
             String orchestrationUri, String requestScope) throws ApiException {
-        RequestClient requestClient = null;
         HttpResponse response = null;
+        RequestClient requestClient = null;
+
         try {
             requestClient = reqClientFactory.getRequestClient(orchestrationUri);
             response = requestClient.post(requestClientParameter);
         } catch (Exception e) {
-
+            logger.error("Error posting request to BPMN", e);
             ErrorLoggerInfo errorLoggerInfo =
                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
@@ -134,19 +149,17 @@ public class RequestHandlerUtils extends AbstractRestHandler {
                     new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY,
                             ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
             updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
-
             throw clientException;
         }
 
         if (response == null) {
 
-            ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
-                    ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+            ErrorLoggerInfo errorLoggerInfo =
+                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError)
+                            .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
             ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
                     HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
-
             updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
-
             throw clientException;
         }
 
@@ -208,7 +221,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
 
             ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
                             .errorSource(requestClient.getUrl()).build();
             BPMNFailureException bpmnException =
                     new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
@@ -220,7 +233,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         } else {
 
             ErrorLoggerInfo errorLoggerInfo =
-                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
+                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
                             .errorSource(requestClient.getUrl()).build();
 
 
@@ -232,6 +245,9 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         }
     }
 
+
+
+    @Override
     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
             throws RequestDbFailureException {
         if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
@@ -259,12 +275,18 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         } else if (action == Action.addMembers || action == Action.removeMembers) {
             return (ModelType.instanceGroup.toString());
         } else {
-            String requestScope;
+            String requestScope = requestScopeFromUri(requestUri);;
+
+            if (sir.getRequestDetails() == null) {
+                return requestScope;
+            }
+            if (sir.getRequestDetails().getModelInfo() == null) {
+                return requestScope;
+            }
             if (sir.getRequestDetails().getModelInfo().getModelType() == null) {
-                requestScope = requestScopeFromUri(requestUri);
-            } else {
-                requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
+                return requestScope;
             }
+            requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
             return requestScope;
         }
     }
@@ -291,6 +313,22 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         return requestUri;
     }
 
+    public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope,
+            InfraActiveRequests currentActiveReq, String instanceName) throws ApiException {
+        InfraActiveRequests dup = null;
+        boolean inProgress = false;
+
+        dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
+
+        if (dup != null) {
+            inProgress = camundaHistoryCheck(dup, currentActiveReq);
+        }
+
+        if (dup != null && inProgress) {
+            buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup);
+        }
+    }
+
     public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
         InfraActiveRequests dup = null;
@@ -318,7 +356,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         String requestId = duplicateRecord.getRequestId();
         ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
         try {
-            response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId);
+            response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true);
         } catch (RestClientException e) {
             logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}",
                     requestId, e.getMessage());
@@ -412,6 +450,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         throw dupException;
     }
 
+    @Override
     public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
         String requestId = null;
         if (requestContext.getProperty("requestId") != null) {
@@ -472,6 +511,9 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
                 currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
             }
+            if (instanceIdMap.get("PnfId") != null) {
+                currentActiveReq.setPnfId(instanceIdMap.get("PnfId"));
+            }
         }
     }
 
@@ -577,6 +619,8 @@ public class RequestHandlerUtils extends AbstractRestHandler {
             requestScope = ModelType.configuration.name();
         } else if (requestUri.contains(ModelType.vnf.name())) {
             requestScope = ModelType.vnf.name();
+        } else if (requestUri.contains(ModelType.pnf.name())) {
+            requestScope = ModelType.pnf.name();
         } else {
             requestScope = ModelType.service.name();
         }
@@ -599,7 +643,7 @@ public class RequestHandlerUtils extends AbstractRestHandler {
         if (infraActiveRequest != null) {
             request.setTenantId(infraActiveRequest.getTenantId());
             request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId));
-            request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion());
+            request.setCloudRegion(infraActiveRequest.getCloudRegion());
             request.setRequestScope(infraActiveRequest.getRequestScope());
             request.setRequestAction(infraActiveRequest.getRequestAction());
             setInstanceIdAndName(infraActiveRequest, request);
@@ -686,4 +730,567 @@ public class RequestHandlerUtils extends AbstractRestHandler {
                 "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))",
                 "$1" + newRequestorId + "$3");
     }
+
+    public RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
+            boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException {
+        RecipeLookupResult recipeLookupResult = null;
+        // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
+        ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+        // Query MSO Catalog DB
+
+        if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
+            recipeLookupResult = getDefaultVnfUri(sir, action);
+        } else if (action == Action.addMembers || action == Action.removeMembers) {
+            recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
+        } else if (modelInfo.getModelType().equals(ModelType.service)) {
+            try {
+                recipeLookupResult = getServiceURI(sir, action, alaCarteFlag);
+            } catch (IOException e) {
+                ErrorLoggerInfo errorLoggerInfo =
+                        new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+                                .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+                ValidateException validateException =
+                        new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+                                ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+
+                updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+
+                throw validateException;
+            }
+        } else if (modelInfo.getModelType().equals(ModelType.vfModule)
+                || modelInfo.getModelType().equals(ModelType.volumeGroup)
+                || modelInfo.getModelType().equals(ModelType.vnf)) {
+            try {
+                recipeLookupResult = getVnfOrVfModuleUri(sir, action);
+            } catch (ValidationException e) {
+                ErrorLoggerInfo errorLoggerInfo =
+                        new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+                                .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+                ValidateException validateException =
+                        new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+                                ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+
+                updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+
+                throw validateException;
+            }
+        } else if (modelInfo.getModelType().equals(ModelType.network)) {
+            try {
+                recipeLookupResult = getNetworkUri(sir, action);
+            } catch (ValidationException e) {
+
+                ErrorLoggerInfo errorLoggerInfo =
+                        new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
+                                .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+                ValidateException validateException =
+                        new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
+                                ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
+                updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
+
+                throw validateException;
+            }
+        } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
+            recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
+        }
+
+        if (recipeLookupResult == null) {
+            ErrorLoggerInfo errorLoggerInfo =
+                    new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
+                            .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
+
+
+            RecipeNotFoundException recipeNotFoundExceptionException =
+                    new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
+                            HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
+                                    .build();
+
+            updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
+            throw recipeNotFoundExceptionException;
+        }
+        return recipeLookupResult;
+    }
+
+    protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
+            boolean alaCarteFlag) throws IOException {
+        // SERVICE REQUEST
+        // Construct the default service name
+        // TODO need to make this a configurable property
+        String defaultServiceModelName = getDefaultModel(servInstReq);
+        RequestDetails requestDetails = servInstReq.getRequestDetails();
+        ModelInfo modelInfo = requestDetails.getModelInfo();
+        org.onap.so.db.catalog.beans.Service serviceRecord;
+        List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
+        ServiceRecipe recipe = null;
+
+        if (alaCarteFlag) {
+            serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+            if (serviceRecord != null) {
+                recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
+                        action.toString());
+            }
+        } else {
+            serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
+            recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
+                    action.toString());
+            if (recipe == null) {
+                serviceRecordList = catalogDbClient
+                        .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
+                if (!serviceRecordList.isEmpty()) {
+                    for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
+                        recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
+                                action.toString());
+                        if (recipe != null) {
+                            break;
+                        }
+                    }
+                }
+            }
+        }
+
+        // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
+        RequestParameters reqParam = requestDetails.getRequestParameters();
+        if (reqParam != null && alaCarteFlag && recipe == null) {
+            return null;
+        } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
+            mapToLegacyRequest(requestDetails);
+        } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
+            serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
+            recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
+                    action.toString());
+        }
+        if (modelInfo.getModelVersionId() == null) {
+            modelInfo.setModelVersionId(serviceRecord.getModelUUID());
+        }
+        if (recipe == null) {
+            return null;
+        }
+        return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
+    }
+
+    protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
+        RequestParameters reqParam;
+        if (requestDetails.getRequestParameters() == null) {
+            reqParam = new RequestParameters();
+        } else {
+            reqParam = requestDetails.getRequestParameters();
+        }
+        if (requestDetails.getCloudConfiguration() == null) {
+            CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
+            if (cloudConfig != null) {
+                requestDetails.setCloudConfiguration(cloudConfig);
+            }
+        }
+
+        List<Map<String, Object>> userParams = configureUserParams(reqParam);
+        if (!userParams.isEmpty()) {
+            if (reqParam == null) {
+                requestDetails.setRequestParameters(new RequestParameters());
+            }
+            requestDetails.getRequestParameters().setUserParams(userParams);
+        }
+    }
+
+    private Service serviceMapper(Map<String, Object> params) throws IOException {
+        ObjectMapper obj = new ObjectMapper();
+        String input = obj.writeValueAsString(params.get("service"));
+        return obj.readValue(input, Service.class);
+    }
+
+    private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
+        for (Map<String, String> map : sourceUserParams) {
+            for (Map.Entry<String, String> entry : map.entrySet()) {
+                targetUserParams.put(entry.getKey(), entry.getValue());
+            }
+        }
+    }
+
+    protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
+        logger.debug("Configuring UserParams for Macro Request");
+        Map<String, Object> userParams = new HashMap<>();
+
+        for (Map<String, Object> params : reqParams.getUserParams()) {
+            if (params.containsKey("service")) {
+                Service service = serviceMapper(params);
+
+                addUserParams(userParams, service.getInstanceParams());
+
+                for (Networks network : service.getResources().getNetworks()) {
+                    addUserParams(userParams, network.getInstanceParams());
+                }
+
+                for (Vnfs vnf : service.getResources().getVnfs()) {
+                    addUserParams(userParams, vnf.getInstanceParams());
+
+                    for (VfModules vfModule : vnf.getVfModules()) {
+                        addUserParams(userParams, vfModule.getInstanceParams());
+                    }
+                }
+            }
+        }
+
+        return mapFlatMapToNameValue(userParams);
+    }
+
+    protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
+        List<Map<String, Object>> targetUserParams = new ArrayList<>();
+
+        for (Map.Entry<String, Object> map : flatMap.entrySet()) {
+            Map<String, Object> targetMap = new HashMap<>();
+            targetMap.put(NAME, map.getKey());
+            targetMap.put(VALUE, map.getValue());
+            targetUserParams.add(targetMap);
+        }
+        return targetUserParams;
+    }
+
+    protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
+
+        for (Map<String, Object> params : reqParams.getUserParams()) {
+            if (params.containsKey("service")) {
+                Service service = serviceMapper(params);
+
+                Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
+
+                if (targetConfiguration.isPresent()) {
+                    return targetConfiguration.get();
+                } else {
+                    for (Networks network : service.getResources().getNetworks()) {
+                        targetConfiguration = addCloudConfig(network.getCloudConfiguration());
+                        if (targetConfiguration.isPresent()) {
+                            return targetConfiguration.get();
+                        }
+                    }
+
+                    for (Vnfs vnf : service.getResources().getVnfs()) {
+                        targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
+
+                        if (targetConfiguration.isPresent()) {
+                            return targetConfiguration.get();
+                        }
+
+                        for (VfModules vfModule : vnf.getVfModules()) {
+                            targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
+
+                            if (targetConfiguration.isPresent()) {
+                                return targetConfiguration.get();
+                            }
+                        }
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
+    private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
+        String defaultSource = getDefaultModel(sir);
+        VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+        if (vnfRecipe == null) {
+            return null;
+        }
+        return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
+    }
+
+
+    private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
+        String defaultNetworkType = getDefaultModel(sir);
+        ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
+        String modelName = modelInfo.getModelName();
+        Recipe recipe = null;
+
+        if (modelInfo.getModelCustomizationId() != null) {
+            NetworkResourceCustomization networkResourceCustomization = catalogDbClient
+                    .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
+            if (networkResourceCustomization != null) {
+                NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
+                if (networkResource != null) {
+                    if (modelInfo.getModelVersionId() == null) {
+                        modelInfo.setModelVersionId(networkResource.getModelUUID());
+                    }
+                    recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
+                            action.toString());
+                } else {
+                    throw new ValidationException("no catalog entry found");
+                }
+            } else if (action != Action.deleteInstance) {
+                throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
+            }
+        } else {
+            // ok for version < 3 and action delete
+            if (modelName != null) {
+                recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
+            }
+        }
+
+        if (recipe == null) {
+            recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
+        }
+
+        return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
+    }
+
+
+    private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
+        CloudConfiguration targetConfiguration = new CloudConfiguration();
+        if (sourceCloudConfiguration != null) {
+            targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
+            targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
+            targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
+            targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
+            return Optional.of(targetConfiguration);
+        }
+        return Optional.empty();
+    }
+
+    private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
+            throws ValidationException {
+
+        ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
+        String vnfComponentType = modelInfo.getModelType().name();
+
+        RelatedInstanceList[] instanceList = null;
+        if (servInstReq.getRequestDetails() != null) {
+            instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
+        }
+
+        Recipe recipe;
+        String defaultSource = getDefaultModel(servInstReq);
+        String modelCustomizationId = modelInfo.getModelCustomizationId();
+        String modelCustomizationName = modelInfo.getModelCustomizationName();
+        String relatedInstanceModelVersionId = null;
+        String relatedInstanceModelInvariantId = null;
+        String relatedInstanceVersion = null;
+        String relatedInstanceModelCustomizationName = null;
+
+        if (instanceList != null) {
+
+            for (RelatedInstanceList relatedInstanceList : instanceList) {
+
+                RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
+                ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
+                if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
+                    relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
+                    relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
+                }
+
+                if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
+                    relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
+                    relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
+                    relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
+                    relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
+                }
+            }
+
+            if (modelInfo.getModelType().equals(ModelType.vnf)) {
+                // a. For a vnf request (only create, no update currently):
+                // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
+                // vnf_resource_customization.model_customization_uuid.
+                // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
+                // pre-v3), then modelInfo.modelCustomizationName must have
+                // been provided (else create request should be rejected). APIH should use the
+                // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
+                // to â€œjoinâ€�? service_to_resource_customizations with vnf_resource_customization to confirm a
+                // vnf_resource_customization.model_customization_uuid record exists.
+                // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
+                // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
+                // (MODEL_UUID) in SERVICE table.
+                // iii. Regardless of how the value was provided/obtained above, APIH must always populate
+                // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
+                // during 1707 data migration if VID did not provide it originally on request.
+                // iv. Note: continue to construct the â€œvnf-typeâ€�? value and pass to BPMN (must still be populated
+                // in A&AI).
+                // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
+                // look it up in our catalog to construct vnf-type value to pass to BPMN.
+
+                VnfResource vnfResource = null;
+                VnfResourceCustomization vrc = null;
+                // Validation for vnfResource
+
+                if (modelCustomizationId != null) {
+                    vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
+                    if (vrc != null) {
+                        vnfResource = vrc.getVnfResources();
+                    }
+                } else {
+                    org.onap.so.db.catalog.beans.Service service =
+                            catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
+                    if (service == null) {
+                        service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
+                                relatedInstanceModelInvariantId);
+                    }
+
+                    if (service == null) {
+                        throw new ValidationException("service in relatedInstance");
+                    }
+                    for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
+                        if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
+                            vrc = vnfResourceCustom;
+                        }
+                    }
+
+                    if (vrc != null) {
+                        vnfResource = vrc.getVnfResources();
+                        modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
+                        modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
+                    }
+                }
+
+                if (vnfResource == null) {
+                    throw new ValidationException("vnfResource");
+                } else {
+                    if (modelInfo.getModelVersionId() == null) {
+                        modelInfo.setModelVersionId(vnfResource.getModelUUID());
+                    }
+                }
+
+                VnfRecipe vnfRecipe = null;
+
+                if (vrc != null) {
+                    String nfRole = vrc.getNfRole();
+                    if (nfRole != null) {
+                        vnfRecipe =
+                                catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
+                    }
+                }
+
+                if (vnfRecipe == null) {
+                    vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+                }
+
+                if (vnfRecipe == null) {
+                    return null;
+                }
+
+                return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
+            } else {
+                /*
+                 * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
+                 * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
+                 * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
+                 * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
+                 * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
+                 * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
+                 * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
+                 * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
+                 * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
+                 * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
+                 * the request). This means taking each record found // in vf_module_customization and looking up in
+                 * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
+                 * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
+                 */
+                VfModuleCustomization vfmc = null;
+                VnfResource vnfr;
+                VnfResourceCustomization vnfrc;
+                VfModule vfModule = null;
+
+                if (modelInfo.getModelCustomizationId() != null) {
+                    vfmc = catalogDbClient
+                            .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
+                } else {
+                    vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
+                    if (vnfr == null) {
+                        vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
+                                relatedInstanceModelInvariantId, relatedInstanceVersion);
+                    }
+                    vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
+                            relatedInstanceModelCustomizationName, vnfr);
+
+                    List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
+
+                    String vfModuleModelUUID = modelInfo.getModelVersionId();
+                    for (VfModuleCustomization vf : list) {
+                        VfModuleCustomization vfmCustom;
+                        if (vfModuleModelUUID != null) {
+                            vfmCustom = catalogDbClient
+                                    .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
+                                            vf.getModelCustomizationUUID(), vfModuleModelUUID);
+                            if (vfmCustom != null) {
+                                vfModule = vfmCustom.getVfModule();
+                            }
+                        } else {
+                            vfmCustom = catalogDbClient
+                                    .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
+                            if (vfmCustom != null) {
+                                vfModule = vfmCustom.getVfModule();
+                            } else {
+                                vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
+                                        relatedInstanceModelInvariantId, relatedInstanceVersion);
+                            }
+                        }
+
+                        if (vfModule != null) {
+                            modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
+                            modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
+                            break;
+                        }
+                    }
+                }
+
+                if (vfmc == null && vfModule == null) {
+                    throw new ValidationException("vfModuleCustomization");
+                } else if (vfModule == null && vfmc != null) {
+                    vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
+                                                   // VfModuleCustomization table
+                }
+
+                if (modelInfo.getModelVersionId() == null) {
+                    modelInfo.setModelVersionId(vfModule.getModelUUID());
+                }
+
+
+                recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+                        vfModule.getModelUUID(), vnfComponentType, action.toString());
+                if (recipe == null) {
+                    List<VfModule> vfModuleRecords = catalogDbClient
+                            .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
+                    if (!vfModuleRecords.isEmpty()) {
+                        for (VfModule record : vfModuleRecords) {
+                            recipe = catalogDbClient
+                                    .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+                                            record.getModelUUID(), vnfComponentType, action.toString());
+                            if (recipe != null) {
+                                break;
+                            }
+                        }
+                    }
+                }
+                if (recipe == null) {
+                    recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+                            defaultSource, vnfComponentType, action.toString());
+                    if (recipe == null) {
+                        recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
+                                vnfComponentType, action.toString());
+                    }
+
+                    if (recipe == null) {
+                        return null;
+                    }
+                }
+            }
+        } else {
+
+            if (modelInfo.getModelType().equals(ModelType.vnf)) {
+                recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
+                if (recipe == null) {
+                    return null;
+                }
+            } else {
+                recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
+                        defaultSource, vnfComponentType, action.toString());
+
+                if (recipe == null) {
+                    return null;
+                }
+            }
+        }
+
+        return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
+    }
 }