531d87c22992d929e2672fffa078e069d26cf453
[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         } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
725             recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
726         }
727
728         if (recipeLookupResult == null) {
729             ErrorLoggerInfo errorLoggerInfo =
730                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
731                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
732
733
734             RecipeNotFoundException recipeNotFoundExceptionException =
735                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
736                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
737                                     .build();
738
739             updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
740             throw recipeNotFoundExceptionException;
741         }
742         return recipeLookupResult;
743     }
744
745     protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
746             boolean alaCarteFlag) throws IOException {
747         // SERVICE REQUEST
748         // Construct the default service name
749         // TODO need to make this a configurable property
750         String defaultServiceModelName = getDefaultModel(servInstReq);
751         RequestDetails requestDetails = servInstReq.getRequestDetails();
752         ModelInfo modelInfo = requestDetails.getModelInfo();
753         org.onap.so.db.catalog.beans.Service serviceRecord;
754         List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
755         ServiceRecipe recipe = null;
756
757         if (alaCarteFlag) {
758             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
759             if (serviceRecord != null) {
760                 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
761                         action.toString());
762             }
763         } else {
764             serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
765             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
766                     action.toString());
767             if (recipe == null) {
768                 serviceRecordList = catalogDbClient
769                         .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
770                 if (!serviceRecordList.isEmpty()) {
771                     for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
772                         recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
773                                 action.toString());
774                         if (recipe != null) {
775                             break;
776                         }
777                     }
778                 }
779             }
780         }
781
782         // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
783         RequestParameters reqParam = requestDetails.getRequestParameters();
784         if (reqParam != null && alaCarteFlag && recipe == null) {
785             return null;
786         } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
787             mapToLegacyRequest(requestDetails);
788         } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
789             serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
790             recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
791                     action.toString());
792         }
793         if (modelInfo.getModelVersionId() == null) {
794             modelInfo.setModelVersionId(serviceRecord.getModelUUID());
795         }
796         if (recipe == null) {
797             return null;
798         }
799         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
800     }
801
802     protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
803         RequestParameters reqParam;
804         if (requestDetails.getRequestParameters() == null) {
805             reqParam = new RequestParameters();
806         } else {
807             reqParam = requestDetails.getRequestParameters();
808         }
809         if (requestDetails.getCloudConfiguration() == null) {
810             CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
811             if (cloudConfig != null) {
812                 requestDetails.setCloudConfiguration(cloudConfig);
813             }
814         }
815
816         List<Map<String, Object>> userParams = configureUserParams(reqParam);
817         if (!userParams.isEmpty()) {
818             if (reqParam == null) {
819                 requestDetails.setRequestParameters(new RequestParameters());
820             }
821             requestDetails.getRequestParameters().setUserParams(userParams);
822         }
823     }
824
825     private Service serviceMapper(Map<String, Object> params) throws IOException {
826         ObjectMapper obj = new ObjectMapper();
827         String input = obj.writeValueAsString(params.get("service"));
828         return obj.readValue(input, Service.class);
829     }
830
831     private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
832         for (Map<String, String> map : sourceUserParams) {
833             for (Map.Entry<String, String> entry : map.entrySet()) {
834                 targetUserParams.put(entry.getKey(), entry.getValue());
835             }
836         }
837     }
838
839     protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
840         logger.debug("Configuring UserParams for Macro Request");
841         Map<String, Object> userParams = new HashMap<>();
842
843         for (Map<String, Object> params : reqParams.getUserParams()) {
844             if (params.containsKey("service")) {
845                 Service service = serviceMapper(params);
846
847                 // Filter out non-string params for backward compatibility
848                 Map<String, String> svcStrParams = service.getInstanceParams().stream().map(Map::entrySet)
849                         .flatMap(Set::stream).filter(e -> e.getValue() instanceof String)
850                         .collect(Collectors.toMap(Entry::getKey, e -> (String) e.getValue()));
851                 userParams.putAll(svcStrParams);
852
853                 for (Networks network : service.getResources().getNetworks()) {
854                     addUserParams(userParams, network.getInstanceParams());
855                 }
856
857                 for (Vnfs vnf : service.getResources().getVnfs()) {
858                     addUserParams(userParams, vnf.getInstanceParams());
859
860                     for (VfModules vfModule : vnf.getVfModules()) {
861                         addUserParams(userParams, vfModule.getInstanceParams());
862                     }
863                 }
864             }
865         }
866
867         return mapFlatMapToNameValue(userParams);
868     }
869
870     protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
871         List<Map<String, Object>> targetUserParams = new ArrayList<>();
872
873         for (Map.Entry<String, Object> map : flatMap.entrySet()) {
874             Map<String, Object> targetMap = new HashMap<>();
875             targetMap.put(NAME, map.getKey());
876             targetMap.put(VALUE, map.getValue());
877             targetUserParams.add(targetMap);
878         }
879         return targetUserParams;
880     }
881
882     protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
883
884         for (Map<String, Object> params : reqParams.getUserParams()) {
885             if (params.containsKey("service")) {
886                 Service service = serviceMapper(params);
887
888                 Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
889
890                 if (targetConfiguration.isPresent()) {
891                     return targetConfiguration.get();
892                 } else {
893                     for (Networks network : service.getResources().getNetworks()) {
894                         targetConfiguration = addCloudConfig(network.getCloudConfiguration());
895                         if (targetConfiguration.isPresent()) {
896                             return targetConfiguration.get();
897                         }
898                     }
899
900                     for (Vnfs vnf : service.getResources().getVnfs()) {
901                         targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
902
903                         if (targetConfiguration.isPresent()) {
904                             return targetConfiguration.get();
905                         }
906
907                         for (VfModules vfModule : vnf.getVfModules()) {
908                             targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
909
910                             if (targetConfiguration.isPresent()) {
911                                 return targetConfiguration.get();
912                             }
913                         }
914                     }
915                 }
916             }
917         }
918
919         return null;
920     }
921
922     protected Optional<String> getServiceInstanceIdForValidationError(ServiceInstancesRequest sir,
923             HashMap<String, String> instanceIdMap, String requestScope) {
924         if (instanceIdMap != null && !instanceIdMap.isEmpty() && instanceIdMap.get("serviceInstanceId") != null) {
925             return Optional.of(instanceIdMap.get("serviceInstanceId"));
926         } else {
927             return getServiceInstanceIdForInstanceGroup(requestScope, sir);
928         }
929     }
930
931     protected Optional<String> getServiceInstanceIdForInstanceGroup(String requestScope, ServiceInstancesRequest sir) {
932         if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
933             RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
934             if (relatedInstances != null) {
935                 for (RelatedInstanceList relatedInstanceList : relatedInstances) {
936                     RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
937                     if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
938                         return Optional.ofNullable(relatedInstance.getInstanceId());
939                     }
940                 }
941             }
942         }
943         return Optional.empty();
944     }
945
946     private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
947         String defaultSource = getDefaultModel(sir);
948         VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
949         if (vnfRecipe == null) {
950             return null;
951         }
952         return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
953     }
954
955
956     private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
957         String defaultNetworkType = getDefaultModel(sir);
958         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
959         String modelName = modelInfo.getModelName();
960         Recipe recipe = null;
961
962         if (modelInfo.getModelCustomizationId() != null) {
963             NetworkResourceCustomization networkResourceCustomization = catalogDbClient
964                     .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
965             if (networkResourceCustomization != null) {
966                 NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
967                 if (networkResource != null) {
968                     if (modelInfo.getModelVersionId() == null) {
969                         modelInfo.setModelVersionId(networkResource.getModelUUID());
970                     }
971                     recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
972                             action.toString());
973                 } else {
974                     throw new ValidationException("no catalog entry found");
975                 }
976             } else if (action != Action.deleteInstance) {
977                 throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
978             }
979         } else {
980             // ok for version < 3 and action delete
981             if (modelName != null) {
982                 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
983             }
984         }
985
986         if (recipe == null) {
987             recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
988         }
989
990         return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
991     }
992
993
994     private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
995         CloudConfiguration targetConfiguration = new CloudConfiguration();
996         if (sourceCloudConfiguration != null) {
997             targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
998             targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
999             targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
1000             targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
1001             return Optional.of(targetConfiguration);
1002         }
1003         return Optional.empty();
1004     }
1005
1006     private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
1007             throws ValidationException {
1008
1009         ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
1010         String vnfComponentType = modelInfo.getModelType().name();
1011
1012         RelatedInstanceList[] instanceList = null;
1013         if (servInstReq.getRequestDetails() != null) {
1014             instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
1015         }
1016
1017         Recipe recipe;
1018         String defaultSource = getDefaultModel(servInstReq);
1019         String modelCustomizationId = modelInfo.getModelCustomizationId();
1020         String modelCustomizationName = modelInfo.getModelCustomizationName();
1021         String relatedInstanceModelVersionId = null;
1022         String relatedInstanceModelInvariantId = null;
1023         String relatedInstanceVersion = null;
1024         String relatedInstanceModelCustomizationName = null;
1025
1026         if (instanceList != null) {
1027
1028             for (RelatedInstanceList relatedInstanceList : instanceList) {
1029
1030                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
1031                 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
1032                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
1033                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1034                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1035                 }
1036
1037                 if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
1038                     relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1039                     relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
1040                     relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1041                     relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
1042                 }
1043             }
1044
1045             if (modelInfo.getModelType().equals(ModelType.vnf)) {
1046                 // a. For a vnf request (only create, no update currently):
1047                 // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
1048                 // vnf_resource_customization.model_customization_uuid.
1049                 // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1050                 // pre-v3), then modelInfo.modelCustomizationName must have
1051                 // been provided (else create request should be rejected). APIH should use the
1052                 // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
1053                 // to â€œjoinâ€�? service_to_resource_customizations with vnf_resource_customization to confirm a
1054                 // vnf_resource_customization.model_customization_uuid record exists.
1055                 // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
1056                 // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
1057                 // (MODEL_UUID) in SERVICE table.
1058                 // iii. Regardless of how the value was provided/obtained above, APIH must always populate
1059                 // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
1060                 // during 1707 data migration if VID did not provide it originally on request.
1061                 // iv. Note: continue to construct the â€œvnf-typeâ€�? value and pass to BPMN (must still be populated
1062                 // in A&AI).
1063                 // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
1064                 // look it up in our catalog to construct vnf-type value to pass to BPMN.
1065
1066                 VnfResource vnfResource = null;
1067                 VnfResourceCustomization vrc = null;
1068                 // Validation for vnfResource
1069
1070                 if (modelCustomizationId != null) {
1071                     vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
1072                     if (vrc != null) {
1073                         vnfResource = vrc.getVnfResources();
1074                     }
1075                 } else {
1076                     org.onap.so.db.catalog.beans.Service service =
1077                             catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
1078                     if (service == null) {
1079                         service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
1080                                 relatedInstanceModelInvariantId);
1081                     }
1082
1083                     if (service == null) {
1084                         throw new ValidationException("service in relatedInstance");
1085                     }
1086                     for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
1087                         if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
1088                             vrc = vnfResourceCustom;
1089                         }
1090                     }
1091
1092                     if (vrc != null) {
1093                         vnfResource = vrc.getVnfResources();
1094                         modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
1095                         modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
1096                     }
1097                 }
1098
1099                 if (vnfResource == null) {
1100                     throw new ValidationException("vnfResource");
1101                 } else {
1102                     if (modelInfo.getModelVersionId() == null) {
1103                         modelInfo.setModelVersionId(vnfResource.getModelUUID());
1104                     }
1105                 }
1106
1107                 VnfRecipe vnfRecipe = null;
1108
1109                 if (vrc != null) {
1110                     String nfRole = vrc.getNfRole();
1111                     if (nfRole != null) {
1112                         vnfRecipe =
1113                                 catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
1114                     }
1115                 }
1116
1117                 if (vnfRecipe == null) {
1118                     vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1119                 }
1120
1121                 if (vnfRecipe == null) {
1122                     return null;
1123                 }
1124
1125                 return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
1126             } else {
1127                 /*
1128                  * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1129                  * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
1130                  * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
1131                  * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
1132                  * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
1133                  * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
1134                  * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
1135                  * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
1136                  * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
1137                  * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
1138                  * the request). This means taking each record found // in vf_module_customization and looking up in
1139                  * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
1140                  * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
1141                  */
1142                 VfModuleCustomization vfmc = null;
1143                 VnfResource vnfr;
1144                 VnfResourceCustomization vnfrc;
1145                 VfModule vfModule = null;
1146
1147                 if (modelInfo.getModelCustomizationId() != null) {
1148                     vfmc = catalogDbClient
1149                             .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
1150                 } else {
1151                     vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
1152                     if (vnfr == null) {
1153                         vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
1154                                 relatedInstanceModelInvariantId, relatedInstanceVersion);
1155                     }
1156                     vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
1157                             relatedInstanceModelCustomizationName, vnfr);
1158
1159                     List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
1160
1161                     String vfModuleModelUUID = modelInfo.getModelVersionId();
1162                     for (VfModuleCustomization vf : list) {
1163                         VfModuleCustomization vfmCustom;
1164                         if (vfModuleModelUUID != null) {
1165                             vfmCustom = catalogDbClient
1166                                     .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
1167                                             vf.getModelCustomizationUUID(), vfModuleModelUUID);
1168                             if (vfmCustom != null) {
1169                                 vfModule = vfmCustom.getVfModule();
1170                             }
1171                         } else {
1172                             vfmCustom = catalogDbClient
1173                                     .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
1174                             if (vfmCustom != null) {
1175                                 vfModule = vfmCustom.getVfModule();
1176                             } else {
1177                                 vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
1178                                         relatedInstanceModelInvariantId, relatedInstanceVersion);
1179                             }
1180                         }
1181
1182                         if (vfModule != null) {
1183                             modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
1184                             modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
1185                             break;
1186                         }
1187                     }
1188                 }
1189
1190                 if (vfmc == null && vfModule == null) {
1191                     throw new ValidationException("vfModuleCustomization");
1192                 } else if (vfModule == null && vfmc != null) {
1193                     vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
1194                                                    // VfModuleCustomization table
1195                 }
1196
1197                 if (modelInfo.getModelVersionId() == null) {
1198                     modelInfo.setModelVersionId(vfModule.getModelUUID());
1199                 }
1200
1201
1202                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1203                         vfModule.getModelUUID(), vnfComponentType, action.toString());
1204                 if (recipe == null) {
1205                     List<VfModule> vfModuleRecords = catalogDbClient
1206                             .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
1207                     if (!vfModuleRecords.isEmpty()) {
1208                         for (VfModule record : vfModuleRecords) {
1209                             recipe = catalogDbClient
1210                                     .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1211                                             record.getModelUUID(), vnfComponentType, action.toString());
1212                             if (recipe != null) {
1213                                 break;
1214                             }
1215                         }
1216                     }
1217                 }
1218                 if (recipe == null) {
1219                     recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1220                             defaultSource, vnfComponentType, action.toString());
1221                     if (recipe == null) {
1222                         recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
1223                                 vnfComponentType, action.toString());
1224                     }
1225
1226                     if (recipe == null) {
1227                         return null;
1228                     }
1229                 }
1230             }
1231         } else {
1232
1233             if (modelInfo.getModelType().equals(ModelType.vnf)) {
1234                 recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1235                 if (recipe == null) {
1236                     return null;
1237                 }
1238             } else {
1239                 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1240                         defaultSource, vnfComponentType, action.toString());
1241
1242                 if (recipe == null) {
1243                     return null;
1244                 }
1245             }
1246         }
1247
1248         return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
1249     }
1250 }