2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7 * Modifications Copyright (C) 2019 IBM.
8 * ================================================================================
9 * Modifications Copyright (c) 2019 Samsung
10 * ================================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
22 * ============LICENSE_END=========================================================
25 package org.onap.so.apihandlerinfra;
28 import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID;
29 import java.io.IOException;
31 import java.sql.Timestamp;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
36 import java.util.Optional;
37 import javax.ws.rs.container.ContainerRequestContext;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import org.apache.commons.lang.StringUtils;
41 import org.apache.http.HttpResponse;
42 import org.apache.http.HttpStatus;
43 import org.camunda.bpm.engine.history.HistoricProcessInstance;
44 import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
45 import org.onap.logging.ref.slf4j.ONAPLogConstants;
46 import org.onap.so.apihandler.camundabeans.CamundaResponse;
47 import org.onap.so.apihandler.common.CommonConstants;
48 import org.onap.so.apihandler.common.ErrorNumbers;
49 import org.onap.so.apihandler.common.RequestClient;
50 import org.onap.so.apihandler.common.RequestClientFactory;
51 import org.onap.so.apihandler.common.RequestClientParameter;
52 import org.onap.so.apihandler.common.ResponseBuilder;
53 import org.onap.so.apihandler.common.ResponseHandler;
54 import org.onap.so.apihandlerinfra.exceptions.ApiException;
55 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
56 import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
57 import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException;
58 import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException;
59 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
60 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
61 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
62 import org.onap.so.apihandlerinfra.exceptions.VfModuleNotFoundException;
63 import org.onap.so.apihandlerinfra.infra.rest.handler.AbstractRestHandler;
64 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
65 import org.onap.so.constants.Status;
66 import org.onap.so.db.catalog.beans.NetworkResource;
67 import org.onap.so.db.catalog.beans.NetworkResourceCustomization;
68 import org.onap.so.db.catalog.beans.Recipe;
69 import org.onap.so.db.catalog.beans.ServiceRecipe;
70 import org.onap.so.db.catalog.beans.VfModule;
71 import org.onap.so.db.catalog.beans.VfModuleCustomization;
72 import org.onap.so.db.catalog.beans.VnfRecipe;
73 import org.onap.so.db.catalog.beans.VnfResource;
74 import org.onap.so.db.catalog.beans.VnfResourceCustomization;
75 import org.onap.so.db.catalog.client.CatalogDbClient;
76 import org.onap.so.db.request.beans.InfraActiveRequests;
77 import org.onap.so.db.request.client.RequestsDbClient;
78 import org.onap.so.exceptions.ValidationException;
79 import org.onap.so.logger.ErrorCode;
80 import org.onap.so.logger.LogConstants;
81 import org.onap.so.logger.MessageEnum;
82 import org.onap.so.serviceinstancebeans.CloudConfiguration;
83 import org.onap.so.serviceinstancebeans.ModelInfo;
84 import org.onap.so.serviceinstancebeans.ModelType;
85 import org.onap.so.serviceinstancebeans.Networks;
86 import org.onap.so.serviceinstancebeans.RelatedInstance;
87 import org.onap.so.serviceinstancebeans.RelatedInstanceList;
88 import org.onap.so.serviceinstancebeans.RequestDetails;
89 import org.onap.so.serviceinstancebeans.RequestParameters;
90 import org.onap.so.serviceinstancebeans.Service;
91 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
92 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
93 import org.onap.so.serviceinstancebeans.VfModules;
94 import org.onap.so.serviceinstancebeans.Vnfs;
95 import org.onap.so.utils.UUIDChecker;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
99 import org.springframework.beans.factory.annotation.Autowired;
100 import org.springframework.core.env.Environment;
101 import org.springframework.http.ResponseEntity;
102 import org.springframework.stereotype.Component;
103 import org.springframework.web.client.RestClientException;
104 import com.fasterxml.jackson.annotation.JsonInclude.Include;
105 import com.fasterxml.jackson.databind.ObjectMapper;
108 public class RequestHandlerUtils extends AbstractRestHandler {
110 private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class);
112 protected static final String SAVE_TO_DB = "save instance to db";
113 private static final String NAME = "name";
114 private static final String VALUE = "value";
117 private Environment env;
120 private RequestClientFactory reqClientFactory;
123 private ResponseBuilder builder;
126 private MsoRequest msoRequest;
129 private CamundaRequestHandler camundaRequestHandler;
132 private CatalogDbClient catalogDbClient;
134 public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter,
135 String orchestrationUri, String requestScope) throws ApiException {
136 HttpResponse response = null;
137 RequestClient requestClient = null;
140 requestClient = reqClientFactory.getRequestClient(orchestrationUri);
141 response = requestClient.post(requestClientParameter);
142 } catch (Exception e) {
143 logger.error("Error posting request to BPMN", e);
144 ErrorLoggerInfo errorLoggerInfo =
145 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError)
146 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
147 String url = requestClient != null ? requestClient.getUrl() : "";
148 ClientConnectionException clientException =
149 new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY,
150 ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build();
151 updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
152 throw clientException;
155 if (response == null) {
157 ErrorLoggerInfo errorLoggerInfo =
158 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcessError)
159 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
160 ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(),
161 HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build();
162 updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage());
163 throw clientException;
166 ResponseHandler respHandler = null;
167 int bpelStatus = 500;
169 respHandler = new ResponseHandler(response, requestClient.getType());
170 bpelStatus = respHandler.getStatus();
171 } catch (ApiException e) {
172 logger.error("Exception occurred", e);
173 ErrorLoggerInfo errorLoggerInfo =
174 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
175 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
176 ValidateException validateException =
177 new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
178 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
179 .errorInfo(errorLoggerInfo).build();
180 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
181 throw validateException;
184 // BPEL accepted the request, the request is in progress
185 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
186 ServiceInstancesResponse jsonResponse;
187 CamundaResponse camundaResp = respHandler.getResponse();
189 if ("Success".equalsIgnoreCase(camundaResp.getMessage())) {
191 ObjectMapper mapper = new ObjectMapper();
192 jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class);
193 jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId());
194 Optional<URL> selfLinkUrl =
195 buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId());
196 if (selfLinkUrl.isPresent()) {
197 jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get());
199 jsonResponse.getRequestReferences().setRequestSelfLink(null);
201 } catch (IOException e) {
202 logger.error("Exception occurred", e);
203 ErrorLoggerInfo errorLoggerInfo =
204 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
205 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
206 ValidateException validateException =
207 new ValidateException.Builder("Exception caught mapping Camunda JSON response to object",
208 HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
209 .errorInfo(errorLoggerInfo).build();
210 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
211 throw validateException;
213 return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(),
214 jsonResponse, requestClientParameter.getApiVersion());
218 List<String> variables = new ArrayList<>();
219 variables.add(bpelStatus + "");
220 String camundaJSONResponseBody = respHandler.getResponseBody();
221 if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
223 ErrorLoggerInfo errorLoggerInfo =
224 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
225 .errorSource(requestClient.getUrl()).build();
226 BPMNFailureException bpmnException =
227 new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus,
228 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
230 updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage());
235 ErrorLoggerInfo errorLoggerInfo =
236 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcessError)
237 .errorSource(requestClient.getUrl()).build();
240 BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus),
241 bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
242 updateStatus(currentActiveReq, Status.FAILED, servException.getMessage());
251 public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
252 throws RequestDbFailureException {
253 if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
254 aq.setStatusMessage(errorMessage);
255 aq.setProgress(new Long(100));
256 aq.setRequestStatus(status.toString());
257 Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
258 aq.setEndTime(endTimeStamp);
260 infraActiveRequestsClient.save(aq);
261 } catch (Exception e) {
262 ErrorLoggerInfo errorLoggerInfo =
263 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
264 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
265 throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(),
266 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
267 .errorInfo(errorLoggerInfo).build();
272 public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) {
273 if (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig) {
274 return (ModelType.vnf.name());
275 } else if (action == Action.addMembers || action == Action.removeMembers) {
276 return (ModelType.instanceGroup.toString());
278 String requestScope = requestScopeFromUri(requestUri);;
280 if (sir.getRequestDetails() == null) {
283 if (sir.getRequestDetails().getModelInfo() == null) {
286 if (sir.getRequestDetails().getModelInfo().getModelType() == null) {
289 requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
295 public void validateHeaders(ContainerRequestContext context) throws ValidationException {
296 MultivaluedMap<String, String> headers = context.getHeaders();
297 if (!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)) {
298 throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true);
300 if (!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)) {
301 throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true);
303 if (!headers.containsKey(REQUESTOR_ID)) {
304 throw new ValidationException(REQUESTOR_ID + " header", true);
308 public String getRequestUri(ContainerRequestContext context, String uriPrefix) {
309 String requestUri = context.getUriInfo().getPath();
310 String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
311 MDC.put(LogConstants.HTTP_URL, httpUrl);
312 requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length());
316 public void checkForDuplicateRequests(Actions action, HashMap<String, String> instanceIdMap, String requestScope,
317 InfraActiveRequests currentActiveReq, String instanceName) throws ApiException {
318 InfraActiveRequests dup = null;
319 boolean inProgress = false;
321 dup = duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq);
324 inProgress = camundaHistoryCheck(dup, currentActiveReq);
327 if (dup != null && inProgress) {
328 buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, requestScope, dup);
332 public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap,
333 String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
334 InfraActiveRequests dup = null;
336 if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
337 || action == Action.activateInstance || action == Action.assignInstance))) {
338 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
340 } catch (Exception e) {
341 ErrorLoggerInfo errorLoggerInfo =
342 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
343 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
344 RequestDbFailureException requestDbFailureException =
345 new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
346 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
347 .errorInfo(errorLoggerInfo).build();
348 updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
349 throw requestDbFailureException;
354 public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq)
355 throws RequestDbFailureException, ContactCamundaException {
356 String requestId = duplicateRecord.getRequestId();
357 ResponseEntity<List<HistoricProcessInstanceEntity>> response = null;
359 response = camundaRequestHandler.getCamundaProcessInstanceHistory(requestId, true, true, false);
360 } catch (RestClientException e) {
361 logger.error("Error querying Camunda for process-instance history for requestId: {}, exception: {}",
362 requestId, e.getMessage());
363 ContactCamundaException contactCamundaException =
364 new ContactCamundaException.Builder("process-instance", requestId, e.toString(),
365 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
367 updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage());
368 throw contactCamundaException;
371 if (response.getBody().isEmpty()) {
372 updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed");
379 public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action,
380 String requestId, String requestUri) throws ApiException {
382 ObjectMapper mapper = new ObjectMapper();
383 return mapper.readValue(requestJSON, ServiceInstancesRequest.class);
385 } catch (IOException e) {
387 ErrorLoggerInfo errorLoggerInfo =
388 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
389 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
391 ValidateException validateException =
392 new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
393 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
394 String requestScope = requestScopeFromUri(requestUri);
396 msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
397 requestScope, requestJSON);
399 throw validateException;
403 public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action,
404 String version, String requestJSON, Boolean aLaCarte, String requestId,
405 InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException {
406 int reqVersion = Integer.parseInt(version.substring(1));
408 msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
409 } catch (Exception e) {
410 logger.error("failed to parse request", e);
411 ErrorLoggerInfo errorLoggerInfo =
412 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
413 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
414 ValidateException validateException =
415 new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
416 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
418 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
420 throw validateException;
424 public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action,
425 HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup)
426 throws ApiException {
428 String instance = null;
429 if (instanceName != null) {
430 instance = instanceName;
432 instance = instanceIdMap.get(requestScope + "InstanceId");
434 ErrorLoggerInfo errorLoggerInfo =
435 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError)
436 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
438 DuplicateRequestException dupException =
439 new DuplicateRequestException.Builder(requestScope, instance, dup.getRequestStatus(),
440 dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
441 .errorInfo(errorLoggerInfo).build();
443 updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage());
449 public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
450 String requestId = null;
451 if (requestContext.getProperty("requestId") != null) {
452 requestId = requestContext.getProperty("requestId").toString();
454 if (UUIDChecker.isValidUUID(requestId)) {
457 ErrorLoggerInfo errorLoggerInfo =
458 new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
459 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
460 ValidateException validateException =
461 new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
462 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
463 .errorInfo(errorLoggerInfo).build();
465 throw validateException;
469 public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId,
470 Map<String, String> instanceIdMap) {
471 if (StringUtils.isNotBlank(instanceId)) {
472 if (ModelType.service.name().equalsIgnoreCase(requestScope)) {
473 currentActiveReq.setServiceInstanceId(instanceId);
474 } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) {
475 currentActiveReq.setVnfId(instanceId);
476 } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) {
477 currentActiveReq.setVfModuleId(instanceId);
478 } else if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) {
479 currentActiveReq.setVolumeGroupId(instanceId);
480 } else if (ModelType.network.name().equalsIgnoreCase(requestScope)) {
481 currentActiveReq.setNetworkId(instanceId);
482 } else if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) {
483 currentActiveReq.setConfigurationId(instanceId);
484 } else if (ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)) {
485 currentActiveReq.setInstanceGroupId(instanceId);
487 } else if (instanceIdMap != null && !instanceIdMap.isEmpty()) {
488 if (instanceIdMap.get("serviceInstanceId") != null) {
489 currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId"));
491 if (instanceIdMap.get("vnfInstanceId") != null) {
492 currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId"));
494 if (instanceIdMap.get("vfModuleInstanceId") != null) {
495 currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId"));
497 if (instanceIdMap.get("volumeGroupInstanceId") != null) {
498 currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId"));
500 if (instanceIdMap.get("networkInstanceId") != null) {
501 currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId"));
503 if (instanceIdMap.get("configurationInstanceId") != null) {
504 currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId"));
506 if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) {
507 currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID));
509 if (instanceIdMap.get("pnfName") != null) {
510 currentActiveReq.setPnfName(instanceIdMap.get("pnfName"));
515 public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest,
516 boolean isAlaCarte, Actions action) throws IOException {
517 ObjectMapper mapper = new ObjectMapper();
518 mapper.setSerializationInclusion(Include.NON_NULL);
519 if (serviceInstRequest != null) {
520 return mapper.writeValueAsString(serviceInstRequest);
522 return msoRawRequest;
526 public Optional<String> retrieveModelName(RequestParameters requestParams) {
527 String requestTestApi = null;
528 TestApi testApi = null;
530 if (requestParams != null) {
531 requestTestApi = requestParams.getTestApi();
534 if (requestTestApi == null) {
535 if (requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) {
536 requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API);
538 requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API);
543 testApi = TestApi.valueOf(requestTestApi);
544 return Optional.of(testApi.getModelName());
545 } catch (Exception e) {
546 logger.warn("Catching the exception on the valueOf enum call and continuing", e);
547 throw new IllegalArgumentException("Invalid TestApi is provided", e);
551 public String getDefaultModel(ServiceInstancesRequest sir) {
552 String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT";
553 Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters());
554 if (oModelName.isPresent()) {
555 defaultModel = oModelName.get();
560 public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag) {
561 String serviceType = null;
562 if (requestScope.equalsIgnoreCase(ModelType.service.toString())) {
563 String defaultServiceModelName = getDefaultModel(sir);
564 org.onap.so.db.catalog.beans.Service serviceRecord;
566 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
567 if (serviceRecord != null) {
568 serviceType = serviceRecord.getServiceType();
572 catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId());
573 if (serviceRecord != null) {
574 serviceType = serviceRecord.getServiceType();
576 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
577 if (serviceRecord != null) {
578 serviceType = serviceRecord.getServiceType();
583 serviceType = msoRequest.getServiceInstanceType(sir, requestScope);
588 protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) {
589 if (sir.getServiceInstanceId() != null) {
590 return sir.getServiceInstanceId();
591 } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) {
592 RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList();
593 if (relatedInstances != null) {
594 for (RelatedInstanceList relatedInstanceList : relatedInstances) {
595 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
596 if (relatedInstance.getModelInfo().getModelType() == ModelType.service) {
597 return relatedInstance.getInstanceId();
605 private String requestScopeFromUri(String requestUri) {
607 if (requestUri.contains(ModelType.network.name())) {
608 requestScope = ModelType.network.name();
609 } else if (requestUri.contains(ModelType.vfModule.name())) {
610 requestScope = ModelType.vfModule.name();
611 } else if (requestUri.contains(ModelType.volumeGroup.name())) {
612 requestScope = ModelType.volumeGroup.name();
613 } else if (requestUri.contains(ModelType.configuration.name())) {
614 requestScope = ModelType.configuration.name();
615 } else if (requestUri.contains(ModelType.vnf.name())) {
616 requestScope = ModelType.vnf.name();
617 } else if (requestUri.contains(ModelType.pnf.name())) {
618 requestScope = ModelType.pnf.name();
620 requestScope = ModelType.service.name();
625 protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest,
626 String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId,
627 String originalRequestId) throws ApiException {
628 InfraActiveRequests request = new InfraActiveRequests();
629 request.setRequestId(requestId);
630 request.setStartTime(startTimeStamp);
631 request.setSource(source);
632 request.setRequestUrl(requestUri);
633 request.setProgress(new Long(5));
634 request.setRequestorId(requestorId);
635 request.setRequestStatus(Status.IN_PROGRESS.toString());
636 request.setOriginalRequestId(originalRequestId);
637 request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
638 if (infraActiveRequest != null) {
639 request.setTenantId(infraActiveRequest.getTenantId());
640 request.setRequestBody(updateRequestorIdInRequestBody(infraActiveRequest, requestorId));
641 request.setCloudRegion(infraActiveRequest.getCloudRegion());
642 request.setRequestScope(infraActiveRequest.getRequestScope());
643 request.setRequestAction(infraActiveRequest.getRequestAction());
644 setInstanceIdAndName(infraActiveRequest, request);
649 protected void setInstanceIdAndName(InfraActiveRequests infraActiveRequest,
650 InfraActiveRequests currentActiveRequest) throws ApiException {
651 String requestScope = infraActiveRequest.getRequestScope();
653 ModelType type = ModelType.valueOf(requestScope);
654 String instanceName = type.getName(infraActiveRequest);
655 if (instanceName == null && type.equals(ModelType.vfModule)) {
656 logger.error("vfModule for requestId: {} being resumed does not have an instanceName.",
657 infraActiveRequest.getRequestId());
658 ValidateException validateException = new ValidateException.Builder(
659 "vfModule for requestId: " + infraActiveRequest.getRequestId()
660 + " being resumed does not have an instanceName.",
661 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).build();
662 updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
663 throw validateException;
665 if (instanceName != null) {
666 type.setName(currentActiveRequest, instanceName);
668 type.setId(currentActiveRequest, type.getId(infraActiveRequest));
669 } catch (IllegalArgumentException e) {
671 "requestScope \"{}\" does not match a ModelType enum. Unable to set instanceId and instanceName from the original request.",
676 protected Boolean getIsBaseVfModule(ModelInfo modelInfo, Actions action, String vnfType,
677 String sdcServiceModelVersion, InfraActiveRequests currentActiveReq) throws ApiException {
678 // Get VF Module-specific base module indicator
680 String modelVersionId = modelInfo.getModelVersionId();
681 Boolean isBaseVfModule = false;
683 if (modelVersionId != null) {
684 vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId);
685 } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) {
686 vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(),
687 modelInfo.getModelVersion());
691 if (vfm.getIsBase()) {
692 isBaseVfModule = true;
694 } else if (action == Action.createInstance || action == Action.updateInstance) {
695 String serviceVersionText = "";
696 if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) {
697 serviceVersionText = " with version " + sdcServiceModelVersion;
699 String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName()
700 + serviceVersionText + " not found in MSO Catalog DB";
701 ErrorLoggerInfo errorLoggerInfo =
702 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
703 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
704 VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage,
705 HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build();
706 updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage());
707 throw vfModuleException;
709 return isBaseVfModule;
712 protected ModelType getModelType(Actions action, ModelInfo modelInfo) {
713 if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
714 return ModelType.vnf;
715 } else if (action == Action.addMembers || action == Action.removeMembers) {
716 return ModelType.instanceGroup;
718 return modelInfo.getModelType();
722 protected String updateRequestorIdInRequestBody(InfraActiveRequests infraActiveRequest, String newRequestorId) {
723 String requestBody = infraActiveRequest.getRequestBody();
724 return requestBody.replaceAll(
725 "(?s)(\"requestInfo\"\\s*?:\\s*?\\{.*?\"requestorId\"\\s*?:\\s*?\")(.*?)(\"[ ]*(?:,|\\R|\\}))",
726 "$1" + newRequestorId + "$3");
729 public RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action,
730 boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException {
731 RecipeLookupResult recipeLookupResult = null;
732 // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action
733 ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
734 // Query MSO Catalog DB
736 if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) {
737 recipeLookupResult = getDefaultVnfUri(sir, action);
738 } else if (action == Action.addMembers || action == Action.removeMembers) {
739 recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
740 } else if (modelInfo.getModelType().equals(ModelType.service)) {
742 recipeLookupResult = getServiceURI(sir, action, alaCarteFlag);
743 } catch (IOException e) {
744 ErrorLoggerInfo errorLoggerInfo =
745 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
746 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
749 ValidateException validateException =
750 new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
751 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
753 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
755 throw validateException;
757 } else if (modelInfo.getModelType().equals(ModelType.vfModule)
758 || modelInfo.getModelType().equals(ModelType.volumeGroup)
759 || modelInfo.getModelType().equals(ModelType.vnf)) {
761 recipeLookupResult = getVnfOrVfModuleUri(sir, action);
762 } catch (ValidationException e) {
763 ErrorLoggerInfo errorLoggerInfo =
764 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
765 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
768 ValidateException validateException =
769 new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
770 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
772 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
774 throw validateException;
776 } else if (modelInfo.getModelType().equals(ModelType.network)) {
778 recipeLookupResult = getNetworkUri(sir, action);
779 } catch (ValidationException e) {
781 ErrorLoggerInfo errorLoggerInfo =
782 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
783 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
786 ValidateException validateException =
787 new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
788 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
789 updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
791 throw validateException;
793 } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) {
794 recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180);
797 if (recipeLookupResult == null) {
798 ErrorLoggerInfo errorLoggerInfo =
799 new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
800 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
803 RecipeNotFoundException recipeNotFoundExceptionException =
804 new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
805 HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
808 updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
809 throw recipeNotFoundExceptionException;
811 return recipeLookupResult;
814 protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action,
815 boolean alaCarteFlag) throws IOException {
817 // Construct the default service name
818 // TODO need to make this a configurable property
819 String defaultServiceModelName = getDefaultModel(servInstReq);
820 RequestDetails requestDetails = servInstReq.getRequestDetails();
821 ModelInfo modelInfo = requestDetails.getModelInfo();
822 org.onap.so.db.catalog.beans.Service serviceRecord;
823 List<org.onap.so.db.catalog.beans.Service> serviceRecordList;
824 ServiceRecipe recipe = null;
827 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
828 if (serviceRecord != null) {
829 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
833 serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId());
834 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(),
836 if (recipe == null) {
837 serviceRecordList = catalogDbClient
838 .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId());
839 if (!serviceRecordList.isEmpty()) {
840 for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) {
841 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),
843 if (recipe != null) {
851 // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found
852 RequestParameters reqParam = requestDetails.getRequestParameters();
853 if (reqParam != null && alaCarteFlag && recipe == null) {
855 } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) {
856 mapToLegacyRequest(requestDetails);
857 } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default
858 serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
859 recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),
862 if (modelInfo.getModelVersionId() == null) {
863 modelInfo.setModelVersionId(serviceRecord.getModelUUID());
865 if (recipe == null) {
868 return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());
871 protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException {
872 RequestParameters reqParam;
873 if (requestDetails.getRequestParameters() == null) {
874 reqParam = new RequestParameters();
876 reqParam = requestDetails.getRequestParameters();
878 if (requestDetails.getCloudConfiguration() == null) {
879 CloudConfiguration cloudConfig = configureCloudConfig(reqParam);
880 if (cloudConfig != null) {
881 requestDetails.setCloudConfiguration(cloudConfig);
885 List<Map<String, Object>> userParams = configureUserParams(reqParam);
886 if (!userParams.isEmpty()) {
887 if (reqParam == null) {
888 requestDetails.setRequestParameters(new RequestParameters());
890 requestDetails.getRequestParameters().setUserParams(userParams);
894 private Service serviceMapper(Map<String, Object> params) throws IOException {
895 ObjectMapper obj = new ObjectMapper();
896 String input = obj.writeValueAsString(params.get("service"));
897 return obj.readValue(input, Service.class);
900 private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) {
901 for (Map<String, String> map : sourceUserParams) {
902 for (Map.Entry<String, String> entry : map.entrySet()) {
903 targetUserParams.put(entry.getKey(), entry.getValue());
908 protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException {
909 logger.debug("Configuring UserParams for Macro Request");
910 Map<String, Object> userParams = new HashMap<>();
912 for (Map<String, Object> params : reqParams.getUserParams()) {
913 if (params.containsKey("service")) {
914 Service service = serviceMapper(params);
916 addUserParams(userParams, service.getInstanceParams());
918 for (Networks network : service.getResources().getNetworks()) {
919 addUserParams(userParams, network.getInstanceParams());
922 for (Vnfs vnf : service.getResources().getVnfs()) {
923 addUserParams(userParams, vnf.getInstanceParams());
925 for (VfModules vfModule : vnf.getVfModules()) {
926 addUserParams(userParams, vfModule.getInstanceParams());
932 return mapFlatMapToNameValue(userParams);
935 protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) {
936 List<Map<String, Object>> targetUserParams = new ArrayList<>();
938 for (Map.Entry<String, Object> map : flatMap.entrySet()) {
939 Map<String, Object> targetMap = new HashMap<>();
940 targetMap.put(NAME, map.getKey());
941 targetMap.put(VALUE, map.getValue());
942 targetUserParams.add(targetMap);
944 return targetUserParams;
947 protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException {
949 for (Map<String, Object> params : reqParams.getUserParams()) {
950 if (params.containsKey("service")) {
951 Service service = serviceMapper(params);
953 Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration());
955 if (targetConfiguration.isPresent()) {
956 return targetConfiguration.get();
958 for (Networks network : service.getResources().getNetworks()) {
959 targetConfiguration = addCloudConfig(network.getCloudConfiguration());
960 if (targetConfiguration.isPresent()) {
961 return targetConfiguration.get();
965 for (Vnfs vnf : service.getResources().getVnfs()) {
966 targetConfiguration = addCloudConfig(vnf.getCloudConfiguration());
968 if (targetConfiguration.isPresent()) {
969 return targetConfiguration.get();
972 for (VfModules vfModule : vnf.getVfModules()) {
973 targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration());
975 if (targetConfiguration.isPresent()) {
976 return targetConfiguration.get();
987 private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) {
988 String defaultSource = getDefaultModel(sir);
989 VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
990 if (vnfRecipe == null) {
993 return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
997 private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException {
998 String defaultNetworkType = getDefaultModel(sir);
999 ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
1000 String modelName = modelInfo.getModelName();
1001 Recipe recipe = null;
1003 if (modelInfo.getModelCustomizationId() != null) {
1004 NetworkResourceCustomization networkResourceCustomization = catalogDbClient
1005 .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId());
1006 if (networkResourceCustomization != null) {
1007 NetworkResource networkResource = networkResourceCustomization.getNetworkResource();
1008 if (networkResource != null) {
1009 if (modelInfo.getModelVersionId() == null) {
1010 modelInfo.setModelVersionId(networkResource.getModelUUID());
1012 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(),
1015 throw new ValidationException("no catalog entry found");
1017 } else if (action != Action.deleteInstance) {
1018 throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true);
1021 // ok for version < 3 and action delete
1022 if (modelName != null) {
1023 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString());
1027 if (recipe == null) {
1028 recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString());
1031 return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null;
1035 private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) {
1036 CloudConfiguration targetConfiguration = new CloudConfiguration();
1037 if (sourceCloudConfiguration != null) {
1038 targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli());
1039 targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId());
1040 targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId());
1041 targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner());
1042 return Optional.of(targetConfiguration);
1044 return Optional.empty();
1047 private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action)
1048 throws ValidationException {
1050 ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo();
1051 String vnfComponentType = modelInfo.getModelType().name();
1053 RelatedInstanceList[] instanceList = null;
1054 if (servInstReq.getRequestDetails() != null) {
1055 instanceList = servInstReq.getRequestDetails().getRelatedInstanceList();
1059 String defaultSource = getDefaultModel(servInstReq);
1060 String modelCustomizationId = modelInfo.getModelCustomizationId();
1061 String modelCustomizationName = modelInfo.getModelCustomizationName();
1062 String relatedInstanceModelVersionId = null;
1063 String relatedInstanceModelInvariantId = null;
1064 String relatedInstanceVersion = null;
1065 String relatedInstanceModelCustomizationName = null;
1067 if (instanceList != null) {
1069 for (RelatedInstanceList relatedInstanceList : instanceList) {
1071 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
1072 ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo();
1073 if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) {
1074 relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1075 relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1078 if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) {
1079 relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId();
1080 relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId();
1081 relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion();
1082 relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName();
1086 if (modelInfo.getModelType().equals(ModelType.vnf)) {
1087 // a. For a vnf request (only create, no update currently):
1088 // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in
1089 // vnf_resource_customization.model_customization_uuid.
1090 // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1091 // pre-v3), then modelInfo.modelCustomizationName must have
1092 // been provided (else create request should be rejected). APIH should use the
1093 // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName
1094 // to “join�? service_to_resource_customizations with vnf_resource_customization to confirm a
1095 // vnf_resource_customization.model_customization_uuid record exists.
1096 // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use
1097 // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId
1098 // (MODEL_UUID) in SERVICE table.
1099 // iii. Regardless of how the value was provided/obtained above, APIH must always populate
1100 // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated
1101 // during 1707 data migration if VID did not provide it originally on request.
1102 // iv. Note: continue to construct the “vnf-type�? value and pass to BPMN (must still be populated
1104 // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to
1105 // look it up in our catalog to construct vnf-type value to pass to BPMN.
1107 VnfResource vnfResource = null;
1108 VnfResourceCustomization vrc = null;
1109 // Validation for vnfResource
1111 if (modelCustomizationId != null) {
1112 vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId);
1114 vnfResource = vrc.getVnfResources();
1117 org.onap.so.db.catalog.beans.Service service =
1118 catalogDbClient.getServiceByID(relatedInstanceModelVersionId);
1119 if (service == null) {
1120 service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion,
1121 relatedInstanceModelInvariantId);
1124 if (service == null) {
1125 throw new ValidationException("service in relatedInstance");
1127 for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) {
1128 if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) {
1129 vrc = vnfResourceCustom;
1134 vnfResource = vrc.getVnfResources();
1135 modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID());
1136 modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID());
1140 if (vnfResource == null) {
1141 throw new ValidationException("vnfResource");
1143 if (modelInfo.getModelVersionId() == null) {
1144 modelInfo.setModelVersionId(vnfResource.getModelUUID());
1148 VnfRecipe vnfRecipe = null;
1151 String nfRole = vrc.getNfRole();
1152 if (nfRole != null) {
1154 catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString());
1158 if (vnfRecipe == null) {
1159 vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1162 if (vnfRecipe == null) {
1166 return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
1169 * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or
1170 * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should
1171 * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId +
1172 * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with
1173 * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record
1174 * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule
1175 * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. //
1176 * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query
1177 * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm
1178 * record matches request data (and to identify the modelCustomizationId associated with the vfModule in
1179 * the request). This means taking each record found // in vf_module_customization and looking up in
1180 * vf_module (using vf_module_customization’s FK into vf_module) to find a match on
1181 * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion).
1183 VfModuleCustomization vfmc = null;
1185 VnfResourceCustomization vnfrc;
1186 VfModule vfModule = null;
1188 if (modelInfo.getModelCustomizationId() != null) {
1189 vfmc = catalogDbClient
1190 .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId());
1192 vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId);
1194 vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(
1195 relatedInstanceModelInvariantId, relatedInstanceVersion);
1197 vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(
1198 relatedInstanceModelCustomizationName, vnfr);
1200 List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations();
1202 String vfModuleModelUUID = modelInfo.getModelVersionId();
1203 for (VfModuleCustomization vf : list) {
1204 VfModuleCustomization vfmCustom;
1205 if (vfModuleModelUUID != null) {
1206 vfmCustom = catalogDbClient
1207 .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(
1208 vf.getModelCustomizationUUID(), vfModuleModelUUID);
1209 if (vfmCustom != null) {
1210 vfModule = vfmCustom.getVfModule();
1213 vfmCustom = catalogDbClient
1214 .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID());
1215 if (vfmCustom != null) {
1216 vfModule = vfmCustom.getVfModule();
1218 vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(
1219 relatedInstanceModelInvariantId, relatedInstanceVersion);
1223 if (vfModule != null) {
1224 modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID());
1225 modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID());
1231 if (vfmc == null && vfModule == null) {
1232 throw new ValidationException("vfModuleCustomization");
1233 } else if (vfModule == null && vfmc != null) {
1234 vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in
1235 // VfModuleCustomization table
1238 if (modelInfo.getModelVersionId() == null) {
1239 modelInfo.setModelVersionId(vfModule.getModelUUID());
1243 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1244 vfModule.getModelUUID(), vnfComponentType, action.toString());
1245 if (recipe == null) {
1246 List<VfModule> vfModuleRecords = catalogDbClient
1247 .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID());
1248 if (!vfModuleRecords.isEmpty()) {
1249 for (VfModule record : vfModuleRecords) {
1250 recipe = catalogDbClient
1251 .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1252 record.getModelUUID(), vnfComponentType, action.toString());
1253 if (recipe != null) {
1259 if (recipe == null) {
1260 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1261 defaultSource, vnfComponentType, action.toString());
1262 if (recipe == null) {
1263 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(
1264 vnfComponentType, action.toString());
1267 if (recipe == null) {
1274 if (modelInfo.getModelType().equals(ModelType.vnf)) {
1275 recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString());
1276 if (recipe == null) {
1280 recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(
1281 defaultSource, vnfComponentType, action.toString());
1283 if (recipe == null) {
1289 return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout());