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