diff options
Diffstat (limited to 'mso-api-handlers')
36 files changed, 1381 insertions, 411 deletions
diff --git a/mso-api-handlers/mso-api-handler-common/pom.xml b/mso-api-handlers/mso-api-handler-common/pom.xml index a3fd37ce2b..865de7998f 100644 --- a/mso-api-handlers/mso-api-handler-common/pom.xml +++ b/mso-api-handlers/mso-api-handler-common/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 84a80e6617..3a7c7ad477 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> @@ -98,6 +98,10 @@ <artifactId>spring-retry</artifactId> </dependency> <dependency> + <groupId>org.springframework.boot</groupId> + <artifactId>spring-boot-starter-webflux</artifactId> + </dependency> + <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java index 17377d881a..f30b66c6b5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/CamundaRequestHandler.java @@ -9,9 +9,11 @@ import javax.ws.rs.core.UriBuilder; import javax.xml.bind.DatatypeConverter; import org.camunda.bpm.engine.impl.persistence.entity.HistoricActivityInstanceEntity; import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.json.JSONObject; import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.utils.CryptoUtils; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -29,6 +31,9 @@ import org.springframework.stereotype.Component; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.WebClient; +import reactor.core.publisher.Flux; @Component public class CamundaRequestHandler { @@ -202,6 +207,20 @@ public class CamundaRequestHandler { return retryTemplate; } + protected void sendCamundaMessages(JSONObject msgJson) { + String url = env.getProperty("mso.camundaURL") + "/sobpmnengine/message"; + HttpHeaders headers = + setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON); + // Workflow may take a long time so use non-blocking request + Flux<String> flux = WebClient.create().post().uri(url).headers(httpHeaders -> { + httpHeaders.set(httpHeaders.AUTHORIZATION, headers.get(httpHeaders.AUTHORIZATION).get(0)); + httpHeaders.set(httpHeaders.ACCEPT, headers.get(httpHeaders.ACCEPT).get(0)); + httpHeaders.set(httpHeaders.CONTENT_TYPE, headers.get(httpHeaders.CONTENT_TYPE).get(0)); + }).body(BodyInserters.fromObject(msgJson.toString())).retrieve().bodyToFlux(String.class); + flux.subscribe(res -> logger.debug("Send Camunda Message: " + res)); + } + protected RestTemplate getRestTemplate(boolean retry) { int timeout; if (retry) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java index dbdc274bc6..88028d32a1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -7,12 +7,14 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -93,7 +95,7 @@ public class InstanceManagement { @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Execute custom workflow", responses = @ApiResponse( + @Operation(description = "Execute custom VNF workflow", responses = @ApiResponse( content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response executeVNFCustomWorkflow(String request, @PathParam("version") String version, @@ -110,20 +112,20 @@ public class InstanceManagement { } @POST - @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfId}/workflows/{workflowUuid}") + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/pnfs/{pnfName}/workflows/{workflowUuid}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @Operation(description = "Execute custom workflow", responses = @ApiResponse( + @Operation(description = "Execute custom PNF workflow", responses = @ApiResponse( content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) @Transactional public Response executePNFCustomWorkflow(String request, @PathParam("version") String version, - @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfId") String pnfId, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("pnfName") String pnfName, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException { String requestId = requestHandlerUtils.getRequestId(requestContext); HashMap<String, String> instanceIdMap = new HashMap<>(); instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("pnfId", pnfId); + instanceIdMap.put("pnfName", pnfName); instanceIdMap.put("workflowUuid", workflowUuid); return processPNFCustomWorkflowRequest(request, Action.forCustomWorkflow, instanceIdMap, version, requestId, requestContext); @@ -133,7 +135,7 @@ public class InstanceManagement { HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException { String serviceInstanceId; - Boolean aLaCarte = true; + boolean aLaCarte = true; ServiceInstancesRequest sir; String apiVersion = version.substring(1); @@ -162,26 +164,14 @@ public class InstanceManagement { currentActiveReq); requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - int requestVersion = Integer.parseInt(version.substring(1)); - String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion); + String vnfType = msoRequest.getVnfType(sir, requestScope); if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) { currentActiveReq.setVnfType(vnfType); } - InfraActiveRequests dup = null; - boolean inProgress = false; - - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } + checkDuplicateAndBuildError(action, instanceIdMap, requestScope, currentActiveReq); - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, - dup); - } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); RequestReferences referencesResponse = new RequestReferences(); @@ -189,7 +179,7 @@ public class InstanceManagement { referencesResponse.setRequestId(requestId); serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; + boolean isBaseVfModule = false; String workflowUuid = null; if (instanceIdMap != null) { @@ -207,17 +197,9 @@ public class InstanceManagement { vnfId = sir.getVnfInstanceId(); } - try { - infraActiveRequestsClient.save(currentActiveReq); - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); - } + saveCurrentActiveRequest(currentActiveReq); - RequestClientParameter requestClientParameter = null; + RequestClientParameter requestClientParameter; try { requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) @@ -237,26 +219,54 @@ public class InstanceManagement { recipeLookupResult.getOrchestrationURI(), requestScope); } + private void saveCurrentActiveRequest(InfraActiveRequests currentActiveReq) throws RequestDbFailureException { + try { + infraActiveRequestsClient.save(currentActiveReq); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + } + + private void checkDuplicateAndBuildError(Actions action, HashMap<String, String> instanceIdMap, String requestScope, + InfraActiveRequests currentActiveReq) throws ApiException { + + InfraActiveRequests dup = + requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); + if (dup == null) { + return; + } + + boolean inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); + } + } + private Response processPNFCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException { - Boolean aLaCarte = false; + boolean aLaCarte = false; ServiceInstancesRequest sir; String apiVersion = version.substring(1); String serviceInstanceId = ""; - String pnfId = ""; + String pnfName = ""; String workflowUuid = ""; if (instanceIdMap != null) { serviceInstanceId = instanceIdMap.get("serviceInstanceId"); - pnfId = instanceIdMap.get("pnfId"); + pnfName = instanceIdMap.get("pnfName"); workflowUuid = instanceIdMap.get("workflowUuid"); } String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); sir.setServiceInstanceId(serviceInstanceId); - sir.setPnfId(pnfId); + sir.setPnfName(pnfName); String requestScope = ModelType.pnf.name(); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -279,37 +289,17 @@ public class InstanceManagement { currentActiveReq); requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - InfraActiveRequests dup = null; - boolean inProgress = false; - - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); - - if (dup != null) { - inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, - dup); - } + checkDuplicateAndBuildError(action, instanceIdMap, requestScope, currentActiveReq); RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid); - try { - infraActiveRequestsClient.save(currentActiveReq); - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) - .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); - } + saveCurrentActiveRequest(currentActiveReq); - RequestClientParameter requestClientParameter = null; + RequestClientParameter requestClientParameter; try { requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()).setRequestAction(action.toString()) - .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfId) + .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfName) .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action)) .setApiVersion(apiVersion).setRequestUri(requestUri).build(); } catch (IOException e) { @@ -326,7 +316,7 @@ public class InstanceManagement { private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq, String workflowUuid) throws ApiException { - RecipeLookupResult recipeLookupResult = null; + RecipeLookupResult recipeLookupResult; try { recipeLookupResult = getCustomWorkflowUri(workflowUuid); @@ -359,14 +349,12 @@ public class InstanceManagement { private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) { - String recipeUri = null; Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid); - if (workflow == null) { - return null; - } else { + if (workflow != null) { String workflowName = workflow.getName(); - recipeUri = "/mso/async/services/" + workflowName; + String recipeUri = "/mso/async/services/" + workflowName; + return new RecipeLookupResult(recipeUri, 180); } - return new RecipeLookupResult(recipeUri, 180); + return null; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java index b7288e4c91..0afc272b0a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/JerseyConfiguration.java @@ -92,6 +92,7 @@ public class JerseyConfiguration extends ResourceConfig { register(NoRecipeExceptionMapper.class); register(RequestConflictMapper.class); register(WorkflowEngineConnectionMapper.class); + register(OrchestrationTasks.class); // this registration seems to be needed to get predictable // execution behavior for the above JSON Exception Mappers register(com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider.class); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java index c077558301..ce371203ab 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoRequest.java @@ -7,12 +7,14 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nokia + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -30,7 +32,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Map.Entry; +import java.util.Optional; import java.util.StringTokenizer; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; @@ -40,7 +42,11 @@ import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; +import org.onap.aai.domain.yang.GenericVnf; +import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.Tenant; import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; @@ -69,7 +75,6 @@ import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.LogConstants; import org.onap.so.serviceinstancebeans.CloudConfiguration; -import org.onap.so.serviceinstancebeans.InstanceDirection; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.PolicyException; @@ -96,7 +101,6 @@ import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; - @Component public class MsoRequest { @@ -106,6 +110,9 @@ public class MsoRequest { @Autowired private ResponseBuilder builder; + @Autowired + private AAIDataRetrieval aaiDataRet; + @Value("${mso.enforceDLP:false}") private boolean enforceDLP; @@ -148,7 +155,6 @@ public class MsoRequest { } - // Parse request JSON public void parse(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, String version, String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) @@ -222,44 +228,31 @@ public class MsoRequest { } } - public Map<String, List<String>> getOrchestrationFilters(MultivaluedMap<String, String> queryParams) - throws ValidationException { - - String queryParam = null; + public Map<String, List<String>> getOrchestrationFilters(MultivaluedMap<String, String> queryParams) { + final String FILTER_KEY = "filter"; Map<String, List<String>> orchestrationFilterParams = new HashMap<>(); + Optional.ofNullable(queryParams.get(FILTER_KEY)).ifPresent(listValues -> listValues + .forEach(value -> addValueToOrchestrationFilterParamsMap(orchestrationFilterParams, value))); - for (Entry<String, List<String>> entry : queryParams.entrySet()) { - queryParam = entry.getKey(); - - try { - if ("filter".equalsIgnoreCase(queryParam)) { - for (String value : entry.getValue()) { - StringTokenizer st = new StringTokenizer(value, ":"); - - int counter = 0; - String mapKey = null; - List<String> orchestrationList = new ArrayList<>(); - while (st.hasMoreElements()) { - if (counter == 0) { - mapKey = st.nextElement() + ""; - } else { - orchestrationList.add(st.nextElement() + ""); - } - counter++; - } - orchestrationFilterParams.put(mapKey, orchestrationList); - } - } + return orchestrationFilterParams; + } - } catch (Exception e) { - throw new ValidationException("QueryParam ServiceInfo", e); - } + private void addValueToOrchestrationFilterParamsMap(Map<String, List<String>> orchestrationFilterParams, + String value) { + final String TOKEN_DELIMITER = ":"; + StringTokenizer stringTokenizer = new StringTokenizer(value, TOKEN_DELIMITER); + if (!stringTokenizer.hasMoreTokens()) { + return; + } + String mapKey = stringTokenizer.nextToken(); + List<String> orchestrationList = new ArrayList<>(); + while (stringTokenizer.hasMoreTokens()) { + orchestrationList.add(stringTokenizer.nextToken()); } - - return orchestrationFilterParams; + orchestrationFilterParams.put(mapKey, orchestrationList); } public InfraActiveRequests createRequestObject(ServiceInstancesRequest servInsReq, Actions action, String requestId, @@ -324,11 +317,30 @@ public class MsoRequest { aq.setVnfId(servInsReq.getVnfInstanceId()); } - if (servInsReq.getPnfId() != null) { + if (servInsReq.getPnfName() != null) { aq.setRequestScope(requestScope); - aq.setPnfId(servInsReq.getPnfId()); + aq.setPnfName(servInsReq.getPnfName()); + } + + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getRequestInfo() != null + && servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId() != null) { + logger.debug("Retrieving productFamilyName to put into requests db"); + + org.onap.aai.domain.yang.Service service = + aaiDataRet.getService(servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId()); + if (service != null) { + logger.debug("Found service by service-id"); + String productFamilyName = service.getServiceDescription(); + if (productFamilyName != null) { + aq.setProductFamilyName(productFamilyName); + } + } } + aq.setProductFamilyName(getProductFamilyNameFromAAI(servInsReq)); + + aq.setTenantName(getTenantNameFromAAI(servInsReq)); + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { if (servInsReq.getRequestDetails().getRequestInfo() != null) { if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { @@ -465,7 +477,6 @@ public class MsoRequest { } - public Response buildResponse(int httpResponseCode, String errorCode, InfraActiveRequests inProgress) { return buildResponseWithError(httpResponseCode, errorCode, inProgress, null); } @@ -474,7 +485,6 @@ public class MsoRequest { String errorString) { - // Log the failed request into the MSO Requests database return Response.status(httpResponseCode).entity(null).build(); @@ -487,7 +497,6 @@ public class MsoRequest { } - public String getServiceType(VnfInputs vnfInputs) { if (vnfInputs.getServiceType() != null) return vnfInputs.getServiceType(); @@ -625,156 +634,105 @@ public class MsoRequest { } - public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { + public String getVfModuleType(ServiceInstancesRequest sir, String requestScope) { - String serviceInstanceType = null; - - String vnfType = null; + String vnfType; String vfModuleType = null; - String vfModuleModelName = null; + String vfModuleModelName; ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList(); String serviceModelName = null; String vnfModelName = null; - String asdcServiceModelVersion = null; String volumeGroupId = null; - boolean isRelatedServiceInstancePresent = false; - boolean isRelatedVnfInstancePresent = false; - boolean isSourceVnfPresent = false; - boolean isDestinationVnfPresent = false; - boolean isConnectionPointPresent = false; - - if (instanceList != null) { - for (RelatedInstanceList relatedInstanceList : instanceList) { - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); - - if (action != Action.deleteInstance) { - - if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - if (InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) - && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) { - isSourceVnfPresent = true; - } else if (InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) - && (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) - || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) - && reqVersion == 6))) { - isDestinationVnfPresent = true; - } - } - - if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) - && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - isConnectionPointPresent = true; - } - } - - if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { - isRelatedServiceInstancePresent = true; - serviceModelName = relatedInstanceModelInfo.getModelName(); - asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion(); - } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) - && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { - isRelatedVnfInstancePresent = true; - vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); - } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { - volumeGroupId = relatedInstance.getInstanceId(); - } + if (instanceList == null) { + return null; + } + for (RelatedInstanceList relatedInstanceList : instanceList) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); + + if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + serviceModelName = relatedInstanceModelInfo.getModelName(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) + && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { + vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { + volumeGroupId = relatedInstance.getInstanceId(); } - - if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) { - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { - vfModuleModelName = modelInfo.getModelName(); - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - vfModuleType = vnfType + "::" + vfModuleModelName; - sir.setVolumeGroupInstanceId(volumeGroupId); - } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) - vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName(); - + } + if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { + vfModuleModelName = modelInfo.getModelName(); + vnfType = serviceModelName + "/" + vnfModelName; + vfModuleType = vnfType + "::" + vfModuleModelName; + sir.setVolumeGroupInstanceId(volumeGroupId); } return vfModuleType; } - public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { + public String getVnfType(ServiceInstancesRequest sir, String requestScope) { - String serviceInstanceType = null; - String networkType = null; String vnfType = null; - String vfModuleType = null; - String vfModuleModelName = null; - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList(); String serviceModelName = null; String vnfModelName = null; - String asdcServiceModelVersion = null; String volumeGroupId = null; - boolean isRelatedServiceInstancePresent = false; - boolean isRelatedVnfInstancePresent = false; - boolean isSourceVnfPresent = false; - boolean isDestinationVnfPresent = false; - boolean isConnectionPointPresent = false; - - if (instanceList != null) { - for (RelatedInstanceList relatedInstanceList : instanceList) { - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); - if (action != Action.deleteInstance) { - - if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - if (InstanceDirection.source.equals(relatedInstance.getInstanceDirection()) - && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) { - isSourceVnfPresent = true; - } else if (InstanceDirection.destination.equals(relatedInstance.getInstanceDirection()) - && (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) - || (relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) - && reqVersion == 6))) { - isDestinationVnfPresent = true; - } - } + if (instanceList == null) { + return null; + } + for (RelatedInstanceList relatedInstanceList : instanceList) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); + + if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + serviceModelName = relatedInstanceModelInfo.getModelName(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) + && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { + vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { + volumeGroupId = relatedInstance.getInstanceId(); + } + } - if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) - && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - isConnectionPointPresent = true; - } - } + if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) { + vnfType = serviceModelName + "/" + vnfModelName; + } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { + vnfType = serviceModelName + "/" + vnfModelName; + sir.setVolumeGroupInstanceId(volumeGroupId); + } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) + vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName(); + return vnfType; + } - if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { - isRelatedServiceInstancePresent = true; - serviceModelName = relatedInstanceModelInfo.getModelName(); - asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion(); - } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) - && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { - isRelatedVnfInstancePresent = true; - vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); - } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { - volumeGroupId = relatedInstance.getInstanceId(); - } + protected String getTenantNameFromAAI(ServiceInstancesRequest servInsReq) { + String tenantName = null; + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getCloudConfiguration() != null + && servInsReq.getRequestDetails().getCloudConfiguration().getTenantId() != null) { + Tenant tenant = aaiDataRet.getTenant(servInsReq.getRequestDetails().getCloudConfiguration().getCloudOwner(), + servInsReq.getRequestDetails().getCloudConfiguration().getLcpCloudRegionId(), + servInsReq.getRequestDetails().getCloudConfiguration().getTenantId()); + if (tenant != null) { + tenantName = tenant.getTenantName(); } - - if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) { - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { - vfModuleModelName = modelInfo.getModelName(); - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - vfModuleType = vnfType + "::" + vfModuleModelName; - sir.setVolumeGroupInstanceId(volumeGroupId); - } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) - vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName(); - } + return tenantName; + } - return vnfType; - + protected String getProductFamilyNameFromAAI(ServiceInstancesRequest servInsReq) { + String productFamilyName = null; + if (servInsReq.getRequestDetails() != null && servInsReq.getRequestDetails().getRequestInfo() != null + && servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId() != null) { + org.onap.aai.domain.yang.Service service = + aaiDataRet.getService(servInsReq.getRequestDetails().getRequestInfo().getProductFamilyId()); + if (service != null) { + productFamilyName = service.getServiceDescription(); + } + } + return productFamilyName; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index ae68cc6032..fec93f72e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java @@ -347,6 +347,13 @@ public class OrchestrationRequests { } else { requestDetails = mapper.readValue(requestBody, RequestDetails.class); } + if (requestDetails.getRequestInfo() != null && iar.getProductFamilyName() != null) { + requestDetails.getRequestInfo().setProductFamilyName(iar.getProductFamilyName()); + } + if (requestDetails.getCloudConfiguration() != null && iar.getTenantName() != null) { + requestDetails.getCloudConfiguration().setTenantName(iar.getTenantName()); + } + } catch (IOException e) { logger.error("Exception occurred", e); ErrorLoggerInfo errorLoggerInfo = diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java new file mode 100644 index 0000000000..90cf50262b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationTasks.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.apihandlerinfra; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import org.apache.http.HttpStatus; +import org.json.JSONObject; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.db.request.beans.OrchestrationTask; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; +import org.onap.so.logger.MessageEnum; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import javax.transaction.Transactional; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import static org.onap.so.apihandlerinfra.Constants.MSO_PROP_APIHANDLER_INFRA; + +@Path("/onap/so/infra/orchestrationTasks") +@OpenAPIDefinition( + info = @Info(title = "onap/so/infra/orchestrationTasks", description = "API Requests for Orchestration Task")) +@Component +public class OrchestrationTasks { + + private static Logger logger = LoggerFactory.getLogger(OrchestrationTasks.class); + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private CamundaRequestHandler camundaRequestHandler; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private ResponseBuilder builder; + + private ObjectMapper mapper = new ObjectMapper(); + + @GET + @Path("/{version:[vV][4-7]}/") + @Operation(description = "Find All Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getAllOrchestrationTasks(@QueryParam("status") String status, + @PathParam("version") String version) { + List<OrchestrationTask> orchestrationTaskList = requestsDbClient.getAllOrchestrationTasks(); + if (status != null && !status.isEmpty()) { + for (Iterator<OrchestrationTask> it = orchestrationTaskList.iterator(); it.hasNext();) { + OrchestrationTask task = it.next(); + if (!status.equals(task.getStatus())) { + it.remove(); + } + } + } + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTaskList, version); + } + + @GET + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Find Orchestrated Task for a given TaskId", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) + throws ApiException { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Lookup", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + } + + @POST + @Path("/{version:[vV][4-7]}/") + @Operation(description = "Create an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response CreateOrchestrationTask(String requestJson, @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class); + requestsDbClient.createOrchestrationTask(orchestrationTask); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Create", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null, + version); + return response; + } + } + + @PUT + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Update an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response UpdateOrchestrationTask(@PathParam("taskId") String taskId, String requestJson, + @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Update", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + + try { + OrchestrationTask orchestrationTask = mapper.readValue(requestJson, OrchestrationTask.class); + requestsDbClient.updateOrchestrationTask(taskId, orchestrationTask); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Update", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, + version); + return response; + } + } + + @DELETE + @Path("/{version:[vV][4-7]}/{taskId}") + @Operation(description = "Delete an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response DeleteOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + try { + OrchestrationTask orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + + try { + requestsDbClient.deleteOrchestrationTask(taskId); + return builder.buildResponse(HttpStatus.SC_OK, null, null, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.COULD_NOT_WRITE_TO_REQUESTS_DB, null, + version); + return response; + } + } + + @POST + @Path("/{version:[vV][4-7]}/{taskId}/commit") + @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response CommitOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + OrchestrationTask orchestrationTask; + try { + orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Commit", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + try { + String taskName = orchestrationTask.getName(); + Map<String, String> commitVar = new HashMap<>(); + commitVar.put("taskAction", "commit"); + JSONObject msgJson = createMessageBody(taskId, taskName, commitVar); + camundaRequestHandler.sendCamundaMessages(msgJson); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version); + return response; + } + + } + + @POST + @Path("/{version:[vV][4-7]}/{taskId}/abort") + @Operation(description = "Commit an Orchestrated Task", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response AbortOrchestrationTask(@PathParam("taskId") String taskId, @PathParam("version") String version) { + OrchestrationTask orchestrationTask; + try { + orchestrationTask = requestsDbClient.getOrchestrationTask(taskId); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Commit", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + return response; + } + try { + String taskName = orchestrationTask.getName(); + Map<String, String> commitVar = new HashMap<>(); + commitVar.put("taskAction", "abort"); + JSONObject msgJson = createMessageBody(taskId, taskName, commitVar); + camundaRequestHandler.sendCamundaMessages(msgJson); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationTask, version); + } catch (Exception e) { + logger.error(LoggingAnchor.FOUR, MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Orchestration Task Delete", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, + MsoException.ServiceException, e.getMessage(), ErrorNumbers.ERROR_FROM_BPEL, null, version); + return response; + } + + } + + private JSONObject createMessageBody(String taskId, String taskName, Map<String, ?> variables) { + JSONObject msgJson = new JSONObject(); + msgJson.put("messageName", taskName); + msgJson.put("businessKey", taskId); + JSONObject processVariables = new JSONObject(); + for (Map.Entry<String, ?> entry : variables.entrySet()) { + JSONObject valueInfo = new JSONObject(); + String key = entry.getKey(); + Object value = entry.getValue(); + valueInfo.put("value", value.toString()); + valueInfo.put("type", value.getClass().getSimpleName()); + processVariables.put(key, valueInfo); + } + msgJson.put("processVariables", processVariables); + return msgJson; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java index 75b7e74d49..38fb1596d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -506,8 +506,8 @@ public class RequestHandlerUtils extends AbstractRestHandler { if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); } - if (instanceIdMap.get("PnfId") != null) { - currentActiveReq.setPnfId(instanceIdMap.get("PnfId")); + if (instanceIdMap.get("pnfName") != null) { + currentActiveReq.setPnfName(instanceIdMap.get("pnfName")); } } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java index 65537cbba0..a15d9cfd48 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -251,25 +251,22 @@ public class ResumeOrchestrationRequest { } try { - requestClientParameter = - new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId()) - .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(infraActiveRequest.getRequestAction()) - .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) - .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) - .setVfModuleId(infraActiveRequest.getVfModuleId()) - .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) - .setNetworkId(infraActiveRequest.getNetworkId()) - .setServiceType(infraActiveRequest.getServiceType()) - .setVnfType(infraActiveRequest.getVnfType()) - .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(), - action, Integer.parseInt(version))) - .setNetworkType(infraActiveRequest.getNetworkType()) - .setRequestDetails(requestHandlerUtils - .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action)) - .setApiVersion(version).setALaCarte(aLaCarte) - .setRequestUri(currentActiveRequest.getRequestUrl()) - .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); + requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(currentActiveRequest.getRequestId()).setBaseVfModule(isBaseVfModule) + .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(infraActiveRequest.getRequestAction()) + .setServiceInstanceId(infraActiveRequest.getServiceInstanceId()) + .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId()) + .setVfModuleId(infraActiveRequest.getVfModuleId()) + .setVolumeGroupId(infraActiveRequest.getVolumeGroupId()) + .setNetworkId(infraActiveRequest.getNetworkId()).setServiceType(infraActiveRequest.getServiceType()) + .setVnfType(infraActiveRequest.getVnfType()) + .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope())) + .setNetworkType(infraActiveRequest.getNetworkType()) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, + aLaCarte, action)) + .setApiVersion(version).setALaCarte(aLaCarte).setRequestUri(currentActiveRequest.getRequestUrl()) + .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build(); } catch (IOException e) { logger.error("IOException while generating requestClientParameter to send to BPMN", e); ErrorLoggerInfo errorLoggerInfo = diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java index 175b212c86..33eae43e44 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ServiceInstances.java @@ -844,17 +844,15 @@ public class ServiceInstances extends AbstractRestHandler { } requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - - int requestVersion = Integer.parseInt(version.substring(1)); String instanceName = null; if (sir.getRequestDetails().getRequestInfo() != null) { instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); } boolean alaCarteFlag = msoRequest.getAlacarteFlag(sir); - String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion); + String vnfType = msoRequest.getVnfType(sir, requestScope); String networkType = msoRequest.getNetworkType(sir, requestScope); String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir); - String vfModuleType = msoRequest.getVfModuleType(sir, requestScope, action, requestVersion); + String vfModuleType = msoRequest.getVfModuleType(sir, requestScope); if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) { currentActiveReq.setVnfType(vnfType); @@ -935,7 +933,7 @@ public class ServiceInstances extends AbstractRestHandler { } - RequestClientParameter requestClientParameter = null; + RequestClientParameter requestClientParameter; try { requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java index 925d10179f..d9955352c6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -6,6 +6,8 @@ * ================================================================================ * Modifications Copyright (c) 2019 Samsung * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -21,34 +23,23 @@ */ package org.onap.so.apihandlerinfra; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.transaction.Transactional; -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.QueryParam; -import javax.ws.rs.core.Response; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.ActivitySequence; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.ArtifactInfo; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.Validation; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowInputParameter; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecification; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecificationList; -import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications; -import org.onap.so.db.catalog.beans.ActivitySpec; -import org.onap.so.db.catalog.beans.ActivitySpecUserParameters; -import org.onap.so.db.catalog.beans.UserParameters; -import org.onap.so.db.catalog.beans.Workflow; -import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; +import org.onap.so.apihandlerinfra.workflowspecificationbeans.*; +import org.onap.so.db.catalog.beans.*; import org.onap.so.db.catalog.client.CatalogDbClient; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; @@ -56,16 +47,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import io.swagger.v3.oas.annotations.OpenAPIDefinition; -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.info.Info; -import io.swagger.v3.oas.annotations.media.ArraySchema; -import io.swagger.v3.oas.annotations.media.Content; -import io.swagger.v3.oas.annotations.media.Schema; -import io.swagger.v3.oas.annotations.responses.ApiResponse; +import javax.transaction.Transactional; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Response; +import java.util.*; +import java.util.stream.Collectors; + @Path("onap/so/infra/workflowSpecifications") @OpenAPIDefinition(info = @Info(title = "onap/so/infra/workflowSpecifications", @@ -82,6 +72,7 @@ public class WorkflowSpecificationsHandler { private static Logger logger = LoggerFactory.getLogger(WorkflowSpecificationsHandler.class); private static final String ARTIFACT_TYPE_WORKFLOW = "workflow"; private static final String NATIVE_WORKFLOW = "native"; + private static final String EMPTY_BODY = ""; @Path("/{version:[vV]1}/workflows") @GET @@ -90,38 +81,62 @@ public class WorkflowSpecificationsHandler { @Transactional public Response queryWorkflowSpecifications(@QueryParam("vnfModelVersionId") String vnfModelVersionId, - @PathParam("version") String version) throws Exception { - + @QueryParam("pnfModelVersionId") String pnfModelVersionId, @PathParam("version") String version) + throws Exception { String apiVersion = version.substring(1); - ObjectMapper mapper1 = new ObjectMapper(); - mapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - List<Workflow> workflows = catalogDbClient.findWorkflowByModelUUID(vnfModelVersionId); + List<Workflow> workflows = new ArrayList<>(); + if (vnfModelVersionId == null && pnfModelVersionId == null) { + workflows.addAll(queryWorkflowSpecificationsForAll()); + } else { + // 1. query workflow specifications for given vnfModelVersionId if need. + if (vnfModelVersionId != null) { + List<Workflow> vnfWorkflows = queryWorkflowSpecificationsForVnf(vnfModelVersionId); + logger.debug("Retrieved " + vnfWorkflows.size() + " workflows for given vnfModelVersionId."); + if (vnfWorkflows.size() > 0) { + workflows.addAll(vnfWorkflows); + } + } - List<Workflow> nativeWorkflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW); - if (nativeWorkflows != null && !nativeWorkflows.isEmpty()) { - workflows.addAll(nativeWorkflows); + // 2. query workflow specifications for given pnfModelVersionId if need. + if (pnfModelVersionId != null) { + List<Workflow> pnfWorkflows = queryWorkflowSpecificationsForPnf(pnfModelVersionId); + logger.debug("Retrieved " + pnfWorkflows.size() + " workflows for given pnfModelVerionId."); + if (pnfWorkflows.size() > 0) { + workflows.addAll(pnfWorkflows); + } + } } - WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); + // Deduplication + List<Workflow> retWorkflows = workflows.stream() + .collect(Collectors.collectingAndThen( + Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Workflow::getArtifactUUID))), + ArrayList::new)); - String jsonResponse; - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.writeValueAsString(workflowSpecifications); - } catch (JsonProcessingException e) { - ErrorLoggerInfo errorLoggerInfo = - new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) - .build(); - ValidateException validateException = - new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; - } + Optional<String> optional = getResponseByWorkflowSpec(retWorkflows); + return builder.buildResponse(HttpStatus.SC_OK, "", optional.isPresent() ? optional.get() : EMPTY_BODY, + apiVersion); + } + + @Path("/{version:[vV]1}/pnfWorkflows") + @GET + @Operation(description = "Finds pnf workflow specifications", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class))))) + @Transactional + public Response getWorkflowsSpecForPnf(@PathParam("version") String version) throws Exception { - return builder.buildResponse(HttpStatus.SC_OK, "", jsonResponse, apiVersion); + final String pnf_resource = "pnf"; + String apiVersion = version.substring(1); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + List<Workflow> workflows = catalogDbClient.findWorkflowByResourceTarget(pnf_resource); + + Optional<String> optional = getResponseByWorkflowSpec(workflows); + return builder.buildResponse(HttpStatus.SC_OK, "", optional.isPresent() ? optional.get() : EMPTY_BODY, + apiVersion); } protected WorkflowSpecifications mapWorkflowsToWorkflowSpecifications(List<Workflow> workflows) { @@ -144,6 +159,28 @@ public class WorkflowSpecificationsHandler { return workflowSpecifications; } + private Optional<String> getResponseByWorkflowSpec(List<Workflow> workflows) throws ValidateException { + WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); + + try { + ObjectMapper mapper = new ObjectMapper(); + return Optional.of(mapper.writeValueAsString(workflowSpecifications)); + } catch (JsonProcessingException e) { + catchAndThrowValidationEx(e); + } + return Optional.empty(); + } + + private Response catchAndThrowValidationEx(JsonProcessingException e) throws ValidateException { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build(); + ValidateException validateException = + new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo) + .build(); + throw validateException; + } + private ArtifactInfo buildArtifactInfo(Workflow workflow) { ArtifactInfo artifactInfo = new ArtifactInfo(); artifactInfo.setArtifactType(ARTIFACT_TYPE_WORKFLOW); @@ -239,4 +276,24 @@ public class WorkflowSpecificationsHandler { } return validationList; } + + private List<Workflow> queryWorkflowSpecificationsForAll() { + List<Workflow> workflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW); + return workflows; + } + + private List<Workflow> queryWorkflowSpecificationsForVnf(String vnfModelVersionId) { + List<Workflow> workflows = catalogDbClient.findWorkflowByVnfModelUUID(vnfModelVersionId); + + List<Workflow> nativeWorkflows = catalogDbClient.findWorkflowBySource(NATIVE_WORKFLOW); + if (!nativeWorkflows.isEmpty()) { + workflows.addAll(nativeWorkflows); + } + return workflows; + } + + private List<Workflow> queryWorkflowSpecificationsForPnf(String pnfModelVersionId) { + List<Workflow> workflows = catalogDbClient.findWorkflowByPnfModelUUID(pnfModelVersionId); + return workflows; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java index 344e5438c9..fee7a3a8f4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/infra/rest/AAIDataRetrieval.java @@ -3,7 +3,9 @@ package org.onap.so.apihandlerinfra.infra.rest; import java.util.Optional; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.L3Network; +import org.onap.aai.domain.yang.Service; import org.onap.aai.domain.yang.ServiceInstance; +import org.onap.aai.domain.yang.Tenant; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VolumeGroup; import org.onap.so.apihandlerinfra.infra.rest.exception.AAIEntityNotFound; @@ -34,7 +36,6 @@ public class AAIDataRetrieval { }); } - public VfModule getAAIVfModule(String vnfId, String vfModuleId) { return this.getAaiResourcesClient() .get(VfModule.class, AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId)) @@ -75,6 +76,24 @@ public class AAIDataRetrieval { }); } + public Service getService(String serviceId) { + return this.getAaiResourcesClient() + .get(Service.class, AAIUriFactory.createResourceUri(AAIObjectType.SERVICE, serviceId)).orElseGet(() -> { + logger.debug("No Service found in A&AI ServiceId: {}", serviceId); + return null; + }); + } + + public Tenant getTenant(String cloudOwner, String cloudRegion, String tenantId) { + return this.getAaiResourcesClient() + .get(Tenant.class, + AAIUriFactory.createResourceUri(AAIObjectType.TENANT, cloudOwner, cloudRegion, tenantId)) + .orElseGet(() -> { + logger.debug("No Tenant found in A&AI TenantId: {}", tenantId); + return null; + }); + } + protected AAIResourcesClient getAaiResourcesClient() { if (aaiResourcesClient == null) { aaiResourcesClient = new AAIResourcesClient(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java index c05ef98fbb..01c7fd33f9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -29,20 +29,13 @@ import com.google.common.base.Strings; public class CustomWorkflowValidation implements ValidationRule { + /** + * This function should be generic both for custom VNF workflow and PNF workflow + */ @Override public ValidationInformation validate(ValidationInformation info) throws ValidationException { RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); - CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); - if (cloudConfiguration == null) { - // throw new ValidationException("cloudConfiguration"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getCloudOwner()))) { - // throw new ValidationException("cloudOwner"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getLcpCloudRegionId()))) { - // throw new ValidationException("lcpCloudRegionId"); - } else if (Strings.isNullOrEmpty((cloudConfiguration.getTenantId()))) { - // throw new ValidationException("tenantId"); - } if (requestParameters == null) { throw new ValidationException("requestParameters"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java index 5c78af3601..ba7fe2b9cb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -192,11 +192,12 @@ public class InstanceManagementTest extends BaseTest { requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = instanceManagementUri + "v1" - + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testpnfcId/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; + + "/serviceInstances/5df8b6de-2083-11e7-93ae-92361f002676/pnfs/testPnfName/workflows/81526781-e55c-4cb7-adb3-97e09d9c76bf"; ResponseEntity<String> response = sendRequest(inputStream("/ExecutePNFCustomWorkflow.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java index f1d5a5487f..d1e5dc717e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/MsoRequestTest.java @@ -22,6 +22,7 @@ package org.onap.so.apihandlerinfra; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; @@ -34,12 +35,19 @@ import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.apache.http.HttpStatus; +import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.domain.yang.Service; +import org.onap.aai.domain.yang.Tenant; import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandlerinfra.infra.rest.AAIDataRetrieval; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.test.context.junit4.rules.SpringClassRule; @@ -75,6 +83,17 @@ public class MsoRequestTest extends BaseTest { @Rule public ExpectedException thrown = ExpectedException.none(); + @Mock + private AAIDataRetrieval aaiDataRet; + + @InjectMocks + private MsoRequest msoRequestMock; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + } + public String inputStream(String JsonInput) throws IOException { JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; String input = new String(Files.readAllBytes(Paths.get(JsonInput))); @@ -1056,5 +1075,37 @@ public class MsoRequestTest extends BaseTest { assertNotNull(result); } + @Test + public void getTenantNameFromAAITest() throws Exception { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class); + String tenantId = "88a6ca3ee0394ade9403f075db23167e"; + String tenantNameFromAAI = "testTenantName"; + String cloudRegion = "mdt1"; + String cloudOwner = "cloudOwner"; + this.sir.getRequestDetails().getCloudConfiguration().setCloudOwner(cloudOwner); + Tenant tenant = new Tenant(); + tenant.setTenantId(tenantId); + tenant.setTenantName(tenantNameFromAAI); + doReturn(tenant).when(aaiDataRet).getTenant(cloudOwner, cloudRegion, tenantId); + String tenantName = msoRequestMock.getTenantNameFromAAI(this.sir); + assertEquals(tenantNameFromAAI, tenantName); + } + + + @Test + public void getProductFamilyNameFromAAITest() throws Exception { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class); + String serviceId = "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb"; + String serviceDescription = "testServiceDescription"; + Service service = new Service(); + service.setServiceId(serviceId); + service.setServiceDescription(serviceDescription); + doReturn(service).when(aaiDataRet).getService(serviceId); + String productFamilyName = msoRequestMock.getProductFamilyNameFromAAI(this.sir); + assertEquals(serviceDescription, productFamilyName); + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java index f566628ee3..1332ffd913 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstancesTest.java @@ -441,6 +441,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -483,6 +487,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -524,6 +532,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); @@ -1939,6 +1951,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); @@ -2114,6 +2130,10 @@ public class ServiceInstancesTest extends BaseTest { .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/service-design-and-creation/services/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("/aai/ServiceFromAAI.json").withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java index 0beab1bd13..21e6d53c14 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -4,6 +4,8 @@ * ================================================================================ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ + * Modifications Copyright (c) 2020 Nordix + * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -20,30 +22,15 @@ package org.onap.so.apihandlerinfra; -import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; -import static com.github.tomakehurst.wiremock.client.WireMock.get; -import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; -import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.json.JSONException; import org.junit.Test; import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowInputParameter; import org.onap.so.apihandlerinfra.workflowspecificationbeans.WorkflowSpecifications; -import org.onap.so.db.catalog.beans.ActivitySpec; -import org.onap.so.db.catalog.beans.ActivitySpecUserParameters; -import org.onap.so.db.catalog.beans.UserParameters; -import org.onap.so.db.catalog.beans.Workflow; -import org.onap.so.db.catalog.beans.WorkflowActivitySpecSequence; +import org.onap.so.db.catalog.beans.*; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -53,10 +40,19 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.util.ResourceUtils; import org.springframework.web.util.UriComponentsBuilder; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; public class WorkflowSpecificationsHandlerTest extends BaseTest { @Autowired @@ -65,19 +61,20 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { @Value("${wiremock.server.port}") private String wiremockPort; - private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows"; + private final String basePath = "onap/so/infra/workflowSpecifications"; @Test - public void queryWorkflowSpecifications_Test_Success() + public void queryWorkflowSpecificationsByVnfModelUUID_Test_Success() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + final String urlPath = basePath + "/v1/workflows"; HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(null, headers); wireMockServer.stubFor(get(urlMatching( - "/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52")) + "/workflow/search/findWorkflowByVnfModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("WorkflowSpecificationsQuery_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -147,7 +144,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { .withBody(getWiremockResponseForCatalogdb("UserParameters6_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)) .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); ResponseEntity<String> response = @@ -174,7 +171,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { @Test public void mapWorkflowsToWorkflowSpecifications_Test_Success() throws Exception { - List<Workflow> workflows = new ArrayList<Workflow>(); + List<Workflow> workflows = new ArrayList<>(); Workflow workflow = new Workflow(); workflow.setArtifactUUID("ab6478e4-ea33-3346-ac12-ab121484a333"); workflow.setArtifactName("inPlaceSoftwareUpdate-1_0.bpmn"); @@ -267,8 +264,7 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { activitySpecUserParameter6.setUserParameters(userParameter6); activitySpecUserParameters.add(activitySpecUserParameter6); - List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = - new ArrayList<WorkflowActivitySpecSequence>(); + List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = new ArrayList<>(); ActivitySpec activitySpec1 = new ActivitySpec(); activitySpec1.setName("VNFQuiesceTrafficActivity"); @@ -324,6 +320,100 @@ public class WorkflowSpecificationsHandlerTest extends BaseTest { assertThat(expectedResult, sameBeanAs(workflowSpecifications).ignoring(WorkflowInputParameter.class)); } + @Test + public void queryWorkflowSpecificationsByPnfModelUUID_Test_Success() throws JSONException, IOException { + + final String urlPath = basePath + "/v1/workflows"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + wireMockServer.stubFor(get(urlMatching( + "/workflow/search/findWorkflowByPnfModelUUID[?]pnfResourceModelUUID=f2d1f2b2-88bb-49da-b716-36ae420ccbff")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "WorkflowSpecificationsForPnfQuery_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflow/4/workflowActivitySpecSequence")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("Empty_workflowActivitySpecSequence_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)) + .queryParam("pnfModelVersionId", "f2d1f2b2-88bb-49da-b716-36ae420ccbff"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + WorkflowSpecifications expectedResponse = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json"))), + WorkflowSpecifications.class); + WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(expectedResponse, sameBeanAs(realResponse)); + assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); + assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); + assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); + assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); + } + + @Test + public void testWorkflowSpecificationsForPnf_Success() throws JSONException, IOException { + + final String urlPath = basePath + "/v1/pnfWorkflows"; + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity(null, headers); + + wireMockServer.stubFor(get(urlMatching("/workflow/search/findByResourceTarget[?]resource_target=pnf")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody( + getWiremockResponseForCatalogdb("WorkflowSpecificationsForPnfWorkflows_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/infraActiveRequests.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching("/workflow/1/workflowActivitySpecSequence")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("Empty_workflowActivitySpecSequence_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(urlPath)); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + WorkflowSpecifications expectedResponse = mapper.readValue( + new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json"))), + WorkflowSpecifications.class); + WorkflowSpecifications realResponse = mapper.readValue(response.getBody(), WorkflowSpecifications.class); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + assertThat(expectedResponse, sameBeanAs(realResponse)); + assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); + assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); + assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); + assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); + } + private String getWiremockResponseForCatalogdb(String file) { try { File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json index 63021b611f..09f94b61a4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecutePNFCustomWorkflow.json @@ -1,20 +1,47 @@ { - "requestDetails": { - "requestParameters": { - "userParams": [{ - "nrmObj": { - "EUtranGenericCell" : [ - {"cellLocalId":1, "pci":5}, - {"cellLocalId":2, "pci":6} - ], - "ExternalEUtranCell" : [ - {"cellLocalId":3, "eNBId": "x"}, - {"cellLocalId":4, "eNBId": "y"} - ], - "EUtranRelation": [{"scellLocalId":5, "tcellLocalId":6}] - } - }], - "payload": "[{\"GNBDUFunction\":{\"gNBId\":1,\"gNBDUId\":5}}]" - } - } + "requestDetails":{ + "subscriberInfo":{ + "globalSubscriberId":"Test" + }, + "requestInfo":{ + "suppressRollback": false, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "requestorId": "tester", + "instanceName":"testInstanceName", + "source":"test" + }, + "cloudConfiguration":{ + "lcpCloudRegionId": "RegionOne", + "tenantId": "7320ec4a5b9d4589ba7c4412ccfd290f", + "cloudOwner": "CloudOwner" + }, + "requestParameters":{ + "subscriptionServiceType": "test", + "userParams":[ + { + "name": "key1", + "value": "val1" + }, + { + "name": "key2", + "value": "val2" + }], + "aLaCarte": false, + "payload": "{\"k1\": \"v1\"}" + }, + "project":{ + "projectName": "Test" + }, + "owningEntity":{ + "owningEntityId":"67f2e84c-734d-4e90-a1e4-d2ffa2e75849", + "owningEntityName":"OE-Test" + }, + "modelInfo":{ + "modelVersion": "2.0", + "modelVersionId": "test-version-id", + "modelInvariantId": "test-invariantUUID", + "modelName": "test-name", + "modelType": "pnf" + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json new file mode 100644 index 0000000000..f0d511789f --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/aai/ServiceFromAAI.json @@ -0,0 +1,4 @@ +{ + "service-id": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "service-description": "testServiceDescription" +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json new file mode 100644 index 0000000000..6779c1f3e4 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/Empty_workflowActivitySpecSequence_Response.json @@ -0,0 +1,5 @@ +{ + "_embedded": { + "workflowActivitySpecSequence": [] + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json new file mode 100644 index 0000000000..b5b93873c8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnf.json @@ -0,0 +1,20 @@ +{ + "workflowSpecificationList": [ + { + "workflowSpecification": { + "artifactInfo": { + "artifactType": "workflow", + "artifactUuid": "b2fd5627-55e4-4f4f-8064-9e6f443e9152", + "artifactName": "DummyPnfWorkflow", + "artifactVersion": "1.0", + "artifactDescription": "Dummy Pnf Workflow to test custom Pnf workflow", + "workflowName": "Dummy Pnf Workflow", + "operationName": "DummyPnfWorkflow", + "workflowSource": "native", + "workflowResourceTarget": "pnf" + }, + "workflowInputParameters": [] + } + } + ] +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfQuery_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfQuery_Response.json new file mode 100644 index 0000000000..a4e1bbcdc5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfQuery_Response.json @@ -0,0 +1,41 @@ +{ + "_embedded": { + "workflow": [ + { + "artifactChecksum": "MANUAL RECORD", + "artifactName": "DummyPnfWorkflow", + "artifactUUID": "b2fd5627-55e4-4f4f-8064-9e6f443e9152", + "body": null, + "created": "2020-02-18T08:28:15.000+0000", + "description": "Dummy Pnf Workflow to test custom Pnf workflow", + "id": 4, + "name": "Dummy Pnf Workflow", + "operationName": "DummyPnfWorkflow", + "pnfResourceWorkflow": null, + "resourceTarget": "pnf", + "source": "native", + "timeoutMinutes": null, + "version": 1.0, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByPnfModelUUID?pnfResourceModelUUID=f2d1f2b2-88bb-49da-b716-36ae420ccbff" + }, + "workflow": { + "href": "http://localhost:8090/workflow/4" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByPnfModelUUID?pnfResourceModelUUID=f2d1f2b2-88bb-49da-b716-36ae420ccbff" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json new file mode 100644 index 0000000000..2447617897 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsForPnfWorkflows_Response.json @@ -0,0 +1,41 @@ +{ + "_embedded": { + "workflow": [ + { + "artifactChecksum": "MANUAL RECORD", + "artifactName": "DummyPnfWorkflow", + "artifactUUID": "b2fd5627-55e4-4f4f-8064-9e6f443e9152", + "body": null, + "created": "2020-02-18T08:28:15.000+0000", + "description": "Dummy Pnf Workflow to test custom Pnf workflow", + "id": 4, + "name": "Dummy Pnf Workflow", + "operationName": "DummyPnfWorkflow", + "pnfResourceWorkflow": null, + "resourceTarget": "pnf", + "source": "native", + "timeoutMinutes": null, + "version": 1.0, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findByResourceTarget?resource_target=pnf" + }, + "workflow": { + "href": "http://localhost:8090/workflow/4" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findByResourceTarget?resource_target=pnf" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/4/workflowActivitySpecSequence" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql index 050780c9a2..85a17dd369 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/schema.sql @@ -1262,7 +1262,7 @@ CREATE TABLE `infra_active_requests` ( `END_TIME` datetime DEFAULT NULL, `SOURCE` varchar(45) DEFAULT NULL, `VNF_ID` varchar(45) DEFAULT NULL, - `PNF_ID` varchar(45) DEFAULT NULL, + `PNF_NAME` varchar(45) DEFAULT NULL, `VNF_NAME` varchar(80) DEFAULT NULL, `VNF_TYPE` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(45) DEFAULT NULL, @@ -1297,6 +1297,8 @@ CREATE TABLE `infra_active_requests` ( `ORIGINAL_REQUEST_ID` varchar(45) DEFAULT NULL, `EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, `ROLLBACK_EXT_SYSTEM_ERROR_SOURCE` varchar(80) DEFAULT NULL, + `TENANT_NAME` varchar(200) DEFAULT NULL, + `PRODUCT_FAMILY_NAME` varchar(200) DEFAULT NULL, PRIMARY KEY (`REQUEST_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; diff --git a/mso-api-handlers/mso-requests-db-repositories/pom.xml b/mso-api-handlers/mso-requests-db-repositories/pom.xml index 4dbf22cd87..efc81384d4 100644 --- a/mso-api-handlers/mso-requests-db-repositories/pom.xml +++ b/mso-api-handlers/mso-requests-db-repositories/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-requests-db-repositories</artifactId> diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java index bba0ad4696..da8f30ab1e 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/InfraActiveRequestsRepositoryImpl.java @@ -245,8 +245,8 @@ public class InfraActiveRequestsRepositoryImpl implements InfraActiveRequestsRep mapKey = "serviceInstanceName"; } else if ("vnfInstanceId".equalsIgnoreCase(mapKey)) { mapKey = "vnfId"; - } else if ("pnfId".equalsIgnoreCase(mapKey)) { - mapKey = "pnfId"; + } else if ("pnfName".equalsIgnoreCase(mapKey)) { + mapKey = "pnfName"; } else if ("vnfInstanceName".equalsIgnoreCase(mapKey)) { mapKey = "vnfName"; } else if ("vfModuleInstanceId".equalsIgnoreCase(mapKey)) { diff --git a/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OrchestrationTaskRepository.java b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OrchestrationTaskRepository.java new file mode 100644 index 0000000000..1093c79638 --- /dev/null +++ b/mso-api-handlers/mso-requests-db-repositories/src/main/java/org/onap/so/db/request/data/repository/OrchestrationTaskRepository.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.db.request.data.repository; + +import org.onap.so.db.request.beans.OrchestrationTask; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.query.Param; +import org.springframework.data.rest.core.annotation.RepositoryRestResource; +import java.util.List; + +@RepositoryRestResource(collectionResourceRel = "orchestrationTask", path = "orchestrationTask") +public interface OrchestrationTaskRepository extends JpaRepository<OrchestrationTask, String> { + + public List<OrchestrationTask> findByStatus(@Param("status") String status); +} diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java new file mode 100644 index 0000000000..0b2aae6730 --- /dev/null +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/java/org/onap/so/db/request/OrchestrationTaskTest.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.db.request; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.so.TestApplication; +import org.onap.so.db.request.beans.OrchestrationTask; +import org.onap.so.db.request.data.repository.OrchestrationTaskRepository; +import org.onap.so.db.request.exceptions.NoEntityFoundException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.junit4.SpringRunner; +import javax.transaction.Transactional; +import java.util.Date; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = TestApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("test") +public class OrchestrationTaskTest { + + @Autowired + private OrchestrationTaskRepository repository; + + @Test + @Transactional + public void timeStampCreated() throws NoEntityFoundException { + + final String testTaskId = "test-task-id"; + final String testRequestId = "test-request-id"; + final String testTaskName = "test-task-name"; + final String testTaskStatus = "test-task-status"; + final String testIsManual = "test-is-manual"; + OrchestrationTask task = new OrchestrationTask(); + + task.setTaskId(testTaskId); + task.setRequestId(testRequestId); + task.setName(testTaskName); + task.setStatus(testTaskStatus); + task.setIsManual(testIsManual); + repository.saveAndFlush(task); + + OrchestrationTask found = + repository.findById(testTaskId).orElseThrow(() -> new NoEntityFoundException("Cannot Find Task")); + + Date createdTime = found.getCreatedTime(); + assertNotNull(createdTime); + assertEquals(testTaskId, found.getTaskId()); + assertEquals(testRequestId, found.getRequestId()); + assertEquals(testTaskName, found.getName()); + assertEquals(testTaskStatus, found.getStatus()); + assertEquals(testIsManual, found.getIsManual()); + } +} diff --git a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql index d2b3a71cad..c6d22f5402 100644 --- a/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql +++ b/mso-api-handlers/mso-requests-db-repositories/src/test/resources/schema.sql @@ -64,7 +64,7 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( END_TIME VARCHAR, SOURCE VARCHAR SELECTIVITY 2, VNF_ID VARCHAR SELECTIVITY 15, - PNF_ID VARCHAR SELECTIVITY 15, + PNF_NAME VARCHAR SELECTIVITY 15, VNF_NAME VARCHAR SELECTIVITY 11, VNF_TYPE VARCHAR SELECTIVITY 5, SERVICE_TYPE VARCHAR SELECTIVITY 1, @@ -100,7 +100,10 @@ CREATE TABLE IF NOT EXISTS PUBLIC.INFRA_ACTIVE_REQUESTS( REQUEST_URL VARCHAR SELECTIVITY 1, ORIGINAL_REQUEST_ID VARCHAR SELECTIVITY 1, EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1, - ROLLBACK_EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1 + ROLLBACK_EXT_SYSTEM_ERROR_SOURCE VARCHAR SELECTIVITY 1, + TENANT_NAME VARCHAR SELECTIVITY 1, + PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1 + ); INSERT INTO PUBLIC.INFRA_ACTIVE_REQUESTS(REQUEST_ID, REQUEST_STATUS, STATUS_MESSAGE, PROGRESS, START_TIME, END_TIME, SOURCE, VNF_ID, VNF_NAME, VNF_TYPE, SERVICE_TYPE, TENANT_ID, VNF_PARAMS, VNF_OUTPUTS, REQUEST_BODY, RESPONSE_BODY, LAST_MODIFIED_BY, MODIFY_TIME, VOLUME_GROUP_ID, VOLUME_GROUP_NAME, VF_MODULE_ID, VF_MODULE_NAME, VF_MODULE_MODEL_NAME, CLOUD_REGION, CALLBACK_URL, CORRELATOR, NETWORK_ID, NETWORK_NAME, NETWORK_TYPE, REQUEST_SCOPE, REQUEST_ACTION, SERVICE_INSTANCE_ID, SERVICE_INSTANCE_NAME, REQUESTOR_ID, CONFIGURATION_ID, CONFIGURATION_NAME, OPERATIONAL_ENV_ID, OPERATIONAL_ENV_NAME, REQUEST_URL) VALUES @@ -169,7 +172,9 @@ CREATE CACHED TABLE PUBLIC.ARCHIVED_INFRA_REQUESTS( OPERATIONAL_ENV_NAME VARCHAR SELECTIVITY 1, INSTANCE_GROUP_ID VARCHAR SELECTIVITY 1, INSTANCE_GROUP_NAME VARCHAR SELECTIVITY 1, - REQUEST_URL VARCHAR SELECTIVITY 1 + REQUEST_URL VARCHAR SELECTIVITY 1, + TENANT_NAME VARCHAR SELECTIVITY 1, + PRODUCT_FAMILY_NAME VARCHAR SELECTIVITY 1 ); CREATE TABLE IF NOT EXISTS cloud_api_requests( @@ -246,11 +251,22 @@ CREATE CACHED TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP( INSERT INTO PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID, CREATE_TIME, MODIFY_TIME) VALUES ('1533c4bd-a3e3-493f-a16d-28c20614415e', '7e813ab5-88d3-4fcb-86c0-498c5d7eef9a', '2017-11-30 15:48:08', '2017-11-30 15:48:08'), ('55429711-809b-4a3b-9ee5-5120d46d9de0', 'cc031e75-4442-4d1a-b774-8a2b434e0a50', '2017-11-30 16:35:36', '2017-11-30 16:35:36'), -('67f0b2d1-9013-4b2b-9914-bbe2288284fb', 'eade1e9d-c1ec-4ef3-bc31-60570fba1573', '2017-11-30 15:54:39', '2017-11-30 15:54:39'); +('67f0b2d1-9013-4b2b-9914-bbe2288284fb', 'eade1e9d-c1ec-4ef3-bc31-60570fba1573', '2017-11-30 15:54:39', '2017-11-30 15:54:39'); -ALTER TABLE PUBLIC.INFRA_ACTIVE_REQUESTS ADD CONSTRAINT PUBLIC.CONSTRAINT_E PRIMARY KEY(REQUEST_ID); -ALTER TABLE PUBLIC.SITE_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_C PRIMARY KEY(SITE_NAME); +ALTER TABLE PUBLIC.INFRA_ACTIVE_REQUESTS ADD CONSTRAINT PUBLIC.CONSTRAINT_E PRIMARY KEY(REQUEST_ID); +ALTER TABLE PUBLIC.SITE_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_C PRIMARY KEY(SITE_NAME); ALTER TABLE PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_7 PRIMARY KEY(DISTRIBUTION_ID); ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_D PRIMARY KEY(DISTRIBUTION_ID, COMPONENT_NAME); -ALTER TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP ADD CONSTRAINT PUBLIC.CONSTRAINT_6 PRIMARY KEY(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID); -ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_DE FOREIGN KEY(DISTRIBUTION_ID) REFERENCES PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS(DISTRIBUTION_ID) NOCHECK;
\ No newline at end of file +ALTER TABLE PUBLIC.WATCHDOG_SERVICE_MOD_VER_ID_LOOKUP ADD CONSTRAINT PUBLIC.CONSTRAINT_6 PRIMARY KEY(DISTRIBUTION_ID, SERVICE_MODEL_VERSION_ID); +ALTER TABLE PUBLIC.WATCHDOG_PER_COMPONENT_DISTRIBUTION_STATUS ADD CONSTRAINT PUBLIC.CONSTRAINT_DE FOREIGN KEY(DISTRIBUTION_ID) REFERENCES PUBLIC.WATCHDOG_DISTRIBUTIONID_STATUS(DISTRIBUTION_ID) NOCHECK; + +CREATE TABLE `orchestration_task` ( + `TASK_ID` varchar(200) NOT NULL, + `REQUEST_ID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `CREATED_TIME` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `STATUS` varchar(200) NOT NULL, + `IS_MANUAL` varchar(20) NOT NULL, + `PARAMS` varchar(20000) DEFAULT NULL, + PRIMARY KEY (`TASK_ID`) +); diff --git a/mso-api-handlers/mso-requests-db/pom.xml b/mso-api-handlers/mso-requests-db/pom.xml index 031f86282a..37bb4175a5 100644 --- a/mso-api-handlers/mso-requests-db/pom.xml +++ b/mso-api-handlers/mso-requests-db/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>mso-api-handlers</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-requests-db</artifactId> diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java index 5848f3b3d9..750fa13c77 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraActiveRequests.java @@ -72,15 +72,15 @@ public class InfraActiveRequests extends InfraRequests { .append("statusMessage", getStatusMessage()).append("progress", getProgress()) .append("startTime", getStartTime()).append("endTime", getEndTime()).append("source", getSource()) .append("vnfId", getVnfId()).append("vnfName", getVnfName()).append("vnfType", getVnfType()) - .append("pnfId", getPnfId()).append("serviceType", getServiceType()).append("tenantId", getTenantId()) - .append("vnfParams", getVnfParams()).append("vnfOutputs", getVnfOutputs()) - .append("requestBody", getRequestBody()).append("responseBody", getResponseBody()) - .append("lastModifiedBy", getLastModifiedBy()).append("modifyTime", getModifyTime()) - .append("volumeGroupId", getVolumeGroupId()).append("volumeGroupName", getVolumeGroupName()) - .append("vfModuleId", getVfModuleId()).append("vfModuleName", getVfModuleName()) - .append("vfModuleModelName", getVfModuleModelName()).append("CloudRegion", getCloudRegion()) - .append("callBackUrl", getCallBackUrl()).append("correlator", getCorrelator()) - .append("serviceInstanceId", getServiceInstanceId()) + .append("pnfName", getPnfName()).append("serviceType", getServiceType()) + .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) + .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) + .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) + .append("modifyTime", getModifyTime()).append("volumeGroupId", getVolumeGroupId()) + .append("volumeGroupName", getVolumeGroupName()).append("vfModuleId", getVfModuleId()) + .append("vfModuleName", getVfModuleName()).append("vfModuleModelName", getVfModuleModelName()) + .append("CloudRegion", getCloudRegion()).append("callBackUrl", getCallBackUrl()) + .append("correlator", getCorrelator()).append("serviceInstanceId", getServiceInstanceId()) .append("serviceInstanceName", getServiceInstanceName()).append("requestScope", getRequestScope()) .append("requestAction", getRequestAction()).append("networkId", getNetworkId()) .append("networkName", getNetworkName()).append("networkType", getNetworkType()) @@ -89,6 +89,7 @@ public class InfraActiveRequests extends InfraRequests { .append("operationalEnvName", getOperationalEnvName()).append("requestUrl", getRequestUrl()) .append("originalRequestId", getOriginalRequestId()) .append("extSystemErrorSource", getExtSystemErrorSource()) - .append("rollbackExtSystemErrorSource", getRollbackExtSystemErrorSource()).toString(); + .append("rollbackExtSystemErrorSource", getRollbackExtSystemErrorSource()) + .append("tenantName", getTenantName()).append("productFamilyName", getProductFamilyName()).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java index 8f798a207c..66768ea349 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/InfraRequests.java @@ -74,8 +74,8 @@ public abstract class InfraRequests implements java.io.Serializable { private String source; @Column(name = "VNF_ID", length = 45) private String vnfId; - @Column(name = "PNF_ID", length = 45) - private String pnfId; + @Column(name = "PNF_NAME", length = 45) + private String pnfName; @Column(name = "VNF_NAME", length = 80) private String vnfName; @Column(name = "VNF_TYPE", length = 200) @@ -149,6 +149,10 @@ public abstract class InfraRequests implements java.io.Serializable { private String extSystemErrorSource; @Column(name = "ROLLBACK_EXT_SYSTEM_ERROR_SOURCE", length = 80) private String rollbackExtSystemErrorSource; + @Column(name = "TENANT_NAME", length = 80) + private String tenantName; + @Column(name = "PRODUCT_FAMILY_NAME", length = 80) + private String productFamilyName; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "SO_REQUEST_ID", referencedColumnName = "REQUEST_ID", updatable = false) @@ -249,12 +253,12 @@ public abstract class InfraRequests implements java.io.Serializable { this.vnfId = vnfId; } - public String getPnfId() { - return this.pnfId; + public String getPnfName() { + return this.pnfName; } - public void setPnfId(String pnfId) { - this.pnfId = pnfId; + public void setPnfName(String pnfName) { + this.pnfName = pnfName; } public String getVnfName() { @@ -550,6 +554,22 @@ public abstract class InfraRequests implements java.io.Serializable { this.rollbackExtSystemErrorSource = rollbackExtSystemErrorSource; } + public String getTenantName() { + return tenantName; + } + + public void setTenantName(String tenantName) { + this.tenantName = tenantName; + } + + public String getProductFamilyName() { + return productFamilyName; + } + + public void setProductFamilyName(String productFamilyName) { + this.productFamilyName = productFamilyName; + } + @PrePersist protected void onCreate() { if (requestScope == null) @@ -592,7 +612,7 @@ public abstract class InfraRequests implements java.io.Serializable { .append("flowStatus", getFlowStatus()).append("retryStatusMessage", getRetryStatusMessage()) .append("progress", getProgress()).append("startTime", getStartTime()).append("endTime", getEndTime()) .append("source", getSource()).append("vnfId", getVnfId()).append("vnfName", getVnfName()) - .append("pnfId", getPnfId()).append("vnfType", getVnfType()).append("serviceType", getServiceType()) + .append("pnfName", getPnfName()).append("vnfType", getVnfType()).append("serviceType", getServiceType()) .append("tenantId", getTenantId()).append("vnfParams", getVnfParams()) .append("vnfOutputs", getVnfOutputs()).append("requestBody", getRequestBody()) .append("responseBody", getResponseBody()).append("lastModifiedBy", getLastModifiedBy()) @@ -609,6 +629,7 @@ public abstract class InfraRequests implements java.io.Serializable { .append("operationalEnvName", getOperationalEnvName()).append("instanceGroupId", getInstanceGroupId()) .append("instanceGroupName", getInstanceGroupName()).append("requestUrl", getRequestUrl()) .append("originalRequestId", originalRequestId).append("extSystemErrorSource", extSystemErrorSource) - .append("rollbackExtSystemErrorSource", rollbackExtSystemErrorSource).toString(); + .append("rollbackExtSystemErrorSource", rollbackExtSystemErrorSource).append("tenantName", tenantName) + .append("productFamilyName", productFamilyName).toString(); } } diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OrchestrationTask.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OrchestrationTask.java new file mode 100644 index 0000000000..53760f1b00 --- /dev/null +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/beans/OrchestrationTask.java @@ -0,0 +1,143 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.db.request.beans; + +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.hibernate.annotations.DynamicUpdate; +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; +import java.util.Objects; + +@Entity +@DynamicUpdate +@Table(name = "orchestration_task") +public class OrchestrationTask implements Serializable { + + private static final long serialVersionUID = -9158494554305291596L; + + @Id + @Column(name = "TASK_ID", nullable = false, updatable = false) + private String taskId; + + @Column(name = "REQUEST_ID", nullable = false, updatable = false) + private String requestId; + + @Column(name = "NAME") + private String name; + + @Column(name = "CREATED_TIME") + private Date createdTime; + + @Column(name = "STATUS") + private String status; + + @Column(name = "IS_MANUAL") + private String isManual; + + @Column(name = "PARAMS") + private String params; + + public String getTaskId() { + return taskId; + } + + public void setTaskId(String taskId) { + this.taskId = taskId; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getCreatedTime() { + return createdTime; + } + + public void setCreatedTime(Date createdTime) { + this.createdTime = createdTime; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getIsManual() { + return isManual; + } + + public void setIsManual(String isManual) { + this.isManual = isManual; + } + + public String getParams() { + return params; + } + + public void setParams(String parameters) { + this.params = parameters; + } + + @Override + public boolean equals(final Object other) { + if (this == other) { + return true; + } + if (!(other instanceof OrchestrationTask)) { + return false; + } + OrchestrationTask castOther = (OrchestrationTask) other; + return Objects.equals(getTaskId(), castOther.getTaskId()); + } + + @Override + public int hashCode() { + return Objects.hash(this.getTaskId()); + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("taskId", getTaskId()).toString(); + } + + @PrePersist + protected void onCreate() { + this.createdTime = new Date(); + } + +} + diff --git a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java index 334eb73da4..7b642ab831 100644 --- a/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java +++ b/mso-api-handlers/mso-requests-db/src/main/java/org/onap/so/db/request/client/RequestsDbClient.java @@ -45,6 +45,7 @@ import org.onap.so.db.request.beans.SiteStatus; import org.onap.so.db.request.beans.WatchdogComponentDistributionStatus; import org.onap.so.db.request.beans.WatchdogDistributionStatus; import org.onap.so.db.request.beans.WatchdogServiceModVerIdLookup; +import org.onap.so.db.request.beans.OrchestrationTask; import org.onap.so.db.request.data.controller.InstanceNameDuplicateCheckRequest; import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.springframework.beans.factory.annotation.Autowired; @@ -119,6 +120,8 @@ public class RequestsDbClient { private String getInProgressVolumeGroupsAndVfModules = "/infraActiveRequests/getInProgressVolumeGroupsAndVfModules"; + private String orchestrationTasksURI = "/orchestrationTask"; + private static final String findBySoRequestIdAndGroupIdAndName = "/requestProcessingData/search/findOneBySoRequestIdAndGroupingIdAndName"; @@ -156,6 +159,7 @@ public class RequestsDbClient { findAllByOperationalEnvIdAndRequestIdURI = endpoint + OPERATIONAL_ENV_SERVICE_MODEL_STATUS_SEARCH + findAllByOperationalEnvIdAndRequestIdURI; findOneByRequestId = endpoint + findOneByRequestId; + orchestrationTasksURI = endpoint + orchestrationTasksURI; } protected String getEndpoint() { @@ -520,6 +524,40 @@ public class RequestsDbClient { .getBody(); } + public List<OrchestrationTask> getAllOrchestrationTasks() { + String url = UriBuilder.fromUri(getUri(orchestrationTasksURI)).build().toString(); + HttpEntity<?> entity = getHttpEntity(); + return restTemplate + .exchange(url, HttpMethod.GET, entity, new ParameterizedTypeReference<List<OrchestrationTask>>() {}) + .getBody(); + } + + public OrchestrationTask getOrchestrationTask(String taskId) { + String url = UriBuilder.fromUri(getUri(orchestrationTasksURI + "/" + taskId)).build().toString(); + HttpEntity<?> entity = getHttpEntity(); + return restTemplate.exchange(url, HttpMethod.GET, entity, OrchestrationTask.class).getBody(); + } + + public OrchestrationTask createOrchestrationTask(OrchestrationTask orchestrationTask) { + String url = UriBuilder.fromUri(getUri(orchestrationTasksURI + "/")).build().toString(); + HttpHeaders headers = getHttpHeaders(); + HttpEntity<OrchestrationTask> entity = new HttpEntity<>(orchestrationTask, headers); + return restTemplate.exchange(url, HttpMethod.POST, entity, OrchestrationTask.class).getBody(); + } + + public OrchestrationTask updateOrchestrationTask(String taskId, OrchestrationTask orchestrationTask) { + String url = getUri(orchestrationTasksURI + "/" + taskId).toString(); + HttpHeaders headers = getHttpHeaders(); + HttpEntity<OrchestrationTask> entity = new HttpEntity<>(orchestrationTask, headers); + return restTemplate.exchange(url, HttpMethod.PUT, entity, OrchestrationTask.class).getBody(); + } + + public void deleteOrchestrationTask(String taskId) { + String url = getUri(orchestrationTasksURI + "/" + taskId).toString(); + HttpEntity<?> entity = getHttpEntity(); + restTemplate.exchange(url, HttpMethod.DELETE, entity, Void.class).getBody(); + } + @Component static class ClassURLMapper { private static final Map<Class, String> classURLMap = new HashMap<>(); diff --git a/mso-api-handlers/pom.xml b/mso-api-handlers/pom.xml index b4d5c7070a..5c84ab1d77 100644 --- a/mso-api-handlers/pom.xml +++ b/mso-api-handlers/pom.xml @@ -5,7 +5,7 @@ <parent> <groupId>org.onap.so</groupId> <artifactId>so</artifactId> - <version>1.4.0-SNAPSHOT</version> + <version>1.6.0-SNAPSHOT</version> </parent> <artifactId>mso-api-handlers</artifactId> |