Merge "SO API extenstion to retrieve all PNF workflow"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / RequestHandlerUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
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=========================================================
23  */
24
25 package org.onap.so.apihandlerinfra;
26
27
28 import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
29 import java.io.IOException;
30 import java.net.URL;
31 import java.sql.Timestamp;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
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;
98 import org.slf4j.MDC;
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;
106
107 @Component
108 public class RequestHandlerUtils extends AbstractRestHandler {
109
110     private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
111
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";
115
116     @Autowired
117     private Environment env;
118
119     @Autowired
120     private RequestClientFactory reqClientFactory;
121
122     @Autowired
123     private ResponseBuilder builder;
124
125     @Autowired
126     private MsoRequest msoRequest;
127
128     @Autowired
129     private CamundaRequestHandler camundaRequestHandler;
130
131     @Autowired
132     private CatalogDbClient catalogDbClient;
133
134     public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
135             String orchestrationUri, String requestScope) throws ApiException {
136         HttpResponse response = null;
137         RequestClient requestClient = null;
138
139         try {
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;
153         }
154
155         if (response == null) {
156
157             ErrorLoggerInfo errorLoggerInfo =
158                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError)
159                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
160             ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
161                     HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
162             updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
163             throw clientException;
164         }
165
166         ResponseHandler respHandler = null;
167         int bpelStatus = 500;
168         try {
169             respHandler = new ResponseHandler(response, requestClient.getType());
170             bpelStatus = respHandler.getStatus();
171         } catch (ApiException e) {
172             logger.error("Exception occurred", e);
173             ErrorLoggerInfo errorLoggerInfo =
174                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
175                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
176             ValidateException validateException =
177                     new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
178                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
179                                     .errorInfo(errorLoggerInfo).build();
180             updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
181             throw validateException;
182         }
183
184         // BPEL accepted the request, the request is in progress
185         if (bpelStatus == HttpStatus.SC_ACCEPTED) {
186             ServiceInstancesResponse jsonResponse;
187             CamundaResponse camundaResp = respHandler.getResponse();
188
189             if ("Success".equalsIgnoreCase(camundaResp.getMessage())) {
190                 try {
191                     ObjectMapper mapper = new ObjectMapper();
192                     jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
193                     jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
194                     Optional<URL> selfLinkUrl =
195                             buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
196                     if (selfLinkUrl.isPresent()) {
197                         jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
198                     } else {
199                         jsonResponse.getRequestReferences().setRequestSelfLink(null);
200                     }
201                 } catch (IOException e) {
202                     logger.error("Exception occurred", e);
203                     ErrorLoggerInfo errorLoggerInfo =
204                             new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
205                                     .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
206                     ValidateException validateException =
207                             new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
208                                     HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
209                                             .errorInfo(errorLoggerInfo).build();
210                     updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
211                     throw validateException;
212                 }
213                 return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(),
214                         jsonResponse, requestClientParameter.getApiVersion());
215             }
216         }
217
218         List<String> variables = new ArrayList<>();
219         variables.add(bpelStatus + "");
220         String camundaJSONResponseBody = respHandler.getResponseBody();
221         if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
222
223             ErrorLoggerInfo errorLoggerInfo =
224                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
225                             .errorSource(requestClient.getUrl()).build();
226             BPMNFailureException bpmnException =
227                     new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
228                             ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
229
230             updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
231
232             throw bpmnException;
233         } else {
234
235             ErrorLoggerInfo errorLoggerInfo =
236                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
237                             .errorSource(requestClient.getUrl()).build();
238
239
240             BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
241                     bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
242             updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
243
244             throw servException;
245         }
246     }
247
248
249
250     @Override
251     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
252             throws RequestDbFailureException {
253         if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
254             aq.setStatusMessage(errorMessage);
255             aq.setProgress(new Long(100));
256             aq.setRequestStatus(status.toString());
257             Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
258             aq.setEndTime(endTimeStamp);
259             try {
260                 infraActiveRequestsClient.save(aq);
261             } catch (Exception e) {
262                 ErrorLoggerInfo errorLoggerInfo =
263                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
264                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
265                 throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(),
266                         HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
267                                 .errorInfo(errorLoggerInfo).build();
268             }
269         }
270     }
271
272     public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) {
273         if (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig) {
274             return (ModelType.vnf.name());
275         } else if (action == Action.addMembers || action == Action.removeMembers) {
276             return (ModelType.instanceGroup.toString());
277         } else {
278             String requestScope = requestScopeFromUri(requestUri);;
279
280             if (sir.getRequestDetails() == null) {
281                 return requestScope;
282             }
283             if (sir.getRequestDetails().getModelInfo() == null) {
284                 return requestScope;
285             }
286             if (sir.getRequestDetails().getModelInfo().getModelType() == null) {
287                 return requestScope;
288             }
289             requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
290             return requestScope;
291         }
292     }
293
294
295     public void validateHeaders(ContainerRequestContext context) throws ValidationException {
296         MultivaluedMap<String, String> headers = context.getHeaders();
297         if (!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)) {
298             throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true);
299         }
300         if (!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)) {
301             throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true);
302         }
303         if (!headers.containsKey(REQUESTOR_ID)) {
304             throw new ValidationException(REQUESTOR_ID + " header", true);
305         }
306     }
307
308     public String getRequestUri(ContainerRequestContext context, String uriPrefix) {
309         String requestUri = context.getUriInfo().getPath();
310         String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
311         MDC.put(LogConstants.HTTP_URL, httpUrl);
312         requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length());
313         return requestUri;
314     }
315
316     public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope,
317             InfraActiveRequests currentActiveReq, String instanceName) throws ApiException {
318         InfraActiveRequests dup = null;
319         boolean inProgress = false;
320
321         dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
322
323         if (dup != null) {
324             inProgress = camundaHistoryCheck(dup, currentActiveReq);
325         }
326
327         if (dup != null && inProgress) {
328             buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup);
329         }
330     }
331
332     public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
333             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
334         InfraActiveRequests dup = null;
335         try {
336             if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
337                     || action == Action.activateInstance || action == Action.assignInstance))) {
338                 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
339             }
340         } catch (Exception e) {
341             ErrorLoggerInfo errorLoggerInfo =
342                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
343                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
344             RequestDbFailureException requestDbFailureException =
345                     new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
346                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
347                                     .errorInfo(errorLoggerInfo).build();
348             updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
349             throw requestDbFailureException;
350         }
351         return dup;
352     }
353
354     public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq)
355             throws RequestDbFailureException, ContactCamundaException {
356         String requestId = duplicateRecord.getRequestId();
357         ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
358         try {
359             response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true, true, false);
360         } catch (RestClientException e) {
361             logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}",
362                     requestId, e.getMessage());
363             ContactCamundaException contactCamundaException =
364                     new ContactCamundaException.Builder("process-instance", requestId, e.toString(),
365                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
366                                     .build();
367             updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
368             throw contactCamundaException;
369         }
370
371         if (response.getBody().isEmpty()) {
372             updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
373         } else {
374             return true;
375         }
376         return false;
377     }
378
379     public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action,
380             String requestId, String requestUri) throws ApiException {
381         try {
382             ObjectMapper mapper = new ObjectMapper();
383             return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
384
385         } catch (IOException e) {
386
387             ErrorLoggerInfo errorLoggerInfo =
388                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
389                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
390
391             ValidateException validateException =
392                     new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
393                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
394             String requestScope = requestScopeFromUri(requestUri);
395
396             msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
397                     requestScope, requestJSON);
398
399             throw validateException;
400         }
401     }
402
403     public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
404             String version, String requestJSON, Boolean aLaCarte, String requestId,
405             InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
406         int reqVersion = Integer.parseInt(version.substring(1));
407         try {
408             msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
409         } catch (Exception e) {
410             logger.error("failed to parse request", e);
411             ErrorLoggerInfo errorLoggerInfo =
412                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
413                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
414             ValidateException validateException =
415                     new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
416                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
417
418             updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
419
420             throw validateException;
421         }
422     }
423
424     public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
425             HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
426             throws ApiException {
427
428         String instance = null;
429         if (instanceName != null) {
430             instance = instanceName;
431         } else {
432             instance = instanceIdMap.get(requestScope + "InstanceId");
433         }
434         ErrorLoggerInfo errorLoggerInfo =
435                 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError)
436                         .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
437
438         DuplicateRequestException dupException =
439                 new DuplicateRequestException.Builder(requestScope, instance, dup.getRequestStatus(),
440                         dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
441                                 .errorInfo(errorLoggerInfo).build();
442
443         updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage());
444
445         throw dupException;
446     }
447
448     @Override
449     public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
450         String requestId = null;
451         if (requestContext.getProperty("requestId") != null) {
452             requestId = requestContext.getProperty("requestId").toString();
453         }
454         if (UUIDChecker.isValidUUID(requestId)) {
455             return requestId;
456         } else {
457             ErrorLoggerInfo errorLoggerInfo =
458                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
459                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
460             ValidateException validateException =
461                     new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
462                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
463                                     .errorInfo(errorLoggerInfo).build();
464
465             throw validateException;
466         }
467     }
468
469     public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId,
470             Map<String, String> instanceIdMap) {
471         if (StringUtils.isNotBlank(instanceId)) {
472             if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
473                 currentActiveReq.setServiceInstanceId(instanceId);
474             } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
475                 currentActiveReq.setVnfId(instanceId);
476             } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
477                 currentActiveReq.setVfModuleId(instanceId);
478             } else if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
479                 currentActiveReq.setVolumeGroupId(instanceId);
480             } else if (ModelType.network.name().equalsIgnoreCase(requestScope)) {
481                 currentActiveReq.setNetworkId(instanceId);
482             } else if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
483                 currentActiveReq.setConfigurationId(instanceId);
484             } else if (ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)) {
485                 currentActiveReq.setInstanceGroupId(instanceId);
486             }
487         } else if (instanceIdMap != null && !instanceIdMap.isEmpty()) {
488             if (instanceIdMap.get("serviceInstanceId") != null) {
489                 currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
490             }
491             if (instanceIdMap.get("vnfInstanceId") != null) {
492                 currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId"));
493             }
494             if (instanceIdMap.get("vfModuleInstanceId") != null) {
495                 currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId"));
496             }
497             if (instanceIdMap.get("volumeGroupInstanceId") != null) {
498                 currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId"));
499             }
500             if (instanceIdMap.get("networkInstanceId") != null) {
501                 currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId"));
502             }
503             if (instanceIdMap.get("configurationInstanceId") != null) {
504                 currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
505             }
506             if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
507                 currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
508             }
509             if (instanceIdMap.get("pnfName") != null) {
510                 currentActiveReq.setPnfName(instanceIdMap.get("pnfName"));
511             }
512         }
513     }
514
515     public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest,
516             boolean isAlaCarte, Actions action) throws IOException {
517         ObjectMapper mapper = new ObjectMapper();
518         mapper.setSerializationInclusion(Include.NON_NULL);
519         if (serviceInstRequest != null) {
520             return mapper.writeValueAsString(serviceInstRequest);
521         } else {
522             return msoRawRequest;
523         }
524     }
525
526     public Optional<String> retrieveModelName(RequestParameters requestParams) {
527         String requestTestApi = null;
528         TestApi testApi = null;
529
530         if (requestParams != null) {
531             requestTestApi = requestParams.getTestApi();
532         }
533
534         if (requestTestApi == null) {
535             if (requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) {
536                 requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API);
537             } else {
538                 requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API);
539             }
540         }
541
542         try {
543             testApi = TestApi.valueOf(requestTestApi);
544             return Optional.of(testApi.getModelName());
545         } catch (Exception e) {
546             logger.warn("Catching the exception on the valueOf enum call and continuing", e);
547             throw new IllegalArgumentException("Invalid TestApi is provided", e);
548         }
549     }
550
551     public String getDefaultModel(ServiceInstancesRequest sir) {
552         String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT";
553         Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters());
554         if (oModelName.isPresent()) {
555             defaultModel = oModelName.get();
556         }
557         return defaultModel;
558     }
559
560     public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag) {
561         String serviceType = null;
562         if (requestScope.equalsIgnoreCase(ModelType.service.toString())) {
563             String defaultServiceModelName = getDefaultModel(sir);
564             org.onap.so.db.catalog.beans.Service serviceRecord;
565             if (aLaCarteFlag) {
566                 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
567                 if (serviceRecord != null) {
568                     serviceType = serviceRecord.getServiceType();
569                 }
570             } else {
571                 serviceRecord =
572                         catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId());
573                 if (serviceRecord != null) {
574                     serviceType = serviceRecord.getServiceType();
575                 } else {
576                     serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
577                     if (serviceRecord != null) {
578                         serviceType = serviceRecord.getServiceType();
579                     }
580                 }
581             }
582         } else {
583             serviceType = msoRequest.getServiceInstanceType(sir, requestScope);
584         }
585         return serviceType;
586     }
587
588     protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) {
589         if (sir.getServiceInstanceId() != null) {
590             return sir.getServiceInstanceId();
591         } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
592             RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
593             if (relatedInstances != null) {
594                 for (RelatedInstanceList relatedInstanceList : relatedInstances) {
595                     RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
596                     if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
597                         return relatedInstance.getInstanceId();
598                     }
599                 }
600             }
601         }
602         return null;
603     }
604
605     private String requestScopeFromUri(String requestUri) {
606         String requestScope;
607         if (requestUri.contains(ModelType.network.name())) {
608             requestScope = ModelType.network.name();
609         } else if (requestUri.contains(ModelType.vfModule.name())) {
610             requestScope = ModelType.vfModule.name();
611         } else if (requestUri.contains(ModelType.volumeGroup.name())) {
612             requestScope = ModelType.volumeGroup.name();
613         } else if (requestUri.contains(ModelType.configuration.name())) {
614             requestScope = ModelType.configuration.name();
615         } else if (requestUri.contains(ModelType.vnf.name())) {
616             requestScope = ModelType.vnf.name();
617         } else if (requestUri.contains(ModelType.pnf.name())) {
618             requestScope = ModelType.pnf.name();
619         } else {
620             requestScope = ModelType.service.name();
621         }
622         return requestScope;
623     }
624
625     protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest,
626             String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId,
627             String originalRequestId) throws ApiException {
628         InfraActiveRequests request = new InfraActiveRequests();
629         request.setRequestId(requestId);
630         request.setStartTime(startTimeStamp);
631         request.setSource(source);
632         request.setRequestUrl(requestUri);
633         request.setProgress(new Long(5));
634         request.setRequestorId(requestorId);
635         request.setRequestStatus(Status.IN_PROGRESS.toString());
636         request.setOriginalRequestId(originalRequestId);
637         request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
638         if (infraActiveRequest != null) {
639             request.setTenantId(infraActiveRequest.getTenantId());
640             request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId));
641             request.setCloudRegion(infraActiveRequest.getCloudRegion());
642             request.setRequestScope(infraActiveRequest.getRequestScope());
643             request.setRequestAction(infraActiveRequest.getRequestAction());
644             setInstanceIdAndName(infraActiveRequest, request);
645         }
646         return request;
647     }
648
649     protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest,
650             InfraActiveRequests currentActiveRequest) throws ApiException {
651         String requestScope = infraActiveRequest.getRequestScope();
652         try {
653             ModelType type = ModelType.valueOf(requestScope);
654             String instanceName = type.getName(infraActiveRequest);
655             if (instanceName == null && type.equals(ModelType.vfModule)) {
656                 logger.error("vfModule for requestId: {} being resumed does not have an instanceName.",
657                         infraActiveRequest.getRequestId());
658                 ValidateException validateException = new ValidateException.Builder(
659                         "vfModule for requestId: " + infraActiveRequest.getRequestId()
660                                 + " being resumed does not have an instanceName.",
661                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build();
662                 updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
663                 throw validateException;
664             }
665             if (instanceName != null) {
666                 type.setName(currentActiveRequest, instanceName);
667             }
668             type.setId(currentActiveRequest, type.getId(infraActiveRequest));
669         } catch (IllegalArgumentException e) {
670             logger.error(
671                     "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.",
672                     requestScope);
673         }
674     }
675
676     protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType,
677             String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException {
678         // Get VF Module-specific base module indicator
679         VfModule vfm = null;
680         String modelVersionId = modelInfo.getModelVersionId();
681         Boolean isBaseVfModule = false;
682
683         if (modelVersionId != null) {
684             vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
685         } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
686             vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
687                     modelInfo.getModelVersion());
688         }
689
690         if (vfm != null) {
691             if (vfm.getIsBase()) {
692                 isBaseVfModule = true;
693             }
694         } else if (action == Action.createInstance || action == Action.updateInstance) {
695             String serviceVersionText = "";
696             if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
697                 serviceVersionText = " with version " + sdcServiceModelVersion;
698             }
699             String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
700                     + serviceVersionText + " not found in MSO Catalog DB";
701             ErrorLoggerInfo errorLoggerInfo =
702                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
703                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
704             VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
705                     HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
706             updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
707             throw vfModuleException;
708         }
709         return isBaseVfModule;
710     }
711
712     protected ModelType getModelType(Actions action, ModelInfo modelInfo) {
713         if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
714             return ModelType.vnf;
715         } else if (action == Action.addMembers || action == Action.removeMembers) {
716             return ModelType.instanceGroup;
717         } else {
718             return modelInfo.getModelType();
719         }
720     }
721
722     protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) {
723         String requestBody = infraActiveRequest.getRequestBody();
724         return requestBody.replaceAll(
725                 "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))",
726                 "$1" + newRequestorId + "$3");
727     }
728
729     public RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
730             boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException {
731         RecipeLookupResult recipeLookupResult = null;
732         // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
733         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
734         // Query MSO Catalog DB
735
736         if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
737             recipeLookupResult = getDefaultVnfUri(sir, action);
738         } else if (action == Action.addMembers || action == Action.removeMembers) {
739             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
740         } else if (modelInfo.getModelType().equals(ModelType.service)) {
741             try {
742                 recipeLookupResult = getServiceURI(sir, action, alaCarteFlag);
743             } catch (IOException e) {
744                 ErrorLoggerInfo errorLoggerInfo =
745                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
746                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
747
748
749                 ValidateException validateException =
750                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
751                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
752
753                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
754
755                 throw validateException;
756             }
757         } else if (modelInfo.getModelType().equals(ModelType.vfModule)
758                 || modelInfo.getModelType().equals(ModelType.volumeGroup)
759                 || modelInfo.getModelType().equals(ModelType.vnf)) {
760             try {
761                 recipeLookupResult = getVnfOrVfModuleUri(sir, action);
762             } catch (ValidationException e) {
763                 ErrorLoggerInfo errorLoggerInfo =
764                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
765                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
766
767
768                 ValidateException validateException =
769                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
770                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
771
772                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
773
774                 throw validateException;
775             }
776         } else if (modelInfo.getModelType().equals(ModelType.network)) {
777             try {
778                 recipeLookupResult = getNetworkUri(sir, action);
779             } catch (ValidationException e) {
780
781                 ErrorLoggerInfo errorLoggerInfo =
782                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
783                                 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
784
785
786                 ValidateException validateException =
787                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
788                                 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
789                 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
790
791                 throw validateException;
792             }
793         } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
794             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
795         }
796
797         if (recipeLookupResult == null) {
798             ErrorLoggerInfo errorLoggerInfo =
799                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
800                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
801
802
803             RecipeNotFoundException recipeNotFoundExceptionException =
804                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
805                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
806                                     .build();
807
808             updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
809             throw recipeNotFoundExceptionException;
810         }
811         return recipeLookupResult;
812     }
813
814     protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
815             boolean alaCarteFlag) throws IOException {
816         // SERVICE REQUEST
817         // Construct the default service name
818         // TODO need to make this a configurable property
819         String defaultServiceModelName = getDefaultModel(servInstReq);
820         RequestDetails requestDetails = servInstReq.getRequestDetails();
821         ModelInfo modelInfo = requestDetails.getModelInfo();
822         org.onap.so.db.catalog.beans.Service serviceRecord;
823         List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
824         ServiceRecipe recipe = null;
825
826         if (alaCarteFlag) {
827             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
828             if (serviceRecord != null) {
829                 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
830                         action.toString());
831             }
832         } else {
833             serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
834             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
835                     action.toString());
836             if (recipe == null) {
837                 serviceRecordList = catalogDbClient
838                         .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
839                 if (!serviceRecordList.isEmpty()) {
840                     for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
841                         recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
842                                 action.toString());
843                         if (recipe != null) {
844                             break;
845                         }
846                     }
847                 }
848             }
849         }
850
851         // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
852         RequestParameters reqParam = requestDetails.getRequestParameters();
853         if (reqParam != null && alaCarteFlag && recipe == null) {
854             return null;
855         } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
856             mapToLegacyRequest(requestDetails);
857         } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
858             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
859             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
860                     action.toString());
861         }
862         if (modelInfo.getModelVersionId() == null) {
863             modelInfo.setModelVersionId(serviceRecord.getModelUUID());
864         }
865         if (recipe == null) {
866             return null;
867         }
868         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
869     }
870
871     protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
872         RequestParameters reqParam;
873         if (requestDetails.getRequestParameters() == null) {
874             reqParam = new RequestParameters();
875         } else {
876             reqParam = requestDetails.getRequestParameters();
877         }
878         if (requestDetails.getCloudConfiguration() == null) {
879             CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
880             if (cloudConfig != null) {
881                 requestDetails.setCloudConfiguration(cloudConfig);
882             }
883         }
884
885         List<Map<String, Object>> userParams = configureUserParams(reqParam);
886         if (!userParams.isEmpty()) {
887             if (reqParam == null) {
888                 requestDetails.setRequestParameters(new RequestParameters());
889             }
890             requestDetails.getRequestParameters().setUserParams(userParams);
891         }
892     }
893
894     private Service serviceMapper(Map<String, Object> params) throws IOException {
895         ObjectMapper obj = new ObjectMapper();
896         String input = obj.writeValueAsString(params.get("service"));
897         return obj.readValue(input, Service.class);
898     }
899
900     private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
901         for (Map<String, String> map : sourceUserParams) {
902             for (Map.Entry<String, String> entry : map.entrySet()) {
903                 targetUserParams.put(entry.getKey(), entry.getValue());
904             }
905         }
906     }
907
908     protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
909         logger.debug("Configuring UserParams for Macro Request");
910         Map<String, Object> userParams = new HashMap<>();
911
912         for (Map<String, Object> params : reqParams.getUserParams()) {
913             if (params.containsKey("service")) {
914                 Service service = serviceMapper(params);
915
916                 addUserParams(userParams, service.getInstanceParams());
917
918                 for (Networks network : service.getResources().getNetworks()) {
919                     addUserParams(userParams, network.getInstanceParams());
920                 }
921
922                 for (Vnfs vnf : service.getResources().getVnfs()) {
923                     addUserParams(userParams, vnf.getInstanceParams());
924
925                     for (VfModules vfModule : vnf.getVfModules()) {
926                         addUserParams(userParams, vfModule.getInstanceParams());
927                     }
928                 }
929             }
930         }
931
932         return mapFlatMapToNameValue(userParams);
933     }
934
935     protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
936         List<Map<String, Object>> targetUserParams = new ArrayList<>();
937
938         for (Map.Entry<String, Object> map : flatMap.entrySet()) {
939             Map<String, Object> targetMap = new HashMap<>();
940             targetMap.put(NAME, map.getKey());
941             targetMap.put(VALUE, map.getValue());
942             targetUserParams.add(targetMap);
943         }
944         return targetUserParams;
945     }
946
947     protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
948
949         for (Map<String, Object> params : reqParams.getUserParams()) {
950             if (params.containsKey("service")) {
951                 Service service = serviceMapper(params);
952
953                 Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
954
955                 if (targetConfiguration.isPresent()) {
956                     return targetConfiguration.get();
957                 } else {
958                     for (Networks network : service.getResources().getNetworks()) {
959                         targetConfiguration = addCloudConfig(network.getCloudConfiguration());
960                         if (targetConfiguration.isPresent()) {
961                             return targetConfiguration.get();
962                         }
963                     }
964
965                     for (Vnfs vnf : service.getResources().getVnfs()) {
966                         targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
967
968                         if (targetConfiguration.isPresent()) {
969                             return targetConfiguration.get();
970                         }
971
972                         for (VfModules vfModule : vnf.getVfModules()) {
973                             targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
974
975                             if (targetConfiguration.isPresent()) {
976                                 return targetConfiguration.get();
977                             }
978                         }
979                     }
980                 }
981             }
982         }
983
984         return null;
985     }
986
987     private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
988         String defaultSource = getDefaultModel(sir);
989         VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
990         if (vnfRecipe == null) {
991             return null;
992         }
993         return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
994     }
995
996
997     private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
998         String defaultNetworkType = getDefaultModel(sir);
999         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
1000         String modelName = modelInfo.getModelName();
1001         Recipe recipe = null;
1002
1003         if (modelInfo.getModelCustomizationId() != null) {
1004             NetworkResourceCustomization networkResourceCustomization = catalogDbClient
1005                     .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
1006             if (networkResourceCustomization != null) {
1007                 NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
1008                 if (networkResource != null) {
1009                     if (modelInfo.getModelVersionId() == null) {
1010                         modelInfo.setModelVersionId(networkResource.getModelUUID());
1011                     }
1012                     recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
1013                             action.toString());
1014                 } else {
1015                     throw new ValidationException("no catalog entry found");
1016                 }
1017             } else if (action != Action.deleteInstance) {
1018                 throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
1019             }
1020         } else {
1021             // ok for version < 3 and action delete
1022             if (modelName != null) {
1023                 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
1024             }
1025         }
1026
1027         if (recipe == null) {
1028             recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
1029         }
1030
1031         return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
1032     }
1033
1034
1035     private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
1036         CloudConfiguration targetConfiguration = new CloudConfiguration();
1037         if (sourceCloudConfiguration != null) {
1038             targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
1039             targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
1040             targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
1041             targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
1042             return Optional.of(targetConfiguration);
1043         }
1044         return Optional.empty();
1045     }
1046
1047     private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
1048             throws ValidationException {
1049
1050         ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
1051         String vnfComponentType = modelInfo.getModelType().name();
1052
1053         RelatedInstanceList[] instanceList = null;
1054         if (servInstReq.getRequestDetails() != null) {
1055             instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
1056         }
1057
1058         Recipe recipe;
1059         String defaultSource = getDefaultModel(servInstReq);
1060         String modelCustomizationId = modelInfo.getModelCustomizationId();
1061         String modelCustomizationName = modelInfo.getModelCustomizationName();
1062         String relatedInstanceModelVersionId = null;
1063         String relatedInstanceModelInvariantId = null;
1064         String relatedInstanceVersion = null;
1065         String relatedInstanceModelCustomizationName = null;
1066
1067         if (instanceList != null) {
1068
1069             for (RelatedInstanceList relatedInstanceList : instanceList) {
1070
1071                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
1072                 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
1073                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
1074                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1075                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1076                 }
1077
1078                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
1079                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1080                     relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
1081                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1082                     relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
1083                 }
1084             }
1085
1086             if (modelInfo.getModelType().equals(ModelType.vnf)) {
1087                 // a. For a vnf request (only create, no update currently):
1088                 // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
1089                 // vnf_resource_customization.model_customization_uuid.
1090                 // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1091                 // pre-v3), then modelInfo.modelCustomizationName must have
1092                 // been provided (else create request should be rejected). APIH should use the
1093                 // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
1094                 // to â€œjoinâ€�? service_to_resource_customizations with vnf_resource_customization to confirm a
1095                 // vnf_resource_customization.model_customization_uuid record exists.
1096                 // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
1097                 // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
1098                 // (MODEL_UUID) in SERVICE table.
1099                 // iii. Regardless of how the value was provided/obtained above, APIH must always populate
1100                 // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
1101                 // during 1707 data migration if VID did not provide it originally on request.
1102                 // iv. Note: continue to construct the â€œvnf-typeâ€�? value and pass to BPMN (must still be populated
1103                 // in A&AI).
1104                 // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
1105                 // look it up in our catalog to construct vnf-type value to pass to BPMN.
1106
1107                 VnfResource vnfResource = null;
1108                 VnfResourceCustomization vrc = null;
1109                 // Validation for vnfResource
1110
1111                 if (modelCustomizationId != null) {
1112                     vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
1113                     if (vrc != null) {
1114                         vnfResource = vrc.getVnfResources();
1115                     }
1116                 } else {
1117                     org.onap.so.db.catalog.beans.Service service =
1118                             catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
1119                     if (service == null) {
1120                         service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
1121                                 relatedInstanceModelInvariantId);
1122                     }
1123
1124                     if (service == null) {
1125                         throw new ValidationException("service in relatedInstance");
1126                     }
1127                     for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
1128                         if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
1129                             vrc = vnfResourceCustom;
1130                         }
1131                     }
1132
1133                     if (vrc != null) {
1134                         vnfResource = vrc.getVnfResources();
1135                         modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
1136                         modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
1137                     }
1138                 }
1139
1140                 if (vnfResource == null) {
1141                     throw new ValidationException("vnfResource");
1142                 } else {
1143                     if (modelInfo.getModelVersionId() == null) {
1144                         modelInfo.setModelVersionId(vnfResource.getModelUUID());
1145                     }
1146                 }
1147
1148                 VnfRecipe vnfRecipe = null;
1149
1150                 if (vrc != null) {
1151                     String nfRole = vrc.getNfRole();
1152                     if (nfRole != null) {
1153                         vnfRecipe =
1154                                 catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
1155                     }
1156                 }
1157
1158                 if (vnfRecipe == null) {
1159                     vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1160                 }
1161
1162                 if (vnfRecipe == null) {
1163                     return null;
1164                 }
1165
1166                 return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
1167             } else {
1168                 /*
1169                  * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1170                  * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
1171                  * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
1172                  * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
1173                  * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
1174                  * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
1175                  * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
1176                  * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
1177                  * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
1178                  * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
1179                  * the request). This means taking each record found // in vf_module_customization and looking up in
1180                  * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
1181                  * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
1182                  */
1183                 VfModuleCustomization vfmc = null;
1184                 VnfResource vnfr;
1185                 VnfResourceCustomization vnfrc;
1186                 VfModule vfModule = null;
1187
1188                 if (modelInfo.getModelCustomizationId() != null) {
1189                     vfmc = catalogDbClient
1190                             .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
1191                 } else {
1192                     vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
1193                     if (vnfr == null) {
1194                         vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
1195                                 relatedInstanceModelInvariantId, relatedInstanceVersion);
1196                     }
1197                     vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
1198                             relatedInstanceModelCustomizationName, vnfr);
1199
1200                     List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
1201
1202                     String vfModuleModelUUID = modelInfo.getModelVersionId();
1203                     for (VfModuleCustomization vf : list) {
1204                         VfModuleCustomization vfmCustom;
1205                         if (vfModuleModelUUID != null) {
1206                             vfmCustom = catalogDbClient
1207                                     .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
1208                                             vf.getModelCustomizationUUID(), vfModuleModelUUID);
1209                             if (vfmCustom != null) {
1210                                 vfModule = vfmCustom.getVfModule();
1211                             }
1212                         } else {
1213                             vfmCustom = catalogDbClient
1214                                     .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
1215                             if (vfmCustom != null) {
1216                                 vfModule = vfmCustom.getVfModule();
1217                             } else {
1218                                 vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
1219                                         relatedInstanceModelInvariantId, relatedInstanceVersion);
1220                             }
1221                         }
1222
1223                         if (vfModule != null) {
1224                             modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
1225                             modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
1226                             break;
1227                         }
1228                     }
1229                 }
1230
1231                 if (vfmc == null && vfModule == null) {
1232                     throw new ValidationException("vfModuleCustomization");
1233                 } else if (vfModule == null && vfmc != null) {
1234                     vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
1235                                                    // VfModuleCustomization table
1236                 }
1237
1238                 if (modelInfo.getModelVersionId() == null) {
1239                     modelInfo.setModelVersionId(vfModule.getModelUUID());
1240                 }
1241
1242
1243                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1244                         vfModule.getModelUUID(), vnfComponentType, action.toString());
1245                 if (recipe == null) {
1246                     List<VfModule> vfModuleRecords = catalogDbClient
1247                             .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
1248                     if (!vfModuleRecords.isEmpty()) {
1249                         for (VfModule record : vfModuleRecords) {
1250                             recipe = catalogDbClient
1251                                     .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1252                                             record.getModelUUID(), vnfComponentType, action.toString());
1253                             if (recipe != null) {
1254                                 break;
1255                             }
1256                         }
1257                     }
1258                 }
1259                 if (recipe == null) {
1260                     recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1261                             defaultSource, vnfComponentType, action.toString());
1262                     if (recipe == null) {
1263                         recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
1264                                 vnfComponentType, action.toString());
1265                     }
1266
1267                     if (recipe == null) {
1268                         return null;
1269                     }
1270                 }
1271             }
1272         } else {
1273
1274             if (modelInfo.getModelType().equals(ModelType.vnf)) {
1275                 recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1276                 if (recipe == null) {
1277                     return null;
1278                 }
1279             } else {
1280                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1281                         defaultSource, vnfComponentType, action.toString());
1282
1283                 if (recipe == null) {
1284                     return null;
1285                 }
1286             }
1287         }
1288
1289         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
1290     }
1291 }