2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 
   6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
 
   7  * Modifications Copyright (C) 2019 IBM.
 
   8  * ================================================================================
 
   9  * Modifications Copyright (c) 2019 Samsung
 
  10  * ================================================================================
 
  11  * Licensed under the Apache License, Version 2.0 (the "License");
 
  12  * you may not use this file except in compliance with the License.
 
  13  * You may obtain a copy of the License at
 
  15  *      http://www.apache.org/licenses/LICENSE-2.0
 
  17  * Unless required by applicable law or agreed to in writing, software
 
  18  * distributed under the License is distributed on an "AS IS" BASIS,
 
  19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
  20  * See the License for the specific language governing permissions and
 
  21  * limitations under the License.
 
  22  * ============LICENSE_END=========================================================
 
  25 package org.onap.so.apihandlerinfra;
 
  28 import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
 
  29 import java.io.IOException;
 
  31 import java.sql.Timestamp;
 
  32 import java.util.ArrayList;
 
  33 import java.util.HashMap;
 
  34 import java.util.List;
 
  36 import java.util.Optional;
 
  37 import javax.ws.rs.container.ContainerRequestContext;
 
  38 import javax.ws.rs.core.MultivaluedMap;
 
  39 import javax.ws.rs.core.Response;
 
  40 import org.apache.commons.lang.StringUtils;
 
  41 import org.apache.http.HttpResponse;
 
  42 import org.apache.http.HttpStatus;
 
  43 import org.camunda.bpm.engine.history.HistoricProcessInstance;
 
  44 import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
 
  45 import org.onap.logging.ref.slf4j.ONAPLogConstants;
 
  46 import org.onap.so.apihandler.camundabeans.CamundaResponse;
 
  47 import org.onap.so.apihandler.common.CommonConstants;
 
  48 import org.onap.so.apihandler.common.ErrorNumbers;
 
  49 import org.onap.so.apihandler.common.RequestClient;
 
  50 import org.onap.so.apihandler.common.RequestClientFactory;
 
  51 import org.onap.so.apihandler.common.RequestClientParameter;
 
  52 import org.onap.so.apihandler.common.ResponseBuilder;
 
  53 import org.onap.so.apihandler.common.ResponseHandler;
 
  54 import org.onap.so.apihandlerinfra.exceptions.ApiException;
 
  55 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
 
  56 import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
 
  57 import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
 
  58 import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
 
  59 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
 
  60 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
 
  61 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
 
  62 import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException;
 
  63 import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler;
 
  64 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
 
  65 import org.onap.so.constants.Status;
 
  66 import org.onap.so.db.catalog.beans.NetworkResource;
 
  67 import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
 
  68 import org.onap.so.db.catalog.beans.Recipe;
 
  69 import org.onap.so.db.catalog.beans.ServiceRecipe;
 
  70 import org.onap.so.db.catalog.beans.VfModule;
 
  71 import org.onap.so.db.catalog.beans.VfModuleCustomization;
 
  72 import org.onap.so.db.catalog.beans.VnfRecipe;
 
  73 import org.onap.so.db.catalog.beans.VnfResource;
 
  74 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
 
  75 import org.onap.so.db.catalog.client.CatalogDbClient;
 
  76 import org.onap.so.db.request.beans.InfraActiveRequests;
 
  77 import org.onap.so.db.request.client.RequestsDbClient;
 
  78 import org.onap.so.exceptions.ValidationException;
 
  79 import org.onap.so.logger.ErrorCode;
 
  80 import org.onap.so.logger.LogConstants;
 
  81 import org.onap.so.logger.MessageEnum;
 
  82 import org.onap.so.serviceinstancebeans.CloudConfiguration;
 
  83 import org.onap.so.serviceinstancebeans.ModelInfo;
 
  84 import org.onap.so.serviceinstancebeans.ModelType;
 
  85 import org.onap.so.serviceinstancebeans.Networks;
 
  86 import org.onap.so.serviceinstancebeans.RelatedInstance;
 
  87 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
 
  88 import org.onap.so.serviceinstancebeans.RequestDetails;
 
  89 import org.onap.so.serviceinstancebeans.RequestParameters;
 
  90 import org.onap.so.serviceinstancebeans.Service;
 
  91 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
 
  92 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
 
  93 import org.onap.so.serviceinstancebeans.VfModules;
 
  94 import org.onap.so.serviceinstancebeans.Vnfs;
 
  95 import org.onap.so.utils.UUIDChecker;
 
  96 import org.slf4j.Logger;
 
  97 import org.slf4j.LoggerFactory;
 
  99 import org.springframework.beans.factory.annotation.Autowired;
 
 100 import org.springframework.core.env.Environment;
 
 101 import org.springframework.http.ResponseEntity;
 
 102 import org.springframework.stereotype.Component;
 
 103 import org.springframework.web.client.RestClientException;
 
 104 import com.fasterxml.jackson.annotation.JsonInclude.Include;
 
 105 import com.fasterxml.jackson.databind.ObjectMapper;
 
 108 public class RequestHandlerUtils extends AbstractRestHandler {
 
 110     private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
 
 112     protected static final String SAVE_TO_DB = "save instance to db";
 
 113     private static final String NAME = "name";
 
 114     private static final String VALUE = "value";
 
 117     private Environment env;
 
 120     private RequestClientFactory reqClientFactory;
 
 123     private ResponseBuilder builder;
 
 126     private MsoRequest msoRequest;
 
 129     private CamundaRequestHandler camundaRequestHandler;
 
 132     private CatalogDbClient catalogDbClient;
 
 134     public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
 
 135             String orchestrationUri, String requestScope) throws ApiException {
 
 136         HttpResponse response = null;
 
 137         RequestClient requestClient = null;
 
 140             requestClient = reqClientFactory.getRequestClient(orchestrationUri);
 
 141             response = requestClient.post(requestClientParameter);
 
 142         } catch (Exception e) {
 
 143             logger.error("Error posting request to BPMN", e);
 
 144             ErrorLoggerInfo errorLoggerInfo =
 
 145                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
 
 146                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 147             String url = requestClient != null ? requestClient.getUrl() : "";
 
 148             ClientConnectionException clientException =
 
 149                     new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY,
 
 150                             ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
 
 151             updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
 
 152             throw clientException;
 
 155         if (response == null) {
 
 157             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
 
 158                     ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 159             ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
 
 160                     HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
 
 161             updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
 
 162             throw clientException;
 
 165         ResponseHandler respHandler = null;
 
 166         int bpelStatus = 500;
 
 168             respHandler = new ResponseHandler(response, requestClient.getType());
 
 169             bpelStatus = respHandler.getStatus();
 
 170         } catch (ApiException e) {
 
 171             logger.error("Exception occurred", e);
 
 172             ErrorLoggerInfo errorLoggerInfo =
 
 173                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
 
 174                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 175             ValidateException validateException =
 
 176                     new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
 
 177                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
 
 178                                     .errorInfo(errorLoggerInfo).build();
 
 179             updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 180             throw validateException;
 
 183         // BPEL accepted the request, the request is in progress
 
 184         if (bpelStatus == HttpStatus.SC_ACCEPTED) {
 
 185             ServiceInstancesResponse jsonResponse;
 
 186             CamundaResponse camundaResp = respHandler.getResponse();
 
 188             if ("Success".equalsIgnoreCase(camundaResp.getMessage())) {
 
 190                     ObjectMapper mapper = new ObjectMapper();
 
 191                     jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
 
 192                     jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
 
 193                     Optional<URL> selfLinkUrl =
 
 194                             buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
 
 195                     if (selfLinkUrl.isPresent()) {
 
 196                         jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
 
 198                         jsonResponse.getRequestReferences().setRequestSelfLink(null);
 
 200                 } catch (IOException e) {
 
 201                     logger.error("Exception occurred", e);
 
 202                     ErrorLoggerInfo errorLoggerInfo =
 
 203                             new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
 
 204                                     .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 205                     ValidateException validateException =
 
 206                             new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
 
 207                                     HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
 
 208                                             .errorInfo(errorLoggerInfo).build();
 
 209                     updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 210                     throw validateException;
 
 212                 return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(),
 
 213                         jsonResponse, requestClientParameter.getApiVersion());
 
 217         List<String> variables = new ArrayList<>();
 
 218         variables.add(bpelStatus + "");
 
 219         String camundaJSONResponseBody = respHandler.getResponseBody();
 
 220         if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
 
 222             ErrorLoggerInfo errorLoggerInfo =
 
 223                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
 
 224                             .errorSource(requestClient.getUrl()).build();
 
 225             BPMNFailureException bpmnException =
 
 226                     new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
 
 227                             ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
 
 229             updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
 
 234             ErrorLoggerInfo errorLoggerInfo =
 
 235                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError)
 
 236                             .errorSource(requestClient.getUrl()).build();
 
 239             BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
 
 240                     bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
 
 241             updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
 
 250     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
 
 251             throws RequestDbFailureException {
 
 252         if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
 
 253             aq.setStatusMessage(errorMessage);
 
 254             aq.setProgress(new Long(100));
 
 255             aq.setRequestStatus(status.toString());
 
 256             Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
 
 257             aq.setEndTime(endTimeStamp);
 
 259                 infraActiveRequestsClient.save(aq);
 
 260             } catch (Exception e) {
 
 261                 ErrorLoggerInfo errorLoggerInfo =
 
 262                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
 
 263                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 264                 throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(),
 
 265                         HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
 
 266                                 .errorInfo(errorLoggerInfo).build();
 
 271     public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) {
 
 272         if (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig) {
 
 273             return (ModelType.vnf.name());
 
 274         } else if (action == Action.addMembers || action == Action.removeMembers) {
 
 275             return (ModelType.instanceGroup.toString());
 
 278             if (sir.getRequestDetails().getModelInfo().getModelType() == null) {
 
 279                 requestScope = requestScopeFromUri(requestUri);
 
 281                 requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
 
 288     public void validateHeaders(ContainerRequestContext context) throws ValidationException {
 
 289         MultivaluedMap<String, String> headers = context.getHeaders();
 
 290         if (!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)) {
 
 291             throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true);
 
 293         if (!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)) {
 
 294             throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true);
 
 296         if (!headers.containsKey(REQUESTOR_ID)) {
 
 297             throw new ValidationException(REQUESTOR_ID + " header", true);
 
 301     public String getRequestUri(ContainerRequestContext context, String uriPrefix) {
 
 302         String requestUri = context.getUriInfo().getPath();
 
 303         String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
 
 304         MDC.put(LogConstants.HTTP_URL, httpUrl);
 
 305         requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length());
 
 309     public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope,
 
 310             InfraActiveRequests currentActiveReq, String instanceName) throws ApiException {
 
 311         InfraActiveRequests dup = null;
 
 312         boolean inProgress = false;
 
 314         dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
 
 317             inProgress = camundaHistoryCheck(dup, currentActiveReq);
 
 320         if (dup != null && inProgress) {
 
 321             buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup);
 
 325     public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
 
 326             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
 
 327         InfraActiveRequests dup = null;
 
 329             if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
 
 330                     || action == Action.activateInstance || action == Action.assignInstance))) {
 
 331                 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
 
 333         } catch (Exception e) {
 
 334             ErrorLoggerInfo errorLoggerInfo =
 
 335                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
 
 336                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 337             RequestDbFailureException requestDbFailureException =
 
 338                     new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
 
 339                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
 
 340                                     .errorInfo(errorLoggerInfo).build();
 
 341             updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
 
 342             throw requestDbFailureException;
 
 347     public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq)
 
 348             throws RequestDbFailureException, ContactCamundaException {
 
 349         String requestId = duplicateRecord.getRequestId();
 
 350         ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
 
 352             response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true);
 
 353         } catch (RestClientException e) {
 
 354             logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}",
 
 355                     requestId, e.getMessage());
 
 356             ContactCamundaException contactCamundaException =
 
 357                     new ContactCamundaException.Builder("process-instance", requestId, e.toString(),
 
 358                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
 
 360             updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
 
 361             throw contactCamundaException;
 
 364         if (response.getBody().isEmpty()) {
 
 365             updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
 
 367         for (HistoricProcessInstance instance : response.getBody()) {
 
 368             if (("ACTIVE").equals(instance.getState())) {
 
 371                 updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
 
 377     public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action,
 
 378             String requestId, String requestUri) throws ApiException {
 
 380             ObjectMapper mapper = new ObjectMapper();
 
 381             return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
 
 383         } catch (IOException e) {
 
 385             ErrorLoggerInfo errorLoggerInfo =
 
 386                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 387                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 389             ValidateException validateException =
 
 390                     new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 391                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 392             String requestScope = requestScopeFromUri(requestUri);
 
 394             msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
 
 395                     requestScope, requestJSON);
 
 397             throw validateException;
 
 401     public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
 
 402             String version, String requestJSON, Boolean aLaCarte, String requestId,
 
 403             InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
 
 404         int reqVersion = Integer.parseInt(version.substring(1));
 
 406             msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
 
 407         } catch (Exception e) {
 
 408             logger.error("failed to parse request", e);
 
 409             ErrorLoggerInfo errorLoggerInfo =
 
 410                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 411                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 412             ValidateException validateException =
 
 413                     new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 414                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 416             updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 418             throw validateException;
 
 422     public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
 
 423             HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
 
 424             throws ApiException {
 
 426         String instance = null;
 
 427         if (instanceName != null) {
 
 428             instance = instanceName;
 
 430             instance = instanceIdMap.get(requestScope + "InstanceId");
 
 432         ErrorLoggerInfo errorLoggerInfo =
 
 433                 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError)
 
 434                         .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 436         DuplicateRequestException dupException =
 
 437                 new DuplicateRequestException.Builder(requestScope, instance, dup.getRequestStatus(),
 
 438                         dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
 
 439                                 .errorInfo(errorLoggerInfo).build();
 
 441         updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage());
 
 447     public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
 
 448         String requestId = null;
 
 449         if (requestContext.getProperty("requestId") != null) {
 
 450             requestId = requestContext.getProperty("requestId").toString();
 
 452         if (UUIDChecker.isValidUUID(requestId)) {
 
 455             ErrorLoggerInfo errorLoggerInfo =
 
 456                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
 
 457                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 458             ValidateException validateException =
 
 459                     new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
 
 460                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
 
 461                                     .errorInfo(errorLoggerInfo).build();
 
 463             throw validateException;
 
 467     public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId,
 
 468             Map<String, String> instanceIdMap) {
 
 469         if (StringUtils.isNotBlank(instanceId)) {
 
 470             if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
 
 471                 currentActiveReq.setServiceInstanceId(instanceId);
 
 472             } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
 
 473                 currentActiveReq.setVnfId(instanceId);
 
 474             } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
 
 475                 currentActiveReq.setVfModuleId(instanceId);
 
 476             } else if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
 
 477                 currentActiveReq.setVolumeGroupId(instanceId);
 
 478             } else if (ModelType.network.name().equalsIgnoreCase(requestScope)) {
 
 479                 currentActiveReq.setNetworkId(instanceId);
 
 480             } else if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
 
 481                 currentActiveReq.setConfigurationId(instanceId);
 
 482             } else if (ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)) {
 
 483                 currentActiveReq.setInstanceGroupId(instanceId);
 
 485         } else if (instanceIdMap != null && !instanceIdMap.isEmpty()) {
 
 486             if (instanceIdMap.get("serviceInstanceId") != null) {
 
 487                 currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
 
 489             if (instanceIdMap.get("vnfInstanceId") != null) {
 
 490                 currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId"));
 
 492             if (instanceIdMap.get("vfModuleInstanceId") != null) {
 
 493                 currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId"));
 
 495             if (instanceIdMap.get("volumeGroupInstanceId") != null) {
 
 496                 currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId"));
 
 498             if (instanceIdMap.get("networkInstanceId") != null) {
 
 499                 currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId"));
 
 501             if (instanceIdMap.get("configurationInstanceId") != null) {
 
 502                 currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
 
 504             if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
 
 505                 currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
 
 510     public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest,
 
 511             boolean isAlaCarte, Actions action) throws IOException {
 
 512         ObjectMapper mapper = new ObjectMapper();
 
 513         mapper.setSerializationInclusion(Include.NON_NULL);
 
 514         if (serviceInstRequest != null) {
 
 515             return mapper.writeValueAsString(serviceInstRequest);
 
 517             return msoRawRequest;
 
 521     public Optional<String> retrieveModelName(RequestParameters requestParams) {
 
 522         String requestTestApi = null;
 
 523         TestApi testApi = null;
 
 525         if (requestParams != null) {
 
 526             requestTestApi = requestParams.getTestApi();
 
 529         if (requestTestApi == null) {
 
 530             if (requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) {
 
 531                 requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API);
 
 533                 requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API);
 
 538             testApi = TestApi.valueOf(requestTestApi);
 
 539             return Optional.of(testApi.getModelName());
 
 540         } catch (Exception e) {
 
 541             logger.warn("Catching the exception on the valueOf enum call and continuing", e);
 
 542             throw new IllegalArgumentException("Invalid TestApi is provided", e);
 
 546     public String getDefaultModel(ServiceInstancesRequest sir) {
 
 547         String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT";
 
 548         Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters());
 
 549         if (oModelName.isPresent()) {
 
 550             defaultModel = oModelName.get();
 
 555     public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag) {
 
 556         String serviceType = null;
 
 557         if (requestScope.equalsIgnoreCase(ModelType.service.toString())) {
 
 558             String defaultServiceModelName = getDefaultModel(sir);
 
 559             org.onap.so.db.catalog.beans.Service serviceRecord;
 
 561                 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
 
 562                 if (serviceRecord != null) {
 
 563                     serviceType = serviceRecord.getServiceType();
 
 567                         catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId());
 
 568                 if (serviceRecord != null) {
 
 569                     serviceType = serviceRecord.getServiceType();
 
 571                     serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
 
 572                     if (serviceRecord != null) {
 
 573                         serviceType = serviceRecord.getServiceType();
 
 578             serviceType = msoRequest.getServiceInstanceType(sir, requestScope);
 
 583     protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) {
 
 584         if (sir.getServiceInstanceId() != null) {
 
 585             return sir.getServiceInstanceId();
 
 586         } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
 
 587             RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
 
 588             if (relatedInstances != null) {
 
 589                 for (RelatedInstanceList relatedInstanceList : relatedInstances) {
 
 590                     RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
 
 591                     if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
 
 592                         return relatedInstance.getInstanceId();
 
 600     private String requestScopeFromUri(String requestUri) {
 
 602         if (requestUri.contains(ModelType.network.name())) {
 
 603             requestScope = ModelType.network.name();
 
 604         } else if (requestUri.contains(ModelType.vfModule.name())) {
 
 605             requestScope = ModelType.vfModule.name();
 
 606         } else if (requestUri.contains(ModelType.volumeGroup.name())) {
 
 607             requestScope = ModelType.volumeGroup.name();
 
 608         } else if (requestUri.contains(ModelType.configuration.name())) {
 
 609             requestScope = ModelType.configuration.name();
 
 610         } else if (requestUri.contains(ModelType.vnf.name())) {
 
 611             requestScope = ModelType.vnf.name();
 
 613             requestScope = ModelType.service.name();
 
 618     protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest,
 
 619             String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId,
 
 620             String originalRequestId) throws ApiException {
 
 621         InfraActiveRequests request = new InfraActiveRequests();
 
 622         request.setRequestId(requestId);
 
 623         request.setStartTime(startTimeStamp);
 
 624         request.setSource(source);
 
 625         request.setRequestUrl(requestUri);
 
 626         request.setProgress(new Long(5));
 
 627         request.setRequestorId(requestorId);
 
 628         request.setRequestStatus(Status.IN_PROGRESS.toString());
 
 629         request.setOriginalRequestId(originalRequestId);
 
 630         request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
 
 631         if (infraActiveRequest != null) {
 
 632             request.setTenantId(infraActiveRequest.getTenantId());
 
 633             request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId));
 
 634             request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion());
 
 635             request.setRequestScope(infraActiveRequest.getRequestScope());
 
 636             request.setRequestAction(infraActiveRequest.getRequestAction());
 
 637             setInstanceIdAndName(infraActiveRequest, request);
 
 642     protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest,
 
 643             InfraActiveRequests currentActiveRequest) throws ApiException {
 
 644         String requestScope = infraActiveRequest.getRequestScope();
 
 646             ModelType type = ModelType.valueOf(requestScope);
 
 647             String instanceName = type.getName(infraActiveRequest);
 
 648             if (instanceName == null && type.equals(ModelType.vfModule)) {
 
 649                 logger.error("vfModule for requestId: {} being resumed does not have an instanceName.",
 
 650                         infraActiveRequest.getRequestId());
 
 651                 ValidateException validateException = new ValidateException.Builder(
 
 652                         "vfModule for requestId: " + infraActiveRequest.getRequestId()
 
 653                                 + " being resumed does not have an instanceName.",
 
 654                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build();
 
 655                 updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
 
 656                 throw validateException;
 
 658             if (instanceName != null) {
 
 659                 type.setName(currentActiveRequest, instanceName);
 
 661             type.setId(currentActiveRequest, type.getId(infraActiveRequest));
 
 662         } catch (IllegalArgumentException e) {
 
 664                     "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.",
 
 669     protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType,
 
 670             String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException {
 
 671         // Get VF Module-specific base module indicator
 
 673         String modelVersionId = modelInfo.getModelVersionId();
 
 674         Boolean isBaseVfModule = false;
 
 676         if (modelVersionId != null) {
 
 677             vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
 
 678         } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
 
 679             vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
 
 680                     modelInfo.getModelVersion());
 
 684             if (vfm.getIsBase()) {
 
 685                 isBaseVfModule = true;
 
 687         } else if (action == Action.createInstance || action == Action.updateInstance) {
 
 688             String serviceVersionText = "";
 
 689             if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
 
 690                 serviceVersionText = " with version " + sdcServiceModelVersion;
 
 692             String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
 
 693                     + serviceVersionText + " not found in MSO Catalog DB";
 
 694             ErrorLoggerInfo errorLoggerInfo =
 
 695                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
 
 696                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 697             VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
 
 698                     HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
 
 699             updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
 
 700             throw vfModuleException;
 
 702         return isBaseVfModule;
 
 705     protected ModelType getModelType(Actions action, ModelInfo modelInfo) {
 
 706         if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
 
 707             return ModelType.vnf;
 
 708         } else if (action == Action.addMembers || action == Action.removeMembers) {
 
 709             return ModelType.instanceGroup;
 
 711             return modelInfo.getModelType();
 
 715     protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) {
 
 716         String requestBody = infraActiveRequest.getRequestBody();
 
 717         return requestBody.replaceAll(
 
 718                 "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))",
 
 719                 "$1" + newRequestorId + "$3");
 
 722     public RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
 
 723             boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException {
 
 724         RecipeLookupResult recipeLookupResult = null;
 
 725         // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
 
 726         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
 
 727         // Query MSO Catalog DB
 
 729         if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
 
 730             recipeLookupResult = getDefaultVnfUri(sir, action);
 
 731         } else if (action == Action.addMembers || action == Action.removeMembers) {
 
 732             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
 
 733         } else if (modelInfo.getModelType().equals(ModelType.service)) {
 
 735                 recipeLookupResult = getServiceURI(sir, action, alaCarteFlag);
 
 736             } catch (IOException e) {
 
 737                 ErrorLoggerInfo errorLoggerInfo =
 
 738                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 739                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 742                 ValidateException validateException =
 
 743                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 744                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 746                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 748                 throw validateException;
 
 750         } else if (modelInfo.getModelType().equals(ModelType.vfModule)
 
 751                 || modelInfo.getModelType().equals(ModelType.volumeGroup)
 
 752                 || modelInfo.getModelType().equals(ModelType.vnf)) {
 
 754                 recipeLookupResult = getVnfOrVfModuleUri(sir, action);
 
 755             } catch (ValidationException e) {
 
 756                 ErrorLoggerInfo errorLoggerInfo =
 
 757                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 758                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 761                 ValidateException validateException =
 
 762                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 763                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 765                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 767                 throw validateException;
 
 769         } else if (modelInfo.getModelType().equals(ModelType.network)) {
 
 771                 recipeLookupResult = getNetworkUri(sir, action);
 
 772             } catch (ValidationException e) {
 
 774                 ErrorLoggerInfo errorLoggerInfo =
 
 775                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 776                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 779                 ValidateException validateException =
 
 780                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 781                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 782                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 784                 throw validateException;
 
 786         } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
 
 787             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
 
 790         if (recipeLookupResult == null) {
 
 791             ErrorLoggerInfo errorLoggerInfo =
 
 792                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
 
 793                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 796             RecipeNotFoundException recipeNotFoundExceptionException =
 
 797                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
 
 798                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
 
 801             updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
 
 802             throw recipeNotFoundExceptionException;
 
 804         return recipeLookupResult;
 
 807     protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
 
 808             boolean alaCarteFlag) throws IOException {
 
 810         // Construct the default service name
 
 811         // TODO need to make this a configurable property
 
 812         String defaultServiceModelName = getDefaultModel(servInstReq);
 
 813         RequestDetails requestDetails = servInstReq.getRequestDetails();
 
 814         ModelInfo modelInfo = requestDetails.getModelInfo();
 
 815         org.onap.so.db.catalog.beans.Service serviceRecord;
 
 816         List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
 
 817         ServiceRecipe recipe = null;
 
 820             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
 
 821             if (serviceRecord != null) {
 
 822                 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
 
 826             serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
 
 827             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
 
 829             if (recipe == null) {
 
 830                 serviceRecordList = catalogDbClient
 
 831                         .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
 
 832                 if (!serviceRecordList.isEmpty()) {
 
 833                     for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
 
 834                         recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
 
 836                         if (recipe != null) {
 
 844         // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
 
 845         RequestParameters reqParam = requestDetails.getRequestParameters();
 
 846         if (reqParam != null && alaCarteFlag && recipe == null) {
 
 848         } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
 
 849             mapToLegacyRequest(requestDetails);
 
 850         } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
 
 851             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
 
 852             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
 
 855         if (modelInfo.getModelVersionId() == null) {
 
 856             modelInfo.setModelVersionId(serviceRecord.getModelUUID());
 
 858         if (recipe == null) {
 
 861         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
 
 864     protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
 
 865         RequestParameters reqParam;
 
 866         if (requestDetails.getRequestParameters() == null) {
 
 867             reqParam = new RequestParameters();
 
 869             reqParam = requestDetails.getRequestParameters();
 
 871         if (requestDetails.getCloudConfiguration() == null) {
 
 872             CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
 
 873             if (cloudConfig != null) {
 
 874                 requestDetails.setCloudConfiguration(cloudConfig);
 
 878         List<Map<String, Object>> userParams = configureUserParams(reqParam);
 
 879         if (!userParams.isEmpty()) {
 
 880             if (reqParam == null) {
 
 881                 requestDetails.setRequestParameters(new RequestParameters());
 
 883             requestDetails.getRequestParameters().setUserParams(userParams);
 
 887     private Service serviceMapper(Map<String, Object> params) throws IOException {
 
 888         ObjectMapper obj = new ObjectMapper();
 
 889         String input = obj.writeValueAsString(params.get("service"));
 
 890         return obj.readValue(input, Service.class);
 
 893     private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
 
 894         for (Map<String, String> map : sourceUserParams) {
 
 895             for (Map.Entry<String, String> entry : map.entrySet()) {
 
 896                 targetUserParams.put(entry.getKey(), entry.getValue());
 
 901     protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
 
 902         logger.debug("Configuring UserParams for Macro Request");
 
 903         Map<String, Object> userParams = new HashMap<>();
 
 905         for (Map<String, Object> params : reqParams.getUserParams()) {
 
 906             if (params.containsKey("service")) {
 
 907                 Service service = serviceMapper(params);
 
 909                 addUserParams(userParams, service.getInstanceParams());
 
 911                 for (Networks network : service.getResources().getNetworks()) {
 
 912                     addUserParams(userParams, network.getInstanceParams());
 
 915                 for (Vnfs vnf : service.getResources().getVnfs()) {
 
 916                     addUserParams(userParams, vnf.getInstanceParams());
 
 918                     for (VfModules vfModule : vnf.getVfModules()) {
 
 919                         addUserParams(userParams, vfModule.getInstanceParams());
 
 925         return mapFlatMapToNameValue(userParams);
 
 928     protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
 
 929         List<Map<String, Object>> targetUserParams = new ArrayList<>();
 
 931         for (Map.Entry<String, Object> map : flatMap.entrySet()) {
 
 932             Map<String, Object> targetMap = new HashMap<>();
 
 933             targetMap.put(NAME, map.getKey());
 
 934             targetMap.put(VALUE, map.getValue());
 
 935             targetUserParams.add(targetMap);
 
 937         return targetUserParams;
 
 940     protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
 
 942         for (Map<String, Object> params : reqParams.getUserParams()) {
 
 943             if (params.containsKey("service")) {
 
 944                 Service service = serviceMapper(params);
 
 946                 Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
 
 948                 if (targetConfiguration.isPresent()) {
 
 949                     return targetConfiguration.get();
 
 951                     for (Networks network : service.getResources().getNetworks()) {
 
 952                         targetConfiguration = addCloudConfig(network.getCloudConfiguration());
 
 953                         if (targetConfiguration.isPresent()) {
 
 954                             return targetConfiguration.get();
 
 958                     for (Vnfs vnf : service.getResources().getVnfs()) {
 
 959                         targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
 
 961                         if (targetConfiguration.isPresent()) {
 
 962                             return targetConfiguration.get();
 
 965                         for (VfModules vfModule : vnf.getVfModules()) {
 
 966                             targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
 
 968                             if (targetConfiguration.isPresent()) {
 
 969                                 return targetConfiguration.get();
 
 980     private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
 
 981         String defaultSource = getDefaultModel(sir);
 
 982         VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
 
 983         if (vnfRecipe == null) {
 
 986         return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
 
 990     private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
 
 991         String defaultNetworkType = getDefaultModel(sir);
 
 992         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
 
 993         String modelName = modelInfo.getModelName();
 
 994         Recipe recipe = null;
 
 996         if (modelInfo.getModelCustomizationId() != null) {
 
 997             NetworkResourceCustomization networkResourceCustomization = catalogDbClient
 
 998                     .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
 
 999             if (networkResourceCustomization != null) {
 
1000                 NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
 
1001                 if (networkResource != null) {
 
1002                     if (modelInfo.getModelVersionId() == null) {
 
1003                         modelInfo.setModelVersionId(networkResource.getModelUUID());
 
1005                     recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
 
1008                     throw new ValidationException("no catalog entry found");
 
1010             } else if (action != Action.deleteInstance) {
 
1011                 throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
 
1014             // ok for version < 3 and action delete
 
1015             if (modelName != null) {
 
1016                 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
 
1020         if (recipe == null) {
 
1021             recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
 
1024         return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
 
1028     private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
 
1029         CloudConfiguration targetConfiguration = new CloudConfiguration();
 
1030         if (sourceCloudConfiguration != null) {
 
1031             targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
 
1032             targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
 
1033             targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
 
1034             targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
 
1035             return Optional.of(targetConfiguration);
 
1037         return Optional.empty();
 
1040     private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
 
1041             throws ValidationException {
 
1043         ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
 
1044         String vnfComponentType = modelInfo.getModelType().name();
 
1046         RelatedInstanceList[] instanceList = null;
 
1047         if (servInstReq.getRequestDetails() != null) {
 
1048             instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
 
1052         String defaultSource = getDefaultModel(servInstReq);
 
1053         String modelCustomizationId = modelInfo.getModelCustomizationId();
 
1054         String modelCustomizationName = modelInfo.getModelCustomizationName();
 
1055         String relatedInstanceModelVersionId = null;
 
1056         String relatedInstanceModelInvariantId = null;
 
1057         String relatedInstanceVersion = null;
 
1058         String relatedInstanceModelCustomizationName = null;
 
1060         if (instanceList != null) {
 
1062             for (RelatedInstanceList relatedInstanceList : instanceList) {
 
1064                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
 
1065                 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
 
1066                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
 
1067                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
 
1068                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
 
1071                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
 
1072                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
 
1073                     relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
 
1074                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
 
1075                     relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
 
1079             if (modelInfo.getModelType().equals(ModelType.vnf)) {
 
1080                 // a. For a vnf request (only create, no update currently):
 
1081                 // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
 
1082                 // vnf_resource_customization.model_customization_uuid.
 
1083                 // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
 
1084                 // pre-v3), then modelInfo.modelCustomizationName must have
 
1085                 // been provided (else create request should be rejected). APIH should use the
 
1086                 // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
 
1087                 // to â€œjoinâ€�? service_to_resource_customizations with vnf_resource_customization to confirm a
 
1088                 // vnf_resource_customization.model_customization_uuid record exists.
 
1089                 // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
 
1090                 // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
 
1091                 // (MODEL_UUID) in SERVICE table.
 
1092                 // iii. Regardless of how the value was provided/obtained above, APIH must always populate
 
1093                 // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
 
1094                 // during 1707 data migration if VID did not provide it originally on request.
 
1095                 // iv. Note: continue to construct the â€œvnf-typeâ€�? value and pass to BPMN (must still be populated
 
1097                 // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
 
1098                 // look it up in our catalog to construct vnf-type value to pass to BPMN.
 
1100                 VnfResource vnfResource = null;
 
1101                 VnfResourceCustomization vrc = null;
 
1102                 // Validation for vnfResource
 
1104                 if (modelCustomizationId != null) {
 
1105                     vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
 
1107                         vnfResource = vrc.getVnfResources();
 
1110                     org.onap.so.db.catalog.beans.Service service =
 
1111                             catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
 
1112                     if (service == null) {
 
1113                         service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
 
1114                                 relatedInstanceModelInvariantId);
 
1117                     if (service == null) {
 
1118                         throw new ValidationException("service in relatedInstance");
 
1120                     for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
 
1121                         if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
 
1122                             vrc = vnfResourceCustom;
 
1127                         vnfResource = vrc.getVnfResources();
 
1128                         modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
 
1129                         modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
 
1133                 if (vnfResource == null) {
 
1134                     throw new ValidationException("vnfResource");
 
1136                     if (modelInfo.getModelVersionId() == null) {
 
1137                         modelInfo.setModelVersionId(vnfResource.getModelUUID());
 
1141                 VnfRecipe vnfRecipe = null;
 
1144                     String nfRole = vrc.getNfRole();
 
1145                     if (nfRole != null) {
 
1147                                 catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
 
1151                 if (vnfRecipe == null) {
 
1152                     vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
 
1155                 if (vnfRecipe == null) {
 
1159                 return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
 
1162                  * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
 
1163                  * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
 
1164                  * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
 
1165                  * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
 
1166                  * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
 
1167                  * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
 
1168                  * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
 
1169                  * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
 
1170                  * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
 
1171                  * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
 
1172                  * the request). This means taking each record found // in vf_module_customization and looking up in
 
1173                  * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
 
1174                  * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
 
1176                 VfModuleCustomization vfmc = null;
 
1178                 VnfResourceCustomization vnfrc;
 
1179                 VfModule vfModule = null;
 
1181                 if (modelInfo.getModelCustomizationId() != null) {
 
1182                     vfmc = catalogDbClient
 
1183                             .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
 
1185                     vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
 
1187                         vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
 
1188                                 relatedInstanceModelInvariantId, relatedInstanceVersion);
 
1190                     vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
 
1191                             relatedInstanceModelCustomizationName, vnfr);
 
1193                     List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
 
1195                     String vfModuleModelUUID = modelInfo.getModelVersionId();
 
1196                     for (VfModuleCustomization vf : list) {
 
1197                         VfModuleCustomization vfmCustom;
 
1198                         if (vfModuleModelUUID != null) {
 
1199                             vfmCustom = catalogDbClient
 
1200                                     .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
 
1201                                             vf.getModelCustomizationUUID(), vfModuleModelUUID);
 
1202                             if (vfmCustom != null) {
 
1203                                 vfModule = vfmCustom.getVfModule();
 
1206                             vfmCustom = catalogDbClient
 
1207                                     .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
 
1208                             if (vfmCustom != null) {
 
1209                                 vfModule = vfmCustom.getVfModule();
 
1211                                 vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
 
1212                                         relatedInstanceModelInvariantId, relatedInstanceVersion);
 
1216                         if (vfModule != null) {
 
1217                             modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
 
1218                             modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
 
1224                 if (vfmc == null && vfModule == null) {
 
1225                     throw new ValidationException("vfModuleCustomization");
 
1226                 } else if (vfModule == null && vfmc != null) {
 
1227                     vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
 
1228                                                    // VfModuleCustomization table
 
1231                 if (modelInfo.getModelVersionId() == null) {
 
1232                     modelInfo.setModelVersionId(vfModule.getModelUUID());
 
1236                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
 
1237                         vfModule.getModelUUID(), vnfComponentType, action.toString());
 
1238                 if (recipe == null) {
 
1239                     List<VfModule> vfModuleRecords = catalogDbClient
 
1240                             .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
 
1241                     if (!vfModuleRecords.isEmpty()) {
 
1242                         for (VfModule record : vfModuleRecords) {
 
1243                             recipe = catalogDbClient
 
1244                                     .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
 
1245                                             record.getModelUUID(), vnfComponentType, action.toString());
 
1246                             if (recipe != null) {
 
1252                 if (recipe == null) {
 
1253                     recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
 
1254                             defaultSource, vnfComponentType, action.toString());
 
1255                     if (recipe == null) {
 
1256                         recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
 
1257                                 vnfComponentType, action.toString());
 
1260                     if (recipe == null) {
 
1267             if (modelInfo.getModelType().equals(ModelType.vnf)) {
 
1268                 recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
 
1269                 if (recipe == null) {
 
1273                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
 
1274                         defaultSource, vnfComponentType, action.toString());
 
1276                 if (recipe == null) {
 
1282         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());