diff options
author | Steve Smokowski <ss835w@att.com> | 2019-05-06 14:24:20 +0000 |
---|---|---|
committer | Gerrit Code Review <gerrit@onap.org> | 2019-05-06 14:24:20 +0000 |
commit | 7af16eec7a5ea196de57b47b918d3d88390a715c (patch) | |
tree | 70a46d96a3718f7fc4f2b8e2a91b7323cb8f7b2f /mso-api-handlers | |
parent | 8668df008ae252d0e43d23ef00c8e350bdb0900b (diff) | |
parent | 459276d781151b126e4e36035ef1a04922fc3fd1 (diff) |
Merge "Resume APIH Functionality"
Diffstat (limited to 'mso-api-handlers')
11 files changed, 776 insertions, 77 deletions
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 c491444f39..c1f55c7555 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 @@ -115,8 +115,7 @@ public class InstanceManagement { String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -149,16 +148,15 @@ public class InstanceManagement { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, - currentActiveReq); + 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, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); 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 67d6a0d1fc..7c0d327db7 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 @@ -24,8 +24,8 @@ import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletProperties; -import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandler.filters.RequestIdFilter; +import org.onap.so.apihandler.filters.RequestUriFilter; import org.onap.so.apihandlerinfra.exceptions.ApiExceptionMapper; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; @@ -41,8 +41,6 @@ import io.swagger.jaxrs.listing.SwaggerSerializers; @ApplicationPath("/") public class JerseyConfiguration extends ResourceConfig { - - @PostConstruct public void setUp() { register(GlobalHealthcheckHandler.class); @@ -64,6 +62,7 @@ public class JerseyConfiguration extends ResourceConfig { register(E2EServiceInstances.class); register(WorkflowSpecificationsHandler.class); register(InstanceManagement.class); + register(ResumeOrchestrationRequest.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/OrchestrationRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/OrchestrationRequests.java index 1bbe858859..fc407bd167 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 @@ -42,7 +42,6 @@ import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang3.StringEscapeUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; @@ -68,8 +67,6 @@ 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.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -81,7 +78,6 @@ public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); - @Autowired private RequestsDbClient requestsDbClient; @@ -100,11 +96,9 @@ public class OrchestrationRequests { @PathParam("version") String version, @QueryParam("includeCloudRequest") boolean includeCloudRequest) throws ApiException { - String apiVersion = version.substring(1); GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); - InfraActiveRequests infraActiveRequest = null; List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; try { @@ -116,14 +110,11 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); - - ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup", HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) .errorInfo(errorLoggerInfo).build(); - throw validateException; } @@ -133,7 +124,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) @@ -207,7 +197,6 @@ public class OrchestrationRequests { return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); } - @POST @Path("/{version: [vV][4-7]}/{requestId}/unlock") @Consumes(MediaType.APPLICATION_JSON) @@ -258,7 +247,6 @@ public class OrchestrationRequests { ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) @@ -280,7 +268,6 @@ public class OrchestrationRequests { new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) .build(); - ValidateException validateException = new ValidateException.Builder( "Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked", @@ -307,7 +294,6 @@ public class OrchestrationRequests { String flowStatusMessage = iar.getFlowStatus(); String retryStatusMessage = iar.getRetryStatusMessage(); - InstanceReferences ir = new InstanceReferences(); if (iar.getNetworkId() != null) ir.setNetworkInstanceId(iar.getNetworkId()); @@ -406,7 +392,6 @@ public class OrchestrationRequests { status.setTimeStamp(timeStamp); } - if (iar.getRequestStatus() != null) { status.setRequestState(iar.getRequestStatus()); } 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 bbcc120ab6..f6fc88d559 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 @@ -24,8 +24,20 @@ package org.onap.so.apihandlerinfra; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import java.io.IOException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.Response; +import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; @@ -76,20 +88,8 @@ import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestTemplate; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; -import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; -import java.io.IOException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; @Component public class RequestHandlerUtils { @@ -293,9 +293,8 @@ public class RequestHandlerUtils { return requestUri; } - public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) - throws ApiException { + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, + String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { InfraActiveRequests dup = null; try { if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance @@ -369,8 +368,7 @@ public class RequestHandlerUtils { } public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, - long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) - throws ApiException { + String requestId, String requestUri) throws ApiException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(requestJSON, ServiceInstancesRequest.class); @@ -415,8 +413,8 @@ public class RequestHandlerUtils { } public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, - HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, - String requestScope, InfraActiveRequests dup) throws ApiException { + HashMap<String, String> instanceIdMap, String instanceName, String requestScope, InfraActiveRequests dup) + throws ApiException { String instance = null; if (instanceName != null) { @@ -622,4 +620,27 @@ public class RequestHandlerUtils { return requestScope; } + protected InfraActiveRequests createNewRecordCopyFromInfraActiveRequest(InfraActiveRequests infraActiveRequest, + String requestId, Timestamp startTimeStamp, String source, String requestUri, String requestorId) { + InfraActiveRequests request = new InfraActiveRequests(); + request.setRequestId(requestId); + request.setStartTime(startTimeStamp); + request.setSource(source); + request.setRequestUrl(requestUri); + request.setProgress(new Long(5)); + request.setRequestorId(requestorId); + request.setRequestStatus(Status.IN_PROGRESS.toString()); + request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + if (infraActiveRequest != null) { + request.setTenantId(infraActiveRequest.getTenantId()); + request.setRequestBody(infraActiveRequest.getRequestBody()); + request.setAicCloudRegion(infraActiveRequest.getAicCloudRegion()); + request.setRequestScope(infraActiveRequest.getRequestScope()); + request.setServiceInstanceId(infraActiveRequest.getServiceInstanceId()); + request.setServiceInstanceName(infraActiveRequest.getServiceInstanceName()); + request.setRequestAction(infraActiveRequest.getRequestAction()); + } + return request; + } + } 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 new file mode 100644 index 0000000000..6ca23a339b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequest.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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 java.io.IOException; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.transaction.Transactional; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MdcConstants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.web.client.HttpClientErrorException; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("onap/so/infra/orchestrationRequests") +@Api(value = "onap/so/infra/orchestrationRequests") +@Component +public class ResumeOrchestrationRequest { + private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class); + private static final String SAVE_TO_DB = "save instance to db"; + private static String uriPrefix = "/orchestrationRequests/"; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Autowired + private ServiceInstances serviceInstances; + + @Autowired + private RequestsDbClient requestsDbClient; + + + @POST + @Path("/{version:[vV][7]}/requests/{requestId}/resume") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Resume request for a given requestId", response = Response.class) + @Transactional + public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId, + @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + logger.info("Beginning resume operation for new request: {}", currentRequestId); + InfraActiveRequests infraActiveRequest = null; + String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME); + String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID); + requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + String requestUri = MDC.get(LogConstants.HTTP_URL); + version = version.substring(1); + + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (HttpClientErrorException e) { + logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e) + .errorInfo(errorLoggerInfo).build(); + } + + InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest( + infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId); + + if (infraActiveRequest == null) { + logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId); + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, + ErrorCode.BusinessProcesssError).build(); + ValidateException validateException = new ValidateException.Builder( + "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + + } + + return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri); + } + + protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, + String version, String requestUri) throws ApiException { + String requestBody = infraActiveRequest.getRequestBody(); + Action action = Action.valueOf(infraActiveRequest.getRequestAction()); + String requestId = currentActiveRequest.getRequestId(); + String serviceInstanceName = infraActiveRequest.getServiceInstanceName(); + String requestScope = infraActiveRequest.getRequestScope(); + String serviceInstanceId = infraActiveRequest.getServiceInstanceId(); + + checkForInProgressRequest(currentActiveRequest, serviceInstanceId, requestScope, serviceInstanceName, action); + + ServiceInstancesRequest sir = null; + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri); + Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); + if (aLaCarte == null) { + aLaCarte = false; + } + + String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir); + RecipeLookupResult recipeLookupResult = serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + + requestDbSave(currentActiveRequest); + + RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version, + infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir); + + return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest, String serviceInstanceId, + String requestScope, String serviceInstanceName, Action action) throws ApiException { + boolean inProgress = false; + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, + serviceInstanceName, requestScope, currentActiveRequest); + if (requestInProgress != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest); + } + if (inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, + serviceInstanceName, requestScope, requestInProgress); + } + } + + protected RecipeLookupResult serviceRecipeLookup(InfraActiveRequests currentActiveRequest, + ServiceInstancesRequest sir, Action action, Boolean aLaCarte) + throws ValidateException, RequestDbFailureException { + RecipeLookupResult recipeLookupResult = null; + try { + recipeLookupResult = serviceInstances.getServiceURI(sir, action, aLaCarte); + } catch (IOException e) { + logger.error("IOException while performing service recipe lookup", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage()); + throw validateException; + } + return recipeLookupResult; + } + + protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException { + try { + requestsDbClient.save(currentActiveRequest); + } catch (Exception e) { + logger.error("Exception while saving request to requestDb", 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(); + } + } + + protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version, + InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId, + Boolean aLaCarte, ServiceInstancesRequest sir) throws ValidateException { + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder() + .setRequestId(currentActiveRequest.getRequestId()) + .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()).setNetworkType(infraActiveRequest.getNetworkType()) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, + aLaCarte, Action.valueOf(infraActiveRequest.getRequestAction()))) + .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 = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder( + "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestClientParameter; + } +} 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 931a1eb52b..7c8d24742d 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 @@ -765,8 +765,7 @@ public class ServiceInstances { ServiceInstancesRequest sir = null; String apiVersion = version.substring(1); - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -797,16 +796,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; boolean inProgress = false; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -968,8 +966,8 @@ public class ServiceInstances { throw validateException; } - InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, - requestScope, currentActiveReq); + InfraActiveRequests dup = + requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq); boolean inProgress = false; if (dup != null) { @@ -977,8 +975,8 @@ public class ServiceInstances { } if (dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, null, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope, + dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); @@ -1011,7 +1009,7 @@ public class ServiceInstances { recipeLookupResult.getOrchestrationURI(), requestScope); } - private String getPnfCorrelationId(ServiceInstancesRequest sir) { + protected String getPnfCorrelationId(ServiceInstancesRequest sir) { return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails) .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId")) .orElse(""); @@ -1103,8 +1101,8 @@ public class ServiceInstances { return recipeLookupResult; } - private RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, boolean alaCarteFlag) - throws IOException { + protected RecipeLookupResult getServiceURI(ServiceInstancesRequest servInstReq, Actions action, + boolean alaCarteFlag) throws IOException { // SERVICE REQUEST // Construct the default service name // TODO need to make this a configurable property @@ -1598,8 +1596,7 @@ public class ServiceInstances { long startTime = System.currentTimeMillis(); ServiceInstancesRequest sir = null; - sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, - requestId, requestUri); + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri); String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); @@ -1613,16 +1610,15 @@ public class ServiceInstances { InfraActiveRequests dup = null; - dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName, - requestScope, currentActiveReq); + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName, requestScope, currentActiveReq); if (dup != null) { inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } if (instanceIdMap != null && dup != null && inProgress) { - requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, - msoRequest, instanceName, requestScope, dup); + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, instanceName, + requestScope, dup); } ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java index c678fab03e..4deaccd938 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/OrchestrationRequestsTest.java @@ -42,7 +42,6 @@ import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.apache.http.HttpStatus; -import org.junit.Ignore; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.db.request.beans.InfraActiveRequests; @@ -65,7 +64,6 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class OrchestrationRequestsTest extends BaseTest { @@ -168,7 +166,6 @@ public class OrchestrationRequestsTest extends BaseTest { cloudRequestData.add(cloudData); request.setCloudRequestData(cloudRequestData); testResponse.setRequest(request); - String testRequestId = request.getRequestId(); HttpHeaders headers = new HttpHeaders(); @@ -186,7 +183,6 @@ public class OrchestrationRequestsTest extends BaseTest { assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); - 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)); @@ -334,12 +330,11 @@ public class OrchestrationRequestsTest extends BaseTest { "/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); - // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // Cannot assert anything further here, already have a wiremock in place + // which ensures that the post was // properly called to update. } - - @Test public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { RequestProcessingData entry = new RequestProcessingData(); @@ -413,7 +408,6 @@ public class OrchestrationRequestsTest extends BaseTest { .withStatus(HttpStatus.SC_OK))); } - private void setupTestGetOrchestrationRequestOpenstackDetails(String requestId, String status) throws Exception { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) @@ -426,14 +420,12 @@ public class OrchestrationRequestsTest extends BaseTest { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(String.format(getResponseTemplate, requestId, status)).withStatus(HttpStatus.SC_OK))); - } - - private void setupTestUnlockOrchestrationRequest_invalid_Json() { wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse() .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); + } private void setupTestUnlockOrchestrationRequest_Valid_Status(String requestID, String status) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java new file mode 100644 index 0000000000..e80fd9e690 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsUnitTest.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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 static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertThat; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.db.request.beans.InfraActiveRequests; + +@RunWith(MockitoJUnitRunner.class) +public class RequestHandlerUtilsUnitTest { + + @Spy + private RequestHandlerUtils requestHandler; + + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + private String requestUri = + "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; + private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequestIARNull = new InfraActiveRequests(); + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + @Before + public void setup() throws IOException { + setInfraActiveRequest(); + setCurrentActiveRequest(); + setCurrentActiveRequestNullInfraActive(); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope("service"); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName("serviceInstanceName"); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope("service"); + currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + currentActiveRequest.setServiceInstanceName("serviceInstanceName"); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + } + + private void setCurrentActiveRequestNullInfraActive() throws IOException { + currentActiveRequestIARNull.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequestIARNull.setSource("VID"); + currentActiveRequestIARNull.setStartTime(startTimeStamp); + currentActiveRequestIARNull.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequestIARNull.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequestIARNull.setRequestUrl(requestUri); + currentActiveRequestIARNull.setRequestorId("xxxxxx"); + currentActiveRequestIARNull.setProgress(new Long(5)); + } + + + @Test + public void createNewRecordCopyFromInfraActiveRequestTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(infraActiveRequest, + CURRENT_REQUEST_ID, startTimeStamp, "VID", requestUri, "xxxxxx"); + assertThat(currentActiveRequest, sameBeanAs(result)); + } + + @Test + public void createNewRecordCopyFromInfraActiveRequestNullIARTest() { + InfraActiveRequests result = requestHandler.createNewRecordCopyFromInfraActiveRequest(null, CURRENT_REQUEST_ID, + startTimeStamp, "VID", requestUri, "xxxxxx"); + assertThat(currentActiveRequestIARNull, sameBeanAs(result)); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java new file mode 100644 index 0000000000..92490a66b8 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ResumeOrchestrationRequestTest.java @@ -0,0 +1,328 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. 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 static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.Timestamp; +import java.util.HashMap; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.Response; +import org.junit.Before; +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.Spy; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.apihandlerinfra.exceptions.ValidateException; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.web.client.HttpClientErrorException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.class) +public class ResumeOrchestrationRequestTest { + @Mock + private RequestHandlerUtils requestHandler; + + @Mock + private MsoRequest msoRequest; + + @Mock + private ServiceInstances serviceInstances; + + @Mock + private RequestsDbClient requestDbClient; + + @InjectMocks + @Spy + private ResumeOrchestrationRequest resumeReq; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String CURRENT_REQUEST_ID = "eca3a1b1-43ab-457e-ab1c-367263d148b4"; + private static final String REQUEST_ID = "00032ab7-na18-42e5-965d-8ea592502019"; + private static final String SERVICE_INSTANCE_ID = "00032ab7-na18-42e5-965d-8ea592502018"; + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String REQUEST_SCOPE = "service"; + private final Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + private final Action action = Action.createInstance; + private final Boolean aLaCarte = false; + private final String version = "7"; + private final String requestUri = + "http:localhost:6746/onap/so/infra/orchestrationRequests/v7/00032ab7-na18-42e5-965d-8ea592502019/resume"; + private final RecipeLookupResult lookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 80); + private RequestClientParameter requestClientParameter = null; + private ObjectMapper mapper = new ObjectMapper(); + private InfraActiveRequests infraActiveRequest = new InfraActiveRequests(); + private InfraActiveRequests currentActiveRequest = new InfraActiveRequests(); + private ServiceInstancesRequest sir = new ServiceInstancesRequest(); + private ServiceInstancesRequest sirNullALaCarte = new ServiceInstancesRequest(); + private String requestBody = null; + private String requestBodyNullALaCarte = null; + private ContainerRequestContext requestContext = null; + private HashMap<String, String> instanceIdMap = new HashMap<>(); + + + @Before + public void setup() throws ValidateException, IOException { + // Setup general requestHandler mocks + when(requestHandler.getRequestUri(any(), anyString())).thenReturn(requestUri); + + // Setup InfraActiveRequests + setInfraActiveRequest(); + setCurrentActiveRequest(); + + requestBody = infraActiveRequest.getRequestBody(); + sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); + requestBodyNullALaCarte = getRequestBody("/ALaCarteNull.json"); + sirNullALaCarte = sir = mapper.readValue(requestBodyNullALaCarte, ServiceInstancesRequest.class); + setRequestClientParameter(); + instanceIdMap.put("serviceInstanceId", SERVICE_INSTANCE_ID); + } + + public String getRequestBody(String request) throws IOException { + request = "src/test/resources/ResumeOrchestrationRequest" + request; + return new String(Files.readAllBytes(Paths.get(request))); + } + + private void setInfraActiveRequest() throws IOException { + infraActiveRequest.setTenantId("tenant-id"); + infraActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + infraActiveRequest.setAicCloudRegion("cloudRegion"); + infraActiveRequest.setRequestScope(REQUEST_SCOPE); + infraActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + infraActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + infraActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + infraActiveRequest.setRequestAction(Action.createInstance.toString()); + infraActiveRequest.setServiceType("serviceType"); + } + + private void setCurrentActiveRequest() throws IOException { + currentActiveRequest.setRequestId(CURRENT_REQUEST_ID); + currentActiveRequest.setSource("VID"); + currentActiveRequest.setStartTime(startTimeStamp); + currentActiveRequest.setTenantId("tenant-id"); + currentActiveRequest.setRequestBody(getRequestBody("/RequestBody.json")); + currentActiveRequest.setAicCloudRegion("cloudRegion"); + currentActiveRequest.setRequestScope(REQUEST_SCOPE); + currentActiveRequest.setServiceInstanceId(SERVICE_INSTANCE_ID); + currentActiveRequest.setServiceInstanceName(SERVICE_INSTANCE_NAME); + currentActiveRequest.setRequestStatus(Status.IN_PROGRESS.toString()); + currentActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + currentActiveRequest.setRequestAction(Action.createInstance.toString()); + currentActiveRequest.setRequestUrl(requestUri); + currentActiveRequest.setRequestorId("xxxxxx"); + currentActiveRequest.setProgress(new Long(5)); + } + + private void setRequestClientParameter() { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(CURRENT_REQUEST_ID) + .setRecipeTimeout(80).setRequestAction(Action.createInstance.toString()) + .setServiceInstanceId(SERVICE_INSTANCE_ID).setPnfCorrelationId("pnfCorrelationId").setVnfId(null) + .setVfModuleId(null).setVolumeGroupId(null).setNetworkId(null).setServiceType("serviceType") + .setVnfType(null).setNetworkType(null).setRequestDetails(requestBody).setApiVersion(version) + .setALaCarte(aLaCarte).setRequestUri(requestUri).setInstanceGroupId(null).build(); + } + + @Test + public void resumeOrchestationRequestTest() throws Exception { + Response response = null; + when(requestDbClient.getInfraActiveRequestbyRequestId(REQUEST_ID)).thenReturn(infraActiveRequest); + doReturn(currentActiveRequest).when(requestHandler).createNewRecordCopyFromInfraActiveRequest( + any(InfraActiveRequests.class), nullable(String.class), any(Timestamp.class), nullable(String.class), + nullable(String.class), nullable(String.class)); + doReturn(response).when(resumeReq).resumeRequest(any(InfraActiveRequests.class), any(InfraActiveRequests.class), + anyString(), nullable(String.class)); + + resumeReq.resumeOrchestrationRequest(REQUEST_ID, "v7", requestContext); + + verify(resumeReq).resumeRequest(infraActiveRequest, currentActiveRequest, version, null); + } + + @Test + public void resumeOrchestationRequestDbNullResultTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")).thenReturn(null); + + thrown.expect(ValidateException.class); + thrown.expectMessage( + "Null response from requestDB when searching by requestId: 00032ab7-na18-42e5-965d-8ea592502018"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeOrchestationRequestDbErrorTest() throws Exception { + when(requestDbClient.getInfraActiveRequestbyRequestId("00032ab7-na18-42e5-965d-8ea592502018")) + .thenThrow(HttpClientErrorException.class); + + thrown.expect(ValidateException.class); + thrown.expectMessage("Exception while performing requestDb lookup by requestId"); + resumeReq.resumeOrchestrationRequest("00032ab7-na18-42e5-965d-8ea592502018", "v7", requestContext); + } + + @Test + public void resumeRequestTest() throws ApiException, IOException { + Response response = null; + when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), + anyString())).thenReturn(sir); + when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); + doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + doNothing().when(resumeReq).requestDbSave(currentActiveRequest); + when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), + anyString(), anyString())).thenReturn(response); + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @Test + public void serviceRecipeLookupTest() throws ApiException, IOException { + when(serviceInstances.getServiceURI(any(ServiceInstancesRequest.class), any(Action.class), anyBoolean())) + .thenReturn(lookupResult); + RecipeLookupResult result = resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + assertThat(result, sameBeanAs(lookupResult)); + } + + @Test + public void setRequestClientParameterTest() throws ApiException, IOException { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenReturn(requestBody); + RequestClientParameter result = resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, + currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + assertThat(requestClientParameter, sameBeanAs(result)); + } + + @Test + public void requestDbSaveTest() throws RequestDbFailureException { + doNothing().when(requestDbClient).save(currentActiveRequest); + resumeReq.requestDbSave(currentActiveRequest); + verify(requestDbClient).save(currentActiveRequest); + } + + @Test + public void resumeRequestTestALaCarteNull() throws ApiException, IOException { + Response response = null; + + when(requestHandler.convertJsonToServiceInstanceRequest(anyString(), any(Actions.class), anyString(), + anyString())).thenReturn(sirNullALaCarte); + when(serviceInstances.getPnfCorrelationId(any(ServiceInstancesRequest.class))).thenReturn("pnfCorrelationId"); + doReturn(lookupResult).when(resumeReq).serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + doReturn(requestClientParameter).when(resumeReq).setRequestClientParameter(lookupResult, version, + infraActiveRequest, currentActiveRequest, "pnfCorrelationId", aLaCarte, sir); + doNothing().when(resumeReq).requestDbSave(currentActiveRequest); + when(requestHandler.postBPELRequest(any(InfraActiveRequests.class), any(RequestClientParameter.class), + anyString(), anyString())).thenReturn(response); + doNothing().when(resumeReq).checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + + resumeReq.resumeRequest(infraActiveRequest, currentActiveRequest, version, + "/onap/so/infra/orchestrationRequests/v7/requests/00032ab7-na18-42e5-965d-8ea592502018/resume"); + verify(requestHandler).postBPELRequest(currentActiveRequest, requestClientParameter, + lookupResult.getOrchestrationURI(), infraActiveRequest.getRequestScope()); + } + + @Test + public void serviceRecipeLookupErrorTest() throws IOException, ApiException { + when(serviceInstances.getServiceURI(sir, action, aLaCarte)) + .thenThrow(new IOException("Error occurred on recipe lookup")); + doNothing().when(requestHandler).updateStatus(any(InfraActiveRequests.class), any(Status.class), anyString()); + + thrown.expect(ValidateException.class); + thrown.expectMessage("Error occurred on recipe lookup"); + resumeReq.serviceRecipeLookup(currentActiveRequest, sir, action, aLaCarte); + } + + @Test + public void setRequestClientParameterErrorTest() throws ApiException, IOException { + when(requestHandler.mapJSONtoMSOStyle(anyString(), any(ServiceInstancesRequest.class), anyBoolean(), + any(Action.class))).thenThrow(new IOException("IOException")); + + thrown.expect(ValidateException.class); + thrown.expectMessage("IOException while generating requestClientParameter to send to BPMN: IOException"); + resumeReq.setRequestClientParameter(lookupResult, version, infraActiveRequest, currentActiveRequest, + "pnfCorrelationId", aLaCarte, sir); + } + + @Test + public void checkForInProgressRequest() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + REQUEST_SCOPE, currentActiveRequest); + doReturn(true).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + doThrow(DuplicateRequestException.class).when(requestHandler).buildErrorOnDuplicateRecord(currentActiveRequest, + action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, infraActiveRequest); + + thrown.expect(DuplicateRequestException.class); + resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + } + + @Test + public void checkForInProgressRequestNoInProgressRequests() throws ApiException { + doReturn(null).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + currentActiveRequest); + + resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + currentActiveRequest); + } + + @Test + public void checkForInProgressRequestCamundaHistoryCheckReturnsNoInProgress() throws ApiException { + doReturn(infraActiveRequest).when(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, + REQUEST_SCOPE, currentActiveRequest); + doReturn(false).when(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + + resumeReq.checkForInProgressRequest(currentActiveRequest, SERVICE_INSTANCE_ID, REQUEST_SCOPE, + SERVICE_INSTANCE_NAME, action); + verify(requestHandler).duplicateCheck(action, instanceIdMap, SERVICE_INSTANCE_NAME, REQUEST_SCOPE, + currentActiveRequest); + verify(requestHandler).camundaHistoryCheck(infraActiveRequest, currentActiveRequest); + } + + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json new file mode 100644 index 0000000000..5da139e711 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/ALaCarteNull.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "usePreload": "false" + } + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json new file mode 100644 index 0000000000..5cd31427a0 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ResumeOrchestrationRequest/RequestBody.json @@ -0,0 +1,13 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "requestorId":"xxxxxx", + "instanceName":"testService", + "productFamilyId":"test" + }, + "requestParameters":{ + "aLaCarte":"false" + } + } +}
\ No newline at end of file |