diff options
Diffstat (limited to 'mso-api-handlers/mso-api-handler-infra')
211 files changed, 19990 insertions, 15712 deletions
diff --git a/mso-api-handlers/mso-api-handler-infra/pom.xml b/mso-api-handlers/mso-api-handler-infra/pom.xml index 16dfa68244..1359a7f9db 100644 --- a/mso-api-handlers/mso-api-handler-infra/pom.xml +++ b/mso-api-handlers/mso-api-handler-infra/pom.xml @@ -233,6 +233,7 @@ <includes> <include>**/AllTestsTestSuite.java</include> </includes> + <parallel>suites</parallel> </configuration> </execution> </executions> diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java index 67bbc3db8e..b921f5beea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/common/ResponseBuilder.java @@ -23,7 +23,6 @@ package org.onap.so.apihandler.common; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @@ -31,31 +30,31 @@ import org.springframework.stereotype.Component; @Component public class ResponseBuilder { - - @Value("${mso.infra.default.versions.apiMinorVersion}") - private String apiMinorVersion; - @Value("${mso.infra.default.versions.apiPatchVersion}") - private String apiPatchVersion; - - public Response buildResponse(int status, String requestId, Object jsonResponse, String apiVersion) { - - if (apiVersion.matches("v[1-9]")) { - apiVersion = apiVersion.substring(1); - } - - String latestVersion = apiVersion + "." + apiMinorVersion + "." + apiPatchVersion; - - javax.ws.rs.core.Response.ResponseBuilder builder = Response.status(status) - .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .header(CommonConstants.X_MINOR_VERSION, apiMinorVersion) - .header(CommonConstants.X_PATCH_VERSION, apiPatchVersion) - .header(CommonConstants.X_LATEST_VERSION, latestVersion); - - if(StringUtils.isNotBlank(requestId)) { - builder.header(CommonConstants.X_TRANSACTION_ID, requestId); - } - - return builder.entity(jsonResponse).build(); - } + + @Value("${mso.infra.default.versions.apiMinorVersion}") + private String apiMinorVersion; + @Value("${mso.infra.default.versions.apiPatchVersion}") + private String apiPatchVersion; + + public Response buildResponse(int status, String requestId, Object jsonResponse, String apiVersion) { + + if (apiVersion.matches("v[1-9]")) { + apiVersion = apiVersion.substring(1); + } + + String latestVersion = apiVersion + "." + apiMinorVersion + "." + apiPatchVersion; + + javax.ws.rs.core.Response.ResponseBuilder builder = + Response.status(status).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .header(CommonConstants.X_MINOR_VERSION, apiMinorVersion) + .header(CommonConstants.X_PATCH_VERSION, apiPatchVersion) + .header(CommonConstants.X_LATEST_VERSION, latestVersion); + + if (StringUtils.isNotBlank(requestId)) { + builder.header(CommonConstants.X_TRANSACTION_ID, requestId); + } + + return builder.entity(jsonResponse).build(); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java index 91ab580b07..a3ff1ab95d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/filters/RequestUriFilter.java @@ -22,37 +22,40 @@ package org.onap.so.apihandler.filters; import java.io.IOException; import java.net.URI; - import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.PreMatching; import javax.ws.rs.core.UriInfo; - import org.onap.so.apihandlerinfra.Constants; @PreMatching public class RequestUriFilter implements ContainerRequestFilter { - private String requestURI; - @Override - public void filter(ContainerRequestContext context) throws IOException { - UriInfo uriInfo = context.getUriInfo(); - URI baseURI = uriInfo.getBaseUri(); - requestURI = uriInfo.getPath(); - - if(requestURI.contains("onap/so/infra/serviceInstances")){ - requestURI = requestURI.replaceFirst("serviceInstances", "serviceInstantiation"); - if(!requestURI.contains(Constants.SERVICE_INSTANCE_PATH)){ - //Adds /serviceInstances after the version provided in the URI - requestURI = new StringBuilder(requestURI).insert(requestURI.indexOf(Constants.SERVICE_INSTANTIATION_PATH) + 24, Constants.SERVICE_INSTANCE_PATH).toString(); - } - requestURI = baseURI + requestURI; - URI uri = URI.create(requestURI); - context.setRequestUri(uri); - } - } - public String getRequestUri(){ - return requestURI; - } + private String requestURI; + + @Override + public void filter(ContainerRequestContext context) throws IOException { + UriInfo uriInfo = context.getUriInfo(); + URI baseURI = uriInfo.getBaseUri(); + requestURI = uriInfo.getPath(); + + if (requestURI.contains("onap/so/infra/serviceInstances")) { + requestURI = requestURI.replaceFirst("serviceInstances", "serviceInstantiation"); + if (!requestURI.contains(Constants.SERVICE_INSTANCE_PATH)) { + // Adds /serviceInstances after the version provided in the URI + requestURI = new StringBuilder(requestURI) + .insert(requestURI.indexOf(Constants.SERVICE_INSTANTIATION_PATH) + 24, + Constants.SERVICE_INSTANCE_PATH) + .toString(); + } + requestURI = baseURI + requestURI; + URI uri = URI.create(requestURI); + context.setRequestUri(uri); + } + } + + public String getRequestUri() { + return requestURI; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java index 74d5f7a9e6..71c56733b6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandler.java @@ -23,7 +23,6 @@ package org.onap.so.apihandler.recipe; import java.io.IOException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; @@ -32,20 +31,19 @@ import org.springframework.web.client.ResponseErrorHandler; -public class CamundaClientErrorHandler implements ResponseErrorHandler{ - - private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class); - - @Override - public void handleError(ClientHttpResponse response) throws IOException { - logger.debug(response.getBody().toString()); - } +public class CamundaClientErrorHandler implements ResponseErrorHandler { + + private static Logger logger = LoggerFactory.getLogger(CamundaClientErrorHandler.class); + + @Override + public void handleError(ClientHttpResponse response) throws IOException { + logger.debug(response.getBody().toString()); + } + + @Override + public boolean hasError(ClientHttpResponse response) throws IOException { + HttpStatus.Series series = response.getStatusCode().series(); + return (HttpStatus.Series.CLIENT_ERROR.equals(series) || HttpStatus.Series.SERVER_ERROR.equals(series)); + } - @Override - public boolean hasError(ClientHttpResponse response) throws IOException { - HttpStatus.Series series = response.getStatusCode().series(); - return (HttpStatus.Series.CLIENT_ERROR.equals(series) - || HttpStatus.Series.SERVER_ERROR.equals(series)); - } - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java index 897e2a5fc8..77dbff9ebb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/Action.java @@ -22,29 +22,7 @@ package org.onap.so.apihandlerinfra; /* * Enum for Status values returned by API Handler to Tail-F -*/ -public enum Action implements Actions{ - createInstance, - updateInstance, - deleteInstance, - configureInstance, - replaceInstance, - activateInstance, - deactivateInstance, - enablePort, - disablePort, - addRelationships, - removeRelationships, - inPlaceSoftwareUpdate, - applyUpdatedConfig, - completeTask, - assignInstance, - unassignInstance, - compareModel, - scaleInstance, - deactivateAndCloudDelete, - scaleOut, - recreateInstance, - addMembers, - removeMembers + */ +public enum Action implements Actions { + createInstance, updateInstance, deleteInstance, configureInstance, replaceInstance, activateInstance, deactivateInstance, enablePort, disablePort, addRelationships, removeRelationships, inPlaceSoftwareUpdate, applyUpdatedConfig, completeTask, assignInstance, unassignInstance, compareModel, scaleInstance, deactivateAndCloudDelete, scaleOut, recreateInstance, addMembers, removeMembers } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java index f3f98f3f2a..bc1972a593 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ApiHandlerApplication.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra; import java.util.concurrent.Executor; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; @@ -31,43 +30,43 @@ import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; -@SpringBootApplication(scanBasePackages = { "org.onap"}) +@SpringBootApplication(scanBasePackages = {"org.onap"}) @EnableAsync public class ApiHandlerApplication { - - @Value("${mso.async.core-pool-size}") - private int corePoolSize; - @Value("${mso.async.max-pool-size}") - private int maxPoolSize; + @Value("${mso.async.core-pool-size}") + private int corePoolSize; + + @Value("${mso.async.max-pool-size}") + private int maxPoolSize; - @Value("${mso.async.queue-capacity}") - private int queueCapacity; + @Value("${mso.async.queue-capacity}") + private int queueCapacity; - private static final String LOGS_DIR = "logs_dir"; + private static final String LOGS_DIR = "logs_dir"; - private static void setLogsDir() { - if (System.getProperty(LOGS_DIR) == null) { - System.getProperties().setProperty(LOGS_DIR, "./logs/apih/"); - } - } + private static void setLogsDir() { + if (System.getProperty(LOGS_DIR) == null) { + System.getProperties().setProperty(LOGS_DIR, "./logs/apih/"); + } + } - public static void main(String[] args) { - SpringApplication.run(ApiHandlerApplication.class, args); - System.getProperties().setProperty("mso.db", "MARIADB"); - System.getProperties().setProperty("server.name", "Springboot"); - setLogsDir(); - } + public static void main(String[] args) { + SpringApplication.run(ApiHandlerApplication.class, args); + System.getProperties().setProperty("mso.db", "MARIADB"); + System.getProperties().setProperty("server.name", "Springboot"); + setLogsDir(); + } - @Bean - public Executor asyncExecutor() { - ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); - executor.setCorePoolSize(corePoolSize); - executor.setMaxPoolSize(maxPoolSize); - executor.setQueueCapacity(queueCapacity); - executor.setThreadNamePrefix("mso-apihandler-infra-"); - executor.setTaskDecorator(new MDCTaskDecorator()); - executor.initialize(); - return executor; - } + @Bean + public Executor asyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize); + executor.setMaxPoolSize(maxPoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setThreadNamePrefix("mso-apihandler-infra-"); + executor.setTaskDecorator(new MDCTaskDecorator()); + executor.initialize(); + return executor; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java index de38bc717a..449aa4ba3f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/E2EServiceInstances.java @@ -28,7 +28,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -39,7 +38,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONObject; @@ -64,7 +62,6 @@ import org.onap.so.db.request.beans.OperationStatus; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestDetails; @@ -76,9 +73,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -88,678 +83,308 @@ import io.swagger.annotations.ApiOperation; @Api(value = "/onap/so/infra/e2eServiceInstances", description = "API Requests for E2E Service Instances") public class E2EServiceInstances { - private HashMap<String, String> instanceIdMap = new HashMap<>(); - private static final Logger logger = LoggerFactory.getLogger(E2EServiceInstances.class); - - private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; - - private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: "; - - @Autowired - private MsoRequest msoRequest; - - @Autowired - private RequestClientFactory requestClientFactory; - - @Autowired - private RequestsDbClient requestsDbClient; - - @Autowired - private CatalogDbClient catalogDbClient; - - @Autowired - private ResponseBuilder builder; - - /** - * POST Requests for E2E Service create Instance on a version provided - * @throws ApiException - */ - - @POST - @Path("/{version:[vV][3-5]}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class) - public Response createE2EServiceInstance(String request, - @PathParam("version") String version) throws ApiException { - - return processE2EserviceInstances(request, Action.createInstance, null, - version); - } - - /** - * PUT Requests for E2E Service update Instance on a version provided - * @throws ApiException - */ - - @PUT - @Path("/{version:[vV][3-5]}/{serviceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId", response = Response.class) - public Response updateE2EServiceInstance(String request, - @PathParam("version") String version, - @PathParam("serviceId") String serviceId) throws ApiException { - - instanceIdMap.put("serviceId", serviceId); - - return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap, - version); - } - - /** - * DELETE Requests for E2E Service delete Instance on a specified version - * and serviceId - * @throws ApiException - */ - - @DELETE - @Path("/{version:[vV][3-5]}/{serviceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class) - public Response deleteE2EServiceInstance(String request, - @PathParam("version") String version, - @PathParam("serviceId") String serviceId) throws ApiException { - - instanceIdMap.put("serviceId", serviceId); - - return deleteE2EserviceInstances(request, Action.deleteInstance, - instanceIdMap, version); - } - - @GET - @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}") - @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", response = Response.class) - @Produces(MediaType.APPLICATION_JSON) - public Response getE2EServiceInstances( - @PathParam("serviceId") String serviceId, - @PathParam("version") String version, - @PathParam("operationId") String operationId) { - return getE2EServiceInstance(serviceId, operationId, version); - } - + private HashMap<String, String> instanceIdMap = new HashMap<>(); + private static final Logger logger = LoggerFactory.getLogger(E2EServiceInstances.class); + + private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA"; + + private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: "; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RequestClientFactory requestClientFactory; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private CatalogDbClient catalogDbClient; + + @Autowired + private ResponseBuilder builder; + + /** + * POST Requests for E2E Service create Instance on a version provided + * + * @throws ApiException + */ + + @POST + @Path("/{version:[vV][3-5]}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class) + public Response createE2EServiceInstance(String request, @PathParam("version") String version) throws ApiException { + + return processE2EserviceInstances(request, Action.createInstance, null, version); + } + + /** + * PUT Requests for E2E Service update Instance on a version provided + * + * @throws ApiException + */ + + @PUT + @Path("/{version:[vV][3-5]}/{serviceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId", + response = Response.class) + public Response updateE2EServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceId") String serviceId) throws ApiException { + + instanceIdMap.put("serviceId", serviceId); + + return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap, version); + } + + /** + * DELETE Requests for E2E Service delete Instance on a specified version and serviceId + * + * @throws ApiException + */ + + @DELETE + @Path("/{version:[vV][3-5]}/{serviceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class) + public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceId") String serviceId) throws ApiException { + + instanceIdMap.put("serviceId", serviceId); + + return deleteE2EserviceInstances(request, Action.deleteInstance, instanceIdMap, version); + } + + @GET + @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}") + @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId", + response = Response.class) + @Produces(MediaType.APPLICATION_JSON) + public Response getE2EServiceInstances(@PathParam("serviceId") String serviceId, + @PathParam("version") String version, @PathParam("operationId") String operationId) { + return getE2EServiceInstance(serviceId, operationId, version); + } + + /** + * Scale Requests for E2E Service scale Instance on a specified version + * + * @throws ApiException + */ + + @POST + @Path("/{version:[vV][3-5]}/{serviceId}/scale") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Scale E2E Service Instance on a specified version", response = Response.class) + public Response scaleE2EServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceId") String serviceId) throws ApiException { + + logger.debug("------------------scale begin------------------"); + instanceIdMap.put("serviceId", serviceId); + return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version); + } + /** - * Scale Requests for E2E Service scale Instance on a specified version - * @throws ApiException + * GET Requests for Comparing model of service instance with target version + * + * @throws ApiException */ - - @POST - @Path("/{version:[vV][3-5]}/{serviceId}/scale") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Scale E2E Service Instance on a specified version",response=Response.class) - public Response scaleE2EServiceInstance(String request, - @PathParam("version") String version, - @PathParam("serviceId") String serviceId) throws ApiException { - - logger.debug("------------------scale begin------------------"); - instanceIdMap.put("serviceId", serviceId); - return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version); - } - /** - * GET Requests for Comparing model of service instance with target version - * @throws ApiException - */ - - @POST - @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", response = Response.class) - public Response compareModelwithTargetVersion(String request, - @PathParam("serviceId") String serviceId, - @PathParam("version") String version) throws ApiException { - - instanceIdMap.put("serviceId", serviceId); - - return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version); - } - - private Response compareModelwithTargetVersion(String requestJSON, Action action, - HashMap<String, String> instanceIdMap, String version) throws ApiException { - - String requestId = UUID.randomUUID().toString(); - long startTime = System.currentTimeMillis(); - - CompareModelsRequest e2eCompareModelReq; - - ObjectMapper mapper = new ObjectMapper(); - try { - e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class); - - } catch (Exception e) { - - logger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString()); - - return response; - } - - return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version); - - } - - private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, - String requestJSON, String requestId, long startTime, Action action, String version) throws ApiException { - - // Define RecipeLookupResult info here instead of query DB for efficiency - String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance"; - int recipeTimeout = 180; - - RequestClient requestClient; - HttpResponse response; - - long subStartTime = System.currentTimeMillis(); - - try { - requestClient = requestClientFactory.getRequestClient(workflowUrl); - - JSONObject jjo = new JSONObject(requestJSON); - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - String serviceId = instanceIdMap.get("serviceId"); - String serviceType = e2eCompareModelReq.getServiceType(); - RequestClientParameter postParam = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(recipeTimeout) - .setRequestAction(action.name()) - .setServiceInstanceId(serviceId) - .setServiceType(serviceType) - .setRequestDetails(bpmnRequest) - .setALaCarte(false).build(); - response = requestClient.post(postParam); - } catch (Exception e) { - Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", - ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine",e); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); - return resp; - } - - if (response == null) { - Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, - instanceIdMap, version); - } - - private Response getE2EServiceInstance(String serviceId, String operationId, String version) { - - GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse(); - - String apiVersion = version.substring(1); - - long startTime = System.currentTimeMillis(); - - OperationStatus operationStatus; - - try { - operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, - operationId); - } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), - "Exception while communciate with Request DB - Infra Request Lookup", e); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, - e.getMessage(), - ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - - } - - if (operationStatus == null) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NO_CONTENT, MsoException.ServiceException, - "E2E serviceId " + serviceId + " is not found in DB", - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), - "Null response from RequestDB when searching by serviceId"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - - } - - e2eServiceResponse.setOperation(operationStatus); - - return builder.buildResponse(HttpStatus.SC_OK, null, e2eServiceResponse, apiVersion); - } - - private Response deleteE2EserviceInstances(String requestJSON, - Action action, HashMap<String, String> instanceIdMap, String version) throws ApiException { - // TODO should be a new one or the same service instance Id - long startTime = System.currentTimeMillis(); - E2EServiceInstanceDeleteRequest e2eDelReq; - - ObjectMapper mapper = new ObjectMapper(); - try { - e2eDelReq = mapper.readValue(requestJSON, - E2EServiceInstanceDeleteRequest.class); - - } catch (Exception e) { - - logger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, - "Mapping of request to JSON object failed. " - + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, - null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - String requestId = UUID.randomUUID().toString(); - RecipeLookupResult recipeLookupResult; - try { - //TODO Get the service template model version uuid from AAI. - recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); - } catch (Exception e) { - logger.error(MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); - - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, - "No communication to catalog DB " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Exception while communciate with " - + "Catalog DB", action, - ModelType.service.name(), requestJSON); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, - "Recipe does not exist in catalog DB", - ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); - - msoRequest.createErrorRequestRecord(Status.FAILED, requestId,"Recipe does not exist in catalog DB", action, ModelType.service.name(), requestJSON); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - RequestClient requestClient; - HttpResponse response; - - long subStartTime = System.currentTimeMillis(); - try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - - JSONObject jjo = new JSONObject(requestJSON); - jjo.put("operationId", requestId); - - String bpmnRequest = jjo.toString(); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - String serviceId = instanceIdMap.get("serviceId"); - String serviceInstanceType = e2eDelReq.getServiceType(); - RequestClientParameter clientParam = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()) - .setServiceInstanceId(serviceId) - .setServiceType(serviceInstanceType) - .setRequestDetails(bpmnRequest) - .setApiVersion(version) - .setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(clientParam); - - } catch (Exception e) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); - logger.debug("End of the transaction, the final response is: " + resp.getEntity()); - return resp; - } - - if (response == null) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, - requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestId, startTime, requestClient, respHandler, - bpelStatus, action, instanceIdMap, version); - } - - private Response updateE2EserviceInstances(String requestJSON, Action action, - HashMap<String, String> instanceIdMap, String version) throws ApiException { - - String requestId = UUID.randomUUID().toString(); - long startTime = System.currentTimeMillis(); - E2EServiceInstanceRequest e2eSir; - String serviceId = instanceIdMap.get("serviceId"); - - ObjectMapper mapper = new ObjectMapper(); - try { - e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class); - - } catch (Exception e) { - - logger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON); - sir.getRequestDetails().getRequestParameters().setaLaCarte(true); - try { - parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId); - } catch (Exception e) { - logger.debug("Validation failed: ", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Error parsing request. " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, null, version); - if (requestId != null) { - logger.debug("Logging failed message to the database"); - } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - RecipeLookupResult recipeLookupResult; - try { - recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); - } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - - return response; - } - - if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, "Recipe does not exist in catalog DB", - ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - - return response; - } - - String serviceInstanceType = e2eSir.getService().getServiceType(); - - RequestClient requestClient; - HttpResponse response; - - long subStartTime = System.currentTimeMillis(); - String sirRequestJson = convertToString(sir); - - try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - RequestClientParameter postParam = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()) - .setServiceInstanceId(serviceId) - .setServiceType(serviceInstanceType) - .setRequestDetails(sirRequestJson) - .setApiVersion(version) - .setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(postParam); - } catch (Exception e) { - logger.debug("Exception while communicate with BPMN engine", e); - Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); - logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); - - return getBPMNResp; - } - - if (response == null) { - Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); - return getBPMNResp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(serviceId, startTime, requestClient, respHandler, - bpelStatus, action, instanceIdMap, version); - } - - private Response processE2EserviceInstances(String requestJSON, Action action, - HashMap<String, String> instanceIdMap, String version) throws ApiException { - - String requestId = UUID.randomUUID().toString(); - long startTime = System.currentTimeMillis(); - E2EServiceInstanceRequest e2eSir; - - MsoRequest msoRequest = new MsoRequest(); - ObjectMapper mapper = new ObjectMapper(); - try { - e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class); - - } catch (Exception e) { - - logger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON); - sir.getRequestDetails().getRequestParameters().setaLaCarte(true); - try { - parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId); - } catch (Exception e) { - logger.debug("Validation failed: ", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Error parsing request. " + e.getMessage(), - ErrorNumbers.SVC_BAD_PARAMETER, null, version); - if (requestId != null) { - logger.debug("Logging failed message to the database"); - } - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - RecipeLookupResult recipeLookupResult; - try { - recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); - } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, - MsoException.ServiceException, "Recipe does not exist in catalog DB", - ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; - } - - String serviceInstanceType = e2eSir.getService().getServiceType(); - - String serviceId = ""; - RequestClient requestClient; - HttpResponse response; - - long subStartTime = System.currentTimeMillis(); - String sirRequestJson = convertToString(sir); - - try { - requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); - - // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - RequestClientParameter parameter = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()) - .setServiceInstanceId(serviceId) - .setServiceType(serviceInstanceType) - .setRequestDetails(sirRequestJson) - .setApiVersion(version) - .setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); - response = requestClient.post(parameter); - } catch (Exception e) { - Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), - ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - if (response == null) { - Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, - MsoException.ServiceException, "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - - ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); - int bpelStatus = respHandler.getStatus(); - - return beplStatusUpdate(requestId, startTime, requestClient, respHandler, - bpelStatus, action, instanceIdMap, version); - } - - private Response scaleE2EserviceInstances(String requestJSON, - Action action, HashMap<String, String> instanceIdMap, String version) throws ApiException { + + @POST + @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation( + value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ", + response = Response.class) + public Response compareModelwithTargetVersion(String request, @PathParam("serviceId") String serviceId, + @PathParam("version") String version) throws ApiException { + + instanceIdMap.put("serviceId", serviceId); + + return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version); + } + + private Response compareModelwithTargetVersion(String requestJSON, Action action, + HashMap<String, String> instanceIdMap, String version) throws ApiException { String requestId = UUID.randomUUID().toString(); long startTime = System.currentTimeMillis(); - E2EServiceInstanceScaleRequest e2eScaleReq; + + CompareModelsRequest e2eCompareModelReq; ObjectMapper mapper = new ObjectMapper(); try { - e2eScaleReq = mapper.readValue(requestJSON, - E2EServiceInstanceScaleRequest.class); + e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class); } catch (Exception e) { logger.debug("Mapping of request to JSON object failed : ", e); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, - "Mapping of request to JSON object failed. " - + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, - null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.SchemaError.getValue(), requestJSON, e); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString()); + + return response; } + return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version); + + } + + private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, String requestJSON, + String requestId, long startTime, Action action, String version) throws ApiException { + + // Define RecipeLookupResult info here instead of query DB for efficiency + String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance"; + int recipeTimeout = 180; + + RequestClient requestClient; + HttpResponse response; + + long subStartTime = System.currentTimeMillis(); + + try { + requestClient = requestClientFactory.getRequestClient(workflowUrl); + + JSONObject jjo = new JSONObject(requestJSON); + String bpmnRequest = jjo.toString(); + + // Capture audit event + logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + String serviceId = instanceIdMap.get("serviceId"); + String serviceType = e2eCompareModelReq.getServiceType(); + RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeTimeout).setRequestAction(action.name()) + .setServiceInstanceId(serviceId).setServiceType(serviceType).setRequestDetails(bpmnRequest) + .setALaCarte(false).build(); + response = requestClient.post(postParam); + } catch (Exception e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", + ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine", e); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); + return resp; + } + + if (response == null) { + Response resp = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, + "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString()); + return resp; + } + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + + return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap, + version); + } + + private Response getE2EServiceInstance(String serviceId, String operationId, String version) { + + GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse(); + + String apiVersion = version.substring(1); + + long startTime = System.currentTimeMillis(); + + OperationStatus operationStatus; + + try { + operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId); + } catch (Exception e) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), + "Exception while communciate with Request DB - Infra Request Lookup", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, + e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + + } + + if (operationStatus == null) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT, + MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB", + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), + "Null response from RequestDB when searching by serviceId"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + + } + + e2eServiceResponse.setOperation(operationStatus); + + return builder.buildResponse(HttpStatus.SC_OK, null, e2eServiceResponse, apiVersion); + } + + private Response deleteE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap, + String version) throws ApiException { + // TODO should be a new one or the same service instance Id + long startTime = System.currentTimeMillis(); + E2EServiceInstanceDeleteRequest e2eDelReq; + + ObjectMapper mapper = new ObjectMapper(); + try { + e2eDelReq = mapper.readValue(requestJSON, E2EServiceInstanceDeleteRequest.class); + + } catch (Exception e) { + + logger.debug("Mapping of request to JSON object failed : ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + String requestId = UUID.randomUUID().toString(); RecipeLookupResult recipeLookupResult; try { - //TODO Get the service template model version uuid from AAI. - recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); + // TODO Get the service template model version uuid from AAI. + recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); + logger.error(MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, - "No communication to catalog DB " + e.getMessage(), + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, + "Exception while communciate with " + "Catalog DB", action, ModelType.service.name(), requestJSON); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; } if (recipeLookupResult == null) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.DataError.getValue(), "No recipe found in DB"); - - Response response = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_NOT_FOUND, MsoException.ServiceException, - "Recipe does not exist in catalog DB", - ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No recipe found in DB", action, ModelType.service.name(), requestJSON); - logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); - return response; + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.DataError.getValue(), "No recipe found in DB"); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "Recipe does not exist in catalog DB", + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Recipe does not exist in catalog DB", action, + ModelType.service.name(), requestJSON); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; } RequestClient requestClient; @@ -775,274 +400,591 @@ public class E2EServiceInstances { String bpmnRequest = jjo.toString(); // Capture audit event - logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); - String serviceId = instanceIdMap.get("serviceId"); - String serviceInstanceType = e2eScaleReq.getService().getServiceType(); - RequestClientParameter postParam = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.name()) - .setServiceInstanceId(serviceId) - .setServiceType(serviceInstanceType) - .setRequestDetails(bpmnRequest) - .setApiVersion(version) - .setALaCarte(false) - .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); + logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + String serviceId = instanceIdMap.get("serviceId"); + String serviceInstanceType = e2eDelReq.getServiceType(); + RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); + response = requestClient.post(clientParam); + + } catch (Exception e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.debug("End of the transaction, the final response is: " + resp.getEntity()); + return resp; + } + + if (response == null) { + Response resp = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, + "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + + return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap, + version); + } + + private Response updateE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap, + String version) throws ApiException { + + String requestId = UUID.randomUUID().toString(); + long startTime = System.currentTimeMillis(); + E2EServiceInstanceRequest e2eSir; + String serviceId = instanceIdMap.get("serviceId"); + + ObjectMapper mapper = new ObjectMapper(); + try { + e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class); + + } catch (Exception e) { + + logger.debug("Mapping of request to JSON object failed : ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON); + sir.getRequestDetails().getRequestParameters().setaLaCarte(true); + try { + parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId); + } catch (Exception e) { + logger.debug("Validation failed: ", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, + "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); + if (requestId != null) { + logger.debug("Logging failed message to the database"); + } + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + RecipeLookupResult recipeLookupResult; + try { + recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); + } catch (Exception e) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + + return response; + } + + if (recipeLookupResult == null) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.DataError.getValue(), "No recipe found in DB"); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "Recipe does not exist in catalog DB", + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + + return response; + } + + String serviceInstanceType = e2eSir.getService().getServiceType(); + + RequestClient requestClient; + HttpResponse response; + + long subStartTime = System.currentTimeMillis(); + String sirRequestJson = convertToString(sir); + + try { + requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); + + // Capture audit event + logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); response = requestClient.post(postParam); - } catch (Exception e) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "Failed calling bpmn " + e.getMessage(), + } catch (Exception e) { + logger.debug("Exception while communicate with BPMN engine", e); + Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); + + return getBPMNResp; } if (response == null) { - Response resp = msoRequest.buildServiceErrorResponse( - HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, - "bpelResponse is null", + Response getBPMNResp = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, + "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity()); + return getBPMNResp; + } + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + + return beplStatusUpdate(serviceId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap, + version); + } + + private Response processE2EserviceInstances(String requestJSON, Action action, + HashMap<String, String> instanceIdMap, String version) throws ApiException { + + String requestId = UUID.randomUUID().toString(); + long startTime = System.currentTimeMillis(); + E2EServiceInstanceRequest e2eSir; + + MsoRequest msoRequest = new MsoRequest(); + ObjectMapper mapper = new ObjectMapper(); + try { + e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class); + + } catch (Exception e) { + + logger.debug("Mapping of request to JSON object failed : ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON); + sir.getRequestDetails().getRequestParameters().setaLaCarte(true); + try { + parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId); + } catch (Exception e) { + logger.debug("Validation failed: ", e); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, + "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version); + if (requestId != null) { + logger.debug("Logging failed message to the database"); + } + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + RecipeLookupResult recipeLookupResult; + try { + recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action); + } catch (Exception e) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + if (recipeLookupResult == null) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.DataError.getValue(), "No recipe found in DB"); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "Recipe does not exist in catalog DB", + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + String serviceInstanceType = e2eSir.getService().getServiceType(); + + String serviceId = ""; + RequestClient requestClient; + HttpResponse response; + + long subStartTime = System.currentTimeMillis(); + String sirRequestJson = convertToString(sir); + + try { + requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); + + // Capture audit event + logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + RequestClientParameter parameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); + response = requestClient.post(parameter); + } catch (Exception e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } + + if (response == null) { + Response resp = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, + "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + + return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap, + version); + } + + private Response scaleE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap, + String version) throws ApiException { + + String requestId = UUID.randomUUID().toString(); + long startTime = System.currentTimeMillis(); + E2EServiceInstanceScaleRequest e2eScaleReq; + + ObjectMapper mapper = new ObjectMapper(); + try { + e2eScaleReq = mapper.readValue(requestJSON, E2EServiceInstanceScaleRequest.class); + + } catch (Exception e) { + + logger.debug("Mapping of request to JSON object failed : ", e); + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, + MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(), + ErrorNumbers.SVC_BAD_PARAMETER, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.SchemaError.getValue(), requestJSON, e); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + RecipeLookupResult recipeLookupResult; + try { + // TODO Get the service template model version uuid from AAI. + recipeLookupResult = getServiceInstanceOrchestrationURI(null, action); + } catch (Exception e) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e); + + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(), + ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, + "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + if (recipeLookupResult == null) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.DataError.getValue(), "No recipe found in DB"); + + Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, + MsoException.ServiceException, "Recipe does not exist in catalog DB", + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version); + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No recipe found in DB", action, + ModelType.service.name(), requestJSON); + logger.debug(END_OF_THE_TRANSACTION + response.getEntity()); + return response; + } + + RequestClient requestClient; + HttpResponse response; + + long subStartTime = System.currentTimeMillis(); + try { + requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI()); + + JSONObject jjo = new JSONObject(requestJSON); + jjo.put("operationId", requestId); + + String bpmnRequest = jjo.toString(); + + // Capture audit event + logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl()); + String serviceId = instanceIdMap.get("serviceId"); + String serviceInstanceType = e2eScaleReq.getService().getServiceType(); + RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType) + .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false) + .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build(); + response = requestClient.post(postParam); + } catch (Exception e) { + Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, + MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(), ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, - ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; + + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; } - ResponseHandler respHandler = new ResponseHandler(response, - requestClient.getType()); + if (response == null) { + Response resp = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException, + "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA, + ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); int bpelStatus = respHandler.getStatus(); - return beplStatusUpdate(requestId, startTime, requestClient, respHandler, - bpelStatus, action, instanceIdMap, version); + return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap, + version); } - private Response beplStatusUpdate(String serviceId, long startTime, - RequestClient requestClient, - ResponseHandler respHandler, int bpelStatus, Action action, - HashMap<String, String> instanceIdMap, String version) { - - String apiVersion = version.substring(1); - - // BPMN accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - String camundaJSONResponseBody = respHandler.getResponseBody(); - logger.debug("Received from Camunda: " + camundaJSONResponseBody); - logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody); - return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion); - } else { - List<String> variables = new ArrayList<>(); - variables.add(bpelStatus + ""); - String camundaJSONResponseBody = respHandler.getResponseBody(); - if (camundaJSONResponseBody != null - && !camundaJSONResponseBody.isEmpty()) { - Response resp = msoRequest.buildServiceErrorResponse( - bpelStatus, MsoException.ServiceException, - "Request Failed due to BPEL error with HTTP Status= %1 " - + '\n' + camundaJSONResponseBody, - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); - logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcesssError.getValue(), - "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } else { - Response resp = msoRequest - .buildServiceErrorResponse( - bpelStatus, - MsoException.ServiceException, - "Request Failed due to BPEL error with HTTP Status= %1", - ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, - variables, version); - logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), - ErrorCode.BusinessProcesssError.getValue(), - "Response from BPEL engine is empty"); - logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); - return resp; - } - } - } - - /** - * Getting recipes from catalogDb - * - * @param serviceModelUUID the service model version uuid - * @param action the action for the service - * @return the service recipe result - */ - private RecipeLookupResult getServiceInstanceOrchestrationURI(String serviceModelUUID, Action action) { - - RecipeLookupResult recipeLookupResult = getServiceURI(serviceModelUUID, action); - - if (recipeLookupResult != null) { - logger.debug( - "Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer - .toString(recipeLookupResult.getRecipeTimeout())); - } else { - logger.debug("No matching recipe record found"); - } - return recipeLookupResult; - } - - /** - * Getting recipes from catalogDb - * If Service recipe is not set, use default recipe, if set , use special recipe. - * @param serviceModelUUID the service version uuid - * @param action the action of the service. - * @return the service recipe result. - */ - private RecipeLookupResult getServiceURI(String serviceModelUUID, Action action) { - - String defaultServiceModelName = "UUI_DEFAULT"; - - Service defaultServiceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - //set recipe as default generic recipe - ServiceRecipe recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(defaultServiceRecord.getModelUUID(), action.name()); - //check the service special recipe - if(null != serviceModelUUID && ! serviceModelUUID.isEmpty()){ - ServiceRecipe serviceSpecialRecipe = catalogDbClient.getFirstByServiceModelUUIDAndAction( - serviceModelUUID, action.name()); - if(null != serviceSpecialRecipe){ - //set service special recipe. - recipe = serviceSpecialRecipe; - } - } - - if (recipe == null) { - return null; - } - return new RecipeLookupResult(recipe.getOrchestrationUri(), - recipe.getRecipeTimeout(), recipe.getParamXsd()); - - } - - /** - * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and - * passing it to camunda engine. - * - * @param e2eSir - * @return - */ - private ServiceInstancesRequest mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, - String requestJSON) { - - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - - String returnString = null; - RequestDetails requestDetails = new RequestDetails(); - ModelInfo modelInfo = new ModelInfo(); - - // ModelInvariantId - modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid()); - - // modelNameVersionId - modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid()); - - // String modelInfoValue = - // e2eSir.getService().getParameters().getNodeTemplateName(); - // String[] arrayOfInfo = modelInfoValue.split(":"); - // String modelName = arrayOfInfo[0]; - // String modelVersion = arrayOfInfo[1]; - - // TODO: To ensure, if we dont get the values from the UUI - String modelName = "voLTE"; - String modelVersion = "1.0"; - // modelName - modelInfo.setModelName(modelName); - - // modelVersion - modelInfo.setModelVersion(modelVersion); - - // modelType - modelInfo.setModelType(ModelType.service); - - // setting modelInfo to requestDetails - requestDetails.setModelInfo(modelInfo); - - SubscriberInfo subscriberInfo = new SubscriberInfo(); - - // globalsubscriberId - subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId()); - - // setting subscriberInfo to requestDetails - requestDetails.setSubscriberInfo(subscriberInfo); - - RequestInfo requestInfo = new RequestInfo(); - - // instanceName - requestInfo.setInstanceName(e2eSir.getService().getName()); - - // source - requestInfo.setSource("UUI"); - - // suppressRollback - requestInfo.setSuppressRollback(true); - - // setting requestInfo to requestDetails - requestDetails.setRequestInfo(requestInfo); - - RequestParameters requestParameters = new RequestParameters(); - - // subscriptionServiceType - requestParameters.setSubscriptionServiceType("MOG"); - - // Userparams - //List<E2EUserParam> userParams; - // userParams = - // e2eSir.getService().getParameters().getRequestParameters().getUserParams(); - List<Map<String, Object>> userParamList = new ArrayList<>(); - Map<String, Object> userParamMap = new HashMap<>(); - // complete json request updated in the camunda - userParamMap.put("UUIRequest", requestJSON); - userParamMap.put("ServiceInstanceName", e2eSir.getService().getName()); - - // Map<String, String> userParamMap3 = null; - // for (E2EUserParam userp : userParams) { - // userParamMap.put(userp.getName(), userp.getValue()); - // - // } - userParamList.add(userParamMap); - requestParameters.setUserParams(userParamList); - - // setting requestParameters to requestDetails - requestDetails.setRequestParameters(requestParameters); - - sir.setRequestDetails(requestDetails); - - return sir; - } - - - private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Action action, String version, - String requestJSON, Boolean aLaCarte, String requestId) throws ValidateException { - int reqVersion = Integer.parseInt(version.substring(1)); - try { - msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); - } catch (Exception 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("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, ModelType.service.name(), requestJSON); - - throw validateException; - } - } - - private String convertToString(ServiceInstancesRequest sir) { - String returnString = null; - // converting to string - ObjectMapper mapper = new ObjectMapper(); - try { - returnString = mapper.writeValueAsString(sir); - } catch (IOException e) { - logger.debug("Exception while converting ServiceInstancesRequest object to string", e); - } - - return returnString; - } + private Response beplStatusUpdate(String serviceId, long startTime, RequestClient requestClient, + ResponseHandler respHandler, int bpelStatus, Action action, HashMap<String, String> instanceIdMap, + String version) { + + String apiVersion = version.substring(1); + + // BPMN accepted the request, the request is in progress + if (bpelStatus == HttpStatus.SC_ACCEPTED) { + String camundaJSONResponseBody = respHandler.getResponseBody(); + logger.debug("Received from Camunda: " + camundaJSONResponseBody); + logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody); + return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion); + } else { + List<String> variables = new ArrayList<>(); + variables.add(bpelStatus + ""); + String camundaJSONResponseBody = respHandler.getResponseBody(); + if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { + Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, + "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); + logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), + ErrorCode.BusinessProcesssError.getValue(), + "Response from BPEL engine is failed with HTTP Status=" + bpelStatus); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } else { + Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException, + "Request Failed due to BPEL error with HTTP Status= %1", + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version); + logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(), + ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is empty"); + logger.debug(END_OF_THE_TRANSACTION + resp.getEntity()); + return resp; + } + } + } + + /** + * Getting recipes from catalogDb + * + * @param serviceModelUUID the service model version uuid + * @param action the action for the service + * @return the service recipe result + */ + private RecipeLookupResult getServiceInstanceOrchestrationURI(String serviceModelUUID, Action action) { + + RecipeLookupResult recipeLookupResult = getServiceURI(serviceModelUUID, action); + + if (recipeLookupResult != null) { + logger.debug("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + + Integer.toString(recipeLookupResult.getRecipeTimeout())); + } else { + logger.debug("No matching recipe record found"); + } + return recipeLookupResult; + } + + /** + * Getting recipes from catalogDb If Service recipe is not set, use default recipe, if set , use special recipe. + * + * @param serviceModelUUID the service version uuid + * @param action the action of the service. + * @return the service recipe result. + */ + private RecipeLookupResult getServiceURI(String serviceModelUUID, Action action) { + + String defaultServiceModelName = "UUI_DEFAULT"; + + Service defaultServiceRecord = + catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + // set recipe as default generic recipe + ServiceRecipe recipe = + catalogDbClient.getFirstByServiceModelUUIDAndAction(defaultServiceRecord.getModelUUID(), action.name()); + // check the service special recipe + if (null != serviceModelUUID && !serviceModelUUID.isEmpty()) { + ServiceRecipe serviceSpecialRecipe = + catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceModelUUID, action.name()); + if (null != serviceSpecialRecipe) { + // set service special recipe. + recipe = serviceSpecialRecipe; + } + } + + if (recipe == null) { + return null; + } + return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout(), recipe.getParamXsd()); + + } + + /** + * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and passing it to camunda engine. + * + * @param e2eSir + * @return + */ + private ServiceInstancesRequest mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, String requestJSON) { + + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + + String returnString = null; + RequestDetails requestDetails = new RequestDetails(); + ModelInfo modelInfo = new ModelInfo(); + + // ModelInvariantId + modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid()); + + // modelNameVersionId + modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid()); + + // String modelInfoValue = + // e2eSir.getService().getParameters().getNodeTemplateName(); + // String[] arrayOfInfo = modelInfoValue.split(":"); + // String modelName = arrayOfInfo[0]; + // String modelVersion = arrayOfInfo[1]; + + // TODO: To ensure, if we dont get the values from the UUI + String modelName = "voLTE"; + String modelVersion = "1.0"; + // modelName + modelInfo.setModelName(modelName); + + // modelVersion + modelInfo.setModelVersion(modelVersion); + + // modelType + modelInfo.setModelType(ModelType.service); + + // setting modelInfo to requestDetails + requestDetails.setModelInfo(modelInfo); + + SubscriberInfo subscriberInfo = new SubscriberInfo(); + + // globalsubscriberId + subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId()); + + // setting subscriberInfo to requestDetails + requestDetails.setSubscriberInfo(subscriberInfo); + + RequestInfo requestInfo = new RequestInfo(); + + // instanceName + requestInfo.setInstanceName(e2eSir.getService().getName()); + + // source + requestInfo.setSource("UUI"); + + // suppressRollback + requestInfo.setSuppressRollback(true); + + // setting requestInfo to requestDetails + requestDetails.setRequestInfo(requestInfo); + + RequestParameters requestParameters = new RequestParameters(); + + // subscriptionServiceType + requestParameters.setSubscriptionServiceType("MOG"); + + // Userparams + // List<E2EUserParam> userParams; + // userParams = + // e2eSir.getService().getParameters().getRequestParameters().getUserParams(); + List<Map<String, Object>> userParamList = new ArrayList<>(); + Map<String, Object> userParamMap = new HashMap<>(); + // complete json request updated in the camunda + userParamMap.put("UUIRequest", requestJSON); + userParamMap.put("ServiceInstanceName", e2eSir.getService().getName()); + + // Map<String, String> userParamMap3 = null; + // for (E2EUserParam userp : userParams) { + // userParamMap.put(userp.getName(), userp.getValue()); + // + // } + userParamList.add(userParamMap); + requestParameters.setUserParams(userParamList); + + // setting requestParameters to requestDetails + requestDetails.setRequestParameters(requestParameters); + + sir.setRequestDetails(requestDetails); + + return sir; + } + + + private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Action action, + String version, String requestJSON, Boolean aLaCarte, String requestId) throws ValidateException { + int reqVersion = Integer.parseInt(version.substring(1)); + try { + msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); + } catch (Exception 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("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, + ModelType.service.name(), requestJSON); + + throw validateException; + } + } + + private String convertToString(ServiceInstancesRequest sir) { + String returnString = null; + // converting to string + ObjectMapper mapper = new ObjectMapper(); + try { + returnString = mapper.writeValueAsString(sir); + } catch (IOException e) { + logger.debug("Exception while converting ServiceInstancesRequest object to string", e); + } + + return returnString; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java index ad20c5c527..4d283f26b1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandler.java @@ -25,12 +25,10 @@ package org.onap.so.apihandlerinfra; import java.net.URI; import java.util.Collections; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; - import javax.annotation.PostConstruct; import javax.transaction.Transactional; import javax.ws.rs.DefaultValue; @@ -42,7 +40,6 @@ import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; - import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.springframework.beans.factory.annotation.Autowired; @@ -58,166 +55,163 @@ import io.swagger.annotations.ApiOperation; @Component @Path("/globalhealthcheck") -@Api(value="/globalhealthcheck",description="APIH Infra Global Health Check") +@Api(value = "/globalhealthcheck", description = "APIH Infra Global Health Check") public class GlobalHealthcheckHandler { - private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class); - private static final String CONTEXTPATH_PROPERTY = "management.context-path"; - private static final String PROPERTY_DOMAIN = "mso.health.endpoints"; - private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb"; - private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb"; - private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc"; - private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack"; - private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn"; - private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc"; - private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc"; - private static final String DEFAULT_PROPERTY_VALUE = ""; - + private static Logger logger = LoggerFactory.getLogger(GlobalHealthcheckHandler.class); + private static final String CONTEXTPATH_PROPERTY = "management.context-path"; + private static final String PROPERTY_DOMAIN = "mso.health.endpoints"; + private static final String CATALOGDB_PROPERTY = PROPERTY_DOMAIN + ".catalogdb"; + private static final String REQUESTDB_PROPERTY = PROPERTY_DOMAIN + ".requestdb"; + private static final String SDNC_PROPERTY = PROPERTY_DOMAIN + ".sdnc"; + private static final String OPENSTACK_PROPERTY = PROPERTY_DOMAIN + ".openstack"; + private static final String BPMN_PROPERTY = PROPERTY_DOMAIN + ".bpmn"; + private static final String ASDC_PROPERTY = PROPERTY_DOMAIN + ".asdc"; + private static final String REQUESTDBATTSVC_PROPERTY = PROPERTY_DOMAIN + ".requestdbattsvc"; + private static final String DEFAULT_PROPERTY_VALUE = ""; + // e.g. /manage private String actuatorContextPath; - private String endpointCatalogdb; - private String endpointRequestdb; - private String endpointSdnc; - private String endpointOpenstack; - private String endpointBpmn; - private String endpointAsdc; - private String endpointRequestdbAttsvc; - - @Autowired - private Environment env; - - @Autowired - private RestTemplate restTemplate; - private final String health = "/health"; - - - @PostConstruct - protected void init() { - actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); - } - + private String endpointCatalogdb; + private String endpointRequestdb; + private String endpointSdnc; + private String endpointOpenstack; + private String endpointBpmn; + private String endpointAsdc; + private String endpointRequestdbAttsvc; + + @Autowired + private Environment env; + + @Autowired + private RestTemplate restTemplate; + private final String health = "/health"; + + + @PostConstruct + protected void init() { + actuatorContextPath = env.getProperty(CONTEXTPATH_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointCatalogdb = env.getProperty(CATALOGDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointRequestdb = env.getProperty(REQUESTDB_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointSdnc = env.getProperty(SDNC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointOpenstack = env.getProperty(OPENSTACK_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointBpmn = env.getProperty(BPMN_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointAsdc = env.getProperty(ASDC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + endpointRequestdbAttsvc = env.getProperty(REQUESTDBATTSVC_PROPERTY, String.class, DEFAULT_PROPERTY_VALUE); + } + @GET @Produces("application/json") - @ApiOperation(value="Performing global health check",response=Response.class) + @ApiOperation(value = "Performing global health check", response = Response.class) @Transactional - public Response globalHealthcheck (@DefaultValue("true") @QueryParam("enableBpmn") boolean enableBpmn, - @Context ContainerRequestContext requestContext) { - Response HEALTH_CHECK_RESPONSE = null; + public Response globalHealthcheck(@DefaultValue("true") @QueryParam("enableBpmn") boolean enableBpmn, + @Context ContainerRequestContext requestContext) { + Response HEALTH_CHECK_RESPONSE = null; // Build internal response object HealthcheckResponse rsp = new HealthcheckResponse(); - - try{ + + try { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); - + // set APIH status, this is the main entry point rsp.setApih(HealthcheckStatus.UP.toString()); // set BPMN rsp.setBpmn(querySubsystemHealth(MsoSubsystems.BPMN)); // set SDNCAdapter - rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC)); + rsp.setSdncAdapter(querySubsystemHealth(MsoSubsystems.SDNC)); // set ASDCController - rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC)); + rsp.setAsdcController(querySubsystemHealth(MsoSubsystems.ASDC)); // set CatalogDbAdapter - rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB)); + rsp.setCatalogdbAdapter(querySubsystemHealth(MsoSubsystems.CATALOGDB)); // set RequestDbAdapter - rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB)); + rsp.setRequestdbAdapter(querySubsystemHealth(MsoSubsystems.REQUESTDB)); // set OpenStackAdapter - rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK)); + rsp.setOpenstackAdapter(querySubsystemHealth(MsoSubsystems.OPENSTACK)); // set RequestDbAdapterAttSvc rsp.setRequestdbAdapterAttsvc(querySubsystemHealth(MsoSubsystems.REQUESTDBATT)); // set Message rsp.setMessage(String.format("HttpStatus: %s", HttpStatus.SC_OK)); logger.info(rsp.toString()); - HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK) - .entity (rsp) - .build (); - - }catch (Exception ex){ - logger.error("Exception occurred", ex); - rsp.setMessage(ex.getMessage()); - HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_INTERNAL_SERVER_ERROR) - .entity (rsp) - .build (); - } - + HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_OK).entity(rsp).build(); + + } catch (Exception ex) { + logger.error("Exception occurred", ex); + rsp.setMessage(ex.getMessage()); + HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(rsp).build(); + } + return HEALTH_CHECK_RESPONSE; } - - protected HttpEntity<String> buildHttpEntityForRequest(){ + + protected HttpEntity<String> buildHttpEntityForRequest() { HttpHeaders headers = new HttpHeaders(); - headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); + headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); headers.set("Content-Type", "application/json"); - HttpEntity<String> entity = new HttpEntity<>("parameters", headers); + HttpEntity<String> entity = new HttpEntity<>("parameters", headers); return entity; } - - protected String querySubsystemHealth(MsoSubsystems subsystem){ - try{ + + protected String querySubsystemHealth(MsoSubsystems subsystem) { + try { // get port number for the subsystem - String ept = getEndpointUrlForSubsystemEnum(subsystem); - - // build final endpoint url - UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health); - URI uri = builder.build(); - logger.info("Calculated URL: {}", uri.toString()); - - ResponseEntity<SubsystemHealthcheckResponse> result = - restTemplate.exchange(uri, HttpMethod.GET, buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class); - - return processResponseFromSubsystem(result,subsystem); - - }catch(Exception ex){ - logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex); - return HealthcheckStatus.DOWN.toString(); - } + String ept = getEndpointUrlForSubsystemEnum(subsystem); + + // build final endpoint url + UriBuilder builder = UriBuilder.fromPath(ept).path(actuatorContextPath).path(health); + URI uri = builder.build(); + logger.info("Calculated URL: {}", uri.toString()); + + ResponseEntity<SubsystemHealthcheckResponse> result = restTemplate.exchange(uri, HttpMethod.GET, + buildHttpEntityForRequest(), SubsystemHealthcheckResponse.class); + + return processResponseFromSubsystem(result, subsystem); + + } catch (Exception ex) { + logger.error("Exception occured in GlobalHealthcheckHandler.querySubsystemHealth() ", ex); + return HealthcheckStatus.DOWN.toString(); + } } - protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, MsoSubsystems subsystem){ - if(result == null || result.getStatusCodeValue() != HttpStatus.SC_OK){ - logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s", - subsystem, - result == null? "NULL": result)); - return HealthcheckStatus.DOWN.toString(); + + protected String processResponseFromSubsystem(ResponseEntity<SubsystemHealthcheckResponse> result, + MsoSubsystems subsystem) { + if (result == null || result.getStatusCodeValue() != HttpStatus.SC_OK) { + logger.error(String.format("Globalhealthcheck: checking subsystem: %s failed ! result object is: %s", + subsystem, result == null ? "NULL" : result)); + return HealthcheckStatus.DOWN.toString(); } - + SubsystemHealthcheckResponse body = result.getBody(); - String status = body.getStatus(); - if("UP".equalsIgnoreCase(status)){ - return HealthcheckStatus.UP.toString(); - }else{ - logger.error("{}, query health endpoint did not return UP status!", subsystem); - return HealthcheckStatus.DOWN.toString(); - } - } - - - protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem){ - switch (subsystem){ - case SDNC: - return this.endpointSdnc; - case ASDC: - return this.endpointAsdc; - case BPMN: - return this.endpointBpmn; - case CATALOGDB: - return this.endpointCatalogdb; - case OPENSTACK: - return this.endpointOpenstack; - case REQUESTDB: - return this.endpointRequestdb; - case REQUESTDBATT: - return this.endpointRequestdbAttsvc; - default: - return ""; - } + String status = body.getStatus(); + if ("UP".equalsIgnoreCase(status)) { + return HealthcheckStatus.UP.toString(); + } else { + logger.error("{}, query health endpoint did not return UP status!", subsystem); + return HealthcheckStatus.DOWN.toString(); + } + } + + + protected String getEndpointUrlForSubsystemEnum(MsoSubsystems subsystem) { + switch (subsystem) { + case SDNC: + return this.endpointSdnc; + case ASDC: + return this.endpointAsdc; + case BPMN: + return this.endpointBpmn; + case CATALOGDB: + return this.endpointCatalogdb; + case OPENSTACK: + return this.endpointOpenstack; + case REQUESTDB: + return this.endpointRequestdb; + case REQUESTDBATT: + return this.endpointRequestdbAttsvc; + default: + return ""; + } } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java index 8f0bbc4e1f..fad3dd4055 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckResponse.java @@ -22,100 +22,95 @@ package org.onap.so.apihandlerinfra; import org.apache.commons.lang3.builder.ToStringBuilder; public class HealthcheckResponse { - private String apih; - private String bpmn; - private String sdncAdapter; - private String asdcController; - private String catalogdbAdapter; - private String requestdbAdapter; - private String openstackAdapter; - private String requestdbAdapterAttsvc; - private String message = ""; - - public String getApih() { - return apih; - } - - public void setApih(String apih) { - this.apih = apih; - } - - public String getBpmn() { - return bpmn; - } - - public void setBpmn(String bpmn) { - this.bpmn = bpmn; - } - - public String getSdncAdapter() { - return sdncAdapter; - } - - public void setSdncAdapter(String sdncAdapter) { - this.sdncAdapter = sdncAdapter; - } - - public String getAsdcController() { - return asdcController; - } - - public void setAsdcController(String asdcController) { - this.asdcController = asdcController; - } - - public String getCatalogdbAdapter() { - return catalogdbAdapter; - } - - public void setCatalogdbAdapter(String catalogdbAdapter) { - this.catalogdbAdapter = catalogdbAdapter; - } - - public String getRequestdbAdapter() { - return requestdbAdapter; - } - - public void setRequestdbAdapter(String requestdbAdapter) { - this.requestdbAdapter = requestdbAdapter; - } - - public String getOpenstackAdapter() { - return openstackAdapter; - } - - public void setOpenstackAdapter(String openstackAdapter) { - this.openstackAdapter = openstackAdapter; - } - - public String getRequestdbAdapterAttsvc() { - return requestdbAdapterAttsvc; - } - - public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) { - this.requestdbAdapterAttsvc = requestdbAdapterAttsvc; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - @Override - public String toString() { - return new ToStringBuilder(this). - append("apih", this.apih). - append("pbmn", this.bpmn). - append("sdncAdapter", this.sdncAdapter). - append("asdcController", this.asdcController). - append("catalogdbAdapter", this.catalogdbAdapter). - append("requestdbAdapter", this.requestdbAdapter). - append("openstackAdapter", this.openstackAdapter). - append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc). - append("message", this.message). - toString(); - } + private String apih; + private String bpmn; + private String sdncAdapter; + private String asdcController; + private String catalogdbAdapter; + private String requestdbAdapter; + private String openstackAdapter; + private String requestdbAdapterAttsvc; + private String message = ""; + + public String getApih() { + return apih; + } + + public void setApih(String apih) { + this.apih = apih; + } + + public String getBpmn() { + return bpmn; + } + + public void setBpmn(String bpmn) { + this.bpmn = bpmn; + } + + public String getSdncAdapter() { + return sdncAdapter; + } + + public void setSdncAdapter(String sdncAdapter) { + this.sdncAdapter = sdncAdapter; + } + + public String getAsdcController() { + return asdcController; + } + + public void setAsdcController(String asdcController) { + this.asdcController = asdcController; + } + + public String getCatalogdbAdapter() { + return catalogdbAdapter; + } + + public void setCatalogdbAdapter(String catalogdbAdapter) { + this.catalogdbAdapter = catalogdbAdapter; + } + + public String getRequestdbAdapter() { + return requestdbAdapter; + } + + public void setRequestdbAdapter(String requestdbAdapter) { + this.requestdbAdapter = requestdbAdapter; + } + + public String getOpenstackAdapter() { + return openstackAdapter; + } + + public void setOpenstackAdapter(String openstackAdapter) { + this.openstackAdapter = openstackAdapter; + } + + public String getRequestdbAdapterAttsvc() { + return requestdbAdapterAttsvc; + } + + public void setRequestdbAdapterAttsvc(String requestdbAdapterAttsvc) { + this.requestdbAdapterAttsvc = requestdbAdapterAttsvc; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + return new ToStringBuilder(this).append("apih", this.apih).append("pbmn", this.bpmn) + .append("sdncAdapter", this.sdncAdapter).append("asdcController", this.asdcController) + .append("catalogdbAdapter", this.catalogdbAdapter).append("requestdbAdapter", this.requestdbAdapter) + .append("openstackAdapter", this.openstackAdapter) + .append("requestdbAdapterAttsvc", this.requestdbAdapterAttsvc).append("message", this.message) + .toString(); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java index 89c4e0efda..077a3c2d60 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/HealthcheckStatus.java @@ -20,15 +20,16 @@ package org.onap.so.apihandlerinfra; public enum HealthcheckStatus { - UP("UP"), DOWN("DOWN"); - - private String status; - private HealthcheckStatus(String status) { - this.status = status; - } - - @Override - public String toString(){ - return status; - } + UP("UP"), DOWN("DOWN"); + + private String status; + + private HealthcheckStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return status; + } } 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 new file mode 100644 index 0000000000..c491444f39 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/InstanceManagement.java @@ -0,0 +1,263 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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 io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.http.HttpStatus; +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.RecipeNotFoundException; +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.catalog.beans.Workflow; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +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.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 java.io.IOException; +import java.util.HashMap; + +@Component +@Path("/onap/so/infra/instanceManagement") +@Api(value = "/onap/so/infra/instanceManagement", description = "Infrastructure API Requests for Instance Management") +public class InstanceManagement { + + private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class); + private static String uriPrefix = "/instanceManagement/"; + private static final String SAVE_TO_DB = "save instance to db"; + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + @Autowired + private CatalogDbClient catalogDbClient; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @POST + @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Execute custom workflow", response = Response.class) + @Transactional + public Response executeCustomWorkflow(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @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("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("workflowUuid", workflowUuid); + return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, + requestContext); + } + + private Response processCustomWorkflowRequest(String requestJSON, Actions action, + HashMap<String, String> instanceIdMap, String version, String requestId, + ContainerRequestContext requestContext) throws ApiException { + String serviceInstanceId = null; + if (instanceIdMap != null) { + serviceInstanceId = instanceIdMap.get("serviceInstanceId"); + } + Boolean aLaCarte = true; + long startTime = System.currentTimeMillis(); + ServiceInstancesRequest sir = null; + String apiVersion = version.substring(1); + + String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix); + + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, + requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); + + try { + requestHandlerUtils.validateHeaders(requestContext); + } catch (ValidationException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_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(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, + currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + + int requestVersion = Integer.parseInt(version.substring(1)); + String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion); + + if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) { + currentActiveReq.setVnfType(vnfType); + } + + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, 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); + } + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); + + RequestReferences referencesResponse = new RequestReferences(); + + referencesResponse.setRequestId(requestId); + + serviceResponse.setRequestReferences(referencesResponse); + Boolean isBaseVfModule = false; + + String workflowUuid = null; + if (instanceIdMap != null) { + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid); + + String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true); + + serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); + String vnfId = ""; + + if (sir.getVnfInstanceId() != null) { + 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(); + } + + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId) + .setServiceType(serviceInstanceType).setVnfType(vnfType) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq, + String workflowUuid) throws ApiException { + RecipeLookupResult recipeLookupResult = null; + + try { + recipeLookupResult = getCustomWorkflowUri(workflowUuid); + } catch (IOException 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(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + if (recipeLookupResult == null) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + RecipeNotFoundException recipeNotFoundExceptionException = + new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, + recipeNotFoundExceptionException.getMessage()); + throw recipeNotFoundExceptionException; + } + + return recipeLookupResult; + } + + private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException { + + String recipeUri = null; + Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid); + if (workflow == null) { + return null; + } else { + String workflowName = workflow.getArtifactName(); + recipeUri = "/mso/async/services/" + workflowName; + } + return new RecipeLookupResult(recipeUri, 180); + } +} 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 182e398461..67d6a0d1fc 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 @@ -22,10 +22,10 @@ package org.onap.so.apihandlerinfra; 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.apihandlerinfra.exceptions.ApiExceptionMapper; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestration; import org.onap.so.apihandlerinfra.tenantisolation.CloudResourcesOrchestration; @@ -33,7 +33,6 @@ import org.onap.so.apihandlerinfra.tenantisolation.ModelDistributionRequest; import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; import org.onap.so.web.exceptions.RuntimeExceptionMapper; import org.springframework.context.annotation.Configuration; - import io.swagger.jaxrs.config.BeanConfig; import io.swagger.jaxrs.listing.ApiListingResource; import io.swagger.jaxrs.listing.SwaggerSerializers; @@ -44,35 +43,38 @@ public class JerseyConfiguration extends ResourceConfig { - @PostConstruct - public void setUp() { - register(GlobalHealthcheckHandler.class); - register(NodeHealthcheckHandler.class); - register(ServiceInstances.class); - register(TasksHandler.class); - register(CloudOrchestration.class); - register(CloudResourcesOrchestration.class); - register(OrchestrationRequests.class); - register(JaxRsFilterLogging.class); - register(ManualTasks.class); - register(TasksHandler.class); - register(ApiListingResource.class); - register(SwaggerSerializers.class); - register(ApiExceptionMapper.class); - register(RuntimeExceptionMapper.class); - register(RequestUriFilter.class); - register(E2EServiceInstances.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); - register(ModelDistributionRequest.class); - property(ServletProperties.FILTER_FORWARD_ON_404, true); - BeanConfig beanConfig = new BeanConfig(); - beanConfig.setVersion("1.0.2"); - beanConfig.setSchemes(new String[] { "https" }); - beanConfig.setResourcePackage("org.onap.so.apihandlerinfra"); - beanConfig.setPrettyPrint(true); - beanConfig.setScan(true); - } + @PostConstruct + public void setUp() { + register(GlobalHealthcheckHandler.class); + register(NodeHealthcheckHandler.class); + register(ServiceInstances.class); + register(TasksHandler.class); + register(CloudOrchestration.class); + register(CloudResourcesOrchestration.class); + register(OrchestrationRequests.class); + register(JaxRsFilterLogging.class); + register(ManualTasks.class); + register(TasksHandler.class); + register(ApiListingResource.class); + register(SwaggerSerializers.class); + register(ApiExceptionMapper.class); + register(RuntimeExceptionMapper.class); + register(RequestUriFilter.class); + register(RequestIdFilter.class); + register(E2EServiceInstances.class); + register(WorkflowSpecificationsHandler.class); + register(InstanceManagement.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); + register(ModelDistributionRequest.class); + property(ServletProperties.FILTER_FORWARD_ON_404, true); + BeanConfig beanConfig = new BeanConfig(); + beanConfig.setVersion("1.0.2"); + beanConfig.setSchemes(new String[] {"https"}); + beanConfig.setResourcePackage("org.onap.so.apihandlerinfra"); + beanConfig.setPrettyPrint(true); + beanConfig.setScan(true); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java index ad589ddc9c..3c06804594 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/ManualTasks.java @@ -24,7 +24,6 @@ package org.onap.so.apihandlerinfra; import java.io.IOException; - import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.POST; @@ -35,7 +34,6 @@ 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.HttpResponse; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -46,7 +44,6 @@ import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskRequestReference; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; @@ -56,193 +53,212 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; 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 com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; - import io.swagger.annotations.ApiOperation; @Path("/tasks") @Component public class ManualTasks { - private static Logger logger = LoggerFactory.getLogger(ManualTasks.class); - - - @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}") - private String taskUri; - - @Autowired - private RequestClientFactory reqClientFactory; - - @Autowired - private MsoRequest msoRequest; - - @Autowired - private ResponseBuilder builder; - - @POST - @Path("/{version:[vV]1}/{taskId}/complete") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Complete specified task",response=Response.class) - @Transactional - public Response completeTask(String request, @PathParam("version") String version, @PathParam("taskId") String taskId, - @Context ContainerRequestContext requestContext) throws ApiException { - - String requestId = requestContext.getProperty("requestId").toString(); - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); - long startTime = System.currentTimeMillis (); - logger.debug ("requestId is: {}", requestId); - TasksRequest taskRequest = null; - String apiVersion = version.substring(1); - - try{ - ObjectMapper mapper = new ObjectMapper(); - taskRequest= mapper.readValue(request, TasksRequest.class); - - if (taskRequest.getRequestDetails() == null) { - throw new ValidationException("requestDetails"); - } - if (taskRequest.getRequestDetails().getRequestInfo() == null) { - throw new ValidationException("requestInfo"); - } - if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) { - throw new ValidationException("source"); - } - if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) { - throw new ValidationException("requestorId"); - } - - }catch(IOException 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; - } - catch(ValidationException 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("Mapping of request to JSON Object failed. " + e.getMessage(), - HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - throw validateException; - - } - //Create Request Record - InfraActiveRequests currentActiveReq = msoRequest.createRequestObject(taskRequest,Action.completeTask,requestId,Status.PENDING,request); - - // Transform the request to Camunda-style Complete request - Variables variablesForComplete = new Variables(); - Value sourceValue = new Value(); - sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource()); - Value responseValue = new Value(); - responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name()); - Value requestorIdValue = new Value(); - requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId()); - variablesForComplete.setSource(sourceValue); - variablesForComplete.setResponseValue(responseValue); - variablesForComplete.setRequestorId(requestorIdValue); - - String camundaJsonReq = null; - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - camundaJsonReq = mapper.writeValueAsString(variablesForComplete); - } catch(JsonProcessingException e){ - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - ValidateException validateException = new ValidateException.Builder("Mapping of JSON object to Camunda request failed", - HttpStatus.SC_INTERNAL_SERVER_ERROR,ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - throw validateException; - } - - RequestClient requestClient = null; - HttpResponse response = null; - long subStartTime = System.currentTimeMillis(); - String requestUrl = taskUri + "/" + taskId + "/complete"; - try { - requestClient = reqClientFactory.getRequestClient (requestUrl); - // Capture audit event - - response = requestClient.post(camundaJsonReq); - - } catch (Exception e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; - } - - if (response == null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), - HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); + private static Logger logger = LoggerFactory.getLogger(ManualTasks.class); + + + @org.springframework.beans.factory.annotation.Value("${mso.camunda.rest.task.uri}") + private String taskUri; + + @Autowired + private RequestClientFactory reqClientFactory; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private ResponseBuilder builder; + + @POST + @Path("/{version:[vV]1}/{taskId}/complete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Complete specified task", response = Response.class) + @Transactional + public Response completeTask(String request, @PathParam("version") String version, + @PathParam("taskId") String taskId, @Context ContainerRequestContext requestContext) throws ApiException { + + String requestId = requestContext.getProperty("requestId").toString(); + logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + long startTime = System.currentTimeMillis(); + logger.debug("requestId is: {}", requestId); + TasksRequest taskRequest = null; + String apiVersion = version.substring(1); + + try { + ObjectMapper mapper = new ObjectMapper(); + taskRequest = mapper.readValue(request, TasksRequest.class); + + if (taskRequest.getRequestDetails() == null) { + throw new ValidationException("requestDetails"); + } + if (taskRequest.getRequestDetails().getRequestInfo() == null) { + throw new ValidationException("requestInfo"); + } + if (empty(taskRequest.getRequestDetails().getRequestInfo().getSource())) { + throw new ValidationException("source"); + } + if (empty(taskRequest.getRequestDetails().getRequestInfo().getRequestorId())) { + throw new ValidationException("requestorId"); + } + + } catch (IOException 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; + } catch (ValidationException 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("Mapping of request to JSON Object failed. " + e.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + throw validateException; + + } + // Create Request Record + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(taskRequest, Action.completeTask, requestId, Status.PENDING, request); + + // Transform the request to Camunda-style Complete request + Variables variablesForComplete = new Variables(); + Value sourceValue = new Value(); + sourceValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getSource()); + Value responseValue = new Value(); + responseValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getResponseValue().name()); + Value requestorIdValue = new Value(); + requestorIdValue.setValue(taskRequest.getRequestDetails().getRequestInfo().getRequestorId()); + variablesForComplete.setSource(sourceValue); + variablesForComplete.setResponseValue(responseValue); + variablesForComplete.setRequestorId(requestorIdValue); + + String camundaJsonReq = null; + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + camundaJsonReq = mapper.writeValueAsString(variablesForComplete); + } catch (JsonProcessingException e) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.UnknownError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + + ValidateException validateException = + new ValidateException.Builder("Mapping of JSON object to Camunda request failed", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + throw validateException; + } + + RequestClient requestClient = null; + HttpResponse response = null; + long subStartTime = System.currentTimeMillis(); + String requestUrl = taskUri + "/" + taskId + "/complete"; + try { + requestClient = reqClientFactory.getRequestClient(requestUrl); + // Capture audit event + + response = requestClient.post(camundaJsonReq); + + } catch (Exception e) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + + + BPMNFailureException bpmnFailureException = + new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) + .build(); throw bpmnFailureException; + } - } + if (response == null) { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, + ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ()); - int bpelStatus = respHandler.getStatus (); - // BPEL accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { - logger.debug ("Received good response from Camunda"); - TaskRequestReference trr = new TaskRequestReference(); - trr.setTaskId(taskId); - String completeResp = null; - try { - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); - completeResp = mapper.writeValueAsString(trr); - } - catch (JsonProcessingException e) { + BPMNFailureException bpmnFailureException = + new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo) + .build(); + + throw bpmnFailureException; - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build(); + } + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); - ValidateException validateException = new ValidateException.Builder("Request Failed due to bad response format" , - bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + // BPEL accepted the request, the request is in progress + if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { + logger.debug("Received good response from Camunda"); + TaskRequestReference trr = new TaskRequestReference(); + trr.setTaskId(taskId); + String completeResp = null; + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + completeResp = mapper.writeValueAsString(trr); + } catch (JsonProcessingException e) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, + ErrorCode.BusinessProcesssError).build(); + + + ValidateException validateException = + new ValidateException.Builder("Request Failed due to bad response format", bpelStatus, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); throw validateException; - } - logger.debug("Response to the caller: {}", completeResp); - logger.debug ("End of the transaction, the final response is: {}", completeResp); - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion); - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build(); + } + logger.debug("Response to the caller: {}", completeResp); + logger.debug("End of the transaction, the final response is: {}", completeResp); + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, completeResp, apiVersion); + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + .build(); BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), - bpelStatus,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); throw bpmnFailureException; - - } - - } - - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } - + + } + + } + + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } + } 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 de7d26379c..277675f310 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 @@ -34,7 +34,6 @@ 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; import javax.xml.XMLConstants; @@ -43,13 +42,13 @@ 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.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.tasksbeans.TasksRequest; import org.onap.so.apihandlerinfra.validation.MembersValidation; import org.onap.so.apihandlerinfra.validation.ApplyUpdatedConfigValidation; import org.onap.so.apihandlerinfra.validation.CloudConfigurationValidation; import org.onap.so.apihandlerinfra.validation.ConfigurationParametersValidation; +import org.onap.so.apihandlerinfra.validation.CustomWorkflowValidation; import org.onap.so.apihandlerinfra.validation.InPlaceSoftwareUpdateValidation; import org.onap.so.apihandlerinfra.validation.InstanceIdMapValidation; import org.onap.so.apihandlerinfra.validation.ModelInfoValidation; @@ -94,7 +93,6 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -103,342 +101,358 @@ import com.fasterxml.jackson.databind.ObjectMapper; @Component public class MsoRequest { - - @Autowired - private RequestsDbClient requestsDbClient; - - @Autowired - private ResponseBuilder builder; - + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private ResponseBuilder builder; + private static Logger logger = LoggerFactory.getLogger(MsoRequest.class); - - public Response buildServiceErrorResponse (int httpResponseCode, MsoException exceptionType, - String errorText, String messageId, List<String> variables, String version) { - - if(errorText.length() > 1999){ - errorText = errorText.substring(0, 1999); - } - - RequestError re = new RequestError(); - - if("PolicyException".equals(exceptionType.name())){ - - PolicyException pe = new PolicyException(); - pe.setMessageId(messageId); - pe.setText(errorText); - if(variables != null){ - for(String variable: variables){ - pe.getVariables().add(variable); - } - } - re.setPolicyException(pe); - - } else { - - ServiceException se = new ServiceException(); - se.setMessageId(messageId); - se.setText(errorText); - if(variables != null){ - for(String variable: variables){ - se.getVariables().add(variable); - } - } - re.setServiceException(se); - } + + public Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String errorText, + String messageId, List<String> variables, String version) { + + if (errorText.length() > 1999) { + errorText = errorText.substring(0, 1999); + } + + RequestError re = new RequestError(); + + if ("PolicyException".equals(exceptionType.name())) { + + PolicyException pe = new PolicyException(); + pe.setMessageId(messageId); + pe.setText(errorText); + if (variables != null) { + for (String variable : variables) { + pe.getVariables().add(variable); + } + } + re.setPolicyException(pe); + + } else { + + ServiceException se = new ServiceException(); + se.setMessageId(messageId); + se.setText(errorText); + if (variables != null) { + for (String variable : variables) { + se.getVariables().add(variable); + } + } + re.setServiceException(se); + } String requestErrorStr = null; - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_DEFAULT); - requestErrorStr = mapper.writeValueAsString(re); - }catch(Exception e){ - logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in buildServiceErrorResponse writing exceptionType to string ", e); - } + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_DEFAULT); + requestErrorStr = mapper.writeValueAsString(re); + } catch (Exception e) { + logger.error("{} {} {}", MessageEnum.APIH_VALIDATION_ERROR.toString(), ErrorCode.DataError.getValue(), + "Exception in buildServiceErrorResponse writing exceptionType to string ", e); + } return builder.buildResponse(httpResponseCode, null, requestErrorStr, version); } - + // Parse request JSON - public void parse (ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, Actions action, String version, - String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) throws ValidationException, IOException { - - logger.debug ("Validating the Service Instance request"); + public void parse(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, + String version, String originalRequestJSON, int reqVersion, Boolean aLaCarteFlag) + throws ValidationException, IOException { + + logger.debug("Validating the Service Instance request"); List<ValidationRule> rules = new ArrayList<>(); - logger.debug ("Incoming version is: {} coverting to int: {}", version, reqVersion); - RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters(); - ValidationInformation info = new ValidationInformation(sir, instanceIdMap, action, - reqVersion, aLaCarteFlag, requestParameters); - + logger.debug("Incoming version is: {} coverting to int: {}", version, reqVersion); + RequestParameters requestParameters = sir.getRequestDetails().getRequestParameters(); + ValidationInformation info = + new ValidationInformation(sir, instanceIdMap, action, reqVersion, aLaCarteFlag, requestParameters); + rules.add(new InstanceIdMapValidation()); - - if(reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate){ - rules.add(new InPlaceSoftwareUpdateValidation()); - }else if(reqVersion >= 6 && action == Action.applyUpdatedConfig){ - rules.add(new ApplyUpdatedConfigValidation()); - }else if(action == Action.addMembers || action == Action.removeMembers){ - rules.add(new MembersValidation()); - }else{ - rules.add(new RequestScopeValidation()); - rules.add(new RequestParametersValidation()); - rules.add(new RequestInfoValidation()); - rules.add(new ModelInfoValidation()); - rules.add(new CloudConfigurationValidation()); - rules.add(new SubscriberInfoValidation()); - rules.add(new PlatformLOBValidation()); - rules.add(new ProjectOwningEntityValidation()); - rules.add(new RelatedInstancesValidation()); - rules.add(new ConfigurationParametersValidation()); - } - if(reqVersion >= 7 && requestParameters != null && requestParameters.getUserParams() != null){ - for(Map<String, Object> params : requestParameters.getUserParams()){ - if(params.containsKey("service")){ - ObjectMapper obj = new ObjectMapper(); - String input = obj.writeValueAsString(params.get("service")); - Service validate = obj.readValue(input, Service.class); - info.setUserParams(validate); - rules.add(new UserParamsValidation()); - break; - } - } - } - for(ValidationRule rule : rules){ - rule.validate(info); - } + + String workflowUuid = null; + if (instanceIdMap != null) { + workflowUuid = instanceIdMap.get("workflowUuid"); + } + + if (workflowUuid != null) { + rules.add(new CustomWorkflowValidation()); + } else if (reqVersion >= 6 && action == Action.inPlaceSoftwareUpdate) { + rules.add(new InPlaceSoftwareUpdateValidation()); + } else if (reqVersion >= 6 && action == Action.applyUpdatedConfig) { + rules.add(new ApplyUpdatedConfigValidation()); + } else if (action == Action.addMembers || action == Action.removeMembers) { + rules.add(new MembersValidation()); + } else { + rules.add(new RequestScopeValidation()); + rules.add(new RequestParametersValidation()); + rules.add(new RequestInfoValidation()); + rules.add(new ModelInfoValidation()); + rules.add(new CloudConfigurationValidation()); + rules.add(new SubscriberInfoValidation()); + rules.add(new PlatformLOBValidation()); + rules.add(new ProjectOwningEntityValidation()); + rules.add(new RelatedInstancesValidation()); + rules.add(new ConfigurationParametersValidation()); + } + if (reqVersion >= 7 && requestParameters != null && requestParameters.getUserParams() != null) { + for (Map<String, Object> params : requestParameters.getUserParams()) { + if (params.containsKey("service")) { + ObjectMapper obj = new ObjectMapper(); + String input = obj.writeValueAsString(params.get("service")); + Service validate = obj.readValue(input, Service.class); + info.setUserParams(validate); + rules.add(new UserParamsValidation()); + break; + } + } + } + for (ValidationRule rule : rules) { + rule.validate(info); + } } - void parseOrchestration (ServiceInstancesRequest sir) throws ValidationException { + + void parseOrchestration(ServiceInstancesRequest sir) throws ValidationException { RequestInfo requestInfo = sir.getRequestDetails().getRequestInfo(); if (requestInfo == null) { - throw new ValidationException ("requestInfo"); + throw new ValidationException("requestInfo"); } - if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source"); + if (empty(requestInfo.getSource())) { + throw new ValidationException("source"); } - if (empty (requestInfo.getRequestorId ())) { - throw new ValidationException ("requestorId"); + if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId"); } } - public Map<String, List<String>> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException { + + public Map<String, List<String>> getOrchestrationFilters(MultivaluedMap<String, String> queryParams) + throws ValidationException { String queryParam = null; Map<String, List<String>> orchestrationFilterParams = new HashMap<>(); - for (Entry<String,List<String>> entry : queryParams.entrySet()) { + 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); - } - } - - }catch(Exception e){ - throw new ValidationException ("QueryParam ServiceInfo", e); - } + 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); + } + } + + } catch (Exception e) { + throw new ValidationException("QueryParam ServiceInfo", e); + } } return orchestrationFilterParams; - } + } - public InfraActiveRequests createRequestObject (ServiceInstancesRequest servInsReq, Actions action, String requestId, - Status status, String originalRequestJSON, String requestScope) { - InfraActiveRequests aq = new InfraActiveRequests (); + public InfraActiveRequests createRequestObject(ServiceInstancesRequest servInsReq, Actions action, String requestId, + Status status, String originalRequestJSON, String requestScope) { + InfraActiveRequests aq = new InfraActiveRequests(); try { if (null == servInsReq) { - servInsReq = new ServiceInstancesRequest (); + servInsReq = new ServiceInstancesRequest(); } String networkType = ""; String vnfType = ""; - aq.setRequestId (requestId); + aq.setRequestId(requestId); aq.setRequestAction(action.toString()); aq.setAction(action.toString()); aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); - Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); - - aq.setStartTime (startTimeStamp); - if(requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance){ - aq.setRequestScope(requestScope); - }else{ - RequestInfo requestInfo =servInsReq.getRequestDetails().getRequestInfo(); - if (requestInfo != null) { - - if(requestInfo.getSource() != null){ - aq.setSource(requestInfo.getSource()); - } - if(requestInfo.getCallbackUrl() != null){ - aq.setCallBackUrl(requestInfo.getCallbackUrl()); - } - if(requestInfo.getCorrelator() != null){ - aq.setCorrelator(requestInfo.getCorrelator()); - } - - if(requestInfo.getRequestorId() != null) { - aq.setRequestorId(requestInfo.getRequestorId()); - } - } - - if (servInsReq.getRequestDetails().getModelInfo() != null || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) { - aq.setRequestScope(requestScope); - } - - if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { - CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); - if(cloudConfiguration.getLcpCloudRegionId() != null) { - aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); - } - - if(cloudConfiguration.getTenantId() != null) { - aq.setTenantId(cloudConfiguration.getTenantId()); - } - - } - - if(servInsReq.getServiceInstanceId() != null){ - aq.setServiceInstanceId(servInsReq.getServiceInstanceId()); - } - - if(servInsReq.getVnfInstanceId() != null){ - aq.setVnfId(servInsReq.getVnfInstanceId()); - } - - if(ModelType.service.name().equalsIgnoreCase(requestScope)){ - if(servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null){ - aq.setServiceInstanceName(requestInfo.getInstanceName()); - } - } - - if(ModelType.network.name().equalsIgnoreCase(requestScope)){ - aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); - aq.setNetworkType(networkType); - aq.setNetworkId(servInsReq.getNetworkInstanceId()); - } - - if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)){ - aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); - aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); - aq.setVnfType(vnfType); - - } - - if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)){ - aq.setVfModuleName(requestInfo.getInstanceName()); - aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName()); - aq.setVfModuleId(servInsReq.getVfModuleInstanceId()); - aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); - aq.setVnfType(vnfType); - - } - - if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - aq.setConfigurationId(servInsReq.getConfigurationId()); - aq.setConfigurationName(requestInfo.getInstanceName()); - } - if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())){ - aq.setInstanceGroupId(servInsReq.getInstanceGroupId()); - aq.setInstanceGroupName(requestInfo.getInstanceName()); - } - if(ModelType.vnf.name().equalsIgnoreCase(requestScope)){ - aq.setVnfName(requestInfo.getInstanceName()); - if (null != servInsReq.getRequestDetails()) { - RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList(); - - if (instanceList != null) { - - for(RelatedInstanceList relatedInstanceList : instanceList){ - - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - if(relatedInstance.getModelInfo().getModelType().equals(ModelType.service)){ - aq.setVnfType(vnfType); - } - } - } - } - } + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + + aq.setStartTime(startTimeStamp); + if (requestScope.equals(ModelType.instanceGroup.name()) && action == Action.deleteInstance) { + aq.setRequestScope(requestScope); + } else { + RequestInfo requestInfo = servInsReq.getRequestDetails().getRequestInfo(); + if (requestInfo != null) { + + if (requestInfo.getSource() != null) { + aq.setSource(requestInfo.getSource()); + } + if (requestInfo.getCallbackUrl() != null) { + aq.setCallBackUrl(requestInfo.getCallbackUrl()); + } + if (requestInfo.getCorrelator() != null) { + aq.setCorrelator(requestInfo.getCorrelator()); + } + + if (requestInfo.getRequestorId() != null) { + aq.setRequestorId(requestInfo.getRequestorId()); + } + } + + if (servInsReq.getRequestDetails().getModelInfo() != null + || (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig)) { + aq.setRequestScope(requestScope); + } + + if (servInsReq.getRequestDetails().getCloudConfiguration() != null) { + CloudConfiguration cloudConfiguration = servInsReq.getRequestDetails().getCloudConfiguration(); + if (cloudConfiguration.getLcpCloudRegionId() != null) { + aq.setAicCloudRegion(cloudConfiguration.getLcpCloudRegionId()); + } + + if (cloudConfiguration.getTenantId() != null) { + aq.setTenantId(cloudConfiguration.getTenantId()); + } + + } + + if (servInsReq.getServiceInstanceId() != null) { + aq.setServiceInstanceId(servInsReq.getServiceInstanceId()); + } + + if (servInsReq.getVnfInstanceId() != null) { + aq.setVnfId(servInsReq.getVnfInstanceId()); + } + + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { + if (servInsReq.getRequestDetails().getRequestInfo().getInstanceName() != null) { + aq.setServiceInstanceName(requestInfo.getInstanceName()); + } + } + + if (ModelType.network.name().equalsIgnoreCase(requestScope)) { + aq.setNetworkName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); + aq.setNetworkType(networkType); + aq.setNetworkId(servInsReq.getNetworkInstanceId()); + } + + if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) { + aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); + aq.setVolumeGroupName(servInsReq.getRequestDetails().getRequestInfo().getInstanceName()); + aq.setVnfType(vnfType); + + } + + if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) { + aq.setVfModuleName(requestInfo.getInstanceName()); + aq.setVfModuleModelName(servInsReq.getRequestDetails().getModelInfo().getModelName()); + aq.setVfModuleId(servInsReq.getVfModuleInstanceId()); + aq.setVolumeGroupId(servInsReq.getVolumeGroupInstanceId()); + aq.setVnfType(vnfType); + + } + + if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + aq.setConfigurationId(servInsReq.getConfigurationId()); + aq.setConfigurationName(requestInfo.getInstanceName()); + } + if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.name())) { + aq.setInstanceGroupId(servInsReq.getInstanceGroupId()); + aq.setInstanceGroupName(requestInfo.getInstanceName()); + } + if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) { + if (requestInfo != null) { + aq.setVnfName(requestInfo.getInstanceName()); + } + if (null != servInsReq.getRequestDetails()) { + RelatedInstanceList[] instanceList = servInsReq.getRequestDetails().getRelatedInstanceList(); + + if (instanceList != null) { + + for (RelatedInstanceList relatedInstanceList : instanceList) { + + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + if (relatedInstance.getModelInfo().getModelType().equals(ModelType.service)) { + aq.setVnfType(vnfType); + } + } + } + } + } } - aq.setRequestBody (originalRequestJSON); + aq.setRequestBody(originalRequestJSON); - aq.setRequestStatus (status.toString ()); - aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER); + aq.setRequestStatus(status.toString()); + aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); + logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), + "Exception when creation record request", e); - if (!status.equals (Status.FAILED)) { + if (!status.equals(Status.FAILED)) { throw e; } } return aq; } - - public InfraActiveRequests createRequestObject (TasksRequest taskRequest, Action action, String requestId, - Status status, String originalRequestJSON) { - InfraActiveRequests aq = new InfraActiveRequests (); - try { - - org.onap.so.apihandlerinfra.tasksbeans.RequestInfo requestInfo = taskRequest.getRequestDetails().getRequestInfo(); - aq.setRequestId (requestId); - aq.setRequestAction(action.name()); - aq.setAction(action.name()); - aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); - - Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); - - aq.setStartTime (startTimeStamp); - if (requestInfo != null) { - - if(requestInfo.getSource() != null){ - aq.setSource(requestInfo.getSource()); - } - - if(requestInfo.getRequestorId() != null) { - aq.setRequestorId(requestInfo.getRequestorId()); - } - } - - aq.setRequestBody (originalRequestJSON); - aq.setRequestStatus (status.toString ()); - aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER); - - } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), - "Exception when creation record request", e); - - if (!status.equals (Status.FAILED)) { - throw e; - } - } - return aq; - } - - public void createErrorRequestRecord (Status status, String requestId, String errorMessage, Actions action, String requestScope, String requestJSON) { + + public InfraActiveRequests createRequestObject(TasksRequest taskRequest, Action action, String requestId, + Status status, String originalRequestJSON) { + InfraActiveRequests aq = new InfraActiveRequests(); + try { + + org.onap.so.apihandlerinfra.tasksbeans.RequestInfo requestInfo = + taskRequest.getRequestDetails().getRequestInfo(); + aq.setRequestId(requestId); + aq.setRequestAction(action.name()); + aq.setAction(action.name()); + aq.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + + aq.setStartTime(startTimeStamp); + if (requestInfo != null) { + + if (requestInfo.getSource() != null) { + aq.setSource(requestInfo.getSource()); + } + + if (requestInfo.getRequestorId() != null) { + aq.setRequestorId(requestInfo.getRequestorId()); + } + } + + aq.setRequestBody(originalRequestJSON); + aq.setRequestStatus(status.toString()); + aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + + } catch (Exception e) { + logger.error("{} {} {}", MessageEnum.APIH_DB_INSERT_EXC.toString(), ErrorCode.DataError.getValue(), + "Exception when creation record request", e); + + if (!status.equals(Status.FAILED)) { + throw e; + } + } + return aq; + } + + public void createErrorRequestRecord(Status status, String requestId, String errorMessage, Actions action, + String requestScope, String requestJSON) { try { InfraActiveRequests request = new InfraActiveRequests(requestId); - Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); - request.setStartTime (startTimeStamp); + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + request.setStartTime(startTimeStamp); request.setRequestStatus(status.toString()); request.setStatusMessage(errorMessage); request.setProgress((long) 100); @@ -448,338 +462,345 @@ public class MsoRequest { request.setRequestBody(requestJSON); Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); request.setEndTime(endTimeStamp); - request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); - requestsDbClient.save(request); + request.setRequestUrl(MDC.get(LogConstants.HTTP_URL)); + requestsDbClient.save(request); } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); - logger.debug("Exception: ", e); - } + logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), + ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.debug("Exception: ", e); + } } - - - public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) { - return buildResponseWithError (httpResponseCode, errorCode, inProgress, null); + + public Response buildResponse(int httpResponseCode, String errorCode, InfraActiveRequests inProgress) { + return buildResponseWithError(httpResponseCode, errorCode, inProgress, null); } - public Response buildResponseWithError (int httpResponseCode, - String errorCode, - InfraActiveRequests inProgress, - String errorString) { + public Response buildResponseWithError(int httpResponseCode, String errorCode, InfraActiveRequests inProgress, + String errorString) { // Log the failed request into the MSO Requests database - return Response.status (httpResponseCode).entity (null).build (); + return Response.status(httpResponseCode).entity(null).build(); } - public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) { + public Response buildResponseFailedValidation(int httpResponseCode, String exceptionMessage) { - return Response.status (httpResponseCode).entity (null).build (); + return Response.status(httpResponseCode).entity(null).build(); } - - - - public String getServiceType (VnfInputs vnfInputs) { - if (vnfInputs.getServiceType () != null) - return vnfInputs.getServiceType (); - if (vnfInputs.getServiceId () != null) - return vnfInputs.getServiceId (); - return null; + + + + public String getServiceType(VnfInputs vnfInputs) { + if (vnfInputs.getServiceType() != null) + return vnfInputs.getServiceType(); + if (vnfInputs.getServiceId() != null) + return vnfInputs.getServiceId(); + return null; } - public long translateStatus (RequestStatusType status) { + public long translateStatus(RequestStatusType status) { switch (status) { - case FAILED: - case COMPLETE: - return Constants.PROGRESS_REQUEST_COMPLETED; - case IN_PROGRESS: - return Constants.PROGRESS_REQUEST_IN_PROGRESS; - default: - return 0; + case FAILED: + case COMPLETE: + return Constants.PROGRESS_REQUEST_COMPLETED; + case IN_PROGRESS: + return Constants.PROGRESS_REQUEST_IN_PROGRESS; + default: + return 0; } } - public static String domToStr (Document doc) { + public static String domToStr(Document doc) { if (doc == null) { return null; } try { - StringWriter sw = new StringWriter (); - StreamResult sr = new StreamResult (sw); - TransformerFactory tf = TransformerFactory.newInstance (); - tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET,""); - Transformer t = tf.newTransformer (); - t.setOutputProperty (OutputKeys.STANDALONE, "yes"); - NodeList nl = doc.getDocumentElement ().getChildNodes (); + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + TransformerFactory tf = TransformerFactory.newInstance(); + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, ""); + Transformer t = tf.newTransformer(); + t.setOutputProperty(OutputKeys.STANDALONE, "yes"); + NodeList nl = doc.getDocumentElement().getChildNodes(); DOMSource source = null; - for (int x = 0; x < nl.getLength (); x++) { - Node e = nl.item (x); + for (int x = 0; x < nl.getLength(); x++) { + Node e = nl.item(x); if (e instanceof Element) { - source = new DOMSource (e); + source = new DOMSource(e); break; } } if (source != null) { - t.transform (source, sr); + t.transform(source, sr); - String s = sw.toString (); + String s = sw.toString(); return s; } return null; } catch (Exception e) { - logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), - "Exception in domToStr", e); - } + logger.error("{} {} {}", MessageEnum.APIH_DOM2STR_ERROR.toString(), ErrorCode.DataError.getValue(), + "Exception in domToStr", e); + } return null; } - public void addBPMNSpecificInputs(VnfRequest vnfReq, VnfInputs vnfInputs, String personaModelId, String personaModelVersion, Boolean isBaseVfModule, - String vnfPersonaModelId, String vnfPersonaModelVersion) { - vnfInputs.setPersonaModelId(personaModelId); - vnfInputs.setPersonaModelVersion(personaModelVersion); - vnfInputs.setIsBaseVfModule(isBaseVfModule); - vnfInputs.setVnfPersonaModelId(vnfPersonaModelId); - vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion); + public void addBPMNSpecificInputs(VnfRequest vnfReq, VnfInputs vnfInputs, String personaModelId, + String personaModelVersion, Boolean isBaseVfModule, String vnfPersonaModelId, + String vnfPersonaModelVersion) { + vnfInputs.setPersonaModelId(personaModelId); + vnfInputs.setPersonaModelVersion(personaModelVersion); + vnfInputs.setIsBaseVfModule(isBaseVfModule); + vnfInputs.setVnfPersonaModelId(vnfPersonaModelId); + vnfInputs.setVnfPersonaModelVersion(vnfPersonaModelVersion); + + vnfReq.setVnfInputs(vnfInputs); - vnfReq.setVnfInputs(vnfInputs); - } private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - public String getRequestJSON(ServiceInstancesRequest sir) throws JsonGenerationException, JsonMappingException, IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - //mapper.configure(Feature.WRAP_ROOT_VALUE, true); - logger.debug ("building sir from object {}", sir); - String requestJSON = mapper.writeValueAsString(sir); - - // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields - - logger.debug("REQUEST JSON before mapping: {}", requestJSON); - // modelUuid = modelVersionId - requestJSON = requestJSON.replaceAll("\"modelVersionId\":","\"modelUuid\":"); - // modelCustomizationUuid = modelCustomizationId - requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":","\"modelCustomizationUuid\":"); - // modelInstanceName = modelCustomizationName - requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":","\"modelInstanceName\":"); - // modelInvariantUuid = modelInvariantId - requestJSON = requestJSON.replaceAll("\"modelInvariantId\":","\"modelInvariantUuid\":"); - logger.debug("REQUEST JSON after mapping: {}", requestJSON); - - return requestJSON; + public String getRequestJSON(ServiceInstancesRequest sir) + throws JsonGenerationException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + // mapper.configure(Feature.WRAP_ROOT_VALUE, true); + logger.debug("building sir from object {}", sir); + String requestJSON = mapper.writeValueAsString(sir); + + // Perform mapping from VID-style modelInfo fields to ASDC-style modelInfo fields + + logger.debug("REQUEST JSON before mapping: {}", requestJSON); + // modelUuid = modelVersionId + requestJSON = requestJSON.replaceAll("\"modelVersionId\":", "\"modelUuid\":"); + // modelCustomizationUuid = modelCustomizationId + requestJSON = requestJSON.replaceAll("\"modelCustomizationId\":", "\"modelCustomizationUuid\":"); + // modelInstanceName = modelCustomizationName + requestJSON = requestJSON.replaceAll("\"modelCustomizationName\":", "\"modelInstanceName\":"); + // modelInvariantUuid = modelInvariantId + requestJSON = requestJSON.replaceAll("\"modelInvariantId\":", "\"modelInvariantUuid\":"); + logger.debug("REQUEST JSON after mapping: {}", requestJSON); + + return requestJSON; } - public boolean getAlacarteFlag(ServiceInstancesRequest sir) { - if(sir.getRequestDetails().getRequestParameters() != null && - sir.getRequestDetails().getRequestParameters().getALaCarte() != null) - return sir.getRequestDetails().getRequestParameters().getALaCarte(); - - return false; - } + public boolean getAlacarteFlag(ServiceInstancesRequest sir) { + if (sir.getRequestDetails().getRequestParameters() != null + && sir.getRequestDetails().getRequestParameters().getALaCarte() != null) + return sir.getRequestDetails().getRequestParameters().getALaCarte(); + + return false; + } - public String getNetworkType(ServiceInstancesRequest sir, String requestScope) { - if(requestScope.equalsIgnoreCase(ModelType.network.name())) - return sir.getRequestDetails().getModelInfo().getModelName(); - else return null; - } + public String getNetworkType(ServiceInstancesRequest sir, String requestScope) { + if (requestScope.equalsIgnoreCase(ModelType.network.name())) + return sir.getRequestDetails().getModelInfo().getModelName(); + else + return null; + } - public String getServiceInstanceType(ServiceInstancesRequest sir, String requestScope) { - if(requestScope.equalsIgnoreCase(ModelType.network.name())) - return sir.getRequestDetails().getModelInfo().getModelName(); - else return null; - } + public String getServiceInstanceType(ServiceInstancesRequest sir, String requestScope) { + if (requestScope.equalsIgnoreCase(ModelType.network.name())) + return sir.getRequestDetails().getModelInfo().getModelName(); + else + return null; + } - public String getSDCServiceModelVersion(ServiceInstancesRequest sir) { - String sdcServiceModelVersion = null; - if(sir.getRequestDetails().getRelatedInstanceList() != null) - for(RelatedInstanceList relatedInstanceList : sir.getRequestDetails().getRelatedInstanceList()){ - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo (); - if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)) - sdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion (); - } + public String getSDCServiceModelVersion(ServiceInstancesRequest sir) { + String sdcServiceModelVersion = null; + if (sir.getRequestDetails().getRelatedInstanceList() != null) + for (RelatedInstanceList relatedInstanceList : sir.getRequestDetails().getRelatedInstanceList()) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); + if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) + sdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion(); + } return sdcServiceModelVersion; - } - - - public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { - - 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; + } + + + public String getVfModuleType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { + + 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(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(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 vfModuleType; - - } - - public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { - - 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; + 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 (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 vfModuleType; + + } + + public String getVnfType(ServiceInstancesRequest sir, String requestScope, Actions action, int reqVersion) { + + 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(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(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 vnfType; - - } - - public Optional<URL> buildSelfLinkUrl(String url, String requestId) { - Optional<URL> selfLinkUrl = Optional.empty(); - String version = ""; - try { - URL aUrl = new URL(url); - String aPath = aUrl.getPath(); - if (aPath.indexOf("/v") == -1) { - version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V")+4); - } else { - version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v")+4); - } - String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId); - selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); - } catch (Exception e) { - selfLinkUrl = Optional.empty(); // ignore - } - return selfLinkUrl; - } + 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 (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 vnfType; + + } + + public Optional<URL> buildSelfLinkUrl(String url, String requestId) { + Optional<URL> selfLinkUrl = Optional.empty(); + String version = ""; + try { + URL aUrl = new URL(url); + String aPath = aUrl.getPath(); + if (aPath.indexOf("/v") == -1) { + version = aPath.substring(aPath.indexOf("/V"), aPath.indexOf("/V") + 4); + } else { + version = aPath.substring(aPath.indexOf("/v"), aPath.indexOf("/v") + 4); + } + String selfLinkPath = Constants.ORCHESTRATION_REQUESTS_PATH.concat(version).concat(requestId); + selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath)); + } catch (Exception e) { + selfLinkUrl = Optional.empty(); // ignore + } + return selfLinkUrl; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java index cfdce473a4..fd0df1d2b0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/MsoSubsystems.java @@ -20,23 +20,19 @@ package org.onap.so.apihandlerinfra; public enum MsoSubsystems { - APIH ("API Handler"), - ASDC ("ASDC Controller"), - BPMN ("BPMN Infra"), - CATALOGDB ("CatalogDb Adapter"), - OPENSTACK ("Openstack Adapter"), - REQUESTDB ("RequestDB Adapter"), - REQUESTDBATT ("RequestDB Adapter ATT Svc"), - SDNC ("SDNC Adapter"); - private String subsystem; - private MsoSubsystems(String subsystem){ - this.subsystem = subsystem; - } - - @Override - public String toString(){ - return subsystem; - } - + APIH("API Handler"), ASDC("ASDC Controller"), BPMN("BPMN Infra"), CATALOGDB("CatalogDb Adapter"), OPENSTACK( + "Openstack Adapter"), REQUESTDB( + "RequestDB Adapter"), REQUESTDBATT("RequestDB Adapter ATT Svc"), SDNC("SDNC Adapter"); + private String subsystem; + + private MsoSubsystems(String subsystem) { + this.subsystem = subsystem; + } + + @Override + public String toString() { + return subsystem; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java index 351a35826d..9810895ad9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/NodeHealthcheckHandler.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra; import java.net.UnknownHostException; - import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -31,34 +30,31 @@ import javax.ws.rs.Produces; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.onap.so.logger.MessageEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Path("/nodehealthcheck") -@Api(value="/nodehealthcheck",description="API Handler Infra Node Health Check") +@Api(value = "/nodehealthcheck", description = "API Handler Infra Node Health Check") @Component public class NodeHealthcheckHandler { private static Logger logger = LoggerFactory.getLogger(NodeHealthcheckHandler.class); - - private static final String CHECK_HTML = "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>"; - public static final Response HEALTH_CHECK_RESPONSE = Response.status (HttpStatus.SC_OK) - .entity (CHECK_HTML) - .build (); - + private static final String CHECK_HTML = + "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Health Check</title></head><body>Application ready</body></html>"; + + public static final Response HEALTH_CHECK_RESPONSE = Response.status(HttpStatus.SC_OK).entity(CHECK_HTML).build(); + @GET @Produces("text/html") - @ApiOperation(value="Performing node health check",response=Response.class) + @ApiOperation(value = "Performing node health check", response = Response.class) @Transactional - public Response nodeHealthcheck (@Context ContainerRequestContext requestContext) throws UnknownHostException { + public Response nodeHealthcheck(@Context ContainerRequestContext requestContext) throws UnknownHostException { // Generated RequestId String requestId = requestContext.getProperty("requestId").toString(); logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); 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 f613d3e193..34dcd4b0c4 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 @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -41,14 +40,12 @@ import javax.ws.rs.core.MediaType; 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.http.HttpStatus; 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.apihandlerinfra.exceptions.ValidateException; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.RequestProcessingData; @@ -56,7 +53,6 @@ import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse; import org.onap.so.serviceinstancebeans.GetOrchestrationResponse; import org.onap.so.serviceinstancebeans.InstanceReferences; @@ -69,365 +65,397 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Path("onap/so/infra/orchestrationRequests") -@Api(value="onap/so/infra/orchestrationRequests",description="API Requests for Orchestration requests") +@Api(value = "onap/so/infra/orchestrationRequests", description = "API Requests for Orchestration requests") @Component public class OrchestrationRequests { private static Logger logger = LoggerFactory.getLogger(OrchestrationRequests.class); - + @Autowired - private RequestsDbClient requestsDbClient; + private RequestsDbClient requestsDbClient; @Autowired private MsoRequest msoRequest; - - @Autowired - private ResponseBuilder builder; - @GET - @Path("/{version:[vV][4-7]}/{requestId}") - @ApiOperation(value="Find Orchestrated Requests for a given requestId",response=Response.class) - @Produces(MediaType.APPLICATION_JSON) - @Transactional - public Response getOrchestrationRequest(@PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{ + @Autowired + private ResponseBuilder builder; + + @GET + @Path("/{version:[vV][4-7]}/{requestId}") + @ApiOperation(value = "Find Orchestrated Requests for a given requestId", response = Response.class) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getOrchestrationRequest(@PathParam("requestId") String requestId, + @PathParam("version") String version) throws ApiException { - String apiVersion = version.substring(1); - GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); + String apiVersion = version.substring(1); + GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse(); - InfraActiveRequests infraActiveRequest = null; - List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; - try { - infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); - requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId); + InfraActiveRequests infraActiveRequest = null; + List<org.onap.so.db.request.beans.RequestProcessingData> requestProcessingData = null; + try { + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(requestId); - } catch (Exception e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); + } catch (Exception e) { + logger.error("Exception occurred", e); + 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(); - 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; - throw validateException; + } - } - - if(infraActiveRequest == null) { + if (infraActiveRequest == null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).build(); + 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).errorInfo(errorLoggerInfo).build(); + ValidateException validateException = + new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", + HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); throw validateException; } - + Request request = mapInfraActiveRequestToRequest(infraActiveRequest); - if(!requestProcessingData.isEmpty()){ + if (!requestProcessingData.isEmpty()) { request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); } - request.setRequestId(requestId); + request.setRequestId(requestId); orchestrationResponse.setRequest(request); - + return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion); - } - - @GET - @Path("/{version:[vV][4-7]}") - @ApiOperation(value="Find Orchestrated Requests for a URI Information",response=Response.class) - @Produces(MediaType.APPLICATION_JSON) - @Transactional - public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) throws ApiException{ - - long startTime = System.currentTimeMillis (); - - MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); - - List<InfraActiveRequests> activeRequests = null; - - GetOrchestrationListResponse orchestrationList = null; - Map<String, List<String>> orchestrationMap; - String apiVersion = version.substring(1); - - try { - orchestrationMap = msoRequest.getOrchestrationFilters(queryParams); - if (orchestrationMap.isEmpty()) { - throw new ValidationException("At least one filter query param must be specified"); - } - }catch(ValidationException ex){ - logger.error("Exception occurred", ex); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build(); - ValidateException validateException = new ValidateException.Builder(ex.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); - throw validateException; - - } - - activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap); - - orchestrationList = new GetOrchestrationListResponse(); - List<RequestList> requestLists = new ArrayList<>(); - - for(InfraActiveRequests infraActive : activeRequests){ - List<RequestProcessingData> requestProcessingData = requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); - RequestList requestList = new RequestList(); - Request request = mapInfraActiveRequestToRequest(infraActive); - if(!requestProcessingData.isEmpty()){ - request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); - } - requestList.setRequest(request); - requestLists.add(requestList); - } - - orchestrationList.setRequestList(requestLists); - return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); - } - - - @POST - @Path("/{version: [vV][4-7]}/{requestId}/unlock") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Unlock Orchestrated Requests for a given requestId",response=Response.class) - @Transactional - public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{ - - long startTime = System.currentTimeMillis (); - logger.debug ("requestId is: {}", requestId); - ServiceInstancesRequest sir = null; - - InfraActiveRequests infraActiveRequest = null; - Request request = null; - - try{ - ObjectMapper mapper = new ObjectMapper(); - sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); - } catch(IOException e){ - logger.error("Exception occurred", 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(); + } + + @GET + @Path("/{version:[vV][4-7]}") + @ApiOperation(value = "Find Orchestrated Requests for a URI Information", response = Response.class) + @Produces(MediaType.APPLICATION_JSON) + @Transactional + public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) + throws ApiException { + + long startTime = System.currentTimeMillis(); + + MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); + + List<InfraActiveRequests> activeRequests = null; + + GetOrchestrationListResponse orchestrationList = null; + Map<String, List<String>> orchestrationMap; + String apiVersion = version.substring(1); + + try { + orchestrationMap = msoRequest.getOrchestrationFilters(queryParams); + if (orchestrationMap.isEmpty()) { + throw new ValidationException("At least one filter query param must be specified"); + } + } catch (ValidationException ex) { + logger.error("Exception occurred", ex); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build(); + ValidateException validateException = + new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); + throw validateException; + + } + + activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap); + + orchestrationList = new GetOrchestrationListResponse(); + List<RequestList> requestLists = new ArrayList<>(); + + for (InfraActiveRequests infraActive : activeRequests) { + List<RequestProcessingData> requestProcessingData = + requestsDbClient.getRequestProcessingDataBySoRequestId(infraActive.getRequestId()); + RequestList requestList = new RequestList(); + Request request = mapInfraActiveRequestToRequest(infraActive); + if (!requestProcessingData.isEmpty()) { + request.setRequestProcessingData(mapRequestProcessingData(requestProcessingData)); + } + requestList.setRequest(request); + requestLists.add(requestList); + } + + orchestrationList.setRequestList(requestLists); + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); + } + + + @POST + @Path("/{version: [vV][4-7]}/{requestId}/unlock") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Unlock Orchestrated Requests for a given requestId", response = Response.class) + @Transactional + public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, + @PathParam("version") String version) throws ApiException { + + long startTime = System.currentTimeMillis(); + logger.debug("requestId is: {}", requestId); + ServiceInstancesRequest sir = null; + + InfraActiveRequests infraActiveRequest = null; + Request request = null; + + try { + ObjectMapper mapper = new ObjectMapper(); + sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); + } catch (IOException e) { + logger.error("Exception occurred", 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; - } - try{ - msoRequest.parseOrchestration(sir); - } catch (Exception e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).build(); - ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); + } + try { + msoRequest.parseOrchestration(sir); + } catch (Exception e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .build(); + ValidateException validateException = + new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + throw validateException; + } + + infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); + if (infraActiveRequest == null) { + 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) + .build(); + throw validateException; - } - - infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId); - if(infraActiveRequest == null) { - 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).build(); - - throw validateException; - - }else{ - String status = infraActiveRequest.getRequestStatus(); - if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){ - infraActiveRequest.setRequestStatus("UNLOCKED"); - infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); - infraActiveRequest.setRequestId(requestId); - requestsDbClient.save(infraActiveRequest); - }else{ - - ErrorLoggerInfo errorLoggerInfo = 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", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - } - return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build (); - } - - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException{ - - String requestBody = iar.getRequestBody(); - Request request = new Request(); - - ObjectMapper mapper = new ObjectMapper(); - - request.setRequestId(iar.getRequestId()); - request.setRequestScope(iar.getRequestScope()); - request.setRequestType(iar.getRequestAction()); - String rollbackStatusMessage = iar.getRollbackStatusMessage(); - String flowStatusMessage = iar.getFlowStatus(); - String retryStatusMessage = iar.getRetryStatusMessage(); - - - InstanceReferences ir = new InstanceReferences(); - if(iar.getNetworkId() != null) - ir.setNetworkInstanceId(iar.getNetworkId()); - if(iar.getNetworkName() != null) - ir.setNetworkInstanceName(iar.getNetworkName()); - if(iar.getServiceInstanceId() != null) - ir.setServiceInstanceId(iar.getServiceInstanceId()); - if(iar.getServiceInstanceName() != null) - ir.setServiceInstanceName(iar.getServiceInstanceName()); - if(iar.getVfModuleId() != null) - ir.setVfModuleInstanceId(iar.getVfModuleId()); - if(iar.getVfModuleName() != null) - ir.setVfModuleInstanceName(iar.getVfModuleName()); - if(iar.getVnfId() != null) - ir.setVnfInstanceId(iar.getVnfId()); - if(iar.getVnfName() != null) - ir.setVnfInstanceName(iar.getVnfName()); - if(iar.getVolumeGroupId() != null) - ir.setVolumeGroupInstanceId(iar.getVolumeGroupId()); - if(iar.getVolumeGroupName() != null) - ir.setVolumeGroupInstanceName(iar.getVolumeGroupName()); - if(iar.getRequestorId() != null) - ir.setRequestorId(iar.getRequestorId()); - if(iar.getInstanceGroupId() != null) - ir.setInstanceGroupId(iar.getInstanceGroupId()); - if(iar.getInstanceGroupName() != null) - ir.setInstanceGroupName(iar.getInstanceGroupName()); - - - - request.setInstanceReferences(ir); - - RequestDetails requestDetails = null; - - if(StringUtils.isNotBlank(requestBody)) { - try { - if(requestBody.contains("\"requestDetails\":")){ - ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); - requestDetails = sir.getRequestDetails(); - } else { - requestDetails = mapper.readValue(requestBody, RequestDetails.class); - } - } catch (IOException e) { - logger.error("Exception occurred", 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 : ", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - } - request.setRequestDetails(requestDetails); - - if(iar.getStartTime() != null) { - String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT"; - request.setStartTime(startTimeStamp); - } - if(iar.getEndTime() != null){ - String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; - request.setFinishTime(endTimeStamp); - } - String statusMessages = null; - RequestStatus status = new RequestStatus(); - if(iar.getStatusMessage() != null){ - statusMessages = "STATUS: " + iar.getStatusMessage(); - } - if(flowStatusMessage != null){ - if(statusMessages != null){ - statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage; - }else{ - statusMessages = "FLOW STATUS: " + flowStatusMessage; - } - } - if(retryStatusMessage != null){ - if(statusMessages != null){ - statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage; - }else{ - statusMessages = "RETRY STATUS: " + retryStatusMessage; - } - } - if(rollbackStatusMessage != null){ - if(statusMessages != null){ - statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage; - }else{ - statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage; - } - } - if(statusMessages != null){ - status.setStatusMessage(statusMessages); - } - if(iar.getModifyTime() != null){ - String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT"; - status.setTimeStamp(timeStamp); - } - - - if(iar.getRequestStatus() != null){ - status.setRequestState(iar.getRequestStatus()); - } - - if(iar.getProgress() != null){ - status.setPercentProgress(iar.getProgress().intValue()); - } - - request.setRequestStatus(status); - - return request; - } - - public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData(List<org.onap.so.db.request.beans.RequestProcessingData> processingData){ - List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>(); - org.onap.so.serviceinstancebeans.RequestProcessingData finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData(); - String currentGroupingId = null; - HashMap<String, String> tempMap = new HashMap<>(); - List<HashMap<String, String>> tempList = new ArrayList<>(); - for(RequestProcessingData data : processingData){ - String groupingId = data.getGroupingId(); - String tag = data.getTag(); - if(currentGroupingId == null || !currentGroupingId.equals(groupingId)){ - if(!tempMap.isEmpty()){ - tempList.add(tempMap); - finalProcessingData.setDataPairs(tempList); - addedRequestProcessingData.add(finalProcessingData); - } - finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData(); - if(groupingId != null){ - finalProcessingData.setGroupingId(groupingId); - } - if(tag != null){ - finalProcessingData.setTag(tag); - } - currentGroupingId = groupingId; - tempMap = new HashMap<>(); - tempList = new ArrayList<>(); - if(data.getName() != null && data.getValue() != null){ - tempMap.put(data.getName(), data.getValue()); - } - }else{ - if(data.getName() != null && data.getValue() != null){ - tempMap.put(data.getName(), data.getValue()); - } - } - } - if(tempMap.size() > 0){ - tempList.add(tempMap); - finalProcessingData.setDataPairs(tempList); - } - addedRequestProcessingData.add(finalProcessingData); - return addedRequestProcessingData; - } - } + + } else { + String status = infraActiveRequest.getRequestStatus(); + if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") + || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) { + infraActiveRequest.setRequestStatus("UNLOCKED"); + infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + infraActiveRequest.setRequestId(requestId); + requestsDbClient.save(infraActiveRequest); + } else { + + ErrorLoggerInfo errorLoggerInfo = + 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", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); + + throw validateException; + } + } + return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); + } + + private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { + + String requestBody = iar.getRequestBody(); + Request request = new Request(); + + ObjectMapper mapper = new ObjectMapper(); + + request.setRequestId(iar.getRequestId()); + request.setRequestScope(iar.getRequestScope()); + request.setRequestType(iar.getRequestAction()); + String rollbackStatusMessage = iar.getRollbackStatusMessage(); + String flowStatusMessage = iar.getFlowStatus(); + String retryStatusMessage = iar.getRetryStatusMessage(); + + + InstanceReferences ir = new InstanceReferences(); + if (iar.getNetworkId() != null) + ir.setNetworkInstanceId(iar.getNetworkId()); + if (iar.getNetworkName() != null) + ir.setNetworkInstanceName(iar.getNetworkName()); + if (iar.getServiceInstanceId() != null) + ir.setServiceInstanceId(iar.getServiceInstanceId()); + if (iar.getServiceInstanceName() != null) + ir.setServiceInstanceName(iar.getServiceInstanceName()); + if (iar.getVfModuleId() != null) + ir.setVfModuleInstanceId(iar.getVfModuleId()); + if (iar.getVfModuleName() != null) + ir.setVfModuleInstanceName(iar.getVfModuleName()); + if (iar.getVnfId() != null) + ir.setVnfInstanceId(iar.getVnfId()); + if (iar.getVnfName() != null) + ir.setVnfInstanceName(iar.getVnfName()); + if (iar.getVolumeGroupId() != null) + ir.setVolumeGroupInstanceId(iar.getVolumeGroupId()); + if (iar.getVolumeGroupName() != null) + ir.setVolumeGroupInstanceName(iar.getVolumeGroupName()); + if (iar.getRequestorId() != null) + ir.setRequestorId(iar.getRequestorId()); + if (iar.getInstanceGroupId() != null) + ir.setInstanceGroupId(iar.getInstanceGroupId()); + if (iar.getInstanceGroupName() != null) + ir.setInstanceGroupName(iar.getInstanceGroupName()); + + + + request.setInstanceReferences(ir); + + RequestDetails requestDetails = null; + + if (StringUtils.isNotBlank(requestBody)) { + try { + if (requestBody.contains("\"requestDetails\":")) { + ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class); + requestDetails = sir.getRequestDetails(); + } else { + requestDetails = mapper.readValue(requestBody, RequestDetails.class); + } + } catch (IOException e) { + logger.error("Exception occurred", 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 : ", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + request.setRequestDetails(requestDetails); + + if (iar.getStartTime() != null) { + String startTimeStamp = + new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT"; + request.setStartTime(startTimeStamp); + } + if (iar.getEndTime() != null) { + String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; + request.setFinishTime(endTimeStamp); + } + String statusMessages = null; + RequestStatus status = new RequestStatus(); + if (iar.getStatusMessage() != null) { + statusMessages = "STATUS: " + iar.getStatusMessage(); + } + if (flowStatusMessage != null) { + if (statusMessages != null) { + statusMessages = statusMessages + " " + "FLOW STATUS: " + flowStatusMessage; + } else { + statusMessages = "FLOW STATUS: " + flowStatusMessage; + } + } + if (retryStatusMessage != null) { + if (statusMessages != null) { + statusMessages = statusMessages + " " + "RETRY STATUS: " + retryStatusMessage; + } else { + statusMessages = "RETRY STATUS: " + retryStatusMessage; + } + } + if (rollbackStatusMessage != null) { + if (statusMessages != null) { + statusMessages = statusMessages + " " + "ROLLBACK STATUS: " + rollbackStatusMessage; + } else { + statusMessages = "ROLLBACK STATUS: " + rollbackStatusMessage; + } + } + if (statusMessages != null) { + status.setStatusMessage(statusMessages); + } + if (iar.getModifyTime() != null) { + String timeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getModifyTime()) + " GMT"; + status.setTimeStamp(timeStamp); + } + + + if (iar.getRequestStatus() != null) { + status.setRequestState(iar.getRequestStatus()); + } + + if (iar.getProgress() != null) { + status.setPercentProgress(iar.getProgress().intValue()); + } + + request.setRequestStatus(status); + + return request; + } + + public List<org.onap.so.serviceinstancebeans.RequestProcessingData> mapRequestProcessingData( + List<org.onap.so.db.request.beans.RequestProcessingData> processingData) { + List<org.onap.so.serviceinstancebeans.RequestProcessingData> addedRequestProcessingData = new ArrayList<>(); + org.onap.so.serviceinstancebeans.RequestProcessingData finalProcessingData = + new org.onap.so.serviceinstancebeans.RequestProcessingData(); + String currentGroupingId = null; + HashMap<String, String> tempMap = new HashMap<>(); + List<HashMap<String, String>> tempList = new ArrayList<>(); + for (RequestProcessingData data : processingData) { + String groupingId = data.getGroupingId(); + String tag = data.getTag(); + if (currentGroupingId == null || !currentGroupingId.equals(groupingId)) { + if (!tempMap.isEmpty()) { + tempList.add(tempMap); + finalProcessingData.setDataPairs(tempList); + addedRequestProcessingData.add(finalProcessingData); + } + finalProcessingData = new org.onap.so.serviceinstancebeans.RequestProcessingData(); + if (groupingId != null) { + finalProcessingData.setGroupingId(groupingId); + } + if (tag != null) { + finalProcessingData.setTag(tag); + } + currentGroupingId = groupingId; + tempMap = new HashMap<>(); + tempList = new ArrayList<>(); + if (data.getName() != null && data.getValue() != null) { + tempMap.put(data.getName(), data.getValue()); + } + } else { + if (data.getName() != null && data.getValue() != null) { + tempMap.put(data.getName(), data.getValue()); + } + } + } + if (tempMap.size() > 0) { + tempList.add(tempMap); + finalProcessingData.setDataPairs(tempList); + } + addedRequestProcessingData.add(finalProcessingData); + return addedRequestProcessingData; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java index 83d270552d..8f7403a7f9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RecipeLookupResult.java @@ -27,35 +27,35 @@ public class RecipeLookupResult { private int recipeTimeout; // the service recipe param. private String recipeParamXsd; - + public RecipeLookupResult(String orchestrationURI, int recipeTimeout) { - this.orchestrationURI = orchestrationURI; - this.recipeTimeout = recipeTimeout; + this.orchestrationURI = orchestrationURI; + this.recipeTimeout = recipeTimeout; } - + public RecipeLookupResult(String orchestrationURI, int recipeTimeout, String recipeParamXsd) { this.orchestrationURI = orchestrationURI; this.recipeTimeout = recipeTimeout; this.recipeParamXsd = recipeParamXsd; } - - public String getOrchestrationURI () { - return orchestrationURI; + + public String getOrchestrationURI() { + return orchestrationURI; } - - public void setOrchestrationURI (String orchestrationURI) { - this.orchestrationURI = orchestrationURI; + + public void setOrchestrationURI(String orchestrationURI) { + this.orchestrationURI = orchestrationURI; } - - public int getRecipeTimeout () { - return recipeTimeout; + + public int getRecipeTimeout() { + return recipeTimeout; } - - public void setRecipeTimeout (int recipeTimeout) { - this.recipeTimeout = recipeTimeout; + + public void setRecipeTimeout(int recipeTimeout) { + this.recipeTimeout = recipeTimeout; } - + /** * @return Returns the recipeParamXsd. */ @@ -63,14 +63,14 @@ public class RecipeLookupResult { return recipeParamXsd; } - + /** * @param recipeParamXsd The recipeParamXsd to set. */ public void setRecipeParamXsd(String recipeParamXsd) { this.recipeParamXsd = recipeParamXsd; } - - + + } - + diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java index 86dd048120..c97c80901e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestActionMap.java @@ -25,7 +25,7 @@ import java.util.Map; /* * Map of actions to RequestActions -*/ + */ public class RequestActionMap { private static final Map<String, String> actionMap; 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 new file mode 100644 index 0000000000..bbcc120ab6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/RequestHandlerUtils.java @@ -0,0 +1,625 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.commons.lang.StringUtils; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.camunda.bpm.engine.history.HistoricProcessInstance; +import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandler.camundabeans.CamundaResponse; +import org.onap.so.apihandler.common.CommonConstants; +import org.onap.so.apihandler.common.ErrorNumbers; +import org.onap.so.apihandler.common.RequestClient; +import org.onap.so.apihandler.common.RequestClientFactory; +import org.onap.so.apihandler.common.RequestClientParameter; +import org.onap.so.apihandler.common.ResponseBuilder; +import org.onap.so.apihandler.common.ResponseHandler; +import org.onap.so.apihandlerinfra.exceptions.ApiException; +import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; +import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +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.apihandlerinfra.logging.ErrorLoggerInfo; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LogConstants; +import org.onap.so.logger.MessageEnum; +import org.onap.so.serviceinstancebeans.ModelType; +import org.onap.so.serviceinstancebeans.RelatedInstance; +import org.onap.so.serviceinstancebeans.RelatedInstanceList; +import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.UUIDChecker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.env.Environment; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +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; + +@Component +public class RequestHandlerUtils { + + private static Logger logger = LoggerFactory.getLogger(RequestHandlerUtils.class); + + private static final String SAVE_TO_DB = "save instance to db"; + + @Autowired + private Environment env; + + @Autowired + private RequestClientFactory reqClientFactory; + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + @Autowired + private ResponseBuilder builder; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private CatalogDbClient catalogDbClient; + + public Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, + String orchestrationUri, String requestScope) throws ApiException { + RequestClient requestClient = null; + HttpResponse response = null; + try { + requestClient = reqClientFactory.getRequestClient(orchestrationUri); + response = requestClient.post(requestClientParameter); + } catch (Exception e) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + String url = requestClient != null ? requestClient.getUrl() : ""; + ClientConnectionException clientException = + new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, + ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); + + throw clientException; + } + + if (response == null) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, + ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); + + throw clientException; + } + + ResponseHandler respHandler = null; + int bpelStatus = 500; + try { + respHandler = new ResponseHandler(response, requestClient.getType()); + bpelStatus = respHandler.getStatus(); + } catch (ApiException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + + // BPEL accepted the request, the request is in progress + if (bpelStatus == HttpStatus.SC_ACCEPTED) { + ServiceInstancesResponse jsonResponse; + CamundaResponse camundaResp = respHandler.getResponse(); + + if ("Success".equalsIgnoreCase(camundaResp.getMessage())) { + try { + ObjectMapper mapper = new ObjectMapper(); + jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); + jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); + Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), + requestClientParameter.getRequestId()); + if (selfLinkUrl.isPresent()) { + jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); + } else { + jsonResponse.getRequestReferences().setRequestSelfLink(null); + } + } catch (IOException e) { + logger.error("Exception occurred", e); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", + HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + throw validateException; + } + return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), + jsonResponse, requestClientParameter.getApiVersion()); + } + } + + List<String> variables = new ArrayList<>(); + variables.add(bpelStatus + ""); + String camundaJSONResponseBody = respHandler.getResponseBody(); + if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + .errorSource(requestClient.getUrl()).build(); + BPMNFailureException bpmnException = + new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); + + throw bpmnException; + } else { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + .errorSource(requestClient.getUrl()).build(); + + + BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), + bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, servException.getMessage()); + + throw servException; + } + } + + public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) + throws RequestDbFailureException { + if ((status == Status.FAILED) || (status == Status.COMPLETE)) { + aq.setStatusMessage(errorMessage); + aq.setProgress(new Long(100)); + aq.setRequestStatus(status.toString()); + Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); + aq.setEndTime(endTimeStamp); + try { + infraActiveRequestsClient.save(aq); + } 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(); + } + } + } + + public String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) { + if (action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig) { + return (ModelType.vnf.name()); + } else if (action == Action.addMembers || action == Action.removeMembers) { + return (ModelType.instanceGroup.toString()); + } else { + String requestScope; + if (sir.getRequestDetails().getModelInfo().getModelType() == null) { + requestScope = requestScopeFromUri(requestUri); + } else { + requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); + } + return requestScope; + } + } + + + public void validateHeaders(ContainerRequestContext context) throws ValidationException { + MultivaluedMap<String, String> headers = context.getHeaders(); + if (!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)) { + throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true); + } + if (!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)) { + throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true); + } + if (!headers.containsKey(REQUESTOR_ID)) { + throw new ValidationException(REQUESTOR_ID + " header", true); + } + } + + public String getRequestUri(ContainerRequestContext context, String uriPrefix) { + String requestUri = context.getUriInfo().getPath(); + String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); + MDC.put(LogConstants.HTTP_URL, httpUrl); + requestUri = requestUri.substring(requestUri.indexOf(uriPrefix) + uriPrefix.length()); + return requestUri; + } + + public InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, + MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) + throws ApiException { + InfraActiveRequests dup = null; + try { + if (!(instanceName == null && requestScope.equals("service") && (action == Action.createInstance + || action == Action.activateInstance || action == Action.assignInstance))) { + dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); + } + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + RequestDbFailureException requestDbFailureException = + new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) + .errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage()); + throw requestDbFailureException; + } + return dup; + } + + public boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) + throws RequestDbFailureException, ContactCamundaException { + String requestId = duplicateRecord.getRequestId(); + String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; + String targetUrl = env.getProperty("mso.camundaURL") + path; + HttpHeaders headers = + setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); + HttpEntity<?> requestEntity = new HttpEntity<>(headers); + ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; + try { + response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, + new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>() {}); + } catch (HttpStatusCodeException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ContactCamundaException contactCamundaException = + new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage()); + throw contactCamundaException; + } + if (response.getBody().isEmpty()) { + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + for (HistoricProcessInstance instance : response.getBody()) { + if (instance.getState().equals("ACTIVE")) { + return true; + } else { + updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); + } + } + return false; + } + + protected HttpHeaders setCamundaHeaders(String auth, String msoKey) { + HttpHeaders headers = new HttpHeaders(); + List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); + acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); + headers.setAccept(acceptableMediaTypes); + try { + String userCredentials = CryptoUtils.decrypt(auth, msoKey); + if (userCredentials != null) { + headers.add(HttpHeaders.AUTHORIZATION, + "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); + } + } catch (GeneralSecurityException e) { + logger.error("Security exception", e); + } + return headers; + } + + public ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, + long startTime, ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) + throws ApiException { + try { + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(requestJSON, ServiceInstancesRequest.class); + + } catch (IOException 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("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + String requestScope = requestScopeFromUri(requestUri); + + msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, + requestScope, requestJSON); + + throw validateException; + } + } + + public void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, + String version, String requestJSON, Boolean aLaCarte, String requestId, + InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException { + int reqVersion = Integer.parseInt(version.substring(1)); + try { + msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); + } catch (Exception e) { + logger.error("failed to parse request", 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("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + + throw validateException; + } + } + + public void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, + HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, String instanceName, + String requestScope, InfraActiveRequests dup) throws ApiException { + + String instance = null; + if (instanceName != null) { + instance = instanceName; + } else { + instance = instanceIdMap.get(requestScope + "InstanceId"); + } + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + DuplicateRequestException dupException = + new DuplicateRequestException.Builder(requestScope, instance, dup.getRequestStatus(), + dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + + updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage()); + + throw dupException; + } + + public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { + String requestId = null; + if (requestContext.getProperty("requestId") != null) { + requestId = requestContext.getProperty("requestId").toString(); + } + if (UUIDChecker.isValidUUID(requestId)) { + return requestId; + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ValidateException validateException = + new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + + public void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId, + Map<String, String> instanceIdMap) { + if (StringUtils.isNotBlank(instanceId)) { + if (ModelType.service.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setServiceInstanceId(instanceId); + } else if (ModelType.vnf.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVnfId(instanceId); + } else if (ModelType.vfModule.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVfModuleId(instanceId); + } else if (ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setVolumeGroupId(instanceId); + } else if (ModelType.network.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setNetworkId(instanceId); + } else if (ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + currentActiveReq.setConfigurationId(instanceId); + } else if (ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)) { + currentActiveReq.setInstanceGroupId(instanceId); + } + } else if (instanceIdMap != null && !instanceIdMap.isEmpty()) { + if (instanceIdMap.get("serviceInstanceId") != null) { + currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + } + if (instanceIdMap.get("vnfInstanceId") != null) { + currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId")); + } + if (instanceIdMap.get("vfModuleInstanceId") != null) { + currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId")); + } + if (instanceIdMap.get("volumeGroupInstanceId") != null) { + currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId")); + } + if (instanceIdMap.get("networkInstanceId") != null) { + currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId")); + } + if (instanceIdMap.get("configurationInstanceId") != null) { + currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + } + if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { + currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); + } + } + } + + public String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, + boolean isAlaCarte, Actions action) throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + if (msoRawRequest != null) { + ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); + if (serviceInstRequest != null && serviceInstRequest.getRequestDetails() != null + && serviceInstRequest.getRequestDetails().getRequestParameters() != null) { + if (!isAlaCarte && Action.createInstance.equals(action)) { + sir.getRequestDetails() + .setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); + sir.getRequestDetails().getRequestParameters().setUserParams( + serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); + } + sir.getRequestDetails().getRequestParameters() + .setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); + } + + logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); + return mapper.writeValueAsString(sir); + } + return null; + } + + public Optional<String> retrieveModelName(RequestParameters requestParams) { + String requestTestApi = null; + TestApi testApi = null; + + if (requestParams != null) { + requestTestApi = requestParams.getTestApi(); + } + + if (requestTestApi == null) { + if (requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) { + requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API); + } else { + requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API); + } + } + + try { + testApi = TestApi.valueOf(requestTestApi); + return Optional.of(testApi.getModelName()); + } catch (Exception e) { + logger.warn("Catching the exception on the valueOf enum call and continuing", e); + throw new IllegalArgumentException("Invalid TestApi is provided", e); + } + } + + public String getDefaultModel(ServiceInstancesRequest sir) { + String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT"; + Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters()); + if (oModelName.isPresent()) { + defaultModel = oModelName.get(); + } + return defaultModel; + } + + public String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag) { + String serviceType = null; + if (requestScope.equalsIgnoreCase(ModelType.service.toString())) { + String defaultServiceModelName = getDefaultModel(sir); + org.onap.so.db.catalog.beans.Service serviceRecord; + if (aLaCarteFlag) { + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if (serviceRecord != null) { + serviceType = serviceRecord.getServiceType(); + } + } else { + serviceRecord = + catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId()); + if (serviceRecord != null) { + serviceType = serviceRecord.getServiceType(); + } else { + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if (serviceRecord != null) { + serviceType = serviceRecord.getServiceType(); + } + } + } + } else { + serviceType = msoRequest.getServiceInstanceType(sir, requestScope); + } + return serviceType; + } + + protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir) { + if (sir.getServiceInstanceId() != null) { + return sir.getServiceInstanceId(); + } else if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { + RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList(); + if (relatedInstances != null) { + for (RelatedInstanceList relatedInstanceList : relatedInstances) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + if (relatedInstance.getModelInfo().getModelType() == ModelType.service) { + return relatedInstance.getInstanceId(); + } + } + } + } + return null; + } + + private String requestScopeFromUri(String requestUri) { + String requestScope; + if (requestUri.contains(ModelType.network.name())) { + requestScope = ModelType.network.name(); + } else if (requestUri.contains(ModelType.vfModule.name())) { + requestScope = ModelType.vfModule.name(); + } else if (requestUri.contains(ModelType.volumeGroup.name())) { + requestScope = ModelType.volumeGroup.name(); + } else if (requestUri.contains(ModelType.configuration.name())) { + requestScope = ModelType.configuration.name(); + } else if (requestUri.contains(ModelType.vnf.name())) { + requestScope = ModelType.vnf.name(); + } else { + requestScope = ModelType.service.name(); + } + return requestScope; + } + +} 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 8c5904fb21..931a1eb52b 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 @@ -23,8 +23,6 @@ package org.onap.so.apihandlerinfra; - -import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; @@ -32,22 +30,11 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang.StringUtils; -import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.apihandler.camundabeans.CamundaResponse; import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.apihandler.common.ErrorNumbers; -import org.onap.so.apihandler.common.RequestClient; -import org.onap.so.apihandler.common.RequestClientFactory; import org.onap.so.apihandler.common.RequestClientParameter; -import org.onap.so.apihandler.common.ResponseBuilder; -import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; -import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; -import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.DuplicateRequestException; import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException; import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; @@ -67,7 +54,6 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; -import org.onap.so.logger.LogConstants; import org.onap.so.logger.MessageEnum; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelInfo; @@ -83,24 +69,11 @@ import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; -import org.onap.so.utils.CryptoUtils; -import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.ParameterizedTypeReference; import org.springframework.core.env.Environment; -import org.springframework.http.HttpEntity; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; -import org.springframework.web.client.HttpStatusCodeException; -import org.springframework.web.client.RestTemplate; -import org.camunda.bpm.engine.history.HistoricProcessInstance; -import org.camunda.bpm.engine.impl.persistence.entity.HistoricProcessInstanceEntity; - import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -112,1881 +85,1621 @@ 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.MultivaluedMap; import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; 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 static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; - @Component @Path("/onap/so/infra/serviceInstantiation") -@Api(value="/onap/so/infra/serviceInstantiation",description="Infrastructure API Requests for Service Instances") +@Api(value = "/onap/so/infra/serviceInstantiation", description = "Infrastructure API Requests for Service Instances") public class ServiceInstances { - private static Logger logger = LoggerFactory.getLogger(MsoRequest.class); - private static String NAME = "name"; - private static String VALUE = "value"; - private static final String SAVE_TO_DB = "save instance to db"; - - @Autowired - private Environment env; - - @Autowired - private RequestClientFactory reqClientFactory; - - @Autowired - private CatalogDbClient catalogDbClient; - - @Autowired - private RequestsDbClient infraActiveRequestsClient; - - @Autowired - private ResponseBuilder builder; - - @Autowired - private MsoRequest msoRequest; - - @Autowired - private RestTemplate restTemplate; - - @POST + private static Logger logger = LoggerFactory.getLogger(MsoRequest.class); + private static String NAME = "name"; + private static String VALUE = "value"; + private static String uriPrefix = "/serviceInstantiation/"; + private static final String SAVE_TO_DB = "save instance to db"; + + @Autowired + private Environment env; + + @Autowired + private CatalogDbClient catalogDbClient; + + @Autowired + private RequestsDbClient infraActiveRequestsClient; + + @Autowired + private MsoRequest msoRequest; + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @POST @Path("/{version:[vV][5-7]}/serviceInstances") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create a Service Instance on a version provided",response=Response.class) - @Transactional - public Response createServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.createInstance, null, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/activate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Activate provided Service Instance",response=Response.class) - @Transactional - public Response activateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/deactivate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Deactivate provided Service Instance",response=Response.class) - @Transactional - public Response deactivateServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided Service Instance",response=Response.class) - @Transactional - public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][7]}/serviceInstances/assign") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Assign Service Instance", response=Response.class) - @Transactional - public Response assignServiceInstance(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.assignInstance, null, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/unassign") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Unassign Service Instance", response=Response.class) - @Transactional - public Response unassignServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create Port Mirroring Configuration",response=Response.class) - @Transactional - public Response createPortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided Port",response=Response.class) - @Transactional - public Response deletePortConfiguration(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/enablePort") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Enable Port Mirroring",response=Response.class) - @Transactional - public Response enablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/disablePort") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Disable Port Mirroring",response=Response.class) - @Transactional - public Response disablePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/activate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Activate Port Mirroring",response=Response.class) - @Transactional - public Response activatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/deactivate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Deactivate Port Mirroring",response=Response.class) - @Transactional - public Response deactivatePort(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("configurationInstanceId") String configurationInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("configurationInstanceId", configurationInstanceId); - return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/addRelationships") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Add Relationships to a Service Instance",response=Response.class) - @Transactional - public Response addRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/removeRelationships") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Remove Relationships from Service Instance",response=Response.class) - @Transactional - public Response removeRelationships(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create VNF on a specified version and serviceInstance",response=Response.class) - @Transactional - public Response createVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/replace") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Replace provided VNF instance",response=Response.class) - @Transactional - public Response replaceVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @PUT - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Update VNF on a specified version, serviceInstance and vnfInstance",response=Response.class) - @Transactional - public Response updateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/applyUpdatedConfig") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Apply updated configuration",response=Response.class) - public Response applyUpdatedConfig(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/recreate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Recreate VNF Instance",response=Response.class) - public Response recreateVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided VNF instance",response=Response.class) - @Transactional - public Response deleteVnfInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class) - @Transactional - public Response createVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/replace") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create VfModule on a specified version, serviceInstance and vnfInstance",response=Response.class) - @Transactional - public Response replaceVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, - @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @PUT - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule",response=Response.class) - @Transactional - public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, - @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/inPlaceSoftwareUpdate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Perform VNF software update",response=Response.class) - @Transactional - public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided VfModule instance",response=Response.class) - @Transactional - public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, - @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/deactivateAndCloudDelete") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Deactivate and Cloud Delete VfModule instance",response=Response.class) - @Transactional - public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); - Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version, requestId, getRequestUri(requestContext)); - return response; - } - - @POST - @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/scaleOut") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="VF Auto Scale Out",response=Response.class) - @Transactional - public Response scaleOutVfModule(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create VolumeGroup on a specified version, serviceInstance, vnfInstance",response=Response.class) - @Transactional - public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @PUT - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup",response=Response.class) - @Transactional - public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, - @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided VolumeGroup instance",response=Response.class) - @Transactional - public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("vnfInstanceId") String vnfInstanceId, - @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("vnfInstanceId", vnfInstanceId); - instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create NetworkInstance on a specified version and serviceInstance ",response=Response.class) - @Transactional - public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @PUT - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Update VolumeGroup on a specified version, serviceInstance, networkInstance",response=Response.class) - @Transactional - public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("networkInstanceId", networkInstanceId); - return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete provided Network instance",response=Response.class) - @Transactional - public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId, - @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put("serviceInstanceId", serviceInstanceId); - instanceIdMap.put("networkInstanceId", networkInstanceId); - return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create a Service Instance on a version provided", response = Response.class) + @Transactional + public Response createServiceInstance(String request, @PathParam("version") String version, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.createInstance, null, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Activate provided Service Instance", response = Response.class) + @Transactional + public Response activateServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return serviceInstances(request, Action.activateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/deactivate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deactivate provided Service Instance", response = Response.class) + @Transactional + public Response deactivateServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return serviceInstances(request, Action.deactivateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided Service Instance", response = Response.class) + @Transactional + public Response deleteServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][7]}/serviceInstances/assign") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Assign Service Instance", response = Response.class) + @Transactional + public Response assignServiceInstance(String request, @PathParam("version") String version, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.assignInstance, null, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/unassign") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Unassign Service Instance", response = Response.class) + @Transactional + public Response unassignServiceInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return serviceInstances(request, Action.unassignInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create Port Mirroring Configuration", response = Response.class) + @Transactional + public Response createPortConfiguration(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return configurationRecipeLookup(request, Action.createInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided Port", response = Response.class) + @Transactional + public Response deletePortConfiguration(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("configurationInstanceId") String configurationInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("configurationInstanceId", configurationInstanceId); + return configurationRecipeLookup(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/enablePort") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Enable Port Mirroring", response = Response.class) + @Transactional + public Response enablePort(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("configurationInstanceId") String configurationInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("configurationInstanceId", configurationInstanceId); + return configurationRecipeLookup(request, Action.enablePort, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/disablePort") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Disable Port Mirroring", response = Response.class) + @Transactional + public Response disablePort(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("configurationInstanceId") String configurationInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("configurationInstanceId", configurationInstanceId); + return configurationRecipeLookup(request, Action.disablePort, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Activate Port Mirroring", response = Response.class) + @Transactional + public Response activatePort(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("configurationInstanceId") String configurationInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("configurationInstanceId", configurationInstanceId); + return configurationRecipeLookup(request, Action.activateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/configurations/{configurationInstanceId}/deactivate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deactivate Port Mirroring", response = Response.class) + @Transactional + public Response deactivatePort(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("configurationInstanceId") String configurationInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("configurationInstanceId", configurationInstanceId); + return configurationRecipeLookup(request, Action.deactivateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/addRelationships") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Add Relationships to a Service Instance", response = Response.class) + @Transactional + public Response addRelationships(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return configurationRecipeLookup(request, Action.addRelationships, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/removeRelationships") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Remove Relationships from Service Instance", response = Response.class) + @Transactional + public Response removeRelationships(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return configurationRecipeLookup(request, Action.removeRelationships, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create VNF on a specified version and serviceInstance", response = Response.class) + @Transactional + public Response createVnfInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + try { + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } catch (Exception e) { + logger.error("Error in vnf", e); + throw e; + } + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/replace") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Replace provided VNF instance", response = Response.class) + @Transactional + public Response replaceVnfInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @PUT + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update VNF on a specified version, serviceInstance and vnfInstance", + response = Response.class) + @Transactional + public Response updateVnfInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/applyUpdatedConfig") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Apply updated configuration", response = Response.class) + public Response applyUpdatedConfig(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.applyUpdatedConfig, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/recreate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Recreate VNF Instance", response = Response.class) + public Response recreateVnfInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.recreateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided VNF instance", response = Response.class) + @Transactional + public Response deleteVnfInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create VfModule on a specified version, serviceInstance and vnfInstance", + response = Response.class) + @Transactional + public Response createVfModuleInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/replace") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create VfModule on a specified version, serviceInstance and vnfInstance", + response = Response.class) + @Transactional + public Response replaceVfModuleInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); + return serviceInstances(request, Action.replaceInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @PUT + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update VfModule on a specified version, serviceInstance, vnfInstance and vfModule", + response = Response.class) + @Transactional + public Response updateVfModuleInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][6-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/inPlaceSoftwareUpdate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Perform VNF software update", response = Response.class) + @Transactional + public Response inPlaceSoftwareUpdate(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided VfModule instance", response = Response.class) + @Transactional + public Response deleteVfModuleInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}/deactivateAndCloudDelete") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deactivate and Cloud Delete VfModule instance", response = Response.class) + @Transactional + public Response deactivateAndCloudDeleteVfModuleInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId); + Response response = serviceInstances(request, Action.deactivateAndCloudDelete, instanceIdMap, version, + requestId, requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + return response; + } + + @POST + @Path("/{version:[vV][7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/scaleOut") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "VF Auto Scale Out", response = Response.class) + @Transactional + public Response scaleOutVfModule(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.scaleOut, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create VolumeGroup on a specified version, serviceInstance, vnfInstance", + response = Response.class) + @Transactional + public Response createVolumeGroupInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @PUT + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update VolumeGroup on a specified version, serviceInstance, vnfInstance and volumeGroup", + response = Response.class) + @Transactional + public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided VolumeGroup instance", response = Response.class) + @Transactional + public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId, + @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("vnfInstanceId", vnfInstanceId); + instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create NetworkInstance on a specified version and serviceInstance ", + response = Response.class) + @Transactional + public Response createNetworkInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + return serviceInstances(request, Action.createInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @PUT + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update VolumeGroup on a specified version, serviceInstance, networkInstance", + response = Response.class) + @Transactional + public Response updateNetworkInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("networkInstanceId", networkInstanceId); + return serviceInstances(request, Action.updateInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][5-7]}/serviceInstances/{serviceInstanceId}/networks/{networkInstanceId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete provided Network instance", response = Response.class) + @Transactional + public Response deleteNetworkInstance(String request, @PathParam("version") String version, + @PathParam("serviceInstanceId") String serviceInstanceId, + @PathParam("networkInstanceId") String networkInstanceId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put("serviceInstanceId", serviceInstanceId); + instanceIdMap.put("networkInstanceId", networkInstanceId); + return serviceInstances(request, Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST @Path("/{version:[vV][7]}/instanceGroups") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create instanceGroups",response=Response.class) - @Transactional - public Response createInstanceGroups(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - return serviceInstances(request, Action.createInstance, null, version, requestId, getRequestUri(requestContext)); - } - - @DELETE - @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Delete instanceGroup",response=Response.class) - @Transactional - public Response deleteInstanceGroups(@PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, getRequestUri(requestContext), requestContext); - } - - @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create instanceGroups", response = Response.class) + @Transactional + public Response createInstanceGroups(String request, @PathParam("version") String version, + @Context ContainerRequestContext requestContext) throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + return serviceInstances(request, Action.createInstance, null, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @DELETE + @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Delete instanceGroup", response = Response.class) + @Transactional + public Response deleteInstanceGroups(@PathParam("version") String version, + @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); + return deleteInstanceGroups(Action.deleteInstance, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix), requestContext); + } + + @POST @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/addMembers") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Add instanceGroup members",response=Response.class) - @Transactional - public Response addInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Add instanceGroup members", response = Response.class) + @Transactional + public Response addInstanceGroupMembers(String request, @PathParam("version") String version, + @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); + return serviceInstances(request, Action.addMembers, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + @POST @Path("/{version:[vV][7]}/instanceGroups/{instanceGroupId}/removeMembers") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Remove instanceGroup members",response=Response.class) - @Transactional - public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) throws ApiException { - String requestId = getRequestId(requestContext); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); - return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, getRequestUri(requestContext)); - } - - public String getRequestUri(ContainerRequestContext context){ - String requestUri = context.getUriInfo().getPath(); - String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri); - MDC.put(LogConstants.HTTP_URL, httpUrl); - requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22); - return requestUri; - } - - public void validateHeaders(ContainerRequestContext context) throws ValidationException{ - MultivaluedMap<String, String> headers = context.getHeaders(); - if(!headers.containsKey(ONAPLogConstants.Headers.REQUEST_ID)){ - throw new ValidationException(ONAPLogConstants.Headers.REQUEST_ID + " header", true); - } - if(!headers.containsKey(ONAPLogConstants.Headers.PARTNER_NAME)){ - throw new ValidationException(ONAPLogConstants.Headers.PARTNER_NAME + " header", true); - } - if(!headers.containsKey(REQUESTOR_ID)){ - throw new ValidationException(REQUESTOR_ID + " header", true); - } - } - - public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); - Boolean aLaCarte = null; - long startTime = System.currentTimeMillis (); - ServiceInstancesRequest sir = null; - String apiVersion = version.substring(1); - - sir = convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); - String requestScope = deriveRequestScope(action, sir, requestUri); - InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); - if(sir.getRequestDetails().getRequestParameters() != null){ - aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); - } - parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - - int requestVersion = Integer.parseInt(version.substring(1)); - String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); - boolean alaCarteFlag = msoRequest.getAlacarteFlag(sir); - String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion); - String networkType = msoRequest.getNetworkType(sir,requestScope); - String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir); - String vfModuleType = msoRequest.getVfModuleType(sir,requestScope,action,requestVersion); - - if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){ - currentActiveReq.setVnfType(vnfType); - }else if(requestScope.equalsIgnoreCase(ModelType.network.name()) && networkType != null){ - currentActiveReq.setNetworkType(networkType); - } - - InfraActiveRequests dup = null; - boolean inProgress = false; - - dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); - - if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); - } - ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); - - RequestReferences referencesResponse = new RequestReferences(); - - referencesResponse.setRequestId(requestId); - - serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; - - RecipeLookupResult recipeLookupResult = getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); - String serviceInstanceType = getServiceType(requestScope, sir, alaCarteFlag); - ModelType modelType; - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { - modelType = ModelType.vnf; - }else if(action == Action.addMembers || action == Action.removeMembers){ - modelType = ModelType.instanceGroup; - }else { - modelType =modelInfo.getModelType(); - } - - if (modelType.equals(ModelType.vfModule)) { - - - // Get VF Module-specific base module indicator - VfModule vfm = null; - - String modelVersionId = modelInfo.getModelVersionId(); - - if(modelVersionId != null) { - vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); - } else if(modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null){ - vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), modelInfo.getModelVersion()); - } - - if (vfm != null) { - if (vfm.getIsBase()) { - isBaseVfModule = true; - } + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Remove instanceGroup members", response = Response.class) + @Transactional + public Response removeInstanceGroupMembers(String request, @PathParam("version") String version, + @PathParam("instanceGroupId") String instanceGroupId, @Context ContainerRequestContext requestContext) + throws ApiException { + String requestId = requestHandlerUtils.getRequestId(requestContext); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, instanceGroupId); + return serviceInstances(request, Action.removeMembers, instanceIdMap, version, requestId, + requestHandlerUtils.getRequestUri(requestContext, uriPrefix)); + } + + public Response serviceInstances(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, + String version, String requestId, String requestUri) throws ApiException { + String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + Boolean aLaCarte = null; + long startTime = System.currentTimeMillis(); + ServiceInstancesRequest sir = null; + String apiVersion = version.substring(1); + + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, + requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); + if (sir.getRequestDetails().getRequestParameters() != null) { + aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); + } + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, + currentActiveReq); + 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 networkType = msoRequest.getNetworkType(sir, requestScope); + String sdcServiceModelVersion = msoRequest.getSDCServiceModelVersion(sir); + String vfModuleType = msoRequest.getVfModuleType(sir, requestScope, action, requestVersion); + + if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) { + currentActiveReq.setVnfType(vnfType); + } else if (requestScope.equalsIgnoreCase(ModelType.network.name()) && networkType != null) { + currentActiveReq.setNetworkType(networkType); + } + + InfraActiveRequests dup = null; + boolean inProgress = false; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, 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); + } + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); + + RequestReferences referencesResponse = new RequestReferences(); + + referencesResponse.setRequestId(requestId); + + serviceResponse.setRequestReferences(referencesResponse); + Boolean isBaseVfModule = false; + + RecipeLookupResult recipeLookupResult = + getServiceInstanceOrchestrationURI(sir, action, alaCarteFlag, currentActiveReq); + String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, alaCarteFlag); + ModelType modelType; + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { + modelType = ModelType.vnf; + } else if (action == Action.addMembers || action == Action.removeMembers) { + modelType = ModelType.instanceGroup; + } else { + modelType = modelInfo.getModelType(); + } + + if (modelType.equals(ModelType.vfModule)) { + + + // Get VF Module-specific base module indicator + VfModule vfm = null; + + String modelVersionId = modelInfo.getModelVersionId(); + + if (modelVersionId != null) { + vfm = catalogDbClient.getVfModuleByModelUUID(modelVersionId); + } else if (modelInfo.getModelInvariantId() != null && modelInfo.getModelVersion() != null) { + vfm = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(modelInfo.getModelInvariantId(), + modelInfo.getModelVersion()); + } + + if (vfm != null) { + if (vfm.getIsBase()) { + isBaseVfModule = true; + } } else if (action == Action.createInstance || action == Action.updateInstance) { - // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in Catalog DB. - // This request cannot proceed - - String serviceVersionText = ""; - if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty ()) { - serviceVersionText = " with version " + sdcServiceModelVersion; - } - - String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + serviceVersionText + " not found in MSO Catalog DB"; - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); + // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in + // Catalog DB. + // This request cannot proceed + + String serviceVersionText = ""; + if (sdcServiceModelVersion != null && !sdcServiceModelVersion.isEmpty()) { + serviceVersionText = " with version " + sdcServiceModelVersion; + } + + String errorMessage = "VnfType " + vnfType + " and VF Module Model Name " + modelInfo.getModelName() + + serviceVersionText + " not found in MSO Catalog DB"; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + VfModuleNotFoundException vfModuleException = new VfModuleNotFoundException.Builder(errorMessage, + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, vfModuleException.getMessage()); throw vfModuleException; - } - } - - - serviceInstanceId = setServiceInstanceId(requestScope, sir); - String vnfId = ""; - String vfModuleId = ""; - String volumeGroupId = ""; - String networkId = ""; - String pnfCorrelationId = ""; - String instanceGroupId = null; - - if(sir.getVnfInstanceId () != null){ - vnfId = sir.getVnfInstanceId (); - } - - if(sir.getVfModuleInstanceId () != null){ - vfModuleId = sir.getVfModuleInstanceId (); - } - - if(sir.getVolumeGroupInstanceId () != null){ - volumeGroupId = sir.getVolumeGroupInstanceId (); - } - - if(sir.getNetworkInstanceId () != null){ - networkId = sir.getNetworkInstanceId (); - } - if(sir.getInstanceGroupId() != null){ - instanceGroupId = sir.getInstanceGroupId(); - } + } + } + + + serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir); + String vnfId = ""; + String vfModuleId = ""; + String volumeGroupId = ""; + String networkId = ""; + String pnfCorrelationId = ""; + String instanceGroupId = null; + + if (sir.getVnfInstanceId() != null) { + vnfId = sir.getVnfInstanceId(); + } + + if (sir.getVfModuleInstanceId() != null) { + vfModuleId = sir.getVfModuleInstanceId(); + } + + if (sir.getVolumeGroupInstanceId() != null) { + volumeGroupId = sir.getVolumeGroupInstanceId(); + } + + if (sir.getNetworkInstanceId() != null) { + networkId = sir.getNetworkInstanceId(); + } + if (sir.getInstanceGroupId() != null) { + instanceGroupId = sir.getInstanceGroupId(); + } pnfCorrelationId = getPnfCorrelationId(sir); - try{ + 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(); + } 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(); } - - if(!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance){ - aLaCarte = true; - }else if(aLaCarte == null){ - aLaCarte = false; - } - - RequestClientParameter requestClientParameter = null; - try { - requestClientParameter = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(isBaseVfModule) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.toString()) - .setServiceInstanceId(serviceInstanceId) - .setPnfCorrelationId(pnfCorrelationId) - .setVnfId(vnfId) - .setVfModuleId(vfModuleId) - .setVolumeGroupId(volumeGroupId) - .setNetworkId(networkId) - .setServiceType(serviceInstanceType) - .setVnfType(vnfType) - .setVfModuleType(vfModuleType) - .setNetworkType(networkType) - .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) - .setApiVersion(apiVersion) - .setALaCarte(aLaCarte) - .setRequestUri(requestUri) - .setInstanceGroupId(instanceGroupId).build(); - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - } - return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); - } - public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { - String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); - Boolean aLaCarte = true; - long startTime = System.currentTimeMillis (); - String apiVersion = version.substring(1); - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - sir.setInstanceGroupId(instanceGroupId); - - String requestScope = ModelType.instanceGroup.toString(); - InfraActiveRequests currentActiveReq = msoRequest.createRequestObject (sir, action, requestId, Status.IN_PROGRESS, null, requestScope); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - try { - validateHeaders(requestContext); - } catch (ValidationException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_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(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; - } - - InfraActiveRequests dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq); - boolean inProgress = false; - - if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); - } - - if (dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup); - } - - ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); - - RequestReferences referencesResponse = new RequestReferences(); - - referencesResponse.setRequestId(requestId); - - serviceResponse.setRequestReferences(referencesResponse); - Boolean isBaseVfModule = false; - RecipeLookupResult recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); - - 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(); + if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) { + aLaCarte = true; + } else if (aLaCarte == null) { + aLaCarte = false; } - - RequestClientParameter requestClientParameter = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(isBaseVfModule) - .setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) - .setRequestAction(action.toString()) - .setApiVersion(apiVersion) - .setALaCarte(aLaCarte) - .setRequestUri(requestUri) - .setInstanceGroupId(instanceGroupId).build(); - - return postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope); - } - - private String getPnfCorrelationId(ServiceInstancesRequest sir) { - return Optional.of(sir) - .map(ServiceInstancesRequest::getRequestDetails) - .map(RequestDetails::getRequestParameters) - .map(parameters -> parameters.getUserParamValue("pnfId")) - .orElse(""); - } - - private String deriveRequestScope(Actions action, ServiceInstancesRequest sir, String requestUri) { - if(action == Action.inPlaceSoftwareUpdate || action == Action.applyUpdatedConfig){ - return (ModelType.vnf.name()); - }else if(action == Action.addMembers || action == Action.removeMembers){ - return(ModelType.instanceGroup.toString()); - }else{ - String requestScope; - if(sir.getRequestDetails().getModelInfo().getModelType() == null){ - requestScope = requestScopeFromUri(requestUri); - }else{ - requestScope = sir.getRequestDetails().getModelInfo().getModelType().name(); - } - return requestScope; - } - } - private String requestScopeFromUri(String requestUri){ - String requestScope; - if(requestUri.contains(ModelType.network.name())){ - requestScope = ModelType.network.name(); - }else if(requestUri.contains(ModelType.vfModule.name())){ - requestScope = ModelType.vfModule.name(); - }else if(requestUri.contains(ModelType.volumeGroup.name())){ - requestScope = ModelType.volumeGroup.name(); - }else if(requestUri.contains(ModelType.configuration.name())){ - requestScope = ModelType.configuration.name(); - }else if(requestUri.contains(ModelType.vnf.name())){ - requestScope = ModelType.vnf.name(); - }else{ - requestScope = ModelType.service.name(); - } - return requestScope; - } - private Response postBPELRequest(InfraActiveRequests currentActiveReq, RequestClientParameter requestClientParameter, String orchestrationUri, String requestScope)throws ApiException { - RequestClient requestClient = null; - HttpResponse response = null; - try { - requestClient = reqClientFactory.getRequestClient (orchestrationUri); - response = requestClient.post(requestClientParameter); - } catch (Exception e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - String url = requestClient != null ? requestClient.getUrl() : ""; - ClientConnectionException clientException = new ClientConnectionException.Builder(url, HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).cause(e).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - - throw clientException; - } - - if (response == null) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.BusinessProcesssError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ClientConnectionException clientException = new ClientConnectionException.Builder(requestClient.getUrl(), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, clientException.getMessage()); - - throw clientException; - } - - ResponseHandler respHandler = null; - int bpelStatus = 500; + + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId) + .setPnfCorrelationId(pnfCorrelationId).setVnfId(vnfId).setVfModuleId(vfModuleId) + .setVolumeGroupId(volumeGroupId).setNetworkId(networkId).setServiceType(serviceInstanceType) + .setVnfType(vnfType).setVfModuleType(vfModuleType).setNetworkType(networkType) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri) + .setInstanceGroupId(instanceGroupId).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + public Response deleteInstanceGroups(Actions action, HashMap<String, String> instanceIdMap, String version, + String requestId, String requestUri, ContainerRequestContext requestContext) throws ApiException { + String instanceGroupId = instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID); + Boolean aLaCarte = true; + long startTime = System.currentTimeMillis(); + String apiVersion = version.substring(1); + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setInstanceGroupId(instanceGroupId); + + String requestScope = ModelType.instanceGroup.toString(); + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, null, requestScope); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); try { - respHandler = new ResponseHandler (response, requestClient.getType ()); - bpelStatus = respHandler.getStatus (); - } catch (ApiException e) { + requestHandlerUtils.validateHeaders(requestContext); + } catch (ValidationException e) { logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_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(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } - // BPEL accepted the request, the request is in progress - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - ServiceInstancesResponse jsonResponse; - CamundaResponse camundaResp = respHandler.getResponse(); - - if("Success".equalsIgnoreCase(camundaResp.getMessage())) { - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.readValue(camundaResp.getResponse(), ServiceInstancesResponse.class); - jsonResponse.getRequestReferences().setRequestId(requestClientParameter.getRequestId()); - Optional<URL> selfLinkUrl = msoRequest.buildSelfLinkUrl(currentActiveReq.getRequestUrl(), requestClientParameter.getRequestId()); - if(selfLinkUrl.isPresent()){ - jsonResponse.getRequestReferences().setRequestSelfLink(selfLinkUrl.get()); - } else { - jsonResponse.getRequestReferences().setRequestSelfLink(null); - } - } catch (IOException e) { - logger.error("Exception occurred", e); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Exception caught mapping Camunda JSON response to object", HttpStatus.SC_NOT_ACCEPTABLE, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - throw validateException; - } - return builder.buildResponse(HttpStatus.SC_ACCEPTED, requestClientParameter.getRequestId(), jsonResponse, requestClientParameter.getApiVersion()); - } - } - - List<String> variables = new ArrayList<>(); - variables.add(bpelStatus + ""); - String camundaJSONResponseBody = respHandler.getResponseBody (); - if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); - BPMNFailureException bpmnException = new BPMNFailureException.Builder(String.valueOf(bpelStatus) + camundaJSONResponseBody, bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, bpmnException.getMessage()); - - throw bpmnException; - } else { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).errorSource(requestClient.getUrl()).build(); - - - BPMNFailureException servException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, servException.getMessage()); - - throw servException; - } - } - - private void setInstanceId(InfraActiveRequests currentActiveReq, String requestScope, String instanceId, Map<String, String> instanceIdMap) { - if(StringUtils.isNotBlank(instanceId)) { - if(ModelType.service.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setServiceInstanceId(instanceId); - } else if(ModelType.vnf.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVnfId(instanceId); - } else if(ModelType.vfModule.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVfModuleId(instanceId); - } else if(ModelType.volumeGroup.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setVolumeGroupId(instanceId); - } else if(ModelType.network.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setNetworkId(instanceId); - } else if(ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - currentActiveReq.setConfigurationId(instanceId); - }else if(ModelType.instanceGroup.toString().equalsIgnoreCase(requestScope)){ - currentActiveReq.setInstanceGroupId(instanceId); - } - } else if(instanceIdMap != null && !instanceIdMap.isEmpty()) { - if(instanceIdMap.get("serviceInstanceId") != null){ - currentActiveReq.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); - } - if(instanceIdMap.get("vnfInstanceId") != null){ - currentActiveReq.setVnfId(instanceIdMap.get("vnfInstanceId")); - } - if(instanceIdMap.get("vfModuleInstanceId") != null){ - currentActiveReq.setVfModuleId(instanceIdMap.get("vfModuleInstanceId")); - } - if(instanceIdMap.get("volumeGroupInstanceId") != null){ - currentActiveReq.setVolumeGroupId(instanceIdMap.get("volumeGroupInstanceId")); - } - if(instanceIdMap.get("networkInstanceId") != null){ - currentActiveReq.setNetworkId(instanceIdMap.get("networkInstanceId")); - } - if(instanceIdMap.get("configurationInstanceId") != null){ - currentActiveReq.setConfigurationId(instanceIdMap.get("configurationInstanceId")); - } - if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){ - currentActiveReq.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); - } - } - } - - protected String mapJSONtoMSOStyle(String msoRawRequest, ServiceInstancesRequest serviceInstRequest, boolean isAlaCarte, Actions action) throws IOException { - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - if(msoRawRequest != null){ - ServiceInstancesRequest sir = mapper.readValue(msoRawRequest, ServiceInstancesRequest.class); - if( serviceInstRequest != null && - serviceInstRequest.getRequestDetails() != null && - serviceInstRequest.getRequestDetails().getRequestParameters() != null) { - if( !isAlaCarte && Action.createInstance.equals(action)) { - sir.getRequestDetails().setCloudConfiguration(serviceInstRequest.getRequestDetails().getCloudConfiguration()); - sir.getRequestDetails().getRequestParameters().setUserParams(serviceInstRequest.getRequestDetails().getRequestParameters().getUserParams()); - } - sir.getRequestDetails().getRequestParameters().setUsePreload(serviceInstRequest.getRequestDetails().getRequestParameters().getUsePreload()); - } - - logger.debug("Value as string: {}", mapper.writeValueAsString(sir)); - return mapper.writeValueAsString(sir); - } - return null; - } - - private void buildErrorOnDuplicateRecord(InfraActiveRequests currentActiveReq, Actions action, HashMap<String, String> instanceIdMap, long startTime, MsoRequest msoRequest, - String instanceName, String requestScope, InfraActiveRequests dup) throws ApiException { - - // Found the duplicate record. Return the appropriate error. - String instance = null; - if(instanceName != null){ - instance = instanceName; - }else{ - instance = instanceIdMap.get(requestScope + "InstanceId"); - } - //List<String> variables = new ArrayList<String>(); - //variables.add(dup.getRequestStatus()); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - DuplicateRequestException dupException = new DuplicateRequestException.Builder(requestScope,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, dupException.getMessage()); - - throw dupException; - } - - private InfraActiveRequests duplicateCheck(Actions action, HashMap<String, String> instanceIdMap, long startTime, - MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException { - InfraActiveRequests dup = null; - try { - if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance || action == Action.assignInstance))){ - dup = infraActiveRequestsClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope); - } - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - RequestDbFailureException requestDbFailureException = new RequestDbFailureException.Builder("check for duplicate instance", e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage()); - throw requestDbFailureException; - } - return dup; - } - protected boolean camundaHistoryCheck(InfraActiveRequests duplicateRecord, InfraActiveRequests currentActiveReq) throws RequestDbFailureException, ContactCamundaException{ - String requestId = duplicateRecord.getRequestId(); - String path = env.getProperty("mso.camunda.rest.history.uri") + requestId; - String targetUrl = env.getProperty("mso.camundaURL") + path; - HttpHeaders headers = setCamundaHeaders(env.getRequiredProperty("mso.camundaAuth"), env.getRequiredProperty("mso.msoKey")); - HttpEntity<?> requestEntity = new HttpEntity<>(headers); - ResponseEntity<List<HistoricProcessInstanceEntity>> response = null; - try{ - response = restTemplate.exchange(targetUrl, HttpMethod.GET, requestEntity, new ParameterizedTypeReference<List<HistoricProcessInstanceEntity>>(){}); - }catch(HttpStatusCodeException e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ContactCamundaException contactCamundaException= new ContactCamundaException.Builder(requestId, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, contactCamundaException.getMessage()); - throw contactCamundaException; - } - if(response.getBody().isEmpty()){ - updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); - } - for(HistoricProcessInstance instance : response.getBody()){ - if(instance.getState().equals("ACTIVE")){ - return true; - }else{ - updateStatus(duplicateRecord, Status.COMPLETE, "Request Completed"); - } - } - return false; - } - protected HttpHeaders setCamundaHeaders(String auth, String msoKey) { - HttpHeaders headers = new HttpHeaders(); - List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>(); - acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON); - headers.setAccept(acceptableMediaTypes); - try { - String userCredentials = CryptoUtils.decrypt(auth, msoKey); - if(userCredentials != null) { - headers.add(HttpHeaders.AUTHORIZATION, "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes())); - } - } catch(GeneralSecurityException e) { - logger.error("Security exception", e); + InfraActiveRequests dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, + requestScope, currentActiveReq); + boolean inProgress = false; + + if (dup != null) { + inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq); } - return headers; - } - private ServiceInstancesRequest convertJsonToServiceInstanceRequest(String requestJSON, Actions action, long startTime, - ServiceInstancesRequest sir, MsoRequest msoRequest, String requestId, String requestUri) throws ApiException { - try{ - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(requestJSON, ServiceInstancesRequest.class); + if (dup != null && inProgress) { + requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, + msoRequest, null, requestScope, dup); + } - } catch (IOException e) { + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + RequestReferences referencesResponse = new RequestReferences(); - ValidateException validateException = new ValidateException.Builder("Error mapping request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - String requestScope = requestScopeFromUri(requestUri); + referencesResponse.setRequestId(requestId); - msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action, requestScope, requestJSON); + serviceResponse.setRequestReferences(referencesResponse); + Boolean isBaseVfModule = false; + + RecipeLookupResult recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); + + 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(); + } + + RequestClientParameter requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId) + .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout()) + .setRequestAction(action.toString()).setApiVersion(apiVersion).setALaCarte(aLaCarte) + .setRequestUri(requestUri).setInstanceGroupId(instanceGroupId).build(); + + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, + recipeLookupResult.getOrchestrationURI(), requestScope); + } + + private String getPnfCorrelationId(ServiceInstancesRequest sir) { + return Optional.of(sir).map(ServiceInstancesRequest::getRequestDetails) + .map(RequestDetails::getRequestParameters).map(parameters -> parameters.getUserParamValue("pnfId")) + .orElse(""); + } + + private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, + boolean alaCarteFlag, InfraActiveRequests currentActiveReq) throws ApiException { + RecipeLookupResult recipeLookupResult = null; + // if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + // Query MSO Catalog DB + + if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { + recipeLookupResult = getDefaultVnfUri(sir, action); + } else if (action == Action.addMembers || action == Action.removeMembers) { + recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); + } else if (modelInfo.getModelType().equals(ModelType.service)) { + try { + recipeLookupResult = getServiceURI(sir, action, alaCarteFlag); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw validateException; - } - } - - private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, String version, - String requestJSON, Boolean aLaCarte, String requestId, InfraActiveRequests currentActiveReq) throws ValidateException, RequestDbFailureException { - int reqVersion = Integer.parseInt(version.substring(1)); - try { - msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte); - } catch (Exception e) { - logger.error("failed to parse request", 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("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); - - throw validateException; - } - } - - private RecipeLookupResult getServiceInstanceOrchestrationURI(ServiceInstancesRequest sir, Actions action, boolean alaCarteFlag, - InfraActiveRequests currentActiveReq) throws ApiException { - RecipeLookupResult recipeLookupResult = null; - //if the aLaCarte flag is set to TRUE, the API-H should choose the VID_DEFAULT recipe for the requested action - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - // Query MSO Catalog DB - - if (action == Action.applyUpdatedConfig || action == Action.inPlaceSoftwareUpdate) { - recipeLookupResult = getDefaultVnfUri(sir, action); - }else if(action == Action.addMembers || action == Action.removeMembers){ - recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); - }else if (modelInfo.getModelType().equals(ModelType.service)) { - try { - recipeLookupResult = getServiceURI(sir, action,alaCarteFlag); - } catch (IOException 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(); - - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; - } - } else if (modelInfo.getModelType().equals(ModelType.vfModule) || - modelInfo.getModelType().equals(ModelType.volumeGroup) || modelInfo.getModelType().equals(ModelType.vnf)) { + } + } else if (modelInfo.getModelType().equals(ModelType.vfModule) + || modelInfo.getModelType().equals(ModelType.volumeGroup) + || modelInfo.getModelType().equals(ModelType.vnf)) { try { - recipeLookupResult = getVnfOrVfModuleUri( sir, action); + recipeLookupResult = getVnfOrVfModuleUri(sir, action); } catch (ValidationException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + 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(); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } - }else if (modelInfo.getModelType().equals(ModelType.network)) { + } else if (modelInfo.getModelType().equals(ModelType.network)) { try { - recipeLookupResult = getNetworkUri( sir, action); + recipeLookupResult = getNetworkUri(sir, action); } catch (ValidationException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + 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(); - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; } - }else if(modelInfo.getModelType().equals(ModelType.instanceGroup)){ - recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); + } else if (modelInfo.getModelType().equals(ModelType.instanceGroup)) { + recipeLookupResult = new RecipeLookupResult("/mso/async/services/WorkflowActionBB", 180); } if (recipeLookupResult == null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - RecipeNotFoundException recipeNotFoundExceptionException = new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); + RecipeNotFoundException recipeNotFoundExceptionException = + new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); - updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage()); + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, + recipeNotFoundExceptionException.getMessage()); throw recipeNotFoundExceptionException; - } - return recipeLookupResult; - } - - private 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 - String defaultServiceModelName = getDefaultModel(servInstReq); - RequestDetails requestDetails = servInstReq.getRequestDetails(); - ModelInfo modelInfo = requestDetails.getModelInfo(); - org.onap.so.db.catalog.beans.Service serviceRecord; - List<org.onap.so.db.catalog.beans.Service> serviceRecordList; - ServiceRecipe recipe = null; - - if(alaCarteFlag){ - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - if(serviceRecord !=null){ - recipe =catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),action.toString()); - } - }else{ - serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId()); - recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(), action.toString()); - if (recipe == null){ - serviceRecordList = catalogDbClient.getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId()); - if(!serviceRecordList.isEmpty()){ - for(org.onap.so.db.catalog.beans.Service record : serviceRecordList){ - recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(),action.toString()); - if(recipe != null){ - break; - } - } - } - } - } - - //if an aLaCarte flag was sent in the request, throw an error if the recipe was not found - RequestParameters reqParam = requestDetails.getRequestParameters(); - if(reqParam!=null && alaCarteFlag && recipe==null){ - return null; - } else if(!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) { - mapToLegacyRequest(requestDetails); - }else if (recipe == null) { //aLaCarte wasn't sent, so we'll try the default - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(),action.toString()); - } - if(modelInfo.getModelVersionId() == null) { - modelInfo.setModelVersionId(serviceRecord.getModelUUID()); - } - if(recipe==null){ - return null; - } - return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ()); - } - - protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException { - RequestParameters reqParam; - if (requestDetails.getRequestParameters() == null) { - reqParam = new RequestParameters(); - } else { - reqParam = requestDetails.getRequestParameters(); - } - if(requestDetails.getCloudConfiguration() == null) { - CloudConfiguration cloudConfig = configureCloudConfig(reqParam); - if(cloudConfig != null) { - requestDetails.setCloudConfiguration(cloudConfig); - } - } - - List<Map<String, Object>> userParams = configureUserParams(reqParam); - if(!userParams.isEmpty()) { - if (reqParam == null) { - requestDetails.setRequestParameters(new RequestParameters()); - } - requestDetails.getRequestParameters().setUserParams(userParams); - } - } - - protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException { - - for(Map<String, Object> params : reqParams.getUserParams()){ - if(params.containsKey("service")){ - Service service = serviceMapper(params); - - Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration()); - - if (targetConfiguration.isPresent()) { - return targetConfiguration.get(); - } else { - for(Networks network : service.getResources().getNetworks()) { - targetConfiguration = addCloudConfig(network.getCloudConfiguration()); - if(targetConfiguration.isPresent()) { - return targetConfiguration.get(); - } - } - - for(Vnfs vnf : service.getResources().getVnfs()) { - targetConfiguration = addCloudConfig(vnf.getCloudConfiguration()); - - if(targetConfiguration.isPresent()) { - return targetConfiguration.get(); - } - - for(VfModules vfModule : vnf.getVfModules()) { - targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration()); - - if(targetConfiguration.isPresent()) { - return targetConfiguration.get(); - } - } - } - } - } - } - - return null; - } - - private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) { - CloudConfiguration targetConfiguration = new CloudConfiguration(); - if(sourceCloudConfiguration != null) { - targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli()); - targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId()); - targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId()); - targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner()); - return Optional.of(targetConfiguration); - } - return Optional.empty(); - } - - protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException { - logger.debug("Configuring UserParams for Macro Request"); - Map<String, Object> userParams = new HashMap<>(); - - for(Map<String, Object> params : reqParams.getUserParams()){ - if(params.containsKey("service")){ - Service service = serviceMapper(params); - - addUserParams(userParams, service.getInstanceParams()); - - for(Networks network : service.getResources().getNetworks()) { - addUserParams(userParams, network.getInstanceParams()); - } - - for(Vnfs vnf: service.getResources().getVnfs()) { - addUserParams(userParams, vnf.getInstanceParams()); - - for(VfModules vfModule: vnf.getVfModules()) { - addUserParams(userParams, vfModule.getInstanceParams()); - } - } - } - } - - return mapFlatMapToNameValue(userParams); + } + return recipeLookupResult; + } + + private 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 + String defaultServiceModelName = requestHandlerUtils.getDefaultModel(servInstReq); + RequestDetails requestDetails = servInstReq.getRequestDetails(); + ModelInfo modelInfo = requestDetails.getModelInfo(); + org.onap.so.db.catalog.beans.Service serviceRecord; + List<org.onap.so.db.catalog.beans.Service> serviceRecordList; + ServiceRecipe recipe = null; + + if (alaCarteFlag) { + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + if (serviceRecord != null) { + recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(), + action.toString()); + } + } else { + serviceRecord = catalogDbClient.getServiceByID(modelInfo.getModelVersionId()); + recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(modelInfo.getModelVersionId(), + action.toString()); + if (recipe == null) { + serviceRecordList = catalogDbClient + .getServiceByModelInvariantUUIDOrderByModelVersionDesc(modelInfo.getModelInvariantId()); + if (!serviceRecordList.isEmpty()) { + for (org.onap.so.db.catalog.beans.Service record : serviceRecordList) { + recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(record.getModelUUID(), + action.toString()); + if (recipe != null) { + break; + } + } + } + } + } + + // if an aLaCarte flag was sent in the request, throw an error if the recipe was not found + RequestParameters reqParam = requestDetails.getRequestParameters(); + if (reqParam != null && alaCarteFlag && recipe == null) { + return null; + } else if (!alaCarteFlag && recipe != null && Action.createInstance.equals(action)) { + mapToLegacyRequest(requestDetails); + } else if (recipe == null) { // aLaCarte wasn't sent, so we'll try the default + serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); + recipe = catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceRecord.getModelUUID(), + action.toString()); + } + if (modelInfo.getModelVersionId() == null) { + modelInfo.setModelVersionId(serviceRecord.getModelUUID()); + } + if (recipe == null) { + return null; + } + return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()); + } + + protected void mapToLegacyRequest(RequestDetails requestDetails) throws IOException { + RequestParameters reqParam; + if (requestDetails.getRequestParameters() == null) { + reqParam = new RequestParameters(); + } else { + reqParam = requestDetails.getRequestParameters(); + } + if (requestDetails.getCloudConfiguration() == null) { + CloudConfiguration cloudConfig = configureCloudConfig(reqParam); + if (cloudConfig != null) { + requestDetails.setCloudConfiguration(cloudConfig); + } + } + + List<Map<String, Object>> userParams = configureUserParams(reqParam); + if (!userParams.isEmpty()) { + if (reqParam == null) { + requestDetails.setRequestParameters(new RequestParameters()); + } + requestDetails.getRequestParameters().setUserParams(userParams); + } + } + + protected CloudConfiguration configureCloudConfig(RequestParameters reqParams) throws IOException { + + for (Map<String, Object> params : reqParams.getUserParams()) { + if (params.containsKey("service")) { + Service service = serviceMapper(params); + + Optional<CloudConfiguration> targetConfiguration = addCloudConfig(service.getCloudConfiguration()); + + if (targetConfiguration.isPresent()) { + return targetConfiguration.get(); + } else { + for (Networks network : service.getResources().getNetworks()) { + targetConfiguration = addCloudConfig(network.getCloudConfiguration()); + if (targetConfiguration.isPresent()) { + return targetConfiguration.get(); + } + } + + for (Vnfs vnf : service.getResources().getVnfs()) { + targetConfiguration = addCloudConfig(vnf.getCloudConfiguration()); + + if (targetConfiguration.isPresent()) { + return targetConfiguration.get(); + } + + for (VfModules vfModule : vnf.getVfModules()) { + targetConfiguration = addCloudConfig(vfModule.getCloudConfiguration()); + + if (targetConfiguration.isPresent()) { + return targetConfiguration.get(); + } + } + } + } + } + } + + return null; + } + + private Optional<CloudConfiguration> addCloudConfig(CloudConfiguration sourceCloudConfiguration) { + CloudConfiguration targetConfiguration = new CloudConfiguration(); + if (sourceCloudConfiguration != null) { + targetConfiguration.setAicNodeClli(sourceCloudConfiguration.getAicNodeClli()); + targetConfiguration.setTenantId(sourceCloudConfiguration.getTenantId()); + targetConfiguration.setLcpCloudRegionId(sourceCloudConfiguration.getLcpCloudRegionId()); + targetConfiguration.setCloudOwner(sourceCloudConfiguration.getCloudOwner()); + return Optional.of(targetConfiguration); + } + return Optional.empty(); + } + + protected List<Map<String, Object>> configureUserParams(RequestParameters reqParams) throws IOException { + logger.debug("Configuring UserParams for Macro Request"); + Map<String, Object> userParams = new HashMap<>(); + + for (Map<String, Object> params : reqParams.getUserParams()) { + if (params.containsKey("service")) { + Service service = serviceMapper(params); + + addUserParams(userParams, service.getInstanceParams()); + + for (Networks network : service.getResources().getNetworks()) { + addUserParams(userParams, network.getInstanceParams()); + } + + for (Vnfs vnf : service.getResources().getVnfs()) { + addUserParams(userParams, vnf.getInstanceParams()); + + for (VfModules vfModule : vnf.getVfModules()) { + addUserParams(userParams, vfModule.getInstanceParams()); + } + } + } + } + + return mapFlatMapToNameValue(userParams); } - private Service serviceMapper(Map<String, Object> params) - throws JsonProcessingException, IOException, JsonParseException, JsonMappingException { - ObjectMapper obj = new ObjectMapper(); - String input = obj.writeValueAsString(params.get("service")); - return obj.readValue(input, Service.class); - } - - private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) { - for(Map<String, String> map : sourceUserParams) { - for (Map.Entry<String, String> entry : map.entrySet()) { - targetUserParams.put(entry.getKey(), entry.getValue()); - } - } - } - - protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) { - List<Map<String, Object>> targetUserParams = new ArrayList<>(); - - for(Map.Entry<String, Object> map : flatMap.entrySet()) { - Map<String, Object> targetMap = new HashMap<>(); - targetMap.put(NAME, map.getKey()); - targetMap.put(VALUE, map.getValue()); - targetUserParams.add(targetMap); - } - return targetUserParams; - } - - private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action) throws ValidationException { - - ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo(); - String vnfComponentType = modelInfo.getModelType().name(); - - RelatedInstanceList[] instanceList = null; - if (servInstReq.getRequestDetails() != null) { - instanceList = servInstReq.getRequestDetails().getRelatedInstanceList(); - } - - Recipe recipe = null; - String defaultSource = getDefaultModel(servInstReq); - String modelCustomizationId = modelInfo.getModelCustomizationId(); - String modelCustomizationName = modelInfo.getModelCustomizationName(); - String relatedInstanceModelVersionId = null; - String relatedInstanceModelInvariantId = null; - String relatedInstanceVersion = null; - String relatedInstanceModelCustomizationName = null; - - if (instanceList != null) { - - for(RelatedInstanceList relatedInstanceList : instanceList){ - - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); - if(relatedInstanceModelInfo.getModelType().equals(ModelType.service)){ - relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId(); - relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion(); - } - - if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)){ - relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId(); - relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId(); - relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion(); - relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName(); - } - } - - if(modelInfo.getModelType().equals(ModelType.vnf)) { - // a. For a vnf request (only create, no update currently): - // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in vnf_resource_customization.model_customization_uuid. - // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have - // been provided (else create request should be rejected). APIH should use the relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName - // to “join�? service_to_resource_customizations with vnf_resource_customization to confirm a vnf_resource_customization.model_customization_uuid record exists. - // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId - // (MODEL_UUID) in SERVICE table. - // iii. Regardless of how the value was provided/obtained above, APIH must always populate vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated - // during 1707 data migration if VID did not provide it originally on request. - // iv. Note: continue to construct the “vnf-type�? value and pass to BPMN (must still be populated in A&AI). - // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to look it up in our catalog to construct vnf-type value to pass to BPMN. - - VnfResource vnfResource = null; - VnfResourceCustomization vrc=null; - // Validation for vnfResource - - if(modelCustomizationId!=null) { + private Service serviceMapper(Map<String, Object> params) + throws JsonProcessingException, IOException, JsonParseException, JsonMappingException { + ObjectMapper obj = new ObjectMapper(); + String input = obj.writeValueAsString(params.get("service")); + return obj.readValue(input, Service.class); + } + + private void addUserParams(Map<String, Object> targetUserParams, List<Map<String, String>> sourceUserParams) { + for (Map<String, String> map : sourceUserParams) { + for (Map.Entry<String, String> entry : map.entrySet()) { + targetUserParams.put(entry.getKey(), entry.getValue()); + } + } + } + + protected List<Map<String, Object>> mapFlatMapToNameValue(Map<String, Object> flatMap) { + List<Map<String, Object>> targetUserParams = new ArrayList<>(); + + for (Map.Entry<String, Object> map : flatMap.entrySet()) { + Map<String, Object> targetMap = new HashMap<>(); + targetMap.put(NAME, map.getKey()); + targetMap.put(VALUE, map.getValue()); + targetUserParams.add(targetMap); + } + return targetUserParams; + } + + private RecipeLookupResult getVnfOrVfModuleUri(ServiceInstancesRequest servInstReq, Actions action) + throws ValidationException { + + ModelInfo modelInfo = servInstReq.getRequestDetails().getModelInfo(); + String vnfComponentType = modelInfo.getModelType().name(); + + RelatedInstanceList[] instanceList = null; + if (servInstReq.getRequestDetails() != null) { + instanceList = servInstReq.getRequestDetails().getRelatedInstanceList(); + } + + Recipe recipe = null; + String defaultSource = requestHandlerUtils.getDefaultModel(servInstReq); + String modelCustomizationId = modelInfo.getModelCustomizationId(); + String modelCustomizationName = modelInfo.getModelCustomizationName(); + String relatedInstanceModelVersionId = null; + String relatedInstanceModelInvariantId = null; + String relatedInstanceVersion = null; + String relatedInstanceModelCustomizationName = null; + + if (instanceList != null) { + + for (RelatedInstanceList relatedInstanceList : instanceList) { + + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); + if (relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId(); + relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion(); + } + + if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) { + relatedInstanceModelVersionId = relatedInstanceModelInfo.getModelVersionId(); + relatedInstanceModelInvariantId = relatedInstanceModelInfo.getModelInvariantId(); + relatedInstanceVersion = relatedInstanceModelInfo.getModelVersion(); + relatedInstanceModelCustomizationName = relatedInstanceModelInfo.getModelCustomizationName(); + } + } + + if (modelInfo.getModelType().equals(ModelType.vnf)) { + // a. For a vnf request (only create, no update currently): + // i. (v3-v4) If modelInfo.modelCustomizationId is provided, use it to validate catalog DB has record in + // vnf_resource_customization.model_customization_uuid. + // ii. (v2-v4) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or + // pre-v3), then modelInfo.modelCustomizationName must have + // been provided (else create request should be rejected). APIH should use the + // relatedInstance.modelInfo[service].modelVersionId** + modelInfo[vnf].modelCustomizationName + // to “join�? service_to_resource_customizations with vnf_resource_customization to confirm a + // vnf_resource_customization.model_customization_uuid record exists. + // **If relatedInstance.modelInfo[service].modelVersionId was not provided, use + // relatedInstance.modelInfo[service].modelInvariantId + modelVersion instead to lookup modelVersionId + // (MODEL_UUID) in SERVICE table. + // iii. Regardless of how the value was provided/obtained above, APIH must always populate + // vnfModelCustomizationId in bpmnRequest. It would be assumed it was MSO generated + // during 1707 data migration if VID did not provide it originally on request. + // iv. Note: continue to construct the “vnf-type�? value and pass to BPMN (must still be populated + // in A&AI). + // 1. If modelCustomizationName is NOT provided on a vnf/vfModule request, use modelCustomizationId to + // look it up in our catalog to construct vnf-type value to pass to BPMN. + + VnfResource vnfResource = null; + VnfResourceCustomization vrc = null; + // Validation for vnfResource + + if (modelCustomizationId != null) { vrc = catalogDbClient.getVnfResourceCustomizationByModelCustomizationUUID(modelCustomizationId); - if(vrc != null){ - vnfResource = vrc.getVnfResources(); + if (vrc != null) { + vnfResource = vrc.getVnfResources(); + } + } else { + org.onap.so.db.catalog.beans.Service service = + catalogDbClient.getServiceByID(relatedInstanceModelVersionId); + if (service == null) { + service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion, + relatedInstanceModelInvariantId); + } + + if (service == null) { + throw new ValidationException("service in relatedInstance"); } - } else { - org.onap.so.db.catalog.beans.Service service = catalogDbClient.getServiceByID(relatedInstanceModelVersionId); - if(service == null) { - service = catalogDbClient.getServiceByModelVersionAndModelInvariantUUID(relatedInstanceVersion, relatedInstanceModelInvariantId); - } - - if(service == null) { - throw new ValidationException("service in relatedInstance"); - } for (VnfResourceCustomization vnfResourceCustom : service.getVnfCustomizations()) { if (vnfResourceCustom.getModelInstanceName().equals(modelCustomizationName)) { - vrc=vnfResourceCustom; + vrc = vnfResourceCustom; } } - - if(vrc != null) { - vnfResource = vrc.getVnfResources(); + + if (vrc != null) { + vnfResource = vrc.getVnfResources(); modelInfo.setModelCustomizationId(vrc.getModelCustomizationUUID()); modelInfo.setModelCustomizationUuid(vrc.getModelCustomizationUUID()); - } - } + } + } - if(vnfResource==null){ - throw new ValidationException("vnfResource"); - } else { - if(modelInfo.getModelVersionId() == null) { + if (vnfResource == null) { + throw new ValidationException("vnfResource"); + } else { + if (modelInfo.getModelVersionId() == null) { modelInfo.setModelVersionId(vnfResource.getModelUUID()); - } - } - - VnfRecipe vnfRecipe = null; - - if(vrc != null) { - String nfRole = vrc.getNfRole(); - if(nfRole != null) { - vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString()); - } - } - - if(vnfRecipe == null) { - vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); - } - - if (vnfRecipe == null) { - return null; - } - - return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout()); - } else { - /* (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or pre-v3), then modelInfo.modelCustomizationName must have - // been provided (else create request should be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId + modelInfo[vnf].modelCustomizationName - // to join vnf_to_resource_customizations with vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record exists. - // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. - // For each vf_module_cust_model_customization_uuid value returned, use that UUID to query vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to - // confirm record matches request data (and to identify the modelCustomizationId associated with the vfModule in the request). This means taking each record found - // in vf_module_customization and looking up in vf_module (using vf_module_customization’s FK into vf_module) to find a match on MODEL_INVARIANT_UUID (modelInvariantId) - // and MODEL_VERSION (modelVersion). - */ - VfModuleCustomization vfmc = null; - VnfResource vnfr; - VnfResourceCustomization vnfrc; - VfModule vfModule = null; - - if(modelInfo.getModelCustomizationId() != null) { - vfmc = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId()); - } else { - vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId); - if(vnfr == null){ - vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion(relatedInstanceModelInvariantId, relatedInstanceVersion); - } - vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources(relatedInstanceModelCustomizationName, vnfr); - - List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations(); - - String vfModuleModelUUID = modelInfo.getModelVersionId(); - for(VfModuleCustomization vf : list) { - VfModuleCustomization vfmCustom; - if(vfModuleModelUUID != null){ - vfmCustom = catalogDbClient.getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID(vf.getModelCustomizationUUID(), vfModuleModelUUID); - if(vfmCustom != null){ - vfModule = vfmCustom.getVfModule(); - } - }else{ - vfmCustom = catalogDbClient.getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID()); - if(vfmCustom != null){ - vfModule = vfmCustom.getVfModule(); - }else{ - vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion(relatedInstanceModelInvariantId, relatedInstanceVersion); - } - } - - if(vfModule != null) { - modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID()); - modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID()); - break; - } - } - } - - if(vfmc == null && vfModule == null) { - throw new ValidationException("vfModuleCustomization"); - } else if (vfModule == null && vfmc != null) { - vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in VfModuleCustomization table - } - - if(modelInfo.getModelVersionId() == null) { - modelInfo.setModelVersionId(vfModule.getModelUUID()); - } - - - recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(vfModule.getModelUUID(), vnfComponentType, action.toString()); - if(recipe == null){ - List<VfModule> vfModuleRecords= catalogDbClient.getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID()); - if(!vfModuleRecords.isEmpty()){ - for(VfModule record : vfModuleRecords){ - recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(record.getModelUUID(), vnfComponentType, action.toString()); - if(recipe != null){ - break; - } - } - } - } - if(recipe == null) { - recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(defaultSource, vnfComponentType, action.toString()); - if (recipe == null) { - recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction(vnfComponentType, action.toString()); - } - - if(recipe == null) { - return null; - } - } - } - } else { - - if(modelInfo.getModelType().equals(ModelType.vnf)) { - recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); - if (recipe == null) { - return null; - } - } else { - recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction(defaultSource, vnfComponentType, action.toString()); - - if (recipe == null) { - return null; - } - } - } - - return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ()); - } - + } + } + + VnfRecipe vnfRecipe = null; + + if (vrc != null) { + String nfRole = vrc.getNfRole(); + if (nfRole != null) { + vnfRecipe = + catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(vrc.getNfRole(), action.toString()); + } + } + + if (vnfRecipe == null) { + vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); + } + + if (vnfRecipe == null) { + return null; + } + + return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout()); + } else { + /* + * (v5-v7) If modelInfo.modelCustomizationId is NOT provided (because it is a pre-1702 ASDC model or + * pre-v3), then modelInfo.modelCustomizationName must have // been provided (else create request should + * be rejected). APIH should use the relatedInstance.modelInfo[vnf].modelVersionId + + * modelInfo[vnf].modelCustomizationName // to join vnf_to_resource_customizations with + * vf_resource_customization to confirm a vf_resource_customization.model_customization_uuid record + * exists. // Once the vnfs model_customization_uuid has been obtained, use it to find all vfModule + * customizations for that vnf customization in the vnf_res_custom_to_vf_module_custom join table. // + * For each vf_module_cust_model_customization_uuid value returned, use that UUID to query + * vf_module_customization table along with modelInfo[vfModule|volumeGroup].modelVersionId to // confirm + * record matches request data (and to identify the modelCustomizationId associated with the vfModule in + * the request). This means taking each record found // in vf_module_customization and looking up in + * vf_module (using vf_module_customization’s FK into vf_module) to find a match on + * MODEL_INVARIANT_UUID (modelInvariantId) // and MODEL_VERSION (modelVersion). + */ + VfModuleCustomization vfmc = null; + VnfResource vnfr; + VnfResourceCustomization vnfrc; + VfModule vfModule = null; + + if (modelInfo.getModelCustomizationId() != null) { + vfmc = catalogDbClient + .getVfModuleCustomizationByModelCuztomizationUUID(modelInfo.getModelCustomizationId()); + } else { + vnfr = catalogDbClient.getVnfResourceByModelUUID(relatedInstanceModelVersionId); + if (vnfr == null) { + vnfr = catalogDbClient.getFirstVnfResourceByModelInvariantUUIDAndModelVersion( + relatedInstanceModelInvariantId, relatedInstanceVersion); + } + vnfrc = catalogDbClient.getFirstVnfResourceCustomizationByModelInstanceNameAndVnfResources( + relatedInstanceModelCustomizationName, vnfr); + + List<VfModuleCustomization> list = vnfrc.getVfModuleCustomizations(); + + String vfModuleModelUUID = modelInfo.getModelVersionId(); + for (VfModuleCustomization vf : list) { + VfModuleCustomization vfmCustom; + if (vfModuleModelUUID != null) { + vfmCustom = catalogDbClient + .getVfModuleCustomizationByModelCustomizationUUIDAndVfModuleModelUUID( + vf.getModelCustomizationUUID(), vfModuleModelUUID); + if (vfmCustom != null) { + vfModule = vfmCustom.getVfModule(); + } + } else { + vfmCustom = catalogDbClient + .getVfModuleCustomizationByModelCuztomizationUUID(vf.getModelCustomizationUUID()); + if (vfmCustom != null) { + vfModule = vfmCustom.getVfModule(); + } else { + vfModule = catalogDbClient.getVfModuleByModelInvariantUUIDAndModelVersion( + relatedInstanceModelInvariantId, relatedInstanceVersion); + } + } + + if (vfModule != null) { + modelInfo.setModelCustomizationId(vf.getModelCustomizationUUID()); + modelInfo.setModelCustomizationUuid(vf.getModelCustomizationUUID()); + break; + } + } + } + + if (vfmc == null && vfModule == null) { + throw new ValidationException("vfModuleCustomization"); + } else if (vfModule == null && vfmc != null) { + vfModule = vfmc.getVfModule(); // can't be null as vfModuleModelUUID is not-null property in + // VfModuleCustomization table + } + + if (modelInfo.getModelVersionId() == null) { + modelInfo.setModelVersionId(vfModule.getModelUUID()); + } + + + recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + vfModule.getModelUUID(), vnfComponentType, action.toString()); + if (recipe == null) { + List<VfModule> vfModuleRecords = catalogDbClient + .getVfModuleByModelInvariantUUIDOrderByModelVersionDesc(vfModule.getModelInvariantUUID()); + if (!vfModuleRecords.isEmpty()) { + for (VfModule record : vfModuleRecords) { + recipe = catalogDbClient + .getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + record.getModelUUID(), vnfComponentType, action.toString()); + if (recipe != null) { + break; + } + } + } + } + if (recipe == null) { + recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + defaultSource, vnfComponentType, action.toString()); + if (recipe == null) { + recipe = catalogDbClient.getFirstVnfComponentsRecipeByVnfComponentTypeAndAction( + vnfComponentType, action.toString()); + } + + if (recipe == null) { + return null; + } + } + } + } else { + + if (modelInfo.getModelType().equals(ModelType.vnf)) { + recipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); + if (recipe == null) { + return null; + } + } else { + recipe = catalogDbClient.getFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction( + defaultSource, vnfComponentType, action.toString()); + + if (recipe == null) { + return null; + } + } + } + + return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()); + } + private RecipeLookupResult getDefaultVnfUri(ServiceInstancesRequest sir, Actions action) { - - String defaultSource = getDefaultModel(sir); - VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); + String defaultSource = requestHandlerUtils.getDefaultModel(sir); - if (vnfRecipe == null) { - return null; - } + VnfRecipe vnfRecipe = catalogDbClient.getFirstVnfRecipeByNfRoleAndAction(defaultSource, action.toString()); - return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout()); - } + if (vnfRecipe == null) { + return null; + } + + return new RecipeLookupResult(vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout()); + } private RecipeLookupResult getNetworkUri(ServiceInstancesRequest sir, Actions action) throws ValidationException { - String defaultNetworkType = getDefaultModel(sir); - - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - String modelName = modelInfo.getModelName(); - Recipe recipe = null; - - if(modelInfo.getModelCustomizationId()!=null){ - NetworkResourceCustomization networkResourceCustomization = catalogDbClient.getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId()); - if(networkResourceCustomization != null){ - NetworkResource networkResource = networkResourceCustomization.getNetworkResource(); - if(networkResource!=null){ - if(modelInfo.getModelVersionId() == null) { - modelInfo.setModelVersionId(networkResource.getModelUUID()); - } - recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(), action.toString()); - }else{ - throw new ValidationException("no catalog entry found"); - } - }else if(action != Action.deleteInstance){ - throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true); - } - }else{ - //ok for version < 3 and action delete - if(modelName != null){ - recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString()); - } - } - - if(recipe == null){ - recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString()); - } - - return recipe !=null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null; - } - - private Optional<String> retrieveModelName(RequestParameters requestParams) { - String requestTestApi = null; - TestApi testApi = null; - - if (requestParams != null) { - requestTestApi = requestParams.getTestApi(); - } - - if (requestTestApi == null) { - if(requestParams != null && requestParams.getALaCarte() != null && !requestParams.getALaCarte()) { - requestTestApi = env.getProperty(CommonConstants.MACRO_TEST_API); - } else { - requestTestApi = env.getProperty(CommonConstants.ALACARTE_TEST_API); - } - } - - try { - testApi = TestApi.valueOf(requestTestApi); - return Optional.of(testApi.getModelName()); - } catch (Exception e) { - logger.warn("Catching the exception on the valueOf enum call and continuing", e); - throw new IllegalArgumentException("Invalid TestApi is provided", e); - } - } - - private String getDefaultModel(ServiceInstancesRequest sir) { - String defaultModel = sir.getRequestDetails().getRequestInfo().getSource() + "_DEFAULT"; - Optional<String> oModelName = retrieveModelName(sir.getRequestDetails().getRequestParameters()); - if (oModelName.isPresent()) { - defaultModel = oModelName.get(); - } - return defaultModel; + String defaultNetworkType = requestHandlerUtils.getDefaultModel(sir); + + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + String modelName = modelInfo.getModelName(); + Recipe recipe = null; + + if (modelInfo.getModelCustomizationId() != null) { + NetworkResourceCustomization networkResourceCustomization = catalogDbClient + .getNetworkResourceCustomizationByModelCustomizationUUID(modelInfo.getModelCustomizationId()); + if (networkResourceCustomization != null) { + NetworkResource networkResource = networkResourceCustomization.getNetworkResource(); + if (networkResource != null) { + if (modelInfo.getModelVersionId() == null) { + modelInfo.setModelVersionId(networkResource.getModelUUID()); + } + recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(networkResource.getModelName(), + action.toString()); + } else { + throw new ValidationException("no catalog entry found"); + } + } else if (action != Action.deleteInstance) { + throw new ValidationException("modelCustomizationId for networkResourceCustomization lookup", true); + } + } else { + // ok for version < 3 and action delete + if (modelName != null) { + recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(modelName, action.toString()); + } + } + + if (recipe == null) { + recipe = catalogDbClient.getFirstNetworkRecipeByModelNameAndAction(defaultNetworkType, action.toString()); + } + + return recipe != null ? new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout()) : null; } - - private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId, String requestUri) throws ApiException { - String serviceInstanceId = (instanceIdMap ==null)? null:instanceIdMap.get("serviceInstanceId"); - Boolean aLaCarte = null; - String apiVersion = version.substring(1); - boolean inProgress = false; - - long startTime = System.currentTimeMillis (); - ServiceInstancesRequest sir = null; - - sir = convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri); - String requestScope = deriveRequestScope(action,sir, requestUri); - InfraActiveRequests currentActiveReq = msoRequest.createRequestObject ( sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); - if(sir.getRequestDetails().getRequestParameters() != null){ - aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); - } - parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq); - setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); - String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); - - InfraActiveRequests dup = null; - - dup = duplicateCheck(action, instanceIdMap, startTime, msoRequest, instanceName,requestScope, currentActiveReq); - - if(dup != null){ - inProgress = camundaHistoryCheck(dup, currentActiveReq); - } - - if (instanceIdMap != null && dup != null && inProgress) { - buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, instanceName, requestScope, dup); - } - - ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); - RequestReferences referencesResponse = new RequestReferences(); - referencesResponse.setRequestId(requestId); - serviceResponse.setRequestReferences(referencesResponse); - - - String orchestrationUri = env.getProperty(CommonConstants.ALACARTE_ORCHESTRATION); - String timeOut = env.getProperty(CommonConstants.ALACARTE_RECIPE_TIMEOUT); - - if (StringUtils.isBlank(orchestrationUri) || StringUtils.isBlank(timeOut)) { - String error = StringUtils.isBlank(orchestrationUri) ? "ALaCarte Orchestration URI not found in properties" : "ALaCarte Recipe Timeout not found in properties"; - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); + + + private Response configurationRecipeLookup(String requestJSON, Action action, HashMap<String, String> instanceIdMap, + String version, String requestId, String requestUri) throws ApiException { + String serviceInstanceId = (instanceIdMap == null) ? null : instanceIdMap.get("serviceInstanceId"); + Boolean aLaCarte = null; + String apiVersion = version.substring(1); + boolean inProgress = false; + + long startTime = System.currentTimeMillis(); + ServiceInstancesRequest sir = null; + + sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, + requestId, requestUri); + String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri); + InfraActiveRequests currentActiveReq = + msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope); + if (sir.getRequestDetails().getRequestParameters() != null) { + aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte(); + } + requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, + currentActiveReq); + requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap); + String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName(); + + InfraActiveRequests dup = null; + + dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, 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); + } + + ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse(); + RequestReferences referencesResponse = new RequestReferences(); + referencesResponse.setRequestId(requestId); + serviceResponse.setRequestReferences(referencesResponse); + + + String orchestrationUri = env.getProperty(CommonConstants.ALACARTE_ORCHESTRATION); + String timeOut = env.getProperty(CommonConstants.ALACARTE_RECIPE_TIMEOUT); + + if (StringUtils.isBlank(orchestrationUri) || StringUtils.isBlank(timeOut)) { + String error = StringUtils.isBlank(orchestrationUri) ? "ALaCarte Orchestration URI not found in properties" + : "ALaCarte Recipe Timeout not found in properties"; + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + + ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + + requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage()); throw validateException; - - } - - serviceInstanceId = ""; - String configurationId = ""; - String pnfCorrelationId = ""; - - if(sir.getServiceInstanceId () != null){ - serviceInstanceId = sir.getServiceInstanceId (); - } - - if(sir.getConfigurationId() != null){ + + } + + serviceInstanceId = ""; + String configurationId = ""; + String pnfCorrelationId = ""; + + if (sir.getServiceInstanceId() != null) { + serviceInstanceId = sir.getServiceInstanceId(); + } + + if (sir.getConfigurationId() != null) { configurationId = sir.getConfigurationId(); } pnfCorrelationId = getPnfCorrelationId(sir); - 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(); - } - - if(!requestScope.equalsIgnoreCase(ModelType.service.name())){ - aLaCarte = true; - }else if(aLaCarte == null){ - aLaCarte = false; - } - RequestClientParameter requestClientParameter = null; - try { - requestClientParameter = new RequestClientParameter.Builder() - .setRequestId(requestId) - .setBaseVfModule(false) - .setRecipeTimeout(Integer.parseInt(timeOut)) - .setRequestAction(action.toString()) - .setServiceInstanceId(serviceInstanceId) - .setPnfCorrelationId(pnfCorrelationId) - .setConfigurationId(configurationId) - .setRequestDetails(mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) - .setApiVersion(apiVersion) - .setALaCarte(aLaCarte) - .setRequestUri(requestUri).build(); - } catch (IOException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - } - - return postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, requestScope); - } - - public String getRequestId(ContainerRequestContext requestContext) throws ValidateException { - String requestId = null; - if (requestContext.getProperty("requestId") != null) { - requestId = requestContext.getProperty("requestId").toString(); - } - if (UUIDChecker.isValidUUID(requestId)) { - return requestId; - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - ValidateException validateException = new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; - } + 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(); + } + + if (!requestScope.equalsIgnoreCase(ModelType.service.name())) { + aLaCarte = true; + } else if (aLaCarte == null) { + aLaCarte = false; + } + RequestClientParameter requestClientParameter = null; + try { + requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId).setBaseVfModule(false) + .setRecipeTimeout(Integer.parseInt(timeOut)).setRequestAction(action.toString()) + .setServiceInstanceId(serviceInstanceId).setPnfCorrelationId(pnfCorrelationId) + .setConfigurationId(configurationId) + .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action)) + .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) + .build(); + } + + return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, orchestrationUri, + requestScope); } - public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage) throws RequestDbFailureException{ - if ((status == Status.FAILED) || (status == Status.COMPLETE)) { - aq.setStatusMessage (errorMessage); - aq.setProgress(new Long(100)); - aq.setRequestStatus(status.toString()); - Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis()); - aq.setEndTime (endTimeStamp); - try{ - infraActiveRequestsClient.save(aq); - }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(); - } - } - } - protected String getServiceType(String requestScope, ServiceInstancesRequest sir, Boolean aLaCarteFlag){ - String serviceType = null; - if(requestScope.equalsIgnoreCase(ModelType.service.toString())){ - String defaultServiceModelName = getDefaultModel(sir); - org.onap.so.db.catalog.beans.Service serviceRecord; - if(aLaCarteFlag){ - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - } - }else{ - serviceRecord = catalogDbClient.getServiceByID(sir.getRequestDetails().getModelInfo().getModelVersionId()); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - }else{ - serviceRecord = catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName); - if(serviceRecord != null){ - serviceType = serviceRecord.getServiceType(); - } - } - } - }else{ - serviceType = msoRequest.getServiceInstanceType(sir, requestScope); - } - return serviceType; - } - protected String setServiceInstanceId(String requestScope, ServiceInstancesRequest sir){ - if(sir.getServiceInstanceId () != null){ - return sir.getServiceInstanceId (); - }else if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())){ - RelatedInstanceList[] relatedInstances = sir.getRequestDetails().getRelatedInstanceList(); - if(relatedInstances != null){ - for(RelatedInstanceList relatedInstanceList : relatedInstances){ - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - if(relatedInstance.getModelInfo().getModelType() == ModelType.service){ - return relatedInstance.getInstanceId(); - } - } - } - } - return null; - } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java index 625df66d2a..8b25018ee7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/SubsystemHealthcheckResponse.java @@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra; import java.io.Serializable; public class SubsystemHealthcheckResponse implements Serializable { - private static final long serialVersionUID = 1L; - private String status; + private static final long serialVersionUID = 1L; + private String status; - public String getStatus() { - return status; - } + public String getStatus() { + return status; + } - public void setStatus(String status) { - this.status = status; - } + public void setStatus(String status) { + this.status = status; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java index b7bd28f45f..7bd7f95286 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TasksHandler.java @@ -26,7 +26,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import javax.transaction.Transactional; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -34,7 +33,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; - import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONArray; @@ -48,7 +46,6 @@ import org.onap.so.apihandler.common.ResponseHandler; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tasksbeans.TaskList; import org.onap.so.apihandlerinfra.tasksbeans.TaskVariableValue; @@ -56,264 +53,279 @@ import org.onap.so.apihandlerinfra.tasksbeans.TaskVariables; import org.onap.so.apihandlerinfra.tasksbeans.TasksGetResponse; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Path("onap/so/infra/tasks") -@Api(value="onap/so/infra/tasks",description="Queries of Manual Tasks") +@Api(value = "onap/so/infra/tasks", description = "Queries of Manual Tasks") @Component public class TasksHandler { private static Logger logger = LoggerFactory.getLogger(TasksHandler.class); - + @Value("${mso.camunda.rest.task.uri}") private String requestUrl; - - @Autowired - private RequestClientFactory reqClientFactory; - @Autowired - private ResponseBuilder builder; - + @Autowired + private RequestClientFactory reqClientFactory; + + @Autowired + private ResponseBuilder builder; + @Path("/{version:[vV]1}") @GET - @ApiOperation(value="Finds Manual Tasks",response=Response.class) + @ApiOperation(value = "Finds Manual Tasks", response = Response.class) @Transactional - public Response queryFilters (@QueryParam("taskId") String taskId, - @QueryParam("originalRequestId") String originalRequestId, - @QueryParam("subscriptionServiceType") String subscriptionServiceType, - @QueryParam("nfRole") String nfRole, - @QueryParam("buildingBlockName") String buildingBlockName, - @QueryParam("originalRequestDate") String originalRequestDate, - @QueryParam("originalRequestorId") String originalRequestorId, - @PathParam("version") String version) throws ApiException { - Response responseBack = null; - String apiVersion = version.substring(1); + public Response queryFilters(@QueryParam("taskId") String taskId, + @QueryParam("originalRequestId") String originalRequestId, + @QueryParam("subscriptionServiceType") String subscriptionServiceType, @QueryParam("nfRole") String nfRole, + @QueryParam("buildingBlockName") String buildingBlockName, + @QueryParam("originalRequestDate") String originalRequestDate, + @QueryParam("originalRequestorId") String originalRequestorId, @PathParam("version") String version) + throws ApiException { + Response responseBack = null; + String apiVersion = version.substring(1); // Prepare the query string to /task interface TaskVariables tv = new TaskVariables(); - + List<TaskVariableValue> tvvList = new ArrayList<>(); - + if (originalRequestId != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("originalRequestId"); - tvv.setValue(originalRequestId); - tvv.setOperator("eq"); - tvvList.add(tvv); + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("originalRequestId"); + tvv.setValue(originalRequestId); + tvv.setOperator("eq"); + tvvList.add(tvv); } if (subscriptionServiceType != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("subscriptionServiceType"); - tvv.setValue(subscriptionServiceType); - tvv.setOperator("eq"); - tvvList.add(tvv); + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("subscriptionServiceType"); + tvv.setValue(subscriptionServiceType); + tvv.setOperator("eq"); + tvvList.add(tvv); } if (nfRole != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("nfRole"); - tvv.setValue(nfRole); - tvv.setOperator("eq"); - tvvList.add(tvv); + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("nfRole"); + tvv.setValue(nfRole); + tvv.setOperator("eq"); + tvvList.add(tvv); } if (buildingBlockName != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("buildingBlockName"); - tvv.setValue(buildingBlockName); - tvv.setOperator("eq"); - tvvList.add(tvv); + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("buildingBlockName"); + tvv.setValue(buildingBlockName); + tvv.setOperator("eq"); + tvvList.add(tvv); } if (originalRequestDate != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("originalRequestDate"); - tvv.setValue(originalRequestDate); - tvv.setOperator("eq"); - tvvList.add(tvv); + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("originalRequestDate"); + tvv.setValue(originalRequestDate); + tvv.setOperator("eq"); + tvvList.add(tvv); } if (originalRequestorId != null) { - TaskVariableValue tvv = new TaskVariableValue(); - tvv.setName("originalRequestorId"); - tvv.setValue(originalRequestorId); - tvv.setOperator("eq"); - tvvList.add(tvv); - } - + TaskVariableValue tvv = new TaskVariableValue(); + tvv.setName("originalRequestorId"); + tvv.setValue(originalRequestorId); + tvv.setOperator("eq"); + tvvList.add(tvv); + } + tv.setTaskVariables(tvvList); - + RequestClient requestClient = null; - - HttpResponse response = null; - - try { - requestClient = reqClientFactory.getRequestClient(requestUrl); - // Capture audit event - ObjectMapper mapper = new ObjectMapper(); - String camundaJsonReq = mapper.writeValueAsString(tv); - response = requestClient.post(camundaJsonReq); - - } 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; - } catch(IOException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build(); - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY),HttpStatus.SC_BAD_GATEWAY,ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - throw bpmnFailureException; - } - TasksGetResponse trr = new TasksGetResponse(); - List<TaskList> taskList = new ArrayList<>(); - - ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ()); - int bpelStatus = respHandler.getStatus (); - if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { - String respBody = respHandler.getResponseBody(); - if (respBody != null) { - JSONArray data = new JSONArray(respBody); - - for (int i=0; i<data.length();i++) { - JSONObject taskEntry = data.getJSONObject(i); - String id = taskEntry.getString("id"); - if (taskId != null && !taskId.equals(id)) { - continue; - } - // Get variables info for each task ID - TaskList taskListEntry = null; - taskListEntry = getTaskInfo(id); - - taskList.add(taskListEntry); - - } - trr.setTaskList(taskList); - } - - } else { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError).build(); - - - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - throw bpmnFailureException; - } - - String jsonResponse = null; - try { - ObjectMapper mapper = new ObjectMapper(); - jsonResponse = mapper.writeValueAsString(trr); - } - 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; - } - - return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion); - } + + HttpResponse response = null; + + try { + requestClient = reqClientFactory.getRequestClient(requestUrl); + // Capture audit event + ObjectMapper mapper = new ObjectMapper(); + String camundaJsonReq = mapper.writeValueAsString(tv); + response = requestClient.post(camundaJsonReq); + + } 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; + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) + .build(); + BPMNFailureException bpmnFailureException = + new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw bpmnFailureException; + } + TasksGetResponse trr = new TasksGetResponse(); + List<TaskList> taskList = new ArrayList<>(); + + ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + if (bpelStatus == HttpStatus.SC_NO_CONTENT || bpelStatus == HttpStatus.SC_ACCEPTED) { + String respBody = respHandler.getResponseBody(); + if (respBody != null) { + JSONArray data = new JSONArray(respBody); + + for (int i = 0; i < data.length(); i++) { + JSONObject taskEntry = data.getJSONObject(i); + String id = taskEntry.getString("id"); + if (taskId != null && !taskId.equals(id)) { + continue; + } + // Get variables info for each task ID + TaskList taskListEntry = null; + taskListEntry = getTaskInfo(id); + + taskList.add(taskListEntry); + + } + trr.setTaskList(taskList); + } + + } else { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.BusinessProcesssError) + .build(); + + + BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), + bpelStatus, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + + throw bpmnFailureException; + } + + String jsonResponse = null; + try { + ObjectMapper mapper = new ObjectMapper(); + jsonResponse = mapper.writeValueAsString(trr); + } 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; + } + + return builder.buildResponse(HttpStatus.SC_ACCEPTED, "", jsonResponse, apiVersion); + } // Makes a GET call to Camunda to get variables for this task - private TaskList getTaskInfo(String taskId) throws ApiException{ - TaskList taskList; - String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString(); - HttpResponse getResponse; - - RequestClient requestClient = reqClientFactory.getRequestClient (getRequestUrl); - // Capture audit event - try { - getResponse = requestClient.get(); - }catch(IOException e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build(); - BPMNFailureException validateException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - throw validateException; - } - ResponseHandler respHandler = new ResponseHandler (getResponse, requestClient.getType ()); - int bpelStatus = respHandler.getStatus (); - if (bpelStatus == HttpStatus.SC_ACCEPTED) { - String respBody = respHandler.getResponseBody(); - if (respBody != null) { - taskList = buildTaskList(taskId, respBody); - } - else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build(); + private TaskList getTaskInfo(String taskId) throws ApiException { + TaskList taskList; + String getRequestUrl = UriBuilder.fromUri(requestUrl).path(taskId).path("variables").build().toString(); + HttpResponse getResponse; + + RequestClient requestClient = reqClientFactory.getRequestClient(getRequestUrl); + // Capture audit event + try { + getResponse = requestClient.get(); + } catch (IOException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) + .build(); + BPMNFailureException validateException = + new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw validateException; + } + ResponseHandler respHandler = new ResponseHandler(getResponse, requestClient.getType()); + int bpelStatus = respHandler.getStatus(); + if (bpelStatus == HttpStatus.SC_ACCEPTED) { + String respBody = respHandler.getResponseBody(); + if (respBody != null) { + taskList = buildTaskList(taskId, respBody); + } else { + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, + ErrorCode.AvailabilityError).build(); + BPMNFailureException bpmnFailureException = + new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), + HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(HttpStatus.SC_BAD_GATEWAY), HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw bpmnFailureException; + } - throw bpmnFailureException; - } - - } - else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError).build(); + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, ErrorCode.AvailabilityError) + .build(); + BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), + bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); - BPMNFailureException bpmnFailureException = new BPMNFailureException.Builder(String.valueOf(bpelStatus), bpelStatus, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build(); + throw bpmnFailureException; + } + + return taskList; - throw bpmnFailureException; - } - - return taskList; - } - + private TaskList buildTaskList(String taskId, String respBody) throws JSONException { - TaskList taskList = new TaskList(); - JSONObject variables = new JSONObject(respBody); - - taskList.setTaskId(taskId); - taskList.setType(getOptVariableValue(variables, "type")); - taskList.setNfRole(getOptVariableValue(variables, "nfRole")); - taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType")); - taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId")); - taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId")); - taskList.setErrorSource(getOptVariableValue(variables, "errorSource")); - taskList.setErrorCode(getOptVariableValue(variables, "errorCode")); - taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage")); - taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName")); - taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep")); - taskList.setDescription(getOptVariableValue(variables, "description")); - taskList.setTimeout(getOptVariableValue(variables, "timeout")); - - String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase(); - List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*")); - taskList.setValidResponses(items); - - return taskList; + TaskList taskList = new TaskList(); + JSONObject variables = new JSONObject(respBody); + + taskList.setTaskId(taskId); + taskList.setType(getOptVariableValue(variables, "type")); + taskList.setNfRole(getOptVariableValue(variables, "nfRole")); + taskList.setSubscriptionServiceType(getOptVariableValue(variables, "subscriptionServiceType")); + taskList.setOriginalRequestId(getOptVariableValue(variables, "originalRequestId")); + taskList.setOriginalRequestorId(getOptVariableValue(variables, "originalRequestorId")); + taskList.setErrorSource(getOptVariableValue(variables, "errorSource")); + taskList.setErrorCode(getOptVariableValue(variables, "errorCode")); + taskList.setErrorMessage(getOptVariableValue(variables, "errorMessage")); + taskList.setBuildingBlockName(getOptVariableValue(variables, "buildingBlockName")); + taskList.setBuildingBlockStep(getOptVariableValue(variables, "buildingBlockStep")); + taskList.setDescription(getOptVariableValue(variables, "description")); + taskList.setTimeout(getOptVariableValue(variables, "timeout")); + + String validResponses = getOptVariableValue(variables, "validResponses").toLowerCase(); + List<String> items = Arrays.asList(validResponses.split("\\s*,\\s*")); + taskList.setValidResponses(items); + + return taskList; } - + private String getOptVariableValue(JSONObject variables, String name) throws JSONException { - String variableEntry = variables.optString(name); - String value = ""; - if (!variableEntry.isEmpty()) { - JSONObject variableEntryJson = new JSONObject(variableEntry); - value = variableEntryJson.optString("value"); - } - return value; + String variableEntry = variables.optString(name); + String value = ""; + if (!variableEntry.isEmpty()) { + JSONObject variableEntryJson = new JSONObject(variableEntry); + value = variableEntryJson.optString("value"); + } + return value; } - - + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java index d2e96562ea..7497617e4d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/TestApi.java @@ -21,17 +21,16 @@ package org.onap.so.apihandlerinfra; public enum TestApi { - GR_API("GR-API-DEFAULT"), - VNF_API("VNF-API-DEFAULT"); - - private final String modelName; - - private TestApi(String modelName) { - this.modelName = modelName; - } - - public String getModelName() { - return modelName; - } + GR_API("GR-API-DEFAULT"), VNF_API("VNF-API-DEFAULT"); + + private final String modelName; + + private TestApi(String modelName) { + this.modelName = modelName; + } + + public String getModelName() { + return modelName; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java index aca0fa511e..97b80098e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WebSecurityConfigImpl.java @@ -34,24 +34,21 @@ import org.springframework.util.StringUtils; @Configuration("att-security-config") @Order(2) public class WebSecurityConfigImpl extends WebSecurityConfig { - - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.csrf().disable() - .authorizeRequests() - .antMatchers("/manage/health","/manage/info").permitAll() - .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(),",").toString()) - .and() - .httpBasic(); - - } - - @Override - public void configure(WebSecurity web) throws Exception { - super.configure(web); - StrictHttpFirewall firewall = new MSOSpringFirewall(); - web.httpFirewall(firewall); - } + + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable().authorizeRequests().antMatchers("/manage/health", "/manage/info").permitAll() + .antMatchers("/**").hasAnyRole(StringUtils.collectionToDelimitedString(getRoles(), ",").toString()) + .and().httpBasic(); + + } + + @Override + public void configure(WebSecurity web) throws Exception { + super.configure(web); + StrictHttpFirewall firewall = new MSOSpringFirewall(); + web.httpFirewall(firewall); + } } 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 new file mode 100644 index 0000000000..c480bdfbd3 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandler.java @@ -0,0 +1,222 @@ +/*- + * ============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.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 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.db.catalog.client.CatalogDbClient; +import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.MessageEnum; +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.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("onap/so/infra/workflowSpecifications") +@Api(value = "onap/so/infra/workflowSpecifications", description = "Queries of Workflow Specifications") +@Component +public class WorkflowSpecificationsHandler { + + @Autowired + private ResponseBuilder builder; + + @Autowired + private CatalogDbClient catalogDbClient; + + private static final String ARTIFACT_TYPE_WORKFLOW = "workflow"; + + @Path("/{version:[vV]1}/workflows") + @GET + @ApiOperation(value = "Finds Workflow Specifications", response = Response.class) + @Transactional + + public Response queryWorkflowSpecifications(@QueryParam("vnfModelVersionId") String vnfModelVersionId, + @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); + WorkflowSpecifications workflowSpecifications = mapWorkflowsToWorkflowSpecifications(workflows); + + String jsonResponse = null; + 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; + } + + return builder.buildResponse(HttpStatus.SC_OK, "", jsonResponse, apiVersion); + } + + protected WorkflowSpecifications mapWorkflowsToWorkflowSpecifications(List<Workflow> workflows) { + if (workflows == null || workflows.size() == 0) { + return null; + } + WorkflowSpecifications workflowSpecifications = new WorkflowSpecifications(); + List<WorkflowSpecificationList> workflowSpecificationList = new ArrayList<WorkflowSpecificationList>(); + + for (Workflow workflow : workflows) { + WorkflowSpecificationList workflowSpecificationListItem = new WorkflowSpecificationList(); + WorkflowSpecification workflowSpecification = new WorkflowSpecification(); + workflowSpecification.setArtifactInfo(buildArtifactInfo(workflow)); + workflowSpecification.setActivitySequence(buildActivitySequence(workflow)); + workflowSpecification.setWorkflowInputParameters(buildWorkflowInputParameters(workflow)); + workflowSpecificationListItem.setWorkflowSpecification(workflowSpecification); + workflowSpecificationList.add(workflowSpecificationListItem); + } + workflowSpecifications.setWorkflowSpecificationList(workflowSpecificationList); + return workflowSpecifications; + } + + private ArtifactInfo buildArtifactInfo(Workflow workflow) { + ArtifactInfo artifactInfo = new ArtifactInfo(); + artifactInfo.setArtifactType(ARTIFACT_TYPE_WORKFLOW); + artifactInfo.setArtifactUuid(workflow.getArtifactUUID()); + artifactInfo.setArtifactName(workflow.getArtifactName()); + if (workflow.getVersion() != null) { + artifactInfo.setArtifactVersion(workflow.getVersion().toString()); + } + artifactInfo.setArtifactDescription(workflow.getDescription()); + artifactInfo.setWorkflowName(workflow.getName()); + artifactInfo.setOperationName(workflow.getOperationName()); + artifactInfo.setWorkflowSource(workflow.getSource()); + artifactInfo.setWorkflowResourceTarget(workflow.getResourceTarget()); + return artifactInfo; + } + + private List<ActivitySequence> buildActivitySequence(Workflow workflow) { + List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence(); + if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) { + return null; + } + List<ActivitySequence> activitySequences = new ArrayList<ActivitySequence>(); + for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) { + if (workflowActivitySpecSequence != null) { + ActivitySpec activitySpec = workflowActivitySpecSequence.getActivitySpec(); + if (activitySpec != null) { + ActivitySequence activitySequence = new ActivitySequence(); + activitySequence.setName(activitySpec.getName()); + activitySequence.setDescription(activitySpec.getDescription()); + activitySequences.add(activitySequence); + } + } + } + return activitySequences; + } + + private List<WorkflowInputParameter> buildWorkflowInputParameters(Workflow workflow) { + List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = workflow.getWorkflowActivitySpecSequence(); + if (workflowActivitySpecSequences == null || workflowActivitySpecSequences.size() == 0) { + return null; + } + Map<String, WorkflowInputParameter> workflowInputParameterMap = new HashMap<String, WorkflowInputParameter>(); + for (WorkflowActivitySpecSequence workflowActivitySpecSequence : workflowActivitySpecSequences) { + if (workflowActivitySpecSequence != null) { + ActivitySpec activitySpec = workflowActivitySpecSequence.getActivitySpec(); + if (activitySpec != null) { + List<ActivitySpecUserParameters> activitySpecUserParameters = + activitySpec.getActivitySpecUserParameters(); + if (activitySpecUserParameters != null && activitySpecUserParameters.size() != 0) { + for (ActivitySpecUserParameters activitySpecUserParameter : activitySpecUserParameters) { + UserParameters userParameter = activitySpecUserParameter.getUserParameters(); + if (userParameter != null) { + WorkflowInputParameter workflowInputParameter = + buildWorkflowInputParameter(userParameter); + workflowInputParameterMap.put(userParameter.getName(), workflowInputParameter); + } + } + } + } + } + } + + if (workflowInputParameterMap.size() == 0) { + return null; + } + List<WorkflowInputParameter> workflowInputParameterList = + workflowInputParameterMap.values().stream().collect(Collectors.toList()); + return workflowInputParameterList; + } + + private WorkflowInputParameter buildWorkflowInputParameter(UserParameters userParameter) { + WorkflowInputParameter workflowInputParameter = new WorkflowInputParameter(); + workflowInputParameter.setLabel(userParameter.getLabel()); + workflowInputParameter.setInputType(userParameter.getType()); + workflowInputParameter.setRequired(userParameter.getIsRequried()); + workflowInputParameter.setSoFieldName(userParameter.getName()); + workflowInputParameter.setSoPayloadLocation(userParameter.getPayloadLocation()); + workflowInputParameter.setValidation(buildValidationList(userParameter)); + return workflowInputParameter; + } + + private List<Validation> buildValidationList(UserParameters userParameter) { + List<Validation> validationList = null; + if (userParameter.getMaxLength() != null || userParameter.getAllowableChars() != null) { + validationList = new ArrayList<Validation>(); + Validation validation = new Validation(); + if (userParameter.getMaxLength() != null) { + validation.setMaxLength(userParameter.getMaxLength().toString()); + } + validation.setAllowableChars(userParameter.getAllowableChars()); + validationList.add(validation); + } + return validationList; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java index 3aa54bdfb3..4d81695e55 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/CatalogDBConfig.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.configuration; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -40,41 +39,31 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "entityManagerFactory", - basePackages = {"org.onap.so.db.catalog.data.repository"} - ) +@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", + basePackages = {"org.onap.so.db.catalog.data.repository"}) @Profile({"!test"}) public class CatalogDBConfig { - - @Primary - @Bean(name = "dataSource") - @ConfigurationProperties(prefix = "spring.datasource") - public DataSource dataSource() { - return DataSourceBuilder.create().build(); - } - @Primary - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("dataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.catalog.beans") - .persistenceUnit("catalogDB") - .build(); - } + @Primary + @Bean(name = "dataSource") + @ConfigurationProperties(prefix = "spring.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create().build(); + } + + @Primary + @Bean(name = "entityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("dataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB") + .build(); + } - @Primary - @Bean(name = "transactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("entityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Primary + @Bean(name = "transactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java index 908b864536..1bc54ffe7b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/configuration/RequestDBConfig.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.configuration; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -39,40 +38,30 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager", - basePackages = { "org.onap.so.db.request.data.repository"} - ) +@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory", + transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"}) @Profile({"!test"}) public class RequestDBConfig { - @Bean(name = "requestDataSource") - @ConfigurationProperties(prefix = "request.datasource") - public DataSource dataSource() { - return DataSourceBuilder.create().build(); - } + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "request.datasource") + public DataSource dataSource() { + return DataSourceBuilder.create().build(); + } - @Bean(name = "requestEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("requestDataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.request.beans") - .persistenceUnit("requestDB") - .build(); - } + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB") + .build(); + } - @Bean(name = "requestTransactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("requestEntityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java index 89482f7879..2bca89f980 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/CompareModelsRequest.java @@ -25,44 +25,44 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class CompareModelsRequest { - private String globalSubscriberId; - - private String serviceType; + private String globalSubscriberId; - private String modelInvariantIdTarget; - - private String modelVersionIdTarget; + private String serviceType; + private String modelInvariantIdTarget; - public String getGlobalSubscriberId() { - return globalSubscriberId; - } + private String modelVersionIdTarget; - public void setGlobalSubscriberId(String globalSubscriberId) { - this.globalSubscriberId = globalSubscriberId; - } - public String getServiceType() { - return serviceType; - } + public String getGlobalSubscriberId() { + return globalSubscriberId; + } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } - public String getModelInvariantIdTarget() { - return modelInvariantIdTarget; - } + public String getServiceType() { + return serviceType; + } - public void setModelInvariantIdTarget(String modelInvariantIdTarget) { - this.modelInvariantIdTarget = modelInvariantIdTarget; - } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } - public String getModelVersionIdTarget() { - return modelVersionIdTarget; - } + public String getModelInvariantIdTarget() { + return modelInvariantIdTarget; + } - public void setModelVersionIdTarget(String modelVersionIdTarget) { - this.modelVersionIdTarget = modelVersionIdTarget; - } + public void setModelInvariantIdTarget(String modelInvariantIdTarget) { + this.modelInvariantIdTarget = modelInvariantIdTarget; + } + + public String getModelVersionIdTarget() { + return modelVersionIdTarget; + } + + public void setModelVersionIdTarget(String modelVersionIdTarget) { + this.modelVersionIdTarget = modelVersionIdTarget; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java index a2b410f57f..c620c379ec 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcResp.java @@ -25,13 +25,13 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class DelE2ESvcResp { - private String operationId; + private String operationId; - public String getOperationId() { - return operationId; - } + public String getOperationId() { + return operationId; + } - public void setOperationId(String operationId) { - this.operationId = operationId; - } + public void setOperationId(String operationId) { + this.operationId = operationId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java index 6dfa4b6587..6c8ac55523 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EParameters.java @@ -23,41 +23,40 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.HashMap; import java.util.List; import java.util.Map; -@JsonIgnoreProperties({ "additionalProperties" }) +@JsonIgnoreProperties({"additionalProperties"}) public class E2EParameters { - @JsonProperty("locationConstraints") - List<LocationConstraint> locationConstraints; + @JsonProperty("locationConstraints") + List<LocationConstraint> locationConstraints; + + @JsonProperty("resources") + private List<ResourceRequest> resources; - @JsonProperty("resources") - private List<ResourceRequest> resources; + @JsonProperty("requestInputs") + private HashMap<String, ?> requestInputs; - @JsonProperty("requestInputs") - private HashMap<String, ?> requestInputs; + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<>(); - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); + public Map<String, Object> getAdditionalProperties() { + return additionalProperties; + } - public Map<String, Object> getAdditionalProperties() { - return additionalProperties; - } + public void setAdditionalProperties(Map<String, Object> additionalProperties) { + this.additionalProperties = additionalProperties; + } - public void setAdditionalProperties(Map<String, Object> additionalProperties) { - this.additionalProperties = additionalProperties; - } - /** * @return Returns the resources. */ public List<ResourceRequest> getResources() { return resources; } - + /** * @param resources The resources to set. */ @@ -73,11 +72,11 @@ public class E2EParameters { this.locationConstraints = locationConstraints; } - public HashMap<String, ?> getRequestInputs() { - return requestInputs; - } + public HashMap<String, ?> getRequestInputs() { + return requestInputs; + } - public void setRequestInputs(HashMap<String, ?> requestInputs) { - this.requestInputs = requestInputs; - } + public void setRequestInputs(HashMap<String, ?> requestInputs) { + this.requestInputs = requestInputs; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java index dfe94dd2f0..77abbbfa9a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequest.java @@ -22,92 +22,91 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import java.sql.Timestamp; - import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class E2ERequest { - protected String operationId; - protected String operation; - protected String result; - protected String reason; - protected String userId; - protected String operationContent; - protected long progress; - protected String operateAt; - protected String finishedAt; - - public String getOperationId() { - return operationId; - } - - public void setOperationId(String operationId) { - this.operationId = operationId; - } - - public String getOperation() { - return operation; - } - - public void setOperation(String operation) { - this.operation = operation; - } - - public String getResult() { - return result; - } - - public void setResult(String result) { - this.result = result; - } - - public String getReason() { - return reason; - } - - public void setReason(String reason) { - this.reason = reason; - } - - public String getUserId() { - return userId; - } - - public void setUserId(String userId) { - this.userId = userId; - } - - public String getOperationContent() { - return operationContent; - } - - public void setOperationContent(String operationContent) { - this.operationContent = operationContent; - } - - public long getProgress() { - return progress; - } - - public void setProgress(long progress) { - this.progress = progress; - } - - public String getOperateAt() { - return operateAt; - } - - public void setOperateAt(String operateAt) { - this.operateAt = operateAt; - } - - public String getFinishedAt() { - return finishedAt; - } - - public void setFinishedAt(String finishedAt) { - this.finishedAt = finishedAt; - } + protected String operationId; + protected String operation; + protected String result; + protected String reason; + protected String userId; + protected String operationContent; + protected long progress; + protected String operateAt; + protected String finishedAt; + + public String getOperationId() { + return operationId; + } + + public void setOperationId(String operationId) { + this.operationId = operationId; + } + + public String getOperation() { + return operation; + } + + public void setOperation(String operation) { + this.operation = operation; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getReason() { + return reason; + } + + public void setReason(String reason) { + this.reason = reason; + } + + public String getUserId() { + return userId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public String getOperationContent() { + return operationContent; + } + + public void setOperationContent(String operationContent) { + this.operationContent = operationContent; + } + + public long getProgress() { + return progress; + } + + public void setProgress(long progress) { + this.progress = progress; + } + + public String getOperateAt() { + return operateAt; + } + + public void setOperateAt(String operateAt) { + this.operateAt = operateAt; + } + + public String getFinishedAt() { + return finishedAt; + } + + public void setFinishedAt(String finishedAt) { + this.finishedAt = finishedAt; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java index 9f6a9b438c..f969674ed1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EService.java @@ -22,99 +22,98 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import java.util.HashMap; import java.util.Map; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -@JsonIgnoreProperties({ "additionalProperties" }) +@JsonIgnoreProperties({"additionalProperties"}) public class E2EService { - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; - @JsonProperty("description") - private String description; + @JsonProperty("description") + private String description; - @JsonProperty("serviceInvariantUuid") - private String serviceInvariantUuid; + @JsonProperty("serviceInvariantUuid") + private String serviceInvariantUuid; - @JsonProperty("serviceUuid") - private String serviceUuid; + @JsonProperty("serviceUuid") + private String serviceUuid; - @JsonProperty("globalSubscriberId") - private String globalSubscriberId; + @JsonProperty("globalSubscriberId") + private String globalSubscriberId; - @JsonProperty("serviceType") - private String serviceType; + @JsonProperty("serviceType") + private String serviceType; - @JsonProperty("parameters") - private E2EParameters parameters; + @JsonProperty("parameters") + private E2EParameters parameters; - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<>(); - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public void setDescription(String description) { - this.description = description; - } + public void setDescription(String description) { + this.description = description; + } - public E2EParameters getParameters() { - return parameters; - } + public E2EParameters getParameters() { + return parameters; + } - public void setParameters(E2EParameters parameters) { - this.parameters = parameters; - } + public void setParameters(E2EParameters parameters) { + this.parameters = parameters; + } - public Map<String, Object> getAdditionalProperties() { - return additionalProperties; - } + public Map<String, Object> getAdditionalProperties() { + return additionalProperties; + } - public void setAdditionalProperties(Map<String, Object> additionalProperties) { - this.additionalProperties = additionalProperties; - } + public void setAdditionalProperties(Map<String, Object> additionalProperties) { + this.additionalProperties = additionalProperties; + } - public String getServiceInvariantUuid() { - return serviceInvariantUuid; - } + public String getServiceInvariantUuid() { + return serviceInvariantUuid; + } - public void setServiceInvariantUuid(String serviceInvariantUuid) { - this.serviceInvariantUuid = serviceInvariantUuid; - } + public void setServiceInvariantUuid(String serviceInvariantUuid) { + this.serviceInvariantUuid = serviceInvariantUuid; + } - public String getGlobalSubscriberId() { - return globalSubscriberId; - } + public String getGlobalSubscriberId() { + return globalSubscriberId; + } - public void setGlobalSubscriberId(String globalSubscriberId) { - this.globalSubscriberId = globalSubscriberId; - } + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } - public String getServiceType() { - return serviceType; - } + public String getServiceType() { + return serviceType; + } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } - public String getServiceUuid() { - return serviceUuid; - } + public String getServiceUuid() { + return serviceUuid; + } - public void setServiceUuid(String serviceUuid) { - this.serviceUuid = serviceUuid; - } + public void setServiceUuid(String serviceUuid) { + this.serviceUuid = serviceUuid; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java index a920bdfdc8..3335410658 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequest.java @@ -23,24 +23,24 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; public class E2EServiceInstanceDeleteRequest { - private String globalSubscriberId; - - private String serviceType; - - public String getGlobalSubscriberId() { - return globalSubscriberId; - } - - public void setGlobalSubscriberId(String globalSubscriberId) { - this.globalSubscriberId = globalSubscriberId; - } - - public String getServiceType() { - return serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - + private String globalSubscriberId; + + private String serviceType; + + public String getGlobalSubscriberId() { + return globalSubscriberId; + } + + public void setGlobalSubscriberId(String globalSubscriberId) { + this.globalSubscriberId = globalSubscriberId; + } + + public String getServiceType() { + return serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java index e3edf3b742..9f354f02b4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceRequest.java @@ -22,40 +22,39 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import java.util.HashMap; import java.util.Map; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; -@JsonIgnoreProperties({ "additionalProperties" }) +@JsonIgnoreProperties({"additionalProperties"}) public class E2EServiceInstanceRequest { - @JsonProperty("service") - private E2EService service; + @JsonProperty("service") + private E2EService service; + + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<>(); + + public E2EService getService() { + return service; + } - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); + public void setService(E2EService service) { + this.service = service; + } - public E2EService getService() { - return service; - } + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } - public void setService(E2EService service) { - this.service = service; - } - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } - - - public void setAdditionalProperties(Map<String, Object> additionalProperties) { - this.additionalProperties = additionalProperties; - } + public void setAdditionalProperties(Map<String, Object> additionalProperties) { + this.additionalProperties = additionalProperties; + } - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java index 531824e379..dbfe023684 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParam.java @@ -22,48 +22,47 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import java.util.HashMap; import java.util.Map; - import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class E2EUserParam { - @JsonProperty("name") - private String name; + @JsonProperty("name") + private String name; + + @JsonProperty("value") + private String value; + + @JsonIgnore + private Map<String, Object> additionalProperties = new HashMap<>(); - @JsonProperty("value") - private String value; + public String getName() { + return name; + } - @JsonIgnore - private Map<String, Object> additionalProperties = new HashMap<>(); + public void setName(String name) { + this.name = name; + } - public String getName() { - return name; - } + public String getValue() { + return value; + } - public void setName(String name) { - this.name = name; - } + public void setValue(String value) { + this.value = value; + } - public String getValue() { - return value; - } + public Map<String, Object> getAdditionalProperties() { + return this.additionalProperties; + } - public void setValue(String value) { - this.value = value; - } + public void setAdditionalProperty(String name, Object value) { + this.additionalProperties.put(name, value); + } - public Map<String, Object> getAdditionalProperties() { - return this.additionalProperties; - } + public void setAdditionalProperties(Map<String, Object> additionalProperties) { + this.additionalProperties = additionalProperties; + } - public void setAdditionalProperty(String name, Object value) { - this.additionalProperties.put(name, value); - } - public void setAdditionalProperties(Map<String, Object> additionalProperties) { - this.additionalProperties = additionalProperties; - } - - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java index 5c958ad2a3..f7fa01aeb0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/GetE2EServiceInstanceResponse.java @@ -22,28 +22,27 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.onap.so.db.request.beans.OperationStatus; - import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class GetE2EServiceInstanceResponse { - protected OperationStatus operation; + protected OperationStatus operation; -// public OperationStatus getOperationStatus() { -// return operation; -// } -// -// public void setOperationStatus(OperationStatus requestDB) { -// this.operation = requestDB; -// } + // public OperationStatus getOperationStatus() { + // return operation; + // } + // + // public void setOperationStatus(OperationStatus requestDB) { + // this.operation = requestDB; + // } - public OperationStatus getOperation() { - return operation; - } + public OperationStatus getOperation() { + return operation; + } - public void setOperation(OperationStatus operation) { - this.operation = operation; - } + public void setOperation(OperationStatus operation) { + this.operation = operation; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java index b1256a236b..dc5b69e2f2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/LocationConstraint.java @@ -57,7 +57,7 @@ public class LocationConstraint { this.vnfProfileId = vnfProfileId; } - + /** * @return Returns the locationConstraints. */ @@ -65,7 +65,7 @@ public class LocationConstraint { return locationConstraints; } - + /** * @param locationConstraints The locationConstraints to set. */ diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java index e7baf98411..02885c7bbb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParameters.java @@ -36,6 +36,7 @@ public class NsParameters { private List<LocationConstraint> locationConstraints; private Map<String, Object> additionalParamForNs = new HashMap<>(); + /** * @return Returns the locationConstraints. */ @@ -50,7 +51,7 @@ public class NsParameters { this.locationConstraints = locationConstraints; } - + /** * @return Returns the additionalParamForNs. */ @@ -58,7 +59,7 @@ public class NsParameters { return additionalParamForNs; } - + /** * @param additionalParamForNs The additionalParamForNs to set. */ diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java index 6518523256..44592ce2e4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/ResourceRequest.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; - import java.util.HashMap; import java.util.Map; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java index 72d370425f..5a4b55c048 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/VimLocation.java @@ -26,7 +26,7 @@ public class VimLocation { @JsonProperty("vimId") private String vimId; - + /** * @return Returns the vimId. */ @@ -34,12 +34,12 @@ public class VimLocation { return vimId; } - + /** * @param vimId The vimId to set. */ public void setVimId(String vimId) { this.vimId = vimId; } - + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java index 2312678460..8b85ce7e34 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/package-info.java @@ -19,12 +19,13 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.01.08 at 03:50:12 PM EST +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.01.08 at 03:50:12 PM EST // -@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/request/types/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/request/types/v1", + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.onap.so.apihandlerinfra; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java index 957450fab0..ebb1912503 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestDetails.java @@ -24,16 +24,15 @@ import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @JsonRootName(value = "requestDetails") -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class RequestDetails { - protected RequestInfo requestInfo; - /** + protected RequestInfo requestInfo; + + /** * Gets the value of the requestInfo property. * - * @return - * possible object is - * {@link RequestInfo } + * @return possible object is {@link RequestInfo } * */ public RequestInfo getRequestInfo() { @@ -43,9 +42,7 @@ public class RequestDetails { /** * Sets the value of the requestInfo property. * - * @param value - * allowed object is - * {@link RequestInfo } + * @param value allowed object is {@link RequestInfo } * */ public void setRequestInfo(RequestInfo value) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java index aae8786bb0..61d31b3a55 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/RequestInfo.java @@ -22,19 +22,17 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class RequestInfo { - protected String source; - protected ValidResponses responseValue; + protected String source; + protected ValidResponses responseValue; protected String requestorId; - + /** * Gets the value of the source property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getSource() { @@ -44,30 +42,28 @@ public class RequestInfo { /** * Sets the value of the source property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setSource(String value) { this.source = value; } - public ValidResponses getResponseValue() { - return responseValue; - } + public ValidResponses getResponseValue() { + return responseValue; + } + + public void setResponseValue(ValidResponses responseValue) { + this.responseValue = responseValue; + } - public void setResponseValue(ValidResponses responseValue) { - this.responseValue = responseValue; - } - - public String getRequestorId() { - return requestorId; - } + public String getRequestorId() { + return requestorId; + } - public void setRequestorId(String requestorId) { - this.requestorId = requestorId; - } + public void setRequestorId(String requestorId) { + this.requestorId = requestorId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java index ceba65fa97..f690aa5f01 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskList.java @@ -21,21 +21,20 @@ package org.onap.so.apihandlerinfra.tasksbeans; import java.util.List; - import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) -public class TaskList { - protected String taskId; - protected String type; - protected String nfRole; - protected String subscriptionServiceType; - protected String originalRequestId; - protected String originalRequestorId; - protected String errorSource; - protected String errorCode; - protected String errorMessage; - protected String buildingBlockName; +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) +public class TaskList { + protected String taskId; + protected String type; + protected String nfRole; + protected String subscriptionServiceType; + protected String originalRequestId; + protected String originalRequestorId; + protected String errorSource; + protected String errorCode; + protected String errorMessage; + protected String buildingBlockName; protected String buildingBlockStep; protected String description; protected String timeout; @@ -44,10 +43,8 @@ public class TaskList { /** * Gets the value of the taskId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTaskId() { return taskId; @@ -56,10 +53,8 @@ public class TaskList { /** * Sets the value of the taskId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTaskId(String value) { this.taskId = value; @@ -68,10 +63,8 @@ public class TaskList { /** * Gets the value of the type property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getType() { return type; @@ -80,10 +73,8 @@ public class TaskList { /** * Sets the value of the type property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setType(String value) { this.type = value; @@ -92,10 +83,8 @@ public class TaskList { /** * Gets the value of the nfRole property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getNfRole() { return nfRole; @@ -104,10 +93,8 @@ public class TaskList { /** * Sets the value of the nfRole property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setNfRole(String value) { this.nfRole = value; @@ -116,10 +103,8 @@ public class TaskList { /** * Gets the value of the subscriptionServiceType property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getSubscriptionServiceType() { return subscriptionServiceType; @@ -128,10 +113,8 @@ public class TaskList { /** * Sets the value of the subscriptionServiceType property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setSubscriptionServiceType(String value) { this.subscriptionServiceType = value; @@ -140,10 +123,8 @@ public class TaskList { /** * Gets the value of the originalRequestId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getOriginalRequestId() { return originalRequestId; @@ -152,10 +133,8 @@ public class TaskList { /** * Sets the value of the originalRequestId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setOriginalRequestId(String value) { this.originalRequestId = value; @@ -164,10 +143,8 @@ public class TaskList { /** * Gets the value of the originalRequestorId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getOriginalRequestorId() { return originalRequestorId; @@ -176,10 +153,8 @@ public class TaskList { /** * Sets the value of the originalRequestorId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setOriginalRequestorId(String value) { this.originalRequestorId = value; @@ -188,10 +163,8 @@ public class TaskList { /** * Gets the value of the errorSource property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorSource() { return errorSource; @@ -200,10 +173,8 @@ public class TaskList { /** * Sets the value of the errorSource property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorSource(String value) { this.errorSource = value; @@ -212,10 +183,8 @@ public class TaskList { /** * Gets the value of the errorCode property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorCode() { return errorCode; @@ -224,10 +193,8 @@ public class TaskList { /** * Sets the value of the errorCode property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorCode(String value) { this.errorCode = value; @@ -236,10 +203,8 @@ public class TaskList { /** * Gets the value of the errorMessage property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getErrorMessage() { return errorMessage; @@ -248,10 +213,8 @@ public class TaskList { /** * Sets the value of the errorMessage property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setErrorMessage(String value) { this.errorMessage = value; @@ -260,10 +223,8 @@ public class TaskList { /** * Gets the value of the buildingBlockName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getBuildingBlockName() { return buildingBlockName; @@ -272,10 +233,8 @@ public class TaskList { /** * Sets the value of the buildingBlockName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setBuildingBlockName(String value) { this.buildingBlockName = value; @@ -284,10 +243,8 @@ public class TaskList { /** * Gets the value of the buildingBlockStep property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getBuildingBlockStep() { return buildingBlockStep; @@ -296,22 +253,18 @@ public class TaskList { /** * Sets the value of the buildingBlockStep property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setBuildingBlockStep(String value) { this.buildingBlockStep = value; } - + /** * Gets the value of the description property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getDescription() { return description; @@ -320,22 +273,18 @@ public class TaskList { /** * Sets the value of the description property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setDescription(String value) { this.description = value; } - + /** * Gets the value of the timeout property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTimeout() { return timeout; @@ -344,10 +293,8 @@ public class TaskList { /** * Sets the value of the timeout property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTimeout(String value) { this.timeout = value; @@ -356,10 +303,8 @@ public class TaskList { /** * Gets the value of the validResponses property. * - * @return - * possible object is - * {@link ValidResponses } - * + * @return possible object is {@link ValidResponses } + * */ public List<String> getValidResponses() { return validResponses; @@ -368,16 +313,13 @@ public class TaskList { /** * Sets the value of the validResponses property. * - * @param value - * allowed object is - * {@link ValidResponses } - * + * @param value allowed object is {@link ValidResponses } + * */ public void setValidResponses(List<String> value) { this.validResponses = value; } - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java index 860fe6bddb..18c9005f40 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskRequestReference.java @@ -1,19 +1,15 @@ -/* ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 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 +/* + * ============LICENSE_START======================================================= ONAP - SO + * ================================================================================ Copyright (C) 2017 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 + * 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. + * 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========================================================= */ @@ -21,18 +17,17 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; + @JsonRootName(value = "taskRequestReference") -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class TaskRequestReference { - protected String taskId; - + protected String taskId; + /** * Gets the value of the taskId property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getTaskId() { @@ -42,15 +37,13 @@ public class TaskRequestReference { /** * Sets the value of the taskId property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setTaskId(String value) { this.taskId = value; } - + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java index 441d4f315a..fab42515d5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariableValue.java @@ -22,19 +22,17 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class TaskVariableValue { - protected String name; - protected String value; - protected String operator; - - /** + protected String name; + protected String value; + protected String operator; + + /** * Gets the value of the name property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getName() { @@ -44,22 +42,18 @@ public class TaskVariableValue { /** * Sets the value of the name property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setName(String value) { this.name = value; } - - + + /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getValue() { @@ -69,21 +63,17 @@ public class TaskVariableValue { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setValue(String value) { this.value = value; } - + /** * Gets the value of the operator property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getOperator() { @@ -93,15 +83,13 @@ public class TaskVariableValue { /** * Sets the value of the operator property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setOperator(String value) { this.operator = value; } - - + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java index 7d5b465891..e759b4f87a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TaskVariables.java @@ -21,19 +21,18 @@ package org.onap.so.apihandlerinfra.tasksbeans; import java.util.List; - import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class TaskVariables { - private List<TaskVariableValue> taskVariables; + private List<TaskVariableValue> taskVariables; - public List<TaskVariableValue> getTaskVariables() { - return taskVariables; - } + public List<TaskVariableValue> getTaskVariables() { + return taskVariables; + } - public void setTaskVariables(List<TaskVariableValue> taskVariables) { - this.taskVariables = taskVariables; - } + public void setTaskVariables(List<TaskVariableValue> taskVariables) { + this.taskVariables = taskVariables; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java index 5ee01aeaf6..b0b6f43e03 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksGetResponse.java @@ -24,13 +24,13 @@ import java.util.List; public class TasksGetResponse { - private List<TaskList> taskList; + private List<TaskList> taskList; - public List<TaskList> getTaskList() { - return taskList; - } + public List<TaskList> getTaskList() { + return taskList; + } - public void setTaskList(List<TaskList> taskList) { - this.taskList = taskList; - } + public void setTaskList(List<TaskList> taskList) { + this.taskList = taskList; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java index 0544f536a2..bd37ecd10a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/TasksRequest.java @@ -22,13 +22,13 @@ package org.onap.so.apihandlerinfra.tasksbeans; public class TasksRequest { - private RequestDetails requestDetails; + private RequestDetails requestDetails; - public RequestDetails getRequestDetails() { - return requestDetails; - } + public RequestDetails getRequestDetails() { + return requestDetails; + } - public void setRequestDetails(RequestDetails requestDetails) { - this.requestDetails = requestDetails; - } + public void setRequestDetails(RequestDetails requestDetails) { + this.requestDetails = requestDetails; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java index 18fc7f9739..e25e40ced4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/ValidResponses.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -30,17 +30,11 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public enum ValidResponses { - rollback, - abort, - skip, - retry, - manual, - resume - ; + rollback, abort, skip, retry, manual, resume; public String value() { return name(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java index 98ed5b653f..be113010b4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Value.java @@ -22,17 +22,15 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.databind.annotation.JsonSerialize; -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class Value { - protected String value; - + protected String value; + /** * Gets the value of the value property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getValue() { @@ -42,14 +40,12 @@ public class Value { /** * Sets the value of the value property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setValue(String value) { this.value = value; } - + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java index 1ed011db91..7338f19d28 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tasksbeans/Variables.java @@ -22,20 +22,19 @@ package org.onap.so.apihandlerinfra.tasksbeans; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.annotation.JsonSerialize; + @JsonRootName(value = "variables") -@JsonSerialize(include=JsonSerialize.Inclusion.NON_DEFAULT) +@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT) public class Variables { - protected Value source; - protected Value responseValue; + protected Value source; + protected Value responseValue; protected Value requestorId; - + /** * Gets the value of the source property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public Value getSource() { @@ -45,30 +44,28 @@ public class Variables { /** * Sets the value of the source property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setSource(Value value) { this.source = value; } - public Value getResponseValue() { - return responseValue; - } + public Value getResponseValue() { + return responseValue; + } - public void setResponseValue(Value responseValue) { - this.responseValue = responseValue; - } + public void setResponseValue(Value responseValue) { + this.responseValue = responseValue; + } - - public Value getRequestorId() { - return requestorId; - } - public void setRequestorId(Value requestorId) { - this.requestorId = requestorId; - } + public Value getRequestorId() { + return requestorId; + } + + public void setRequestorId(Value requestorId) { + this.requestorId = requestorId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java index 1ea77acf95..db2b5b6b4e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/AaiClientPropertiesImpl.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolation; import java.net.MalformedURLException; import java.net.URL; - import org.onap.so.client.aai.AAIProperties; import org.onap.so.client.aai.AAIVersion; import org.onap.so.spring.SpringContextHelper; @@ -30,39 +29,40 @@ import org.springframework.context.ApplicationContext; public class AaiClientPropertiesImpl implements AAIProperties { - private String aaiEndpoint; - private String auth; - private String key; - public AaiClientPropertiesImpl() { - - ApplicationContext context = SpringContextHelper.getAppContext(); - aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint"); - this.auth = context.getEnvironment().getProperty("aai.auth"); - this.key = context.getEnvironment().getProperty("mso.msoKey"); - } + private String aaiEndpoint; + private String auth; + private String key; + + public AaiClientPropertiesImpl() { + + ApplicationContext context = SpringContextHelper.getAppContext(); + aaiEndpoint = context.getEnvironment().getProperty("mso.aai.endpoint"); + this.auth = context.getEnvironment().getProperty("aai.auth"); + this.key = context.getEnvironment().getProperty("mso.msoKey"); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(aaiEndpoint); + } - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL(aaiEndpoint); - } + @Override + public String getSystemName() { + return "MSO"; + } - @Override - public String getSystemName() { - return "MSO"; - } - - @Override - public AAIVersion getDefaultVersion() { - return AAIVersion.LATEST; - } + @Override + public AAIVersion getDefaultVersion() { + return AAIVersion.LATEST; + } - @Override - public String getAuth() { - return this.auth; - } + @Override + public String getAuth() { + return this.auth; + } - @Override - public String getKey() { - return this.key; - } + @Override + public String getKey() { + return this.key; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java index be8f603a28..d79d73c036 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestration.java @@ -27,7 +27,6 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.UUID; - import javax.inject.Provider; import javax.transaction.Transactional; import javax.ws.rs.Consumes; @@ -39,7 +38,6 @@ 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.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.Constants; @@ -61,186 +59,199 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Component @Path("/onap/so/infra/cloudResources") -@Api(value="/onap/so/infra/cloudResources",description="API Requests for cloud resources - Tenant Isolation") +@Api(value = "/onap/so/infra/cloudResources", description = "API Requests for cloud resources - Tenant Isolation") public class CloudOrchestration { - private static Logger logger = LoggerFactory.getLogger(CloudOrchestration.class); - private static final String ENVIRONMENT_ID_KEY = "operationalEnvironmentId"; - - @Autowired - private TenantIsolationRequest tenantIsolationRequest ; - - @Autowired - private RequestsDbClient requestsDbClient; - - @Autowired - private Provider<TenantIsolationRunnable> tenantIsolationRunnable; - - @POST - @Path("/{version:[vV][1]}/operationalEnvironments") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Create an Operational Environment",response=Response.class) - @Transactional - public Response createOperationEnvironment(String request, @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException{ - logger.debug("Received request to Create Operational Environment"); - return cloudOrchestration(request, Action.create, null, version, getRequestId(requestContext)); - } - - @POST - @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/activate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Activate an Operational Environment",response=Response.class) - @Transactional - public Response activateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId, - @Context ContainerRequestContext requestContext) throws ApiException{ - logger.debug("Received request to Activate an Operational Environment"); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId); - return cloudOrchestration(request, Action.activate, instanceIdMap, version, getRequestId(requestContext)); - } - - @POST - @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/deactivate") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Deactivate an Operational Environment",response=Response.class) - @Transactional - public Response deactivateOperationEnvironment(String request, @PathParam("version") String version, @PathParam("operationalEnvironmentId") String operationalEnvironmentId, @Context ContainerRequestContext requestContext) throws ApiException{ - logger.debug("Received request to Deactivate an Operational Environment"); - HashMap<String, String> instanceIdMap = new HashMap<>(); - instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId); - return cloudOrchestration(request, Action.deactivate, instanceIdMap, version, getRequestId(requestContext)); - } - - - private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, String version, String requestId) throws ApiException{ - logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); - long startTime = System.currentTimeMillis (); - CloudOrchestrationRequest cor = null; - tenantIsolationRequest.setRequestId(requestId); - - cor = convertJsonToCloudOrchestrationRequest(requestJSON, action, startTime, cor); - - try { - tenantIsolationRequest.parse(cor, instanceIdMap, action); - }catch(ValidationException e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, - ErrorCode.SchemaError).build(); - - - throw 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(); - } - - String instanceName = cor.getRequestDetails().getRequestInfo().getInstanceName(); - String resourceType = cor.getRequestDetails().getRequestInfo().getResourceType().name(); - InfraActiveRequests dup = null; - - dup = duplicateCheck(action, instanceIdMap, startTime, instanceName, resourceType); - - if(dup == null && (Action.activate.equals(action) || Action.deactivate.equals(action))) { - dup = requestsDbClient.checkVnfIdStatus(cor.getOperationalEnvironmentId()); - } - - if(dup != null) { - String instance = null; - if(instanceName != null){ - instance = instanceName; - }else if (instanceIdMap != null){ - instance = instanceIdMap.get(resourceType + "InstanceId"); - } - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).build(); - - - throw new DuplicateRequestException.Builder(resourceType,instance,dup.getRequestStatus(),dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - } - - String instanceId = null; - - if(instanceIdMap != null && instanceIdMap.get(ENVIRONMENT_ID_KEY) != null) { - instanceId = instanceIdMap.get(ENVIRONMENT_ID_KEY); - } else { - instanceId = UUID.randomUUID().toString(); - tenantIsolationRequest.setOperationalEnvironmentId(instanceId); - cor.setOperationalEnvironmentId(instanceId); - } - - tenantIsolationRequest.createRequestRecord(Status.IN_PROGRESS, action); - - OperationalEnvironment opEnv = cor.getRequestDetails().getRequestParameters().getOperationalEnvironmentType(); - String operationalEnvType = opEnv != null ? opEnv.name() : null; - - TenantIsolationRunnable runnable = tenantIsolationRunnable.get(); - runnable.run(action, operationalEnvType, cor, requestId); - - String encodedValue; - try { - encodedValue = new String(instanceId.getBytes("UTF-8")); - } catch(UnsupportedEncodingException ex) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, - ErrorCode.DataError).build(); - - - throw new ValidateException.Builder("Could not encode instanceID" + ex.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER) - .cause(ex).errorInfo(errorLoggerInfo).build(); - } - - TenantSyncResponse tenantResponse = new TenantSyncResponse(); - RequestReferences reqReference = new RequestReferences(); - reqReference.setInstanceId(encodedValue); - reqReference.setRequestId(requestId); - tenantResponse.setRequestReferences(reqReference); - - return Response.ok(tenantResponse).build(); - } - - private InfraActiveRequests duplicateCheck(Action action, HashMap<String, String> instanceIdMap, long startTime, - String instanceName, String requestScope) throws ApiException { - try { - return requestsDbClient.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope); - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); - - - throw new ValidateException.Builder("Duplicate Check Request", HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - } - } - - private CloudOrchestrationRequest convertJsonToCloudOrchestrationRequest(String requestJSON, Action action, long startTime, - CloudOrchestrationRequest cor) throws ApiException { - try{ - logger.debug("Converting incoming JSON request to Object"); - ObjectMapper mapper = new ObjectMapper(); - return mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - } catch(IOException 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(); - if (tenantIsolationRequest.getRequestId () != null) { - tenantIsolationRequest.createRequestRecord (Status.FAILED, action); - } - throw validateException; - } - } - - private String getRequestId(ContainerRequestContext requestContext) { - return requestContext.getProperty("requestId").toString(); - } + private static Logger logger = LoggerFactory.getLogger(CloudOrchestration.class); + private static final String ENVIRONMENT_ID_KEY = "operationalEnvironmentId"; + + @Autowired + private TenantIsolationRequest tenantIsolationRequest; + + @Autowired + private RequestsDbClient requestsDbClient; + + @Autowired + private Provider<TenantIsolationRunnable> tenantIsolationRunnable; + + @POST + @Path("/{version:[vV][1]}/operationalEnvironments") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Create an Operational Environment", response = Response.class) + @Transactional + public Response createOperationEnvironment(String request, @PathParam("version") String version, + @Context ContainerRequestContext requestContext) throws ApiException { + logger.debug("Received request to Create Operational Environment"); + return cloudOrchestration(request, Action.create, null, version, getRequestId(requestContext)); + } + + @POST + @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/activate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Activate an Operational Environment", response = Response.class) + @Transactional + public Response activateOperationEnvironment(String request, @PathParam("version") String version, + @PathParam("operationalEnvironmentId") String operationalEnvironmentId, + @Context ContainerRequestContext requestContext) throws ApiException { + logger.debug("Received request to Activate an Operational Environment"); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId); + return cloudOrchestration(request, Action.activate, instanceIdMap, version, getRequestId(requestContext)); + } + + @POST + @Path("/{version:[vV][1]}/operationalEnvironments/{operationalEnvironmentId}/deactivate") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Deactivate an Operational Environment", response = Response.class) + @Transactional + public Response deactivateOperationEnvironment(String request, @PathParam("version") String version, + @PathParam("operationalEnvironmentId") String operationalEnvironmentId, + @Context ContainerRequestContext requestContext) throws ApiException { + logger.debug("Received request to Deactivate an Operational Environment"); + HashMap<String, String> instanceIdMap = new HashMap<>(); + instanceIdMap.put(ENVIRONMENT_ID_KEY, operationalEnvironmentId); + return cloudOrchestration(request, Action.deactivate, instanceIdMap, version, getRequestId(requestContext)); + } + + + private Response cloudOrchestration(String requestJSON, Action action, HashMap<String, String> instanceIdMap, + String version, String requestId) throws ApiException { + logger.info("{} {}", MessageEnum.APIH_GENERATED_REQUEST_ID.toString(), requestId); + long startTime = System.currentTimeMillis(); + CloudOrchestrationRequest cor = null; + tenantIsolationRequest.setRequestId(requestId); + + cor = convertJsonToCloudOrchestrationRequest(requestJSON, action, startTime, cor); + + try { + tenantIsolationRequest.parse(cor, instanceIdMap, action); + } catch (ValidationException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .build(); + + + throw 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(); + } + + String instanceName = cor.getRequestDetails().getRequestInfo().getInstanceName(); + String resourceType = cor.getRequestDetails().getRequestInfo().getResourceType().name(); + InfraActiveRequests dup = null; + + dup = duplicateCheck(action, instanceIdMap, startTime, instanceName, resourceType); + + if (dup == null && (Action.activate.equals(action) || Action.deactivate.equals(action))) { + dup = requestsDbClient.checkVnfIdStatus(cor.getOperationalEnvironmentId()); + } + + if (dup != null) { + String instance = null; + if (instanceName != null) { + instance = instanceName; + } else if (instanceIdMap != null) { + instance = instanceIdMap.get(resourceType + "InstanceId"); + } + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_FOUND, ErrorCode.SchemaError).build(); + + + throw new DuplicateRequestException.Builder(resourceType, instance, dup.getRequestStatus(), + dup.getRequestId(), HttpStatus.SC_CONFLICT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + } + + String instanceId = null; + + if (instanceIdMap != null && instanceIdMap.get(ENVIRONMENT_ID_KEY) != null) { + instanceId = instanceIdMap.get(ENVIRONMENT_ID_KEY); + } else { + instanceId = UUID.randomUUID().toString(); + tenantIsolationRequest.setOperationalEnvironmentId(instanceId); + cor.setOperationalEnvironmentId(instanceId); + } + + tenantIsolationRequest.createRequestRecord(Status.IN_PROGRESS, action); + + OperationalEnvironment opEnv = cor.getRequestDetails().getRequestParameters().getOperationalEnvironmentType(); + String operationalEnvType = opEnv != null ? opEnv.name() : null; + + TenantIsolationRunnable runnable = tenantIsolationRunnable.get(); + runnable.run(action, operationalEnvType, cor, requestId); + + String encodedValue; + try { + encodedValue = new String(instanceId.getBytes("UTF-8")); + } catch (UnsupportedEncodingException ex) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.DataError).build(); + + + throw new ValidateException.Builder("Could not encode instanceID" + ex.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex).errorInfo(errorLoggerInfo) + .build(); + } + + TenantSyncResponse tenantResponse = new TenantSyncResponse(); + RequestReferences reqReference = new RequestReferences(); + reqReference.setInstanceId(encodedValue); + reqReference.setRequestId(requestId); + tenantResponse.setRequestReferences(reqReference); + + return Response.ok(tenantResponse).build(); + } + + private InfraActiveRequests duplicateCheck(Action action, HashMap<String, String> instanceIdMap, long startTime, + String instanceName, String requestScope) throws ApiException { + try { + return requestsDbClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + + + throw new ValidateException.Builder("Duplicate Check Request", HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + } + } + + private CloudOrchestrationRequest convertJsonToCloudOrchestrationRequest(String requestJSON, Action action, + long startTime, CloudOrchestrationRequest cor) throws ApiException { + try { + logger.debug("Converting incoming JSON request to Object"); + ObjectMapper mapper = new ObjectMapper(); + return mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + } catch (IOException 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(); + if (tenantIsolationRequest.getRequestId() != null) { + tenantIsolationRequest.createRequestRecord(Status.FAILED, action); + } + throw validateException; + } + } + + private String getRequestId(ContainerRequestContext requestContext) { + return requestContext.getProperty("requestId").toString(); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java index d387928e22..6660cc653c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationRequest.java @@ -21,61 +21,58 @@ package org.onap.so.apihandlerinfra.tenantisolation; import java.io.Serializable; - import org.onap.so.apihandlerinfra.tenantisolationbeans.Distribution; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; - import com.fasterxml.jackson.annotation.JsonProperty; public class CloudOrchestrationRequest implements Serializable { - private static final long serialVersionUID = -4959169541182257787L; - @JsonProperty("requestDetails") - private RequestDetails requestDetails; - @JsonProperty("operationalEnvironmentId") - private String operationalEnvironmentId; - @JsonProperty("distribution") - private Distribution distribution; - @JsonProperty("distributionId") - private String distributionId; - - public String getOperationalEnvironmentId() { - return operationalEnvironmentId; - } + private static final long serialVersionUID = -4959169541182257787L; + @JsonProperty("requestDetails") + private RequestDetails requestDetails; + @JsonProperty("operationalEnvironmentId") + private String operationalEnvironmentId; + @JsonProperty("distribution") + private Distribution distribution; + @JsonProperty("distributionId") + private String distributionId; + + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + public void setOperationalEnvironmentId(String operationalEnvironmentId) { + this.operationalEnvironmentId = operationalEnvironmentId; + } + + public RequestDetails getRequestDetails() { + return requestDetails; + } - public void setOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; - } + public void setRequestDetails(RequestDetails requestDetails) { + this.requestDetails = requestDetails; + } - public RequestDetails getRequestDetails() { - return requestDetails; - } - - public void setRequestDetails(RequestDetails requestDetails){ - this.requestDetails = requestDetails; - } + public Distribution getDistribution() { + return distribution; + } - public Distribution getDistribution() { - return distribution; - } + public void setDistribution(Distribution distribution) { + this.distribution = distribution; + } - public void setDistribution(Distribution distribution) { - this.distribution = distribution; - } + public String getDistributionId() { + return distributionId; + } - public String getDistributionId() { - return distributionId; - } + public void setDistributionId(String distributionId) { + this.distributionId = distributionId; + } - public void setDistributionId(String distributionId) { - this.distributionId = distributionId; - } - - @Override - public String toString() { - return "ServiceInstancesRequest [requestDetails=" + requestDetails - + ", operationalEnvironmentId=" + operationalEnvironmentId - + ", distribution=" + distribution - + ", distributionId=" + distributionId + "]"; - } + @Override + public String toString() { + return "ServiceInstancesRequest [requestDetails=" + requestDetails + ", operationalEnvironmentId=" + + operationalEnvironmentId + ", distribution=" + distribution + ", distributionId=" + distributionId + + "]"; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java index fe74b108ba..be6d5b06ca 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestration.java @@ -27,7 +27,6 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; - import javax.transaction.Transactional; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -40,14 +39,12 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; - import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandler.common.ResponseBuilder; import org.onap.so.apihandlerinfra.Constants; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList; import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse; @@ -60,231 +57,257 @@ import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; 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 com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Component @Path("onap/so/infra/cloudResourcesRequests") -@Api(value="onap/so/infra/cloudResourcesRequests",description="API GET Requests for cloud resources - Tenant Isolation") +@Api(value = "onap/so/infra/cloudResourcesRequests", + description = "API GET Requests for cloud resources - Tenant Isolation") public class CloudResourcesOrchestration { - private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class); - - @Autowired - RequestsDbClient requestDbClient; - - @Autowired - private ResponseBuilder builder; - - @POST - @Path("/{version: [vV][1]}/{requestId}/unlock") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Unlock CloudOrchestration requests for a specified requestId") - @Transactional - public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{ - TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId); - InfraActiveRequests infraActiveRequest = null; - - CloudOrchestrationRequest cor = null; - - logger.debug ("requestId is: " + requestId); - - try{ - ObjectMapper mapper = new ObjectMapper(); - cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - } catch(IOException 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; - } - - try{ - msoRequest.parseOrchestration(cor); - } catch (ValidationException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, - ErrorCode.SchemaError).build(); - ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER) - .cause(e).errorInfo(errorLoggerInfo).build(); - throw validateException; - } - try { - infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId); - }catch(Exception e){ - ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); - throw validateException; - } - if(infraActiveRequest == null) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; - - }else{ - String status = infraActiveRequest.getRequestStatus(); - if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){ - infraActiveRequest.setRequestStatus("UNLOCKED"); - infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); - infraActiveRequest.setRequestId(requestId); - requestDbClient.save(infraActiveRequest); - }else{ - ErrorLoggerInfo errorLoggerInfo = 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", - HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - } - - return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build (); - } - - @GET - @Path("/{version:[vV][1]}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Get status of an Operational Environment based on filter criteria",response=Response.class) - @Transactional - public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version ) throws ApiException{ - - MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); - List<String> requestIdKey = queryParams.get("requestId"); - String apiVersion = version.substring(1); - - if(queryParams.size() == 1 && requestIdKey != null) { - String requestId = requestIdKey.get(0); - - CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse(); - TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (requestId); - InfraActiveRequests requestDB = null; - - try { - requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId); - } catch (Exception e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build(); - ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e) - .errorInfo(errorLoggerInfo).build(); - throw validateException; - } - - if(requestDB == null) { - 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) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - - Request request = mapInfraActiveRequestToRequest(requestDB); - cloudOrchestrationGetResponse.setRequest(request); - return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion); - - } else { - TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (); - List<InfraActiveRequests> activeRequests = null; - CloudOrchestrationRequestList orchestrationList = null; - - - Map<String, String> orchestrationMap; - try{ - orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams); - }catch(ValidationException ex){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder(ex.getMessage(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex) - .errorInfo(errorLoggerInfo).build(); - - throw validateException; - - } - activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap); - orchestrationList = new CloudOrchestrationRequestList(); - List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>(); - - for(InfraActiveRequests infraActive : activeRequests){ - - Request request = mapInfraActiveRequestToRequest(infraActive); - CloudOrchestrationResponse requestList = new CloudOrchestrationResponse(); - requestList.setRequest(request); - requestLists.add(requestList); - } - orchestrationList.setRequestList(requestLists); - - return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); - } - } - - private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { - Request request = new Request(); - request.setRequestId(iar.getRequestId()); - request.setRequestScope(iar.getRequestScope()); - request.setRequestType(iar.getRequestAction()); - - InstanceReferences ir = new InstanceReferences(); - - if(iar.getOperationalEnvId() != null) - ir.setOperationalEnvironmentId(iar.getOperationalEnvId()); - if(iar.getOperationalEnvName() != null) - ir.setOperationalEnvName(iar.getOperationalEnvName()); - if(iar.getRequestorId() != null) - ir.setRequestorId(iar.getRequestorId()); - - request.setInstanceReferences(ir); - String requestBody = iar.getRequestBody(); - RequestDetails requestDetails = null; - - if (requestBody != null) { - try { - ObjectMapper mapper = new ObjectMapper(); - requestDetails = mapper.readValue(requestBody, RequestDetails.class); - } catch (IOException 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; - } - } - - request.setRequestDetails(requestDetails); - String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT"; - request.setStartTime(startTimeStamp); - - RequestStatus status = new RequestStatus(); - if(iar.getStatusMessage() != null){ - status.setStatusMessage(iar.getStatusMessage()); - } - - if(iar.getEndTime() != null){ - String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; - status.setTimeStamp(endTimeStamp); - } - - if(iar.getRequestStatus() != null){ - status.setRequestState(iar.getRequestStatus()); - } - - if(iar.getProgress() != null){ - status.setPercentProgress(iar.getProgress().toString()); - } - - request.setRequestStatus(status); - - return request; - } + private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class); + + @Autowired + RequestsDbClient requestDbClient; + + @Autowired + private ResponseBuilder builder; + + @POST + @Path("/{version: [vV][1]}/{requestId}/unlock") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Unlock CloudOrchestration requests for a specified requestId") + @Transactional + public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, + @PathParam("version") String version) throws ApiException { + TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId); + InfraActiveRequests infraActiveRequest = null; + + CloudOrchestrationRequest cor = null; + + logger.debug("requestId is: " + requestId); + + try { + ObjectMapper mapper = new ObjectMapper(); + cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + } catch (IOException 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; + } + + try { + msoRequest.parseOrchestration(cor); + } catch (ValidationException e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .build(); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + throw validateException; + } + try { + infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (Exception e) { + ValidateException validateException = new ValidateException.Builder(e.getMessage(), + HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build(); + throw validateException; + } + if (infraActiveRequest == null) { + + ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, + ErrorCode.BusinessProcesssError).build(); + ValidateException validateException = + new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + + } else { + String status = infraActiveRequest.getRequestStatus(); + if (status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") + || status.equalsIgnoreCase("PENDING_MANUAL_TASK")) { + infraActiveRequest.setRequestStatus("UNLOCKED"); + infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + infraActiveRequest.setRequestId(requestId); + requestDbClient.save(infraActiveRequest); + } else { + ErrorLoggerInfo errorLoggerInfo = + 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", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); + + throw validateException; + } + } + + return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build(); + } + + @GET + @Path("/{version:[vV][1]}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Get status of an Operational Environment based on filter criteria", + response = Response.class) + @Transactional + public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version) + throws ApiException { + + MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); + List<String> requestIdKey = queryParams.get("requestId"); + String apiVersion = version.substring(1); + + if (queryParams.size() == 1 && requestIdKey != null) { + String requestId = requestIdKey.get(0); + + CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse(); + TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest(requestId); + InfraActiveRequests requestDB = null; + + try { + requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError) + .build(); + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + throw validateException; + } + + if (requestDB == null) { + 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) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + + Request request = mapInfraActiveRequestToRequest(requestDB); + cloudOrchestrationGetResponse.setRequest(request); + return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion); + + } else { + TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest(); + List<InfraActiveRequests> activeRequests = null; + CloudOrchestrationRequestList orchestrationList = null; + + + Map<String, String> orchestrationMap; + try { + orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams); + } catch (ValidationException ex) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + ValidateException validateException = + new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); + + throw validateException; + + } + activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap); + orchestrationList = new CloudOrchestrationRequestList(); + List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>(); + + for (InfraActiveRequests infraActive : activeRequests) { + + Request request = mapInfraActiveRequestToRequest(infraActive); + CloudOrchestrationResponse requestList = new CloudOrchestrationResponse(); + requestList.setRequest(request); + requestLists.add(requestList); + } + orchestrationList.setRequestList(requestLists); + + return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion); + } + } + + private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException { + Request request = new Request(); + request.setRequestId(iar.getRequestId()); + request.setRequestScope(iar.getRequestScope()); + request.setRequestType(iar.getRequestAction()); + + InstanceReferences ir = new InstanceReferences(); + + if (iar.getOperationalEnvId() != null) + ir.setOperationalEnvironmentId(iar.getOperationalEnvId()); + if (iar.getOperationalEnvName() != null) + ir.setOperationalEnvName(iar.getOperationalEnvName()); + if (iar.getRequestorId() != null) + ir.setRequestorId(iar.getRequestorId()); + + request.setInstanceReferences(ir); + String requestBody = iar.getRequestBody(); + RequestDetails requestDetails = null; + + if (requestBody != null) { + try { + ObjectMapper mapper = new ObjectMapper(); + requestDetails = mapper.readValue(requestBody, RequestDetails.class); + } catch (IOException 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; + } + } + + request.setRequestDetails(requestDetails); + String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT"; + request.setStartTime(startTimeStamp); + + RequestStatus status = new RequestStatus(); + if (iar.getStatusMessage() != null) { + status.setStatusMessage(iar.getStatusMessage()); + } + + if (iar.getEndTime() != null) { + String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT"; + status.setTimeStamp(endTimeStamp); + } + + if (iar.getRequestStatus() != null) { + status.setRequestState(iar.getRequestStatus()); + } + + if (iar.getProgress() != null) { + status.setPercentProgress(iar.getProgress().toString()); + } + + request.setRequestStatus(status); + + return request; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java index 60a05d74e5..f7b3811bce 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/GrmClientPropertiesImpl.java @@ -22,54 +22,52 @@ package org.onap.so.apihandlerinfra.tenantisolation; import java.net.MalformedURLException; import java.net.URL; - import javax.ws.rs.core.MediaType; - import org.onap.so.client.grm.GRMProperties; import org.onap.so.spring.SpringContextHelper; import org.springframework.context.ApplicationContext; public class GrmClientPropertiesImpl implements GRMProperties { - private String grmEndpoint; - private String grmAuth; - private String grmKey; - - public GrmClientPropertiesImpl() { - ApplicationContext context = SpringContextHelper.getAppContext(); - grmEndpoint = context.getEnvironment().getProperty("mso.grm.endpoint"); - grmAuth = context.getEnvironment().getProperty("mso.grm.auth"); - grmKey = context.getEnvironment().getProperty("mso.msoKey"); - } - - @Override - public URL getEndpoint() throws MalformedURLException { - return new URL(grmEndpoint); - } + private String grmEndpoint; + private String grmAuth; + private String grmKey; + + public GrmClientPropertiesImpl() { + ApplicationContext context = SpringContextHelper.getAppContext(); + grmEndpoint = context.getEnvironment().getProperty("mso.grm.endpoint"); + grmAuth = context.getEnvironment().getProperty("mso.grm.auth"); + grmKey = context.getEnvironment().getProperty("mso.msoKey"); + } + + @Override + public URL getEndpoint() throws MalformedURLException { + return new URL(grmEndpoint); + } - @Override - public String getSystemName() { - return "MSO"; - } + @Override + public String getSystemName() { + return "MSO"; + } - @Override - public String getDefaultVersion() { - return "v1"; - } + @Override + public String getDefaultVersion() { + return "v1"; + } - @Override - public String getAuth() { - return grmAuth; - } + @Override + public String getAuth() { + return grmAuth; + } - @Override - public String getKey() { - return grmKey; - } + @Override + public String getKey() { + return grmKey; + } - @Override - public String getContentType() { - return MediaType.APPLICATION_JSON; - } + @Override + public String getContentType() { + return MediaType.APPLICATION_JSON; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java index 4be1ec9187..b2933df030 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequest.java @@ -24,7 +24,6 @@ package org.onap.so.apihandlerinfra.tenantisolation; import java.io.IOException; import java.util.List; - import javax.inject.Provider; import javax.transaction.Transactional; import javax.ws.rs.Consumes; @@ -34,7 +33,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; @@ -54,110 +52,118 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Component @Path("/onap/so/infra/modelDistributions") -@Api(value="/onap/so/infra/modelDistributions",description="API Requests for Model Distributions") +@Api(value = "/onap/so/infra/modelDistributions", description = "API Requests for Model Distributions") public class ModelDistributionRequest { - - private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class); - @Autowired - private Provider<TenantIsolationRunnable> tenantIsolationRunnable; - - @PATCH - @Path("/{version:[vV][1]}/distributions/{distributionId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value="Update model distribution status",response=Response.class) - @Transactional - public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version, @PathParam("distributionId") String distributionId) throws ApiException{ - long startTime = System.currentTimeMillis (); - Distribution distributionRequest = null; - - try { - ObjectMapper mapper = new ObjectMapper(); - distributionRequest = mapper.readValue(requestJSON, Distribution.class); - } catch(IOException 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; - - } - - try { - parse(distributionRequest); - } catch(ValidationException e) { - - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, - ErrorCode.SchemaError).build(); - - - ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER) - .cause(e).errorInfo(errorLoggerInfo).build(); - throw validateException; - } - - CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); - cor.setDistribution(distributionRequest); - cor.setDistributionId(distributionId); - - TenantIsolationRunnable runnable = tenantIsolationRunnable.get(); - runnable.run(Action.distributionStatus, null, cor, null); - - return Response.ok().build(); - } - - private void parse(Distribution distributionRequest) throws ValidationException { - if(distributionRequest.getStatus() == null) { - throw new ValidationException("status"); - } - - if(StringUtils.isBlank(distributionRequest.getErrorReason()) && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) { - throw new ValidationException("errorReason"); - } - } - - private Response buildServiceErrorResponse (int httpResponseCode, MsoException exceptionType, String text, - String messageId, List<String> variables) throws ApiException{ - RequestError re = new RequestError(); - ServiceException se = new ServiceException(); - se.setMessageId(messageId); - se.setText(text); - if(variables != null){ - if(variables != null){ - for(String variable: variables){ - se.getVariables().add(variable); - } - } - } - re.setServiceException(se); + + private static Logger logger = LoggerFactory.getLogger(ModelDistributionRequest.class); + @Autowired + private Provider<TenantIsolationRunnable> tenantIsolationRunnable; + + @PATCH + @Path("/{version:[vV][1]}/distributions/{distributionId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "Update model distribution status", response = Response.class) + @Transactional + public Response updateModelDistributionStatus(String requestJSON, @PathParam("version") String version, + @PathParam("distributionId") String distributionId) throws ApiException { + long startTime = System.currentTimeMillis(); + Distribution distributionRequest = null; + + try { + ObjectMapper mapper = new ObjectMapper(); + distributionRequest = mapper.readValue(requestJSON, Distribution.class); + } catch (IOException 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; + + } + + try { + parse(distributionRequest); + } catch (ValidationException e) { + + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError) + .build(); + + + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); + throw validateException; + } + + CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); + cor.setDistribution(distributionRequest); + cor.setDistributionId(distributionId); + + TenantIsolationRunnable runnable = tenantIsolationRunnable.get(); + runnable.run(Action.distributionStatus, null, cor, null); + + return Response.ok().build(); + } + + private void parse(Distribution distributionRequest) throws ValidationException { + if (distributionRequest.getStatus() == null) { + throw new ValidationException("status"); + } + + if (StringUtils.isBlank(distributionRequest.getErrorReason()) + && Status.DISTRIBUTION_COMPLETE_ERROR.equals(distributionRequest.getStatus())) { + throw new ValidationException("errorReason"); + } + } + + private Response buildServiceErrorResponse(int httpResponseCode, MsoException exceptionType, String text, + String messageId, List<String> variables) throws ApiException { + RequestError re = new RequestError(); + ServiceException se = new ServiceException(); + se.setMessageId(messageId); + se.setText(text); + if (variables != null) { + if (variables != null) { + for (String variable : variables) { + se.getVariables().add(variable); + } + } + } + re.setServiceException(se); String requestErrorStr = null; - try{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_DEFAULT); - requestErrorStr = mapper.writeValueAsString(re); - }catch(JsonProcessingException e){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_DEFAULT); + requestErrorStr = mapper.writeValueAsString(re); + } catch (JsonProcessingException e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).build(); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.DataError).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; + 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; } - return Response.status (httpResponseCode).entity(requestErrorStr).build (); + return Response.status(httpResponseCode).entity(requestErrorStr).build(); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java index 82a5d1ebbf..696616099f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequest.java @@ -27,9 +27,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; - import javax.ws.rs.core.MultivaluedMap; - import org.apache.commons.lang3.StringUtils; import org.onap.so.apihandlerinfra.Constants; import org.onap.so.apihandlerinfra.Status; @@ -49,14 +47,12 @@ import org.onap.so.db.request.client.RequestsDbClient; import org.onap.so.exceptions.ValidationException; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @@ -75,316 +71,323 @@ public class TenantIsolationRequest { private long progress = Constants.PROGRESS_REQUEST_RECEIVED; private String requestScope; private CloudOrchestrationRequest cor; - + @Autowired - private RequestsDbClient requestsDbClient; - + private RequestsDbClient requestsDbClient; + private static Logger logger = LoggerFactory.getLogger(TenantIsolationRequest.class); - TenantIsolationRequest (String requestId) { + TenantIsolationRequest(String requestId) { this.requestId = requestId; } - TenantIsolationRequest () { + TenantIsolationRequest() {} + + void parse(CloudOrchestrationRequest request, HashMap<String, String> instanceIdMap, Action action) + throws ValidationException { + this.cor = request; + this.requestInfo = request.getRequestDetails().getRequestInfo(); + + try { + ObjectMapper mapper = new ObjectMapper(); + requestJSON = mapper.writeValueAsString(request.getRequestDetails()); + + } catch (JsonProcessingException e) { + throw new ValidationException("Parse ServiceInstanceRequest to JSON string", true); + } + + String envId = null; + if (instanceIdMap != null) { + envId = instanceIdMap.get("operationalEnvironmentId"); + if (envId != null && !UUIDChecker.isValidUUID(envId)) { + throw new ValidationException("operationalEnvironmentId", true); + } + cor.setOperationalEnvironmentId(envId); + } + + this.operationalEnvironmentId = envId; + + RequestDetails requestDetails = request.getRequestDetails(); + RequestParameters requestParameters = requestDetails.getRequestParameters(); + + requestInfoValidation(action, requestInfo); + + requestParamsValidation(action, requestParameters); + + relatedInstanceValidation(action, requestDetails, requestParameters); + + } + + private void relatedInstanceValidation(Action action, RequestDetails requestDetails, + RequestParameters requestParameters) throws ValidationException { + RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList(); + + if (requestParameters == null) { + throw new ValidationException("requestParameters", true); + } + if ((Action.activate.equals(action) || Action.deactivate.equals(action)) + && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) { + throw new ValidationException("operationalEnvironmentType in requestParameters", true); + } + + if (!Action.deactivate.equals(action) + && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) { + if (instanceList != null && instanceList.length > 0) { + for (RelatedInstanceList relatedInstanceList : instanceList) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + + if (relatedInstance.getResourceType() == null) { + throw new ValidationException("ResourceType in relatedInstance", true); + } + + if (!empty(relatedInstance.getInstanceName()) + && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { + throw new ValidationException("instanceName format", true); + } + + if (empty(relatedInstance.getInstanceId())) { + throw new ValidationException("instanceId in relatedInstance", true); + } + + if (!UUIDChecker.isValidUUID(relatedInstance.getInstanceId())) { + throw new ValidationException("instanceId format in relatedInstance", true); + } + } + } else { + throw new ValidationException("relatedInstanceList", true); + } + } } - - void parse(CloudOrchestrationRequest request, HashMap<String,String> instanceIdMap, Action action) throws ValidationException { - this.cor = request; - this.requestInfo = request.getRequestDetails().getRequestInfo(); - - try{ - ObjectMapper mapper = new ObjectMapper(); - requestJSON = mapper.writeValueAsString(request.getRequestDetails()); - - } catch(JsonProcessingException e){ - throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", true); + + private void requestParamsValidation(Action action, RequestParameters requestParameters) + throws ValidationException { + + if (requestParameters != null) { + if (!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) { + throw new ValidationException("OperationalEnvironmentType", true); + } + + if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) { + throw new ValidationException("Tenant Context", true); + } + if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) { + throw new ValidationException("Workload Context", true); + } + + Manifest manifest = requestParameters.getManifest(); + + if (Action.activate.equals(action)) { + if (manifest == null) { + throw new ValidationException("Manifest on Activate", true); + } else { + List<ServiceModelList> serviceModelList = manifest.getServiceModelList(); + + if (serviceModelList.isEmpty()) { + throw new ValidationException(" empty ServiceModelList", true); + } + + for (ServiceModelList list : serviceModelList) { + if (empty(list.getServiceModelVersionId())) { + throw new ValidationException("ServiceModelVersionId", true); + } + + if (!UUIDChecker.isValidUUID(list.getServiceModelVersionId())) { + throw new ValidationException("ServiceModelVersionId format", true); + } + + if (list.getRecoveryAction() == null) { + throw new ValidationException("RecoveryAction", true); + } + } + } + } + } else if (!Action.deactivate.equals(action)) { + throw new ValidationException("request Parameters", true); + } + } + + private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException { + + if (Action.create.equals(action) && empty(requestInfo.getInstanceName())) { + throw new ValidationException("instanceName", true); + } + + if (!empty(requestInfo.getInstanceName()) + && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { + throw new ValidationException("instanceName format", true); + } + + if (empty(requestInfo.getSource())) { + throw new ValidationException("source", true); } - - String envId = null; - if(instanceIdMap != null) { - envId = instanceIdMap.get("operationalEnvironmentId"); - if(envId != null && !UUIDChecker.isValidUUID (envId)){ - throw new ValidationException ("operationalEnvironmentId", true); - } - cor.setOperationalEnvironmentId(envId); - } - - this.operationalEnvironmentId = envId; - - RequestDetails requestDetails = request.getRequestDetails(); - RequestParameters requestParameters = requestDetails.getRequestParameters(); - - requestInfoValidation(action, requestInfo); - - requestParamsValidation(action, requestParameters); - - relatedInstanceValidation(action, requestDetails, requestParameters); - - } - - private void relatedInstanceValidation(Action action, RequestDetails requestDetails, RequestParameters requestParameters) throws ValidationException { - RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList(); - - if (requestParameters == null) { - throw new ValidationException("requestParameters", true); - } - if((Action.activate.equals(action) || Action.deactivate.equals(action)) && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) { - throw new ValidationException("operationalEnvironmentType in requestParameters", true); - } - - if(!Action.deactivate.equals(action) && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) { - if(instanceList != null && instanceList.length > 0) { - for(RelatedInstanceList relatedInstanceList : instanceList){ - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - - if(relatedInstance.getResourceType() == null) { - throw new ValidationException("ResourceType in relatedInstance", true); - } - - if(!empty(relatedInstance.getInstanceName()) && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { - throw new ValidationException ("instanceName format", true); - } - - if (empty (relatedInstance.getInstanceId ())) { - throw new ValidationException ("instanceId in relatedInstance", true); - } - - if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) { - throw new ValidationException ("instanceId format in relatedInstance", true); - } - } - } else { - throw new ValidationException ("relatedInstanceList", true); - } - } - } - - private void requestParamsValidation(Action action, RequestParameters requestParameters) throws ValidationException { - - if(requestParameters != null) { - if(!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) { - throw new ValidationException ("OperationalEnvironmentType", true); - } - - if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) { - throw new ValidationException ("Tenant Context", true); - } - if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) { - throw new ValidationException ("Workload Context", true); - } - - Manifest manifest = requestParameters.getManifest(); - - if(Action.activate.equals(action)) { - if(manifest == null) { - throw new ValidationException ("Manifest on Activate", true); - } else { - List<ServiceModelList> serviceModelList = manifest.getServiceModelList(); - - if(serviceModelList.isEmpty()) { - throw new ValidationException (" empty ServiceModelList", true); - } - - for(ServiceModelList list : serviceModelList) { - if(empty(list.getServiceModelVersionId())) { - throw new ValidationException ("ServiceModelVersionId", true); - } - - if (!UUIDChecker.isValidUUID (list.getServiceModelVersionId())) { - throw new ValidationException ("ServiceModelVersionId format", true); - } - - if(list.getRecoveryAction() == null) { - throw new ValidationException ("RecoveryAction", true); - } - } - } - } - } else if(!Action.deactivate.equals(action)) { - throw new ValidationException("request Parameters", true); - } - } - - private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException { - - if(Action.create.equals(action) && empty(requestInfo.getInstanceName())) { - throw new ValidationException ("instanceName", true); - } - - if(!empty(requestInfo.getInstanceName()) && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { - throw new ValidationException ("instanceName format", true); - } - - if (empty(requestInfo.getSource())) { - throw new ValidationException ("source", true); + + if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId", true); } - - if(empty(requestInfo.getRequestorId())) { - throw new ValidationException ("requestorId", true); + + ResourceType resourceType = requestInfo.getResourceType(); + if (resourceType == null) { + throw new ValidationException("resourceType", true); } - - ResourceType resourceType = requestInfo.getResourceType(); - if(resourceType == null) { - throw new ValidationException ("resourceType", true); - } - - this.requestScope = resourceType.name(); - } - - void parseOrchestration (CloudOrchestrationRequest cor) throws ValidationException { + + this.requestScope = resourceType.name(); + } + + void parseOrchestration(CloudOrchestrationRequest cor) throws ValidationException { this.cor = cor; - try{ - ObjectMapper mapper = new ObjectMapper(); - requestJSON = mapper.writeValueAsString(cor.getRequestDetails()); + try { + ObjectMapper mapper = new ObjectMapper(); + requestJSON = mapper.writeValueAsString(cor.getRequestDetails()); - } catch(JsonProcessingException e){ - throw new ValidationException ("Parse CloudOrchestrationRequest to JSON string", e); + } catch (JsonProcessingException e) { + throw new ValidationException("Parse CloudOrchestrationRequest to JSON string", e); } - if(cor.getRequestDetails() == null){ + if (cor.getRequestDetails() == null) { throw new ValidationException("requestDetails", true); } this.requestInfo = cor.getRequestDetails().getRequestInfo(); if (this.requestInfo == null) { - throw new ValidationException ("requestInfo", true); + throw new ValidationException("requestInfo", true); } - if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source", true); + if (empty(requestInfo.getSource())) { + throw new ValidationException("source", true); } - if (empty (requestInfo.getRequestorId ())) { - throw new ValidationException ("requestorId", true); + if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId", true); } } - - public void createRequestRecord (Status status, Action action){ - - InfraActiveRequests aq = new InfraActiveRequests (); - aq.setRequestId (requestId); - - aq.setRequestAction(action.name()); - aq.setAction(action.name()); - - Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis()); - - aq.setStartTime (startTimeStamp); - - if (requestInfo != null) { - - if(requestInfo.getSource() != null){ - aq.setSource(requestInfo.getSource()); - } - if(requestInfo.getRequestorId() != null) { - aq.setRequestorId(requestInfo.getRequestorId()); - } - if(requestInfo.getResourceType() != null) { - aq.setRequestScope(requestInfo.getResourceType().name()); - } - } - - if(ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) { - aq.setOperationalEnvId(operationalEnvironmentId); - aq.setOperationalEnvName(requestInfo.getInstanceName()); - } - - aq.setRequestBody (this.requestJSON); - - aq.setRequestStatus (status.toString ()); - aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER); - - if ((status == Status.FAILED) || (status == Status.COMPLETE)) { - aq.setStatusMessage (this.errorMessage); - aq.setResponseBody (this.responseBody); - aq.setProgress(Long.valueOf(100)); - - Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis()); - aq.setEndTime (endTimeStamp); - } else if(status == Status.IN_PROGRESS) { - aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS); - } - requestsDbClient.save(aq); + + public void createRequestRecord(Status status, Action action) { + + InfraActiveRequests aq = new InfraActiveRequests(); + aq.setRequestId(requestId); + + aq.setRequestAction(action.name()); + aq.setAction(action.name()); + + Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis()); + + aq.setStartTime(startTimeStamp); + + if (requestInfo != null) { + + if (requestInfo.getSource() != null) { + aq.setSource(requestInfo.getSource()); + } + if (requestInfo.getRequestorId() != null) { + aq.setRequestorId(requestInfo.getRequestorId()); + } + if (requestInfo.getResourceType() != null) { + aq.setRequestScope(requestInfo.getResourceType().name()); + } + } + + if (ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) { + aq.setOperationalEnvId(operationalEnvironmentId); + aq.setOperationalEnvName(requestInfo.getInstanceName()); + } + + aq.setRequestBody(this.requestJSON); + + aq.setRequestStatus(status.toString()); + aq.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + + if ((status == Status.FAILED) || (status == Status.COMPLETE)) { + aq.setStatusMessage(this.errorMessage); + aq.setResponseBody(this.responseBody); + aq.setProgress(Long.valueOf(100)); + + Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis()); + aq.setEndTime(endTimeStamp); + } else if (status == Status.IN_PROGRESS) { + aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS); + } + requestsDbClient.save(aq); } - - - public Map<String, String> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException { + + + public Map<String, String> getOrchestrationFilters(MultivaluedMap<String, String> queryParams) + throws ValidationException { String queryParam = null; Map<String, String> orchestrationFilterParams = new HashMap<>(); - for (Entry<String,List<String>> entry : queryParams.entrySet()) { + for (Entry<String, List<String>> entry : queryParams.entrySet()) { queryParam = entry.getKey(); - try{ - for(String value : entry.getValue()) { - if(StringUtils.isBlank(value)) { - throw (new Exception(queryParam + " value")); - } - orchestrationFilterParams.put(queryParam, value); - } - }catch(Exception e){ - throw new ValidationException (e.getMessage(), true); - } + try { + for (String value : entry.getValue()) { + if (StringUtils.isBlank(value)) { + throw (new Exception(queryParam + " value")); + } + orchestrationFilterParams.put(queryParam, value); + } + } catch (Exception e) { + throw new ValidationException(e.getMessage(), true); + } } return orchestrationFilterParams; - } + } + + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } - - public String getRequestId () { + public String getRequestId() { return requestId; } - + public void setRequestId(String requestId) { - this.requestId = requestId; + this.requestId = requestId; + } + + public void updateFinalStatus() { + try { + InfraActiveRequests request = new InfraActiveRequests(requestId); + request.setRequestStatus(status.toString()); + request.setStatusMessage(this.errorMessage); + request.setProgress(this.progress); + request.setResponseBody(this.responseBody); + request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); + requestsDbClient.save(request); + } catch (Exception e) { + logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), + ErrorCode.DataError.getValue(), "Exception when updating record in DB"); + logger.debug("Exception: ", e); + } } - public void updateFinalStatus() { - try { - InfraActiveRequests request = new InfraActiveRequests(requestId); - request.setRequestStatus(status.toString()); - request.setStatusMessage(this.errorMessage); - request.setProgress(this.progress); - request.setResponseBody(this.responseBody); - request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER); - requestsDbClient.save(request); - } catch (Exception e) { - logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(), - ErrorCode.DataError.getValue(), "Exception when updating record in DB"); - logger.debug("Exception: ", e); - } - } - - public void setStatus (RequestStatusType status) { + public void setStatus(RequestStatusType status) { this.status = status; switch (status) { - case FAILED: - case COMPLETE: - this.progress = Constants.PROGRESS_REQUEST_COMPLETED; - break; - case IN_PROGRESS: - this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS; - break; - case PENDING: - break; - case TIMEOUT: - break; - case UNLOCKED: - break; - default: - break; + case FAILED: + case COMPLETE: + this.progress = Constants.PROGRESS_REQUEST_COMPLETED; + break; + case IN_PROGRESS: + this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS; + break; + case PENDING: + break; + case TIMEOUT: + break; + case UNLOCKED: + break; + default: + break; } } - public String getOperationalEnvironmentId() { - return operationalEnvironmentId; - } + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } - public void setOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; - } + public void setOperationalEnvironmentId(String operationalEnvironmentId) { + this.operationalEnvironmentId = operationalEnvironmentId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java index 98104e9073..b2596f9013 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRunnable.java @@ -48,57 +48,63 @@ import org.springframework.stereotype.Component; @Scope("prototype") public class TenantIsolationRunnable { - private static final Logger logger = LoggerFactory.getLogger(TenantIsolationRunnable.class); - - @Autowired - private RequestsDBHelper requestDb; - @Autowired - private CreateEcompOperationalEnvironment createEcompOpEnv; - @Autowired - private CreateVnfOperationalEnvironment createVnfOpEnv; - @Autowired - private ActivateVnfOperationalEnvironment activateVnfOpEnv; - @Autowired - private DeactivateVnfOperationalEnvironment deactivateVnfOpEnv; - @Autowired - private ActivateVnfStatusOperationalEnvironment activateVnfStatusOpEnv; - - @Async - public void run(Action action, String operationalEnvType, CloudOrchestrationRequest cor, String requestId) throws ApiException { + private static final Logger logger = LoggerFactory.getLogger(TenantIsolationRunnable.class); - logger.debug("Starting threadExecution in TenantIsolationRunnable for Action {} and OperationalEnvType: {}", - action.name(), operationalEnvType); - try { - - if(Action.create.equals(action)) { - if(OperationalEnvironment.ECOMP.name().equalsIgnoreCase(operationalEnvType)) { - createEcompOpEnv.execute(requestId, cor); - } else if(OperationalEnvironment.VNF.name().equalsIgnoreCase(operationalEnvType)) { - createVnfOpEnv.execute(requestId, cor); - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = new ValidateException.Builder("Invalid OperationalEnvironment Type specified for Create Action", + @Autowired + private RequestsDBHelper requestDb; + @Autowired + private CreateEcompOperationalEnvironment createEcompOpEnv; + @Autowired + private CreateVnfOperationalEnvironment createVnfOpEnv; + @Autowired + private ActivateVnfOperationalEnvironment activateVnfOpEnv; + @Autowired + private DeactivateVnfOperationalEnvironment deactivateVnfOpEnv; + @Autowired + private ActivateVnfStatusOperationalEnvironment activateVnfStatusOpEnv; + + @Async + public void run(Action action, String operationalEnvType, CloudOrchestrationRequest cor, String requestId) + throws ApiException { + + logger.debug("Starting threadExecution in TenantIsolationRunnable for Action {} and OperationalEnvType: {}", + action.name(), operationalEnvType); + try { + + if (Action.create.equals(action)) { + if (OperationalEnvironment.ECOMP.name().equalsIgnoreCase(operationalEnvType)) { + createEcompOpEnv.execute(requestId, cor); + } else if (OperationalEnvironment.VNF.name().equalsIgnoreCase(operationalEnvType)) { + createVnfOpEnv.execute(requestId, cor); + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError) + .build(); + ValidateException validateException = new ValidateException.Builder( + "Invalid OperationalEnvironment Type specified for Create Action", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo) - .build(); + .build(); throw validateException; - } - } else if(Action.activate.equals(action)) { - activateVnfOpEnv.execute(requestId, cor); - } else if(Action.deactivate.equals(action)) { - deactivateVnfOpEnv.execute(requestId, cor); - } else if(Action.distributionStatus.equals(action)) { - activateVnfStatusOpEnv.execute(requestId, cor); - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = new ValidateException.Builder("Invalid Action specified: " + action, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); + } + } else if (Action.activate.equals(action)) { + activateVnfOpEnv.execute(requestId, cor); + } else if (Action.deactivate.equals(action)) { + deactivateVnfOpEnv.execute(requestId, cor); + } else if (Action.distributionStatus.equals(action)) { + activateVnfStatusOpEnv.execute(requestId, cor); + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + ValidateException validateException = + new ValidateException.Builder("Invalid Action specified: " + action, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); throw validateException; - } - }catch(ApiException e) { + } + } catch (ApiException e) { requestDb.updateInfraFailureCompletion(e.getMessage(), requestId, cor.getOperationalEnvironmentId()); throw e; } - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java index 44198d727d..d79e5311c7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/CreateEcompOperationEnvironmentBean.java @@ -26,137 +26,132 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) -@JsonPropertyOrder({ - "operationalEnvironmentId", - "operationalEnvironmentName", - "operationalEnvironmentType", - "tenantContext", - "workloadContext" -}) +@JsonPropertyOrder({"operationalEnvironmentId", "operationalEnvironmentName", "operationalEnvironmentType", + "tenantContext", "workloadContext"}) public class CreateEcompOperationEnvironmentBean { - @JsonProperty("operationalEnvironmentId") - private String operationalEnvironmentId; - @JsonProperty("operationalEnvironmentName") - private String operationalEnvironmentName; - @JsonProperty("operationalEnvironmentType") - private String operationalEnvironmentType; - @JsonProperty("tenantContext") - private String tenantContext; - @JsonProperty("workloadContext") - private String workloadContext; - @JsonProperty("action") - private String action; - - public CreateEcompOperationEnvironmentBean() {} - - /** - * - * @param operationalEnvironmentId - * @param operationalEnvironmentName - * @param operationalEnvironmentType - * @param tenantContext - * @param workloadContext - */ - public CreateEcompOperationEnvironmentBean(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, - String tenantContext, String workloadContext, String action) { - this.operationalEnvironmentId = operationalEnvironmentId; - this.operationalEnvironmentName = operationalEnvironmentName; - this.operationalEnvironmentType = operationalEnvironmentType; - this.tenantContext = tenantContext; - this.workloadContext = workloadContext; - this.action = action; - } - - @JsonProperty("operationalEnvironmentId") - public String getOperationalEnvironmentId() { - return operationalEnvironmentId; - } - - @JsonProperty("operationalEnvironmentId") - public void setOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; - } - - public CreateEcompOperationEnvironmentBean withOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; - return this; - } - - - @JsonProperty("operationalEnvironmentName") - public String getoperationalEnvironmentName() { - return operationalEnvironmentName; - } - - @JsonProperty("operationalEnvironmentName") - public void setoperationalEnvironmentName(String operationalEnvironmentName) { - this.operationalEnvironmentName = operationalEnvironmentName; - } - - public CreateEcompOperationEnvironmentBean withOperationalEnvironmentName(String operationalEnvironmentName) { - this.operationalEnvironmentName = operationalEnvironmentName; - return this; - } - - @JsonProperty("operationalEnvironmentType") - public String getoperationalEnvironmentType() { - return operationalEnvironmentType; - } - - @JsonProperty("operationalEnvironmentType") - public void setoperationalEnvironmentType(String operationalEnvironmentType) { - this.operationalEnvironmentType = operationalEnvironmentType; - } - - public CreateEcompOperationEnvironmentBean withOperationalEnvironmentType(String operationalEnvironmentType) { - this.operationalEnvironmentType = operationalEnvironmentType; - return this; - } - - @JsonProperty("tenantContext") - public String gettenantContext() { - return tenantContext; - } - - @JsonProperty("tenantContext") - public void settenantContext(String tenantContext) { - this.tenantContext = tenantContext; - } - - public CreateEcompOperationEnvironmentBean withTenantContext(String tenantContext) { - this.tenantContext = tenantContext; - return this; - } - - @JsonProperty("workloadContext") - public String getworkloadContext() { - return workloadContext; - } - - @JsonProperty("workloadContext") - public void setworkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - } - - public CreateEcompOperationEnvironmentBean withWorkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - return this; - } - - @JsonProperty("action") - public String getaction() { - return action; - } - - @JsonProperty("action") - public void setaction(String action) { - this.action = action; - } - - public CreateEcompOperationEnvironmentBean withaction(String action) { - this.action = action; - return this; - } + @JsonProperty("operationalEnvironmentId") + private String operationalEnvironmentId; + @JsonProperty("operationalEnvironmentName") + private String operationalEnvironmentName; + @JsonProperty("operationalEnvironmentType") + private String operationalEnvironmentType; + @JsonProperty("tenantContext") + private String tenantContext; + @JsonProperty("workloadContext") + private String workloadContext; + @JsonProperty("action") + private String action; + + public CreateEcompOperationEnvironmentBean() {} + + /** + * + * @param operationalEnvironmentId + * @param operationalEnvironmentName + * @param operationalEnvironmentType + * @param tenantContext + * @param workloadContext + */ + public CreateEcompOperationEnvironmentBean(String operationalEnvironmentId, String operationalEnvironmentName, + String operationalEnvironmentType, String tenantContext, String workloadContext, String action) { + this.operationalEnvironmentId = operationalEnvironmentId; + this.operationalEnvironmentName = operationalEnvironmentName; + this.operationalEnvironmentType = operationalEnvironmentType; + this.tenantContext = tenantContext; + this.workloadContext = workloadContext; + this.action = action; + } + + @JsonProperty("operationalEnvironmentId") + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + @JsonProperty("operationalEnvironmentId") + public void setOperationalEnvironmentId(String operationalEnvironmentId) { + this.operationalEnvironmentId = operationalEnvironmentId; + } + + public CreateEcompOperationEnvironmentBean withOperationalEnvironmentId(String operationalEnvironmentId) { + this.operationalEnvironmentId = operationalEnvironmentId; + return this; + } + + + @JsonProperty("operationalEnvironmentName") + public String getoperationalEnvironmentName() { + return operationalEnvironmentName; + } + + @JsonProperty("operationalEnvironmentName") + public void setoperationalEnvironmentName(String operationalEnvironmentName) { + this.operationalEnvironmentName = operationalEnvironmentName; + } + + public CreateEcompOperationEnvironmentBean withOperationalEnvironmentName(String operationalEnvironmentName) { + this.operationalEnvironmentName = operationalEnvironmentName; + return this; + } + + @JsonProperty("operationalEnvironmentType") + public String getoperationalEnvironmentType() { + return operationalEnvironmentType; + } + + @JsonProperty("operationalEnvironmentType") + public void setoperationalEnvironmentType(String operationalEnvironmentType) { + this.operationalEnvironmentType = operationalEnvironmentType; + } + + public CreateEcompOperationEnvironmentBean withOperationalEnvironmentType(String operationalEnvironmentType) { + this.operationalEnvironmentType = operationalEnvironmentType; + return this; + } + + @JsonProperty("tenantContext") + public String gettenantContext() { + return tenantContext; + } + + @JsonProperty("tenantContext") + public void settenantContext(String tenantContext) { + this.tenantContext = tenantContext; + } + + public CreateEcompOperationEnvironmentBean withTenantContext(String tenantContext) { + this.tenantContext = tenantContext; + return this; + } + + @JsonProperty("workloadContext") + public String getworkloadContext() { + return workloadContext; + } + + @JsonProperty("workloadContext") + public void setworkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } + + public CreateEcompOperationEnvironmentBean withWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + return this; + } + + @JsonProperty("action") + public String getaction() { + return action; + } + + @JsonProperty("action") + public void setaction(String action) { + this.action = action; + } + + public CreateEcompOperationEnvironmentBean withaction(String action) { + this.action = action; + return this; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java index 55b1ea6198..340d143b42 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClient.java @@ -21,9 +21,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import java.io.IOException; - import javax.inject.Provider; - import org.apache.http.HttpStatus; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.exceptions.ApiException; @@ -33,49 +31,53 @@ import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @Component public class DmaapOperationalEnvClient { - @Autowired - private Provider<OperationalEnvironmentPublisher> dmaapPublisher; - - protected String buildRequest(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, String tenantContext, String workloadContext, String action ) - throws ApiException { - final CreateEcompOperationEnvironmentBean operationalEnv = new CreateEcompOperationEnvironmentBean(); - operationalEnv.withOperationalEnvironmentId(operationalEnvironmentId) - .withOperationalEnvironmentName(operationalEnvironmentName) - .withOperationalEnvironmentType(operationalEnvironmentType) - .withTenantContext(tenantContext) - .withWorkloadContext(workloadContext) - .withaction(action); - try { - return this.getJson(operationalEnv); - }catch(JsonProcessingException ex){ - 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 : " + ex.getMessage(), - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex).errorInfo(errorLoggerInfo).build(); + @Autowired + private Provider<OperationalEnvironmentPublisher> dmaapPublisher; + + protected String buildRequest(String operationalEnvironmentId, String operationalEnvironmentName, + String operationalEnvironmentType, String tenantContext, String workloadContext, String action) + throws ApiException { + final CreateEcompOperationEnvironmentBean operationalEnv = new CreateEcompOperationEnvironmentBean(); + operationalEnv.withOperationalEnvironmentId(operationalEnvironmentId) + .withOperationalEnvironmentName(operationalEnvironmentName) + .withOperationalEnvironmentType(operationalEnvironmentType).withTenantContext(tenantContext) + .withWorkloadContext(workloadContext).withaction(action); + try { + return this.getJson(operationalEnv); + } catch (JsonProcessingException ex) { + 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 : " + ex.getMessage(), + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(ex) + .errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + + protected String getJson(CreateEcompOperationEnvironmentBean obj) throws JsonProcessingException { + + final ObjectMapper mapper = new ObjectMapper(); + return mapper.writeValueAsString(obj); - throw validateException; - } - } + } - protected String getJson(CreateEcompOperationEnvironmentBean obj) throws JsonProcessingException { - - final ObjectMapper mapper = new ObjectMapper(); - return mapper.writeValueAsString(obj); - - } - - public void dmaapPublishOperationalEnvRequest(String operationalEnvironmentId, String operationalEnvironmentName, String operationalEnvironmentType, - String tenantContext, String workloadContext, String action ) throws ApiException, IOException, InterruptedException { + public void dmaapPublishOperationalEnvRequest(String operationalEnvironmentId, String operationalEnvironmentName, + String operationalEnvironmentType, String tenantContext, String workloadContext, String action) + throws ApiException, IOException, InterruptedException { - String request = this.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType, tenantContext, workloadContext, action); - dmaapPublisher.get().send(request); + String request = this.buildRequest(operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + dmaapPublisher.get().send(request); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java index 8409d9c300..4ba69f55e9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapPropertiesImpl.java @@ -22,34 +22,30 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import java.util.HashMap; import java.util.Map; - import org.onap.so.client.dmaap.DmaapProperties; import org.onap.so.spring.SpringContextHelper; import org.springframework.context.ApplicationContext; public class DmaapPropertiesImpl implements DmaapProperties { - private final Map<String, String> props = new HashMap<>(); - private static final String[] propertyNames = { - "mso.so.operational-environment.dmaap.auth", - "mso.msoKey", - "mso.so.operational-environment.publisher.topic", - "mso.so.operational-environment.dmaap.host" - }; - public DmaapPropertiesImpl () { - ApplicationContext context = SpringContextHelper.getAppContext(); - - for (String name : propertyNames) { - this.props.put(name, context.getEnvironment().getProperty(name)); - - } - - } - - @Override - public Map<String, String> getProperties() { - - return this.props; - } + private final Map<String, String> props = new HashMap<>(); + private static final String[] propertyNames = {"mso.so.operational-environment.dmaap.auth", "mso.msoKey", + "mso.so.operational-environment.publisher.topic", "mso.so.operational-environment.dmaap.host"}; + + public DmaapPropertiesImpl() { + ApplicationContext context = SpringContextHelper.getAppContext(); + + for (String name : propertyNames) { + this.props.put(name, context.getEnvironment().getProperty(name)); + + } + + } + + @Override + public Map<String, String> getProperties() { + + return this.props; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java index 31bc6fcb4f..350a091d97 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisher.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import java.io.IOException; import java.util.Optional; - import org.onap.so.client.dmaap.DmaapPublisher; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -31,31 +30,31 @@ import org.springframework.stereotype.Component; @Scope("prototype") public class OperationalEnvironmentPublisher extends DmaapPublisher { - - public OperationalEnvironmentPublisher() throws IOException { - super(); - } - - @Override - public String getAuth() { - - return this.msoProperties.get("mso.so.operational-environment.dmaap.auth"); - } - - @Override - public String getKey() { - - return this.msoProperties.get("mso.msoKey"); - } - - @Override - public String getTopic() { - - return this.msoProperties.get("mso.so.operational-environment.publisher.topic"); - } - - @Override - public Optional<String> getHost() { - return Optional.ofNullable(this.msoProperties.get("mso.so.operational-environment.dmaap.host")); - } + + public OperationalEnvironmentPublisher() throws IOException { + super(); + } + + @Override + public String getAuth() { + + return this.msoProperties.get("mso.so.operational-environment.dmaap.auth"); + } + + @Override + public String getKey() { + + return this.msoProperties.get("mso.msoKey"); + } + + @Override + public String getTopic() { + + return this.msoProperties.get("mso.so.operational-environment.publisher.topic"); + } + + @Override + public Optional<String> getHost() { + return Optional.ofNullable(this.msoProperties.get("mso.so.operational-environment.dmaap.host")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java index 4f4fa1ae35..3ceb8e7897 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailed.java @@ -22,8 +22,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; public class AAIClientCallFailed extends Exception { - public AAIClientCallFailed(String message, Throwable cause) { - super(message, cause); - } + public AAIClientCallFailed(String message, Throwable cause) { + super(message, cause); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java index 9cdef3c9d1..cacbb557b2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailed.java @@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; public class SDCClientCallFailed extends Exception { - private static final long serialVersionUID = 3066575499816576134L; + private static final long serialVersionUID = 3066575499816576134L; + + public SDCClientCallFailed(String message, Throwable cause) { + super(message, cause); + } + + public SDCClientCallFailed(String message) { + super(message); + } - public SDCClientCallFailed(String message, Throwable cause) { - super(message, cause); - } - public SDCClientCallFailed(String message) { - super(message); - } - - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java index af3e7937af..14e6464960 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationException.java @@ -22,15 +22,15 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; public class TenantIsolationException extends Exception { - private static final long serialVersionUID = 6948152225371031774L; - - public TenantIsolationException() { - super(); - - } - - public TenantIsolationException(String msg) { - super ("Tenant Isolation error: " + msg); - - } -}
\ No newline at end of file + private static final long serialVersionUID = 6948152225371031774L; + + public TenantIsolationException() { + super(); + + } + + public TenantIsolationException(String msg) { + super("Tenant Isolation error: " + msg); + + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java index 870fa11b5c..8b3b91ae1a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelper.java @@ -25,9 +25,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; - import javax.ws.rs.NotFoundException; - import org.onap.aai.domain.yang.OperationalEnvironment; import org.onap.so.apihandlerinfra.tenantisolation.exceptions.AAIClientCallFailed; import org.onap.so.client.aai.AAIObjectType; @@ -43,81 +41,89 @@ import org.springframework.stereotype.Component; @Component public class AAIClientHelper { - - private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class); - - /** - * Get managing ECOMP Environment Info from A&AI - * @param id = operationalEnvironmentId - * @return AAIResultWrapper object - */ - public AAIResultWrapper getAaiOperationalEnvironment(String id){ - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id); - uri.depth(Depth.ZERO); - AAIResourcesClient client = this.getClient(); - return client.get(uri, NotFoundException.class); - } - - - /** - * Update managing ECOMP Environment Info from A&AI - * @param id = operationalEnvironmentId - * @param AAIOperationalEnvironment object - */ - public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest){ - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id); - AAIResourcesClient client = this.getClient(); - client.update(uri, aaiRequest); - - } - - - public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) throws Exception { - try { - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId); - AAIResourcesClient aaiClient = this.getClient(); - aaiClient.update(uri, payload); - } - catch(Exception ex) { - logStackTrace(ex); - throw new AAIClientCallFailed("Call to A&AI failed!", ex); - } - } - - /** - * Create an Operational Environment object in A&AI - * @param AAIOperationalEnvironment object - */ - public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment){ - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironment.getOperationalEnvironmentId()); - AAIResourcesClient client = this.getClient(); - client.create(uri, operationalEnvironment); - } - - /** - * Create a relationship between ECOMP managing and VNF Operational Environments - * @param managingEcompOperationalEnvironmentId - * @param vnfOperationalEnvironmentId - * @throws Exception - */ - public void createRelationship(String managingEcompOperationalEnvironmentId, String vnfOperationalEnvironmentId) { - - AAIResourceUri ecompEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, managingEcompOperationalEnvironmentId); - AAIResourceUri vnfEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, vnfOperationalEnvironmentId); - AAIResourcesClient client = this.getClient(); - client.connect(vnfEnvUri, ecompEnvUri); - - } - - private void logStackTrace(Exception e) { - StringWriter sw = new StringWriter(); - e.printStackTrace(new PrintWriter(sw)); - } - - protected AAIResourcesClient getClient() { - return new AAIResourcesClient(); - } + + private static Logger logger = LoggerFactory.getLogger(AAIClientHelper.class); + + /** + * Get managing ECOMP Environment Info from A&AI + * + * @param id = operationalEnvironmentId + * @return AAIResultWrapper object + */ + public AAIResultWrapper getAaiOperationalEnvironment(String id) { + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id); + uri.depth(Depth.ZERO); + AAIResourcesClient client = this.getClient(); + return client.get(uri, NotFoundException.class); + } + + + /** + * Update managing ECOMP Environment Info from A&AI + * + * @param id = operationalEnvironmentId + * @param AAIOperationalEnvironment object + */ + public void updateAaiOperationalEnvironment(String id, OperationalEnvironment aaiRequest) { + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, id); + AAIResourcesClient client = this.getClient(); + client.update(uri, aaiRequest); + + } + + + public void updateAaiOperationalEnvironment(String operationalEnvironmentId, Map<String, String> payload) + throws Exception { + try { + AAIResourceUri uri = + AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, operationalEnvironmentId); + AAIResourcesClient aaiClient = this.getClient(); + aaiClient.update(uri, payload); + } catch (Exception ex) { + logStackTrace(ex); + throw new AAIClientCallFailed("Call to A&AI failed!", ex); + } + } + + /** + * Create an Operational Environment object in A&AI + * + * @param AAIOperationalEnvironment object + */ + public void createOperationalEnvironment(OperationalEnvironment operationalEnvironment) { + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, + operationalEnvironment.getOperationalEnvironmentId()); + AAIResourcesClient client = this.getClient(); + client.create(uri, operationalEnvironment); + } + + /** + * Create a relationship between ECOMP managing and VNF Operational Environments + * + * @param managingEcompOperationalEnvironmentId + * @param vnfOperationalEnvironmentId + * @throws Exception + */ + public void createRelationship(String managingEcompOperationalEnvironmentId, String vnfOperationalEnvironmentId) { + + AAIResourceUri ecompEnvUri = AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, + managingEcompOperationalEnvironmentId); + AAIResourceUri vnfEnvUri = + AAIUriFactory.createResourceUri(AAIObjectType.OPERATIONAL_ENVIRONMENT, vnfOperationalEnvironmentId); + AAIResourcesClient client = this.getClient(); + client.connect(vnfEnvUri, ecompEnvUri); + + } + + private void logStackTrace(Exception e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + } + + protected AAIResourcesClient getClient() { + return new AAIResourcesClient(); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java index dc6019c9cb..b5294cd8b8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilder.java @@ -26,17 +26,21 @@ import org.springframework.stereotype.Component; @Component public class AAIClientObjectBuilder { - - public OperationalEnvironment buildAAIOperationalEnvironment(String status, CloudOrchestrationRequest cloudOrchestrationRequest) { - OperationalEnvironment env = new OperationalEnvironment(); - env.setOperationalEnvironmentId(cloudOrchestrationRequest.getOperationalEnvironmentId()); - env.setOperationalEnvironmentName(cloudOrchestrationRequest.getRequestDetails().getRequestInfo().getInstanceName()); - env.setOperationalEnvironmentType(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString()); - env.setOperationalEnvironmentStatus(status); - env.setTenantContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getTenantContext()); - env.setWorkloadContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getWorkloadContext()); - return env; - } + + public OperationalEnvironment buildAAIOperationalEnvironment(String status, + CloudOrchestrationRequest cloudOrchestrationRequest) { + OperationalEnvironment env = new OperationalEnvironment(); + env.setOperationalEnvironmentId(cloudOrchestrationRequest.getOperationalEnvironmentId()); + env.setOperationalEnvironmentName( + cloudOrchestrationRequest.getRequestDetails().getRequestInfo().getInstanceName()); + env.setOperationalEnvironmentType(cloudOrchestrationRequest.getRequestDetails().getRequestParameters() + .getOperationalEnvironmentType().toString()); + env.setOperationalEnvironmentStatus(status); + env.setTenantContext(cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getTenantContext()); + env.setWorkloadContext( + cloudOrchestrationRequest.getRequestDetails().getRequestParameters().getWorkloadContext()); + return env; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java index de1d9e9cfb..98b49d39d7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelper.java @@ -30,94 +30,89 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfDBHelper { - - private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class); - - /** - * Insert record to OperationalEnvServiceModelStatus table - * @param requestId - String - * @param operationalEnvironmentId - String - * @param serviceModelVersionId - String - * @param status - String - * @param recoveryAction - String - * @param retryCount - int - * @param workloadContext - String - * @return serviceModelStatus - OperationalEnvServiceModelStatus object - */ - public OperationalEnvServiceModelStatus insertRecordToOperationalEnvServiceModelStatus( String requestId, - String operationalEnvironmentId, - String serviceModelVersionId, - String status, - String recoveryAction, - int retryCount, - String workloadContext, - String vnfOperationalEnvironmentId) { - OperationalEnvServiceModelStatus serviceModelStatus = new OperationalEnvServiceModelStatus(); - serviceModelStatus.setRequestId(requestId); - serviceModelStatus.setOperationalEnvId(operationalEnvironmentId); - serviceModelStatus.setServiceModelVersionId(serviceModelVersionId); - serviceModelStatus.setServiceModelVersionDistrStatus(status); - serviceModelStatus.setRecoveryAction(recoveryAction); - serviceModelStatus.setRetryCount(new Integer(retryCount)); - serviceModelStatus.setWorkloadContext(workloadContext); - serviceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - return serviceModelStatus; - } - /** - * Update RetryCount & Status in OperationalEnvServiceModelStatus table - * @param serviceModelStatusResponse - OperationalEnvServiceModelStatus object - * @param status - String - * @param retryCount - int - * @return serviceModelStatusResponse - OperationalEnvServiceModelStatus object - */ - public OperationalEnvServiceModelStatus updateRetryCountAndStatusInOperationalEnvServiceModelStatus(OperationalEnvServiceModelStatus serviceModelStatusResponse, - String status, - int retryCount) { - serviceModelStatusResponse.setServiceModelVersionDistrStatus(status); - serviceModelStatusResponse.setRetryCount(new Integer(retryCount)); - return serviceModelStatusResponse; - } - - /** - * Insert record to OperationalEnvDistributionStatus table - * @param distributionId - String - * @param operationalEnvironmentId - String - * @param serviceModelVersionId - String - * @param requestId - String - * @param status - String - * @param distributionIdErrorReason - String - * @return distStatus - OperationalEnvDistributionStatus object - */ - public OperationalEnvDistributionStatus insertRecordToOperationalEnvDistributionStatus( String distributionId, - String operationalEnvironmentId, - String serviceModelVersionId, - String requestId, - String status, - String distributionIdErrorReason) { - OperationalEnvDistributionStatus distStatus = new OperationalEnvDistributionStatus(); - distStatus.setDistributionId(distributionId); - distStatus.setOperationalEnvId(operationalEnvironmentId); - distStatus.setServiceModelVersionId(serviceModelVersionId); - distStatus.setRequestId(requestId); - distStatus.setDistributionIdStatus(status); - distStatus.setDistributionIdErrorReason(distributionIdErrorReason); - return distStatus; - } - - /** - * Update Status in OperationalEnvDistributionStatus table - * @param distributionStatusResponse - OperationalEnvDistributionStatus object - * @param status - String - * @param distributionIdErrorReason - String - * @return distributionStatusResponse - OperationalEnvDistributionStatus object - */ - public OperationalEnvDistributionStatus updateStatusInOperationalEnvDistributionStatus(OperationalEnvDistributionStatus distributionStatusResponse, - String status, - String distributionIdErrorReason) { - distributionStatusResponse.setDistributionIdStatus(status); - distributionStatusResponse.setDistributionIdErrorReason(distributionIdErrorReason); - return distributionStatusResponse; - } - + private static Logger logger = LoggerFactory.getLogger(ActivateVnfDBHelper.class); + + /** + * Insert record to OperationalEnvServiceModelStatus table + * + * @param requestId - String + * @param operationalEnvironmentId - String + * @param serviceModelVersionId - String + * @param status - String + * @param recoveryAction - String + * @param retryCount - int + * @param workloadContext - String + * @return serviceModelStatus - OperationalEnvServiceModelStatus object + */ + public OperationalEnvServiceModelStatus insertRecordToOperationalEnvServiceModelStatus(String requestId, + String operationalEnvironmentId, String serviceModelVersionId, String status, String recoveryAction, + int retryCount, String workloadContext, String vnfOperationalEnvironmentId) { + OperationalEnvServiceModelStatus serviceModelStatus = new OperationalEnvServiceModelStatus(); + serviceModelStatus.setRequestId(requestId); + serviceModelStatus.setOperationalEnvId(operationalEnvironmentId); + serviceModelStatus.setServiceModelVersionId(serviceModelVersionId); + serviceModelStatus.setServiceModelVersionDistrStatus(status); + serviceModelStatus.setRecoveryAction(recoveryAction); + serviceModelStatus.setRetryCount(new Integer(retryCount)); + serviceModelStatus.setWorkloadContext(workloadContext); + serviceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + return serviceModelStatus; + } + + /** + * Update RetryCount & Status in OperationalEnvServiceModelStatus table + * + * @param serviceModelStatusResponse - OperationalEnvServiceModelStatus object + * @param status - String + * @param retryCount - int + * @return serviceModelStatusResponse - OperationalEnvServiceModelStatus object + */ + public OperationalEnvServiceModelStatus updateRetryCountAndStatusInOperationalEnvServiceModelStatus( + OperationalEnvServiceModelStatus serviceModelStatusResponse, String status, int retryCount) { + serviceModelStatusResponse.setServiceModelVersionDistrStatus(status); + serviceModelStatusResponse.setRetryCount(new Integer(retryCount)); + return serviceModelStatusResponse; + } + + /** + * Insert record to OperationalEnvDistributionStatus table + * + * @param distributionId - String + * @param operationalEnvironmentId - String + * @param serviceModelVersionId - String + * @param requestId - String + * @param status - String + * @param distributionIdErrorReason - String + * @return distStatus - OperationalEnvDistributionStatus object + */ + public OperationalEnvDistributionStatus insertRecordToOperationalEnvDistributionStatus(String distributionId, + String operationalEnvironmentId, String serviceModelVersionId, String requestId, String status, + String distributionIdErrorReason) { + OperationalEnvDistributionStatus distStatus = new OperationalEnvDistributionStatus(); + distStatus.setDistributionId(distributionId); + distStatus.setOperationalEnvId(operationalEnvironmentId); + distStatus.setServiceModelVersionId(serviceModelVersionId); + distStatus.setRequestId(requestId); + distStatus.setDistributionIdStatus(status); + distStatus.setDistributionIdErrorReason(distributionIdErrorReason); + return distStatus; + } + + /** + * Update Status in OperationalEnvDistributionStatus table + * + * @param distributionStatusResponse - OperationalEnvDistributionStatus object + * @param status - String + * @param distributionIdErrorReason - String + * @return distributionStatusResponse - OperationalEnvDistributionStatus object + */ + public OperationalEnvDistributionStatus updateStatusInOperationalEnvDistributionStatus( + OperationalEnvDistributionStatus distributionStatusResponse, String status, + String distributionIdErrorReason) { + distributionStatusResponse.setDistributionIdStatus(status); + distributionStatusResponse.setDistributionIdErrorReason(distributionIdErrorReason); + return distributionStatusResponse; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java index bf5623a9da..b5ba9281a6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelper.java @@ -24,10 +24,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import java.net.URL; import java.util.UUID; - import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; - import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; @@ -49,185 +47,198 @@ import org.springframework.stereotype.Component; @Component public class SDCClientHelper { - private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class); - private static final String SDC_CONTENT_TYPE = "application/json"; - private static final String SDC_ACCEPT_TYPE = "application/json"; - private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/"; - - private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!"; - private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC."; - private final HttpClientFactory httpClientFactory = new HttpClientFactory(); - - @Value("${mso.sdc.endpoint}") - private String sdcEndpoint; - @Value("${mso.sdc.activate.userid}") - private String sdcActivateUserId; - @Value("${mso.sdc.activate.instanceid}") - private String sdcActivateInstanceId; - @Value("${mso.sdc.client.auth}") - private String sdcClientAuth; - @Value("${mso.msoKey}") - private String msoKey; - - /** - * Send POST request to SDC for operational activation - * @param serviceModelVersionI - String - * @param operationalEnvironmentId - String - * @param workloadContext - String - * @return sdcResponseJsonObj - JSONObject object - * @throws JSONException - */ - public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, String workloadContext) throws ApiException { - JSONObject sdcResponseJsonObj = new JSONObject(); - - try { - String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); - String jsonPayload = this.buildJsonWorkloadContext(workloadContext); - String basicAuthCred = getBasicAuth(); - - if ( basicAuthCred == null || "".equals(basicAuthCred) ) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder(" SDC credentials 'mso.sdc.client.auth' not setup in properties file!", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + private static Logger logger = LoggerFactory.getLogger(SDCClientHelper.class); + private static final String SDC_CONTENT_TYPE = "application/json"; + private static final String SDC_ACCEPT_TYPE = "application/json"; + private static String PARTIAL_SDC_URI = "/sdc/v1/catalog/services/"; + + private static String MESSAGE_UNDEFINED_ERROR = "Undefined Error Message!"; + private static String MESSAGE_UNEXPECTED_FORMAT = "Unexpected response format from SDC."; + private final HttpClientFactory httpClientFactory = new HttpClientFactory(); + + @Value("${mso.sdc.endpoint}") + private String sdcEndpoint; + @Value("${mso.sdc.activate.userid}") + private String sdcActivateUserId; + @Value("${mso.sdc.activate.instanceid}") + private String sdcActivateInstanceId; + @Value("${mso.sdc.client.auth}") + private String sdcClientAuth; + @Value("${mso.msoKey}") + private String msoKey; + + /** + * Send POST request to SDC for operational activation + * + * @param serviceModelVersionI - String + * @param operationalEnvironmentId - String + * @param workloadContext - String + * @return sdcResponseJsonObj - JSONObject object + * @throws JSONException + */ + public JSONObject postActivateOperationalEnvironment(String serviceModelVersionId, String operationalEnvironmentId, + String workloadContext) throws ApiException { + JSONObject sdcResponseJsonObj = new JSONObject(); + + try { + String urlString = this.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); + String jsonPayload = this.buildJsonWorkloadContext(workloadContext); + String basicAuthCred = getBasicAuth(); + + if (basicAuthCred == null || "".equals(basicAuthCred)) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + ValidateException validateException = new ValidateException.Builder( + " SDC credentials 'mso.sdc.client.auth' not setup in properties file!", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); throw validateException; - } - - URL url = new URL(urlString); - - HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC); - httpClient.addBasicAuthHeader(sdcClientAuth, msoKey); - httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId); - httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()); - httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE); - httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE); - httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId); - - Response apiResponse = setHttpPostResponse(httpClient, jsonPayload); - int statusCode = apiResponse.getStatus();; - - String responseData = apiResponse.readEntity(String.class); - sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode); - - } catch (Exception ex) { - logger.debug("calling SDC Exception message: {}", ex.getMessage()); - String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage(); - logger.debug(errorMessage); - sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); - sdcResponseJsonObj.put("messageId", ""); - sdcResponseJsonObj.put("message", errorMessage); - - } - return sdcResponseJsonObj; - } - - /** - * set HttpPostResponse - * @param config - RESTConfig object - * @param jsonPayload - String - * @return client - RestClient object - */ - public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException { - try { + } + + URL url = new URL(urlString); + + HttpClient httpClient = httpClientFactory.newJsonClient(url, TargetEntity.SDC); + httpClient.addBasicAuthHeader(sdcClientAuth, msoKey); + httpClient.addAdditionalHeader("X-ECOMP-InstanceID", sdcActivateInstanceId); + httpClient.addAdditionalHeader("X-ECOMP-RequestID", UUID.randomUUID().toString()); + httpClient.addAdditionalHeader("Content-Type", SDCClientHelper.SDC_CONTENT_TYPE); + httpClient.addAdditionalHeader("Accept", SDCClientHelper.SDC_ACCEPT_TYPE); + httpClient.addAdditionalHeader("USER_ID", sdcActivateUserId); + + Response apiResponse = setHttpPostResponse(httpClient, jsonPayload); + int statusCode = apiResponse.getStatus();; + + String responseData = apiResponse.readEntity(String.class); + sdcResponseJsonObj = enhanceJsonResponse(new JSONObject(responseData), statusCode); + + } catch (Exception ex) { + logger.debug("calling SDC Exception message: {}", ex.getMessage()); + String errorMessage = " Encountered Error while calling SDC POST Activate. " + ex.getMessage(); + logger.debug(errorMessage); + sdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + sdcResponseJsonObj.put("messageId", ""); + sdcResponseJsonObj.put("message", errorMessage); + + } + return sdcResponseJsonObj; + } + + /** + * set HttpPostResponse + * + * @param config - RESTConfig object + * @param jsonPayload - String + * @return client - RestClient object + */ + public Response setHttpPostResponse(HttpClient client, String jsonPayload) throws ApiException { + try { return client.post(jsonPayload); - }catch(Exception ex){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder("Bad request could not post payload", - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); + } catch (Exception ex) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + ValidateException validateException = + new ValidateException.Builder("Bad request could not post payload", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build(); throw validateException; } - } - - /** - * enhance Response - * @param sdcResponseJsonObj - JSONObject object - * @param statusCode - int - * @return enhancedAsdcResponseJsonObj - JSONObject object - */ - public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException { - - JSONObject enhancedAsdcResponseJsonObj = new JSONObject(); - - String message = ""; - String messageId = ""; - - if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted - enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId")); - enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); - enhancedAsdcResponseJsonObj.put("messageId", ""); - enhancedAsdcResponseJsonObj.put("message", "Success"); - - } else { // error - if (sdcResponseJsonObj.has("requestError") ) { - JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError"); - if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException") ) { - message = requestErrorObj.getJSONObject("serviceException").getString("text"); - messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId"); - } - if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException") ) { - message = requestErrorObj.getJSONObject("policyException").getString("text"); - messageId = requestErrorObj.getJSONObject("policyException").getString("messageId"); - } - enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); - enhancedAsdcResponseJsonObj.put("messageId", messageId); - enhancedAsdcResponseJsonObj.put("message", message); - - } else { - // unexpected format - enhancedAsdcResponseJsonObj.put("statusCode", String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); - enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR); - enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT); - } - } - return enhancedAsdcResponseJsonObj; - - } - - /** - * Build Uri - * @param serviceModelVersionId - String - * @param operationalEnvironmentId - String - * @return uriBuilder - String - */ - public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) { - String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId +"/activate"; - UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI) - .path(path); - return uriBuilder.build().toString(); - } - - /** - * Build JSON context - * @param workloadContext - String - * @return String json - * @throws JSONException - */ - public String buildJsonWorkloadContext(String workloadContext) throws JSONException { - return new JSONObject().put("workloadContext", workloadContext).toString(); - - } - - /** - * decrypt value - * @param toDecrypt - String - * @param msokey - String - * @return result - String - */ - public synchronized String decrypt(String toDecrypt, String msokey){ - String result = null; - try { - result = CryptoUtils.decrypt(toDecrypt, msokey); - - } - catch (Exception e) { - logger.debug("Failed to decrypt credentials: {}", toDecrypt, e); - } - return result; - } - - private String getBasicAuth() { - return decrypt(sdcClientAuth, msoKey); - } + } + + /** + * enhance Response + * + * @param sdcResponseJsonObj - JSONObject object + * @param statusCode - int + * @return enhancedAsdcResponseJsonObj - JSONObject object + */ + public JSONObject enhanceJsonResponse(JSONObject sdcResponseJsonObj, int statusCode) throws JSONException { + + JSONObject enhancedAsdcResponseJsonObj = new JSONObject(); + + String message = ""; + String messageId = ""; + + if (statusCode == Response.Status.ACCEPTED.getStatusCode()) { // Accepted + enhancedAsdcResponseJsonObj.put("distributionId", sdcResponseJsonObj.get("distributionId")); + enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); + enhancedAsdcResponseJsonObj.put("messageId", ""); + enhancedAsdcResponseJsonObj.put("message", "Success"); + + } else { // error + if (sdcResponseJsonObj.has("requestError")) { + JSONObject requestErrorObj = sdcResponseJsonObj.getJSONObject("requestError"); + if (sdcResponseJsonObj.getJSONObject("requestError").has("serviceException")) { + message = requestErrorObj.getJSONObject("serviceException").getString("text"); + messageId = requestErrorObj.getJSONObject("serviceException").getString("messageId"); + } + if (sdcResponseJsonObj.getJSONObject("requestError").has("policyException")) { + message = requestErrorObj.getJSONObject("policyException").getString("text"); + messageId = requestErrorObj.getJSONObject("policyException").getString("messageId"); + } + enhancedAsdcResponseJsonObj.put("statusCode", Integer.toString(statusCode)); + enhancedAsdcResponseJsonObj.put("messageId", messageId); + enhancedAsdcResponseJsonObj.put("message", message); + + } else { + // unexpected format + enhancedAsdcResponseJsonObj.put("statusCode", + String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())); + enhancedAsdcResponseJsonObj.put("messageId", MESSAGE_UNDEFINED_ERROR); + enhancedAsdcResponseJsonObj.put("message", MESSAGE_UNEXPECTED_FORMAT); + } + } + return enhancedAsdcResponseJsonObj; + + } + + /** + * Build Uri + * + * @param serviceModelVersionId - String + * @param operationalEnvironmentId - String + * @return uriBuilder - String + */ + public String buildUriBuilder(String serviceModelVersionId, String operationalEnvironmentId) { + String path = serviceModelVersionId + "/distribution/" + operationalEnvironmentId + "/activate"; + UriBuilder uriBuilder = UriBuilder.fromPath(sdcEndpoint + SDCClientHelper.PARTIAL_SDC_URI).path(path); + return uriBuilder.build().toString(); + } + + /** + * Build JSON context + * + * @param workloadContext - String + * @return String json + * @throws JSONException + */ + public String buildJsonWorkloadContext(String workloadContext) throws JSONException { + return new JSONObject().put("workloadContext", workloadContext).toString(); + + } + + /** + * decrypt value + * + * @param toDecrypt - String + * @param msokey - String + * @return result - String + */ + public synchronized String decrypt(String toDecrypt, String msokey) { + String result = null; + try { + result = CryptoUtils.decrypt(toDecrypt, msokey); + + } catch (Exception e) { + logger.debug("Failed to decrypt credentials: {}", toDecrypt, e); + } + return result; + } + + private String getBasicAuth() { + return decrypt(sdcClientAuth, msoKey); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java index dde45a81c9..3957f86bab 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironment.java @@ -22,9 +22,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import java.util.List; import java.util.Optional; - import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.json.JSONObject; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -57,145 +55,155 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfOperationalEnvironment { - private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class); - private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3; - private static final String DISTRIBUTION_STATUS_SENT = "SENT"; - private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id"; - - @Autowired - private ActivateVnfDBHelper dbHelper; - @Autowired - private AAIClientHelper aaiHelper; - @Autowired - private RequestsDBHelper requestDb; - @Autowired - private SDCClientHelper sdcClientHelper; - - @Value("${mso.tenant.isolation.retry.count}") - private String sdcRetryCount; - - @Autowired - RequestsDbClient client; - - /** - * The Point-Of-Entry from APIH with VID request to send activate request - * @param requestId - String - * @param request - CloudOrchestrationRequest object - * @return void - nothing - */ - public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{ - String vnfOperationalEnvironmentId = request.getOperationalEnvironmentId(); - - String vidWorkloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext(); - List<ServiceModelList> serviceModelVersionIdList = request.getRequestDetails().getRequestParameters().getManifest().getServiceModelList(); - - String ecompOperationalEnvironmentId = null; - AAIResultWrapper wrapper = getAAIOperationalEnvironment(vnfOperationalEnvironmentId); - Optional<Relationships> optRelationships = wrapper.getRelationships(); - if (optRelationships.isPresent()) { - Relationships relationships = optRelationships.get(); - List<AAIResourceUri> operationalEnvironments = relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT); - if (!operationalEnvironments.isEmpty()) { - ecompOperationalEnvironmentId = operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY); - } - } - logger.debug(" vnfOperationalEnvironmentId : {}", vnfOperationalEnvironmentId); - logger.debug(" ecompOperationalEnvironmentId : {}", ecompOperationalEnvironmentId); - - OperationalEnvironment operationalEnv = wrapper.asBean(OperationalEnvironment.class).get(); - String workloadContext = operationalEnv.getWorkloadContext(); - logger.debug(" aai workloadContext: {}", workloadContext); - if (!vidWorkloadContext.equals(workloadContext)) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - throw new ValidateException.Builder(" The vid workloadContext did not match from aai record. " + " vid workloadContext:" + vidWorkloadContext + " aai workloadContext:" + workloadContext, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - } - if (ecompOperationalEnvironmentId==null) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - throw new ValidateException.Builder(" The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " + OPER_ENVIRONMENT_ID_KEY, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - } - - processActivateSDCRequest(requestId, ecompOperationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId); - - } - - - /** - * The Method to send the Activation Requests to SDC - * @param requestId - String - * @param operationalEnvironmentId - String - * @param serviceModelVersionIdList - List<ServiceModelList> list - * @param workloadContext - String - * @return jsonResponse - JSONObject object - */ - public void processActivateSDCRequest(String requestId, String operationalEnvironmentId, - List<ServiceModelList> serviceModelVersionIdList, - String workloadContext, String vnfOperationalEnvironmentId) throws ApiException { - - JSONObject jsonResponse = null; - int retryCount = 0; - try { - retryCount = Integer.parseInt(sdcRetryCount); - } catch (NumberFormatException e) { - retryCount = DEFAULT_ACTIVATE_RETRY_COUNT; - } - - // loop through the serviceModelVersionId, and send request SDC - for(ServiceModelList serviceModelList : serviceModelVersionIdList){ - String serviceModelVersionId = serviceModelList.getServiceModelVersionId(); - String recoveryAction = serviceModelList.getRecoveryAction().toString().toUpperCase(); - - // should insert 1 row - OperationalEnvServiceModelStatus serviceModelStatus = - dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId, - operationalEnvironmentId, - serviceModelVersionId, - DISTRIBUTION_STATUS_SENT, - recoveryAction, - retryCount, - workloadContext, - vnfOperationalEnvironmentId); - client.save(serviceModelStatus); - - String distributionId = ""; - - jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext); - - String statusCode = jsonResponse.get("statusCode").toString(); - if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) { - distributionId = jsonResponse.get("distributionId").toString(); - // should insert 1 row - OperationalEnvDistributionStatus distStatus = - dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId, - operationalEnvironmentId, - serviceModelVersionId, - requestId, - DISTRIBUTION_STATUS_SENT, - ""); - client.save(distStatus); - - } else { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode + - "; messageId: " + jsonResponse.get("messageId") + - "; message: " + jsonResponse.get("message"); + private static final Logger logger = LoggerFactory.getLogger(ActivateVnfOperationalEnvironment.class); + private static final int DEFAULT_ACTIVATE_RETRY_COUNT = 3; + private static final String DISTRIBUTION_STATUS_SENT = "SENT"; + private static final String OPER_ENVIRONMENT_ID_KEY = "operational-environment-id"; + + @Autowired + private ActivateVnfDBHelper dbHelper; + @Autowired + private AAIClientHelper aaiHelper; + @Autowired + private RequestsDBHelper requestDb; + @Autowired + private SDCClientHelper sdcClientHelper; + + @Value("${mso.tenant.isolation.retry.count}") + private String sdcRetryCount; + + @Autowired + RequestsDbClient client; + + /** + * The Point-Of-Entry from APIH with VID request to send activate request + * + * @param requestId - String + * @param request - CloudOrchestrationRequest object + * @return void - nothing + */ + public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { + String vnfOperationalEnvironmentId = request.getOperationalEnvironmentId(); + + String vidWorkloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext(); + List<ServiceModelList> serviceModelVersionIdList = + request.getRequestDetails().getRequestParameters().getManifest().getServiceModelList(); + + String ecompOperationalEnvironmentId = null; + AAIResultWrapper wrapper = getAAIOperationalEnvironment(vnfOperationalEnvironmentId); + Optional<Relationships> optRelationships = wrapper.getRelationships(); + if (optRelationships.isPresent()) { + Relationships relationships = optRelationships.get(); + List<AAIResourceUri> operationalEnvironments = + relationships.getRelatedAAIUris(AAIObjectType.OPERATIONAL_ENVIRONMENT); + if (!operationalEnvironments.isEmpty()) { + ecompOperationalEnvironmentId = + operationalEnvironments.get(0).getURIKeys().get(OPER_ENVIRONMENT_ID_KEY); + } + } + logger.debug(" vnfOperationalEnvironmentId : {}", vnfOperationalEnvironmentId); + logger.debug(" ecompOperationalEnvironmentId : {}", ecompOperationalEnvironmentId); + + OperationalEnvironment operationalEnv = wrapper.asBean(OperationalEnvironment.class).get(); + String workloadContext = operationalEnv.getWorkloadContext(); + logger.debug(" aai workloadContext: {}", workloadContext); + if (!vidWorkloadContext.equals(workloadContext)) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + throw new ValidateException.Builder( + " The vid workloadContext did not match from aai record. " + " vid workloadContext:" + + vidWorkloadContext + " aai workloadContext:" + workloadContext, + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); + } + if (ecompOperationalEnvironmentId == null) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + throw new ValidateException.Builder( + " The ECOMP OE was not in aai record; the value of relationship.relationship-data key: " + + OPER_ENVIRONMENT_ID_KEY, + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo) + .build(); + } + + processActivateSDCRequest(requestId, ecompOperationalEnvironmentId, serviceModelVersionIdList, workloadContext, + vnfOperationalEnvironmentId); + + } + + + /** + * The Method to send the Activation Requests to SDC + * + * @param requestId - String + * @param operationalEnvironmentId - String + * @param serviceModelVersionIdList - List<ServiceModelList> list + * @param workloadContext - String + * @return jsonResponse - JSONObject object + */ + public void processActivateSDCRequest(String requestId, String operationalEnvironmentId, + List<ServiceModelList> serviceModelVersionIdList, String workloadContext, + String vnfOperationalEnvironmentId) throws ApiException { + + JSONObject jsonResponse = null; + int retryCount = 0; + try { + retryCount = Integer.parseInt(sdcRetryCount); + } catch (NumberFormatException e) { + retryCount = DEFAULT_ACTIVATE_RETRY_COUNT; + } + + // loop through the serviceModelVersionId, and send request SDC + for (ServiceModelList serviceModelList : serviceModelVersionIdList) { + String serviceModelVersionId = serviceModelList.getServiceModelVersionId(); + String recoveryAction = serviceModelList.getRecoveryAction().toString().toUpperCase(); + + // should insert 1 row + OperationalEnvServiceModelStatus serviceModelStatus = + dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId, operationalEnvironmentId, + serviceModelVersionId, DISTRIBUTION_STATUS_SENT, recoveryAction, retryCount, + workloadContext, vnfOperationalEnvironmentId); + client.save(serviceModelStatus); + + String distributionId = ""; + + jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, + operationalEnvironmentId, workloadContext); + + String statusCode = jsonResponse.get("statusCode").toString(); + if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) { + distributionId = jsonResponse.get("distributionId").toString(); + // should insert 1 row + OperationalEnvDistributionStatus distStatus = dbHelper.insertRecordToOperationalEnvDistributionStatus( + distributionId, operationalEnvironmentId, serviceModelVersionId, requestId, + DISTRIBUTION_STATUS_SENT, ""); + client.save(distStatus); + + } else { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + String dbErrorMessage = " Failure calling SDC: statusCode: " + statusCode + "; messageId: " + + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message"); requestDb.updateInfraFailureCompletion(dbErrorMessage, requestId, operationalEnvironmentId); - throw new ValidateException.Builder(dbErrorMessage, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - } - } - - } - - /** - * Get AAIOperationalEnvironment object - * @param operationalEnvironmentId - String - * @return operationalEnv - AAIOperationalEnvironment object - */ - public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) { - return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); - } + throw new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + } + } + + } + + /** + * Get AAIOperationalEnvironment object + * + * @param operationalEnvironmentId - String + * @return operationalEnv - AAIOperationalEnvironment object + */ + public AAIResultWrapper getAAIOperationalEnvironment(String operationalEnvironmentId) { + return aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java index e09dcd8d2d..3005abaf9b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironment.java @@ -25,9 +25,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import java.util.List; import java.util.Optional; - import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.json.JSONObject; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -56,271 +54,278 @@ import org.springframework.stereotype.Component; @Component public class ActivateVnfStatusOperationalEnvironment { - private static Logger logger = LoggerFactory.getLogger(ActivateVnfStatusOperationalEnvironment.class); - private String origRequestId = ""; - private String errorMessage = ""; - private OperationalEnvDistributionStatus queryDistributionDbResponse = null; - private OperationalEnvServiceModelStatus queryServiceModelResponse = null; - private boolean isOverallSuccess = false; - - private final int RETRY_COUNT_ZERO = 0; - private final String ERROR_REASON_ABORTED = "ABORTED"; - private final String RECOVERY_ACTION_RETRY = "RETRY"; - private final String RECOVERY_ACTION_ABORT = "ABORT"; - private final String RECOVERY_ACTION_SKIP = "SKIP"; - private final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); - private final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); - private final String DISTRIBUTION_STATUS_SENT = "SENT"; - - private final String MESSAGE_UNDEFINED_ID = "Undefined Error Message!"; - - @Autowired - private ActivateVnfDBHelper dbHelper; - @Autowired - private RequestsDBHelper requestDb; - @Autowired - private SDCClientHelper sdcClientHelper; - @Autowired - private RequestsDbClient client; - @Autowired - private AAIClientHelper aaiHelper; - - /** - * The Point-Of-Entry from APIH with activate status from SDC - * @param requestId - String - * @param request - CloudOrchestrationRequest - object - * @return void - nothing - */ - public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { - - try { - - String operationalEnvironmentId = ""; - - String sdcDistributionId = request.getDistributionId(); - Distribution sdcStatus = request.getDistribution(); - - // Distribution, Query for operationalEnvironmentId, serviceModelVersionId, origRequestId - this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId); - operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId(); - this.origRequestId = this.queryDistributionDbResponse.getRequestId(); - - // ServiceModel, Query for recoveryAction, retryCountString - this.queryServiceModelResponse = client.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(operationalEnvironmentId, queryDistributionDbResponse.getServiceModelVersionId(), this.origRequestId); - - processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse, this.queryServiceModelResponse); - - // After EVERY status processed, need to query the status of all service modelId - // to determine the OVERALL status if "COMPLETE" or "FAILURE": - checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId); - - // Update AAI to ACTIVE if Overall success - if (isOverallSuccess) { - OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(this.queryServiceModelResponse.getVnfOperationalEnvId()); - if (aaiOpEnv != null) { - aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE"); - aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv); - }else { - requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ", this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId()); - } - } - - } catch(Exception e) { - requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId()); + private static Logger logger = LoggerFactory.getLogger(ActivateVnfStatusOperationalEnvironment.class); + private String origRequestId = ""; + private String errorMessage = ""; + private OperationalEnvDistributionStatus queryDistributionDbResponse = null; + private OperationalEnvServiceModelStatus queryServiceModelResponse = null; + private boolean isOverallSuccess = false; + + private final int RETRY_COUNT_ZERO = 0; + private final String ERROR_REASON_ABORTED = "ABORTED"; + private final String RECOVERY_ACTION_RETRY = "RETRY"; + private final String RECOVERY_ACTION_ABORT = "ABORT"; + private final String RECOVERY_ACTION_SKIP = "SKIP"; + private final String DISTRIBUTION_STATUS_OK = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); + private final String DISTRIBUTION_STATUS_ERROR = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + private final String DISTRIBUTION_STATUS_SENT = "SENT"; + + private final String MESSAGE_UNDEFINED_ID = "Undefined Error Message!"; + + @Autowired + private ActivateVnfDBHelper dbHelper; + @Autowired + private RequestsDBHelper requestDb; + @Autowired + private SDCClientHelper sdcClientHelper; + @Autowired + private RequestsDbClient client; + @Autowired + private AAIClientHelper aaiHelper; + + /** + * The Point-Of-Entry from APIH with activate status from SDC + * + * @param requestId - String + * @param request - CloudOrchestrationRequest - object + * @return void - nothing + */ + public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { + + try { + + String operationalEnvironmentId = ""; + + String sdcDistributionId = request.getDistributionId(); + Distribution sdcStatus = request.getDistribution(); + + // Distribution, Query for operationalEnvironmentId, serviceModelVersionId, origRequestId + this.queryDistributionDbResponse = client.getDistributionStatusById(sdcDistributionId); + operationalEnvironmentId = this.queryDistributionDbResponse.getOperationalEnvId(); + this.origRequestId = this.queryDistributionDbResponse.getRequestId(); + + // ServiceModel, Query for recoveryAction, retryCountString + this.queryServiceModelResponse = + client.findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId(operationalEnvironmentId, + queryDistributionDbResponse.getServiceModelVersionId(), this.origRequestId); + + processActivateSDCStatus(sdcDistributionId, sdcStatus, this.queryDistributionDbResponse, + this.queryServiceModelResponse); + + // After EVERY status processed, need to query the status of all service modelId + // to determine the OVERALL status if "COMPLETE" or "FAILURE": + checkOrUpdateOverallStatus(operationalEnvironmentId, this.origRequestId); + + // Update AAI to ACTIVE if Overall success + if (isOverallSuccess) { + String vnfOperationalEnvironmentId = this.queryServiceModelResponse.getVnfOperationalEnvId(); + OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(vnfOperationalEnvironmentId); + if (aaiOpEnv != null) { + aaiOpEnv.setOperationalEnvironmentStatus("ACTIVE"); + aaiHelper.updateAaiOperationalEnvironment(vnfOperationalEnvironmentId, aaiOpEnv); + } else { + requestDb.updateInfraFailureCompletion("Unable to update ACTIVATE status in AAI. ", + this.origRequestId, this.queryServiceModelResponse.getVnfOperationalEnvId()); + } + } + + } catch (Exception e) { + requestDb.updateInfraFailureCompletion(e.getMessage(), this.origRequestId, + this.queryServiceModelResponse.getVnfOperationalEnvId()); } - - } - - /** - * The Method to process the Activation Status from SDC - * @param sdcDistributionId - string - * @param sdcStatus - Distribution object - * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object - * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object - * @return void - nothing - */ - public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus, OperationalEnvDistributionStatus queryDistributionDbResponse, - OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException { - - String sdcStatusValue = sdcStatus.getStatus().toString(); - String recoveryAction = queryServiceModelResponse.getRecoveryAction(); - int retryCount = queryServiceModelResponse.getRetryCount(); - - // Validate/process status - if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) { - // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK" - OperationalEnvDistributionStatus updateDistStatusOk = - dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, - sdcStatusValue, - ""); - client.save(updateDistStatusOk); - // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!) - OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk = - dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, - sdcStatusValue, - RETRY_COUNT_ZERO); - client.save(updateRetryCountZeroAndStatusOk); - } else { - - // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY" - if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) { - - // RESEND / RETRY serviceModelVersionId to SDC - - JSONObject jsonResponse = callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus); - - } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP' - - if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) { - String modifiedStatus = ""; - String errorReason = ""; - if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) { // considered SUCCESS - modifiedStatus = DISTRIBUTION_STATUS_OK; - } else { - if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) { - modifiedStatus = DISTRIBUTION_STATUS_ERROR; // ABORT, error - errorReason = ERROR_REASON_ABORTED; - } - } - - sdcStatusValue = modifiedStatus; - OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus = - dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, - modifiedStatus, - RETRY_COUNT_ZERO); - client.save(updateRetryCountZeroAndStatus); - OperationalEnvDistributionStatus updateDistStatus = - dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, - modifiedStatus, - errorReason); - client.save(updateDistStatus); - } else { - // RETRY & Count = 0 (do nothing!) - } - } - } - } - - /** - * The Method to call SDC for recoveryActioin RETRY - * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object - * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object - * @param sdcStatus - Distribution object - * @return JSONObject object - */ - public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse, - OperationalEnvServiceModelStatus queryServiceModelResponse, - Distribution sdcStatus) throws ApiException { - - JSONObject jsonResponse = null; - - String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId(); - String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId(); - String originalRequestId = queryServiceModelResponse.getRequestId(); - int retryCount = queryServiceModelResponse.getRetryCount(); - String workloadContext = queryServiceModelResponse.getWorkloadContext(); - - - jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId, workloadContext); - String statusCode = jsonResponse.get("statusCode").toString(); - if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) { - String newDistributionId = jsonResponse.get("distributionId").toString(); - // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record - OperationalEnvDistributionStatus insertNewDistributionId = - dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId, - operEnvironmentId, - serviceModelVersionId, - originalRequestId, - DISTRIBUTION_STATUS_SENT, - ""); - client.save(insertNewDistributionId); - - // update retryCount (less 1) for the serviceModelServiceId - retryCount = retryCount - 1; - // should update 1 row, original insert - OperationalEnvServiceModelStatus updateRetryCountAndStatus = - dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, - DISTRIBUTION_STATUS_SENT, - retryCount); - client.save(updateRetryCountAndStatus); - - // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!). - OperationalEnvDistributionStatus updateStatus = - dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, - DISTRIBUTION_STATUS_ERROR, - sdcStatus.getErrorReason()); - client.save(updateStatus); - } else { - String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode + - "; messageId: " + jsonResponse.get("messageId") + - "; message: " + jsonResponse.get("message"); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder(dbErrorMessage, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId); - throw validateException; - } - - return jsonResponse; - - } - - - /** - * The Method to check the overall status of the Activation for an operationalEnvironmentId - * @param operationalEnvironmentId - string - * @param origRequestId - string - * @return void - nothing - */ - public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException{ - - List<OperationalEnvServiceModelStatus> queryServiceModelResponseList = client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId); - - String status = "Waiting"; - int count = 0; - // loop through the statuses of the service model - for (OperationalEnvServiceModelStatus querySrvModelResponse : queryServiceModelResponseList) { - status = querySrvModelResponse.getServiceModelVersionDistrStatus(); - // all should be OK to be completed. - if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString()) && - (querySrvModelResponse.getRetryCount() == 0))) { - status = "Completed"; - count ++; - } - // one error with zero retry, means all are failures. - if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString()) && - (querySrvModelResponse.getRetryCount() == 0))) { - status = "Failure"; - count = queryServiceModelResponseList.size(); - break; - } - } - - if (status.equals("Completed") && queryServiceModelResponseList.size() == count) { - String messageStatus = "Overall Activation process is complete. " + status; - isOverallSuccess = true; - requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId); - } else { - if (status.equals("Failure") && queryServiceModelResponseList.size() == count) { - this.errorMessage = "Overall Activation process is a Failure. " + status; - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError).build(); - ValidateException validateException = new ValidateException.Builder(this.errorMessage, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + + } + + /** + * The Method to process the Activation Status from SDC + * + * @param sdcDistributionId - string + * @param sdcStatus - Distribution object + * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object + * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object + * @return void - nothing + */ + public void processActivateSDCStatus(String sdcDistributionId, Distribution sdcStatus, + OperationalEnvDistributionStatus queryDistributionDbResponse, + OperationalEnvServiceModelStatus queryServiceModelResponse) throws ApiException { + + String sdcStatusValue = sdcStatus.getStatus().toString(); + String recoveryAction = queryServiceModelResponse.getRecoveryAction(); + int retryCount = queryServiceModelResponse.getRetryCount(); + + // Validate/process status + if (sdcStatus.getStatus().toString().equals(DISTRIBUTION_STATUS_OK)) { + // should update 1 row, update status to "DISTRIBUTION_COMPLETE_OK" + OperationalEnvDistributionStatus updateDistStatusOk = dbHelper + .updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, sdcStatusValue, ""); + client.save(updateDistStatusOk); + // should update 1 row, update status and retryCount = 0 (ie, serviceModelVersionId is DONE!) + OperationalEnvServiceModelStatus updateRetryCountZeroAndStatusOk = + dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, + sdcStatusValue, RETRY_COUNT_ZERO); + client.save(updateRetryCountZeroAndStatusOk); + } else { + + // "DISTRIBUTION_COMPLETE_ERROR", Check if recoveryAction is "RETRY" + if (recoveryAction.equals(RECOVERY_ACTION_RETRY) && retryCount > RETRY_COUNT_ZERO) { + + // RESEND / RETRY serviceModelVersionId to SDC + + JSONObject jsonResponse = + callSDClientForRetry(queryDistributionDbResponse, queryServiceModelResponse, sdcStatus); + + } else { // either RETRY & Count = 0, or 'ABORT', or 'SKIP' + + if (recoveryAction.equals(RECOVERY_ACTION_SKIP) || recoveryAction.equals(RECOVERY_ACTION_ABORT)) { + String modifiedStatus = ""; + String errorReason = ""; + if (recoveryAction.equals(RECOVERY_ACTION_SKIP)) { // considered SUCCESS + modifiedStatus = DISTRIBUTION_STATUS_OK; + } else { + if (recoveryAction.equals(RECOVERY_ACTION_ABORT)) { + modifiedStatus = DISTRIBUTION_STATUS_ERROR; // ABORT, error + errorReason = ERROR_REASON_ABORTED; + } + } + + sdcStatusValue = modifiedStatus; + OperationalEnvServiceModelStatus updateRetryCountZeroAndStatus = + dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus( + queryServiceModelResponse, modifiedStatus, RETRY_COUNT_ZERO); + client.save(updateRetryCountZeroAndStatus); + OperationalEnvDistributionStatus updateDistStatus = + dbHelper.updateStatusInOperationalEnvDistributionStatus(queryDistributionDbResponse, + modifiedStatus, errorReason); + client.save(updateDistStatus); + } else { + // RETRY & Count = 0 (do nothing!) + } + } + } + } + + /** + * The Method to call SDC for recoveryActioin RETRY + * + * @param queryDistributionDbResponse - OperationalEnvDistributionStatus object + * @param queryServiceModelResponse - OperationalEnvServiceModelStatus object + * @param sdcStatus - Distribution object + * @return JSONObject object + */ + public JSONObject callSDClientForRetry(OperationalEnvDistributionStatus queryDistributionDbResponse, + OperationalEnvServiceModelStatus queryServiceModelResponse, Distribution sdcStatus) throws ApiException { + + JSONObject jsonResponse = null; + + String operEnvironmentId = queryDistributionDbResponse.getOperationalEnvId(); + String serviceModelVersionId = queryDistributionDbResponse.getServiceModelVersionId(); + String originalRequestId = queryServiceModelResponse.getRequestId(); + int retryCount = queryServiceModelResponse.getRetryCount(); + String workloadContext = queryServiceModelResponse.getWorkloadContext(); + + + jsonResponse = sdcClientHelper.postActivateOperationalEnvironment(serviceModelVersionId, operEnvironmentId, + workloadContext); + String statusCode = jsonResponse.get("statusCode").toString(); + if (statusCode.equals(String.valueOf(Response.Status.ACCEPTED.getStatusCode()))) { + String newDistributionId = jsonResponse.get("distributionId").toString(); + // should insert 1 row, NEW distributionId for replacement of the serviceModelServiceId record + OperationalEnvDistributionStatus insertNewDistributionId = + dbHelper.insertRecordToOperationalEnvDistributionStatus(newDistributionId, operEnvironmentId, + serviceModelVersionId, originalRequestId, DISTRIBUTION_STATUS_SENT, ""); + client.save(insertNewDistributionId); + + // update retryCount (less 1) for the serviceModelServiceId + retryCount = retryCount - 1; + // should update 1 row, original insert + OperationalEnvServiceModelStatus updateRetryCountAndStatus = + dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(queryServiceModelResponse, + DISTRIBUTION_STATUS_SENT, retryCount); + client.save(updateRetryCountAndStatus); + + // should update 1 row, OLD distributionId set to status error (ie, old distributionId is DONE!). + OperationalEnvDistributionStatus updateStatus = dbHelper.updateStatusInOperationalEnvDistributionStatus( + queryDistributionDbResponse, DISTRIBUTION_STATUS_ERROR, sdcStatus.getErrorReason()); + client.save(updateStatus); + } else { + String dbErrorMessage = "Failure calling SDC: statusCode: " + statusCode + "; messageId: " + + jsonResponse.get("messageId") + "; message: " + jsonResponse.get("message"); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + ValidateException validateException = + new ValidateException.Builder(dbErrorMessage, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestDb.updateInfraFailureCompletion(dbErrorMessage, this.origRequestId, operEnvironmentId); + throw validateException; + } + + return jsonResponse; + + } + + + /** + * The Method to check the overall status of the Activation for an operationalEnvironmentId + * + * @param operationalEnvironmentId - string + * @param origRequestId - string + * @return void - nothing + */ + public void checkOrUpdateOverallStatus(String operationalEnvironmentId, String origRequestId) throws ApiException { + + List<OperationalEnvServiceModelStatus> queryServiceModelResponseList = + client.getAllByOperationalEnvIdAndRequestId(operationalEnvironmentId, origRequestId); + + String status = "Waiting"; + int count = 0; + // loop through the statuses of the service model + for (OperationalEnvServiceModelStatus querySrvModelResponse : queryServiceModelResponseList) { + status = querySrvModelResponse.getServiceModelVersionDistrStatus(); + // all should be OK to be completed. + if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString()) + && (querySrvModelResponse.getRetryCount() == 0))) { + status = "Completed"; + count++; + } + // one error with zero retry, means all are failures. + if ((status.equals(DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString()) + && (querySrvModelResponse.getRetryCount() == 0))) { + status = "Failure"; + count = queryServiceModelResponseList.size(); + break; + } + } + + if (status.equals("Completed") && queryServiceModelResponseList.size() == count) { + String messageStatus = "Overall Activation process is complete. " + status; + isOverallSuccess = true; + requestDb.updateInfraSuccessCompletion(messageStatus, origRequestId, operationalEnvironmentId); + } else { + if (status.equals("Failure") && queryServiceModelResponseList.size() == count) { + this.errorMessage = "Overall Activation process is a Failure. " + status; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError) + .build(); + ValidateException validateException = + new ValidateException.Builder(this.errorMessage, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); requestDb.updateInfraFailureCompletion(this.errorMessage, origRequestId, operationalEnvironmentId); - throw validateException; - } - - } - } - - /** - * Get OperationalEnvironment object - * @param operationalEnvironmentId - String - * @return operationalEnv - OperationalEnvironment object - */ - private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) { - AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); - Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class); - return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null; - } + throw validateException; + } + + } + } + + /** + * Get OperationalEnvironment object + * + * @param operationalEnvironmentId - String + * @return operationalEnv - OperationalEnvironment object + */ + private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) { + AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); + Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class); + return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java index e9c9be9dd4..3812aa9edf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironment.java @@ -41,48 +41,51 @@ import org.springframework.stereotype.Component; @Component public class CreateEcompOperationalEnvironment { - - private static Logger logger = LoggerFactory.getLogger(CreateEcompOperationalEnvironment.class); - - @Autowired - private AAIClientObjectBuilder aaiClientObjectBuilder; - @Autowired - private AAIClientHelper aaiHelper; - @Autowired - private RequestsDBHelper requestDb; - @Autowired - private DmaapOperationalEnvClient dmaapClient; - public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{ + private static Logger logger = LoggerFactory.getLogger(CreateEcompOperationalEnvironment.class); - //Create ECOMP Managing Environment object in A&AI - aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("ACTIVE", request)); + @Autowired + private AAIClientObjectBuilder aaiClientObjectBuilder; + @Autowired + private AAIClientHelper aaiHelper; + @Autowired + private RequestsDBHelper requestDb; + @Autowired + private DmaapOperationalEnvClient dmaapClient; - // Call client to publish to DMaap + public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { + + // Create ECOMP Managing Environment object in A&AI + aaiHelper + .createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("ACTIVE", request)); + + // Call client to publish to DMaap try { - logger.debug("1 {}", request.getOperationalEnvironmentId()); - logger.debug("2 {}", request.getRequestDetails().getRequestInfo().getInstanceName()); - logger.debug("3 {}", request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType() - .toString()); - logger.debug("4 {}", request.getRequestDetails().getRequestParameters().getTenantContext()); - logger.debug("5 {}", request.getRequestDetails().getRequestParameters().getWorkloadContext()); + logger.debug("1 {}", request.getOperationalEnvironmentId()); + logger.debug("2 {}", request.getRequestDetails().getRequestInfo().getInstanceName()); + logger.debug("3 {}", + request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString()); + logger.debug("4 {}", request.getRequestDetails().getRequestParameters().getTenantContext()); + logger.debug("5 {}", request.getRequestDetails().getRequestParameters().getWorkloadContext()); dmaapClient.dmaapPublishOperationalEnvRequest(request.getOperationalEnvironmentId(), request.getRequestDetails().getRequestInfo().getInstanceName(), request.getRequestDetails().getRequestParameters().getOperationalEnvironmentType().toString(), request.getRequestDetails().getRequestParameters().getTenantContext(), - request.getRequestDetails().getRequestParameters().getWorkloadContext(), - "Create"); - }catch(Exception e){ - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e) - .errorInfo(errorLoggerInfo).build(); + request.getRequestDetails().getRequestParameters().getWorkloadContext(), "Create"); + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + ValidateException validateException = + new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build(); requestDb.updateInfraFailureCompletion(e.getMessage(), requestId, request.getOperationalEnvironmentId()); throw validateException; } - //Update request database - requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Created ECOMP OperationalEnvironment.", requestId, request.getOperationalEnvironmentId()); + // Update request database + requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Created ECOMP OperationalEnvironment.", requestId, + request.getOperationalEnvironmentId()); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java index cc3e3aeb16..fe81a07212 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironment.java @@ -24,9 +24,7 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import java.util.ArrayList; import java.util.List; - import javax.ws.rs.NotFoundException; - import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -54,178 +52,184 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; @Component public class CreateVnfOperationalEnvironment { - - private static Logger logger = LoggerFactory.getLogger(CreateVnfOperationalEnvironment.class); - protected CloudOrchestrationRequest request; - - @Autowired - private AAIClientObjectBuilder aaiClientObjectBuilder; - @Autowired - private AAIClientHelper aaiHelper; - @Autowired - private RequestsDBHelper requestDb; - private GRMClient grmClient; - - public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException{ - try { - setRequest(request); - ObjectMapper objectMapper = new ObjectMapper(); - AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId()); - if (aaiResultWrapper.isEmpty()) { - throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI"); - } - OperationalEnvironment aaiEnv = aaiResultWrapper.asBean(OperationalEnvironment.class).get(); - - //Find ECOMP environments in GRM - logger.debug(" Start of GRM findRunningServicesAsString"); - String searchKey = getSearchKey(aaiEnv); - String tenantContext = getTenantContext().toUpperCase(); - String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext); - ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class); - if(sel.getServiceEndPointList().size() == 0) { - throw new TenantIsolationException("GRM did not find any matches for " + searchKey + " in " + tenantContext); - } - - //Replicate end-point for VNF Operating environment in GRM - List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel); - int ctr = 0; - int total = serviceEndpointRequestList.size(); - for (ServiceEndPointRequest requestList : serviceEndpointRequestList) { - logger.debug("Creating endpoint " + ++ctr + " of " + total + ": " + requestList.getServiceEndPoint().getName()); - getGrmClient().addServiceEndPoint(requestList); - } - - //Create VNF operating in A&AI - aaiHelper.createOperationalEnvironment(aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request)); - aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId()); - - //Update request database - requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId, request.getOperationalEnvironmentId()); - - }catch(Exception e) { - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - - - ValidateException validateException = new ValidateException.Builder(e.getMessage(), - HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); - - throw validateException; - } - } - - - protected String getEcompManagingEnvironmentId() throws TenantIsolationException { - RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList(); - if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) { - return relatedInstances[0].getRelatedInstance().getInstanceId(); - } else { - return null; - } - } - - - protected String getTenantContext() throws TenantIsolationException { - if(!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) { - return request.getRequestDetails().getRequestParameters().getTenantContext(); - } - else { - throw new TenantIsolationException("Tenant Context is missing from request!"); - } - } - - - private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList) throws TenantIsolationException { - List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList(); - logger.debug("Number of service endpoints from GRM: {}", endpointList.size()); - List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>(); - for(ServiceEndPoint serviceEndpoint : endpointList) { - serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint)); - } - return serviceEndPointRequestList; - } - - - private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint) throws TenantIsolationException { - - //@TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to fields - Version ver = new Version(); - ver.setMajor(serviceEndpoint.getVersion().getMajor()); - ver.setMinor(serviceEndpoint.getVersion().getMinor()); - ver.setPatch(serviceEndpoint.getVersion().getPatch()); - - ServiceEndPoint endpoint = new ServiceEndPoint(); - endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName())); - - endpoint.setVersion(ver); - endpoint.setHostAddress(serviceEndpoint.getHostAddress()); - endpoint.setListenPort(serviceEndpoint.getListenPort()); - endpoint.setLatitude(serviceEndpoint.getLatitude()); - endpoint.setLongitude(serviceEndpoint.getLongitude()); - endpoint.setContextPath(serviceEndpoint.getContextPath()); - endpoint.setRouteOffer(serviceEndpoint.getRouteOffer()); - - OperationalInfo operInfo = new OperationalInfo(); - operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy()); - operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy()); - - endpoint.setOperationalInfo(operInfo); - endpoint.setProperties(serviceEndpoint.getProperties()); - - String env = getEnvironmentName(serviceEndpoint.getProperties()); - - ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest(); - serviceEndPontRequest.setEnv(env); - serviceEndPontRequest.setServiceEndPoint(endpoint); - - return serviceEndPontRequest; - } - - - protected String getEnvironmentName(List<Property> props) { - String env = ""; - for(Property prop : props) { - if(prop.getName().equalsIgnoreCase("Environment")) { - env = prop.getValue(); - } - } - return env; - } - - - protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException { - // Service name format is: {tenantContext}.{workloadContext}.{serviceName} e.g. TEST.ECOMP_PSL.Inventory - // We need to extract the serviceName, in the above example: "Inventory" - String[] tokens = fqName.split("[.]"); - String serviceName; - if(tokens.length > 0) { - serviceName = tokens[tokens.length-1]; - } - else { - throw new TenantIsolationException("Fully qualified service name is null."); - } - String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext(); - String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext(); - return tenantContext + "." + workloadContext + "." + serviceName; - } - - protected String getSearchKey(OperationalEnvironment aaiEnv) { - return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*"; - } - - public void setRequest(CloudOrchestrationRequest request) { - this.request = request; - } - - private GRMClient getGrmClient() { - if(grmClient == null) { - this.grmClient = new GRMClient(); - } - - return grmClient; - } + + private static Logger logger = LoggerFactory.getLogger(CreateVnfOperationalEnvironment.class); + protected CloudOrchestrationRequest request; + + @Autowired + private AAIClientObjectBuilder aaiClientObjectBuilder; + @Autowired + private AAIClientHelper aaiHelper; + @Autowired + private RequestsDBHelper requestDb; + private GRMClient grmClient; + + public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { + try { + setRequest(request); + ObjectMapper objectMapper = new ObjectMapper(); + AAIResultWrapper aaiResultWrapper = aaiHelper.getAaiOperationalEnvironment(getEcompManagingEnvironmentId()); + if (aaiResultWrapper.isEmpty()) { + throw new NotFoundException(getEcompManagingEnvironmentId() + " not found in A&AI"); + } + OperationalEnvironment aaiEnv = aaiResultWrapper.asBean(OperationalEnvironment.class).get(); + + // Find ECOMP environments in GRM + logger.debug(" Start of GRM findRunningServicesAsString"); + String searchKey = getSearchKey(aaiEnv); + String tenantContext = getTenantContext().toUpperCase(); + String jsonResponse = getGrmClient().findRunningServicesAsString(searchKey, 1, tenantContext); + ServiceEndPointList sel = objectMapper.readValue(jsonResponse, ServiceEndPointList.class); + if (sel.getServiceEndPointList().size() == 0) { + throw new TenantIsolationException( + "GRM did not find any matches for " + searchKey + " in " + tenantContext); + } + + // Replicate end-point for VNF Operating environment in GRM + List<ServiceEndPointRequest> serviceEndpointRequestList = buildEndPointRequestList(sel); + int ctr = 0; + int total = serviceEndpointRequestList.size(); + for (ServiceEndPointRequest requestList : serviceEndpointRequestList) { + logger.debug("Creating endpoint " + ++ctr + " of " + total + ": " + + requestList.getServiceEndPoint().getName()); + getGrmClient().addServiceEndPoint(requestList); + } + + // Create VNF operating in A&AI + aaiHelper.createOperationalEnvironment( + aaiClientObjectBuilder.buildAAIOperationalEnvironment("INACTIVE", request)); + aaiHelper.createRelationship(request.getOperationalEnvironmentId(), getEcompManagingEnvironmentId()); + + // Update request database + requestDb.updateInfraSuccessCompletion("SUCCESSFULLY created VNF operational environment", requestId, + request.getOperationalEnvironmentId()); + + } catch (Exception e) { + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + + + ValidateException validateException = + new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build(); + + throw validateException; + } + } + + + protected String getEcompManagingEnvironmentId() throws TenantIsolationException { + RelatedInstanceList[] relatedInstances = request.getRequestDetails().getRelatedInstanceList(); + if (relatedInstances.length > 0 && relatedInstances[0].getRelatedInstance() != null) { + return relatedInstances[0].getRelatedInstance().getInstanceId(); + } else { + return null; + } + } + + + protected String getTenantContext() throws TenantIsolationException { + if (!StringUtils.isEmpty(request.getRequestDetails().getRequestParameters().getTenantContext())) { + return request.getRequestDetails().getRequestParameters().getTenantContext(); + } else { + throw new TenantIsolationException("Tenant Context is missing from request!"); + } + } + + + private List<ServiceEndPointRequest> buildEndPointRequestList(ServiceEndPointList serviceEndPointList) + throws TenantIsolationException { + List<ServiceEndPoint> endpointList = serviceEndPointList.getServiceEndPointList(); + logger.debug("Number of service endpoints from GRM: {}", endpointList.size()); + List<ServiceEndPointRequest> serviceEndPointRequestList = new ArrayList<ServiceEndPointRequest>(); + for (ServiceEndPoint serviceEndpoint : endpointList) { + serviceEndPointRequestList.add(buildServiceEndpoint(serviceEndpoint)); + } + return serviceEndPointRequestList; + } + + + private ServiceEndPointRequest buildServiceEndpoint(ServiceEndPoint serviceEndpoint) + throws TenantIsolationException { + + // @TODO: handle nulls? Put in a ServiceEndpointWrapper class which will check for nulls and flatten access to + // fields + Version ver = new Version(); + ver.setMajor(serviceEndpoint.getVersion().getMajor()); + ver.setMinor(serviceEndpoint.getVersion().getMinor()); + ver.setPatch(serviceEndpoint.getVersion().getPatch()); + + ServiceEndPoint endpoint = new ServiceEndPoint(); + endpoint.setName(buildServiceNameForVnf(serviceEndpoint.getName())); + + endpoint.setVersion(ver); + endpoint.setHostAddress(serviceEndpoint.getHostAddress()); + endpoint.setListenPort(serviceEndpoint.getListenPort()); + endpoint.setLatitude(serviceEndpoint.getLatitude()); + endpoint.setLongitude(serviceEndpoint.getLongitude()); + endpoint.setContextPath(serviceEndpoint.getContextPath()); + endpoint.setRouteOffer(serviceEndpoint.getRouteOffer()); + + OperationalInfo operInfo = new OperationalInfo(); + operInfo.setCreatedBy(serviceEndpoint.getOperationalInfo().getCreatedBy()); + operInfo.setUpdatedBy(serviceEndpoint.getOperationalInfo().getUpdatedBy()); + + endpoint.setOperationalInfo(operInfo); + endpoint.setProperties(serviceEndpoint.getProperties()); + + String env = getEnvironmentName(serviceEndpoint.getProperties()); + + ServiceEndPointRequest serviceEndPontRequest = new ServiceEndPointRequest(); + serviceEndPontRequest.setEnv(env); + serviceEndPontRequest.setServiceEndPoint(endpoint); + + return serviceEndPontRequest; + } + + + protected String getEnvironmentName(List<Property> props) { + String env = ""; + for (Property prop : props) { + if (prop.getName().equalsIgnoreCase("Environment")) { + env = prop.getValue(); + } + } + return env; + } + + + protected String buildServiceNameForVnf(String fqName) throws TenantIsolationException { + // Service name format is: {tenantContext}.{workloadContext}.{serviceName} e.g. TEST.ECOMP_PSL.Inventory + // We need to extract the serviceName, in the above example: "Inventory" + String[] tokens = fqName.split("[.]"); + String serviceName; + if (tokens.length > 0) { + serviceName = tokens[tokens.length - 1]; + } else { + throw new TenantIsolationException("Fully qualified service name is null."); + } + String tenantContext = request.getRequestDetails().getRequestParameters().getTenantContext(); + String workloadContext = request.getRequestDetails().getRequestParameters().getWorkloadContext(); + return tenantContext + "." + workloadContext + "." + serviceName; + } + + protected String getSearchKey(OperationalEnvironment aaiEnv) { + return aaiEnv.getTenantContext() + "." + aaiEnv.getWorkloadContext() + ".*"; + } + + public void setRequest(CloudOrchestrationRequest request) { + this.request = request; + } + + private GRMClient getGrmClient() { + if (grmClient == null) { + this.grmClient = new GRMClient(); + } + + return grmClient; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java index 7f8b330727..e8ea153a6a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironment.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import java.util.Optional; - import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -45,50 +44,53 @@ import org.springframework.stereotype.Component; @Component public class DeactivateVnfOperationalEnvironment { - private static Logger logger = LoggerFactory.getLogger(DeactivateVnfOperationalEnvironment - .class); - - @Autowired + private static Logger logger = LoggerFactory.getLogger(DeactivateVnfOperationalEnvironment.class); + + @Autowired private AAIClientHelper aaiHelper; - @Autowired + @Autowired private RequestsDBHelper requestDb; - - public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { - String operationalEnvironmentId = request.getOperationalEnvironmentId(); - - OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(operationalEnvironmentId); - if (aaiOpEnv != null) { - String operationalEnvironmentStatus = aaiOpEnv.getOperationalEnvironmentStatus(); - - if(StringUtils.isBlank(operationalEnvironmentStatus)) { - String error = "OperationalEnvironmentStatus is null on OperationalEnvironmentId: " + operationalEnvironmentId; - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - throw new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR) - .errorInfo(errorLoggerInfo) - .build(); - } - - if(operationalEnvironmentStatus.equalsIgnoreCase("ACTIVE")) { - - aaiOpEnv.setOperationalEnvironmentStatus("INACTIVE"); - aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv); - - } else if(!operationalEnvironmentStatus.equalsIgnoreCase("INACTIVE")) { - String error = "Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: " + operationalEnvironmentId; - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException validateException = new ValidateException.Builder(error, - HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); - requestDb.updateInfraFailureCompletion(error, requestId, operationalEnvironmentId); - throw validateException; - } - - requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Deactivated OperationalEnvironment", requestId, operationalEnvironmentId); - } - } - - private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) { - AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); - Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class); - return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null; - } + + public void execute(String requestId, CloudOrchestrationRequest request) throws ApiException { + String operationalEnvironmentId = request.getOperationalEnvironmentId(); + + OperationalEnvironment aaiOpEnv = getAAIOperationalEnvironment(operationalEnvironmentId); + if (aaiOpEnv != null) { + String operationalEnvironmentStatus = aaiOpEnv.getOperationalEnvironmentStatus(); + + if (StringUtils.isBlank(operationalEnvironmentStatus)) { + String error = + "OperationalEnvironmentStatus is null on OperationalEnvironmentId: " + operationalEnvironmentId; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + throw new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + } + + if (operationalEnvironmentStatus.equalsIgnoreCase("ACTIVE")) { + + aaiOpEnv.setOperationalEnvironmentStatus("INACTIVE"); + aaiHelper.updateAaiOperationalEnvironment(operationalEnvironmentId, aaiOpEnv); + + } else if (!operationalEnvironmentStatus.equalsIgnoreCase("INACTIVE")) { + String error = + "Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: " + operationalEnvironmentId; + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + ValidateException validateException = new ValidateException.Builder(error, HttpStatus.SC_BAD_REQUEST, + ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build(); + requestDb.updateInfraFailureCompletion(error, requestId, operationalEnvironmentId); + throw validateException; + } + + requestDb.updateInfraSuccessCompletion("SUCCESSFULLY Deactivated OperationalEnvironment", requestId, + operationalEnvironmentId); + } + } + + private OperationalEnvironment getAAIOperationalEnvironment(String operationalEnvironmentId) { + AAIResultWrapper aaiResult = aaiHelper.getAaiOperationalEnvironment(operationalEnvironmentId); + Optional<OperationalEnvironment> operationalEnvironmentOpt = aaiResult.asBean(OperationalEnvironment.class); + return operationalEnvironmentOpt.isPresent() ? operationalEnvironmentOpt.get() : null; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java index 3f7a5536f3..3fc567e81e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Action.java @@ -21,8 +21,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum Action { - create, - activate, - deactivate, - distributionStatus + create, activate, deactivate, distributionStatus } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java index 25c8538003..71eb6020b4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationRequestList.java @@ -24,14 +24,14 @@ import java.util.List; public class CloudOrchestrationRequestList { - private List<CloudOrchestrationResponse> requestList; + private List<CloudOrchestrationResponse> requestList; - public List<CloudOrchestrationResponse> getRequestList() { - return requestList; - } + public List<CloudOrchestrationResponse> getRequestList() { + return requestList; + } - public void setRequestList(List<CloudOrchestrationResponse> requestList) { - this.requestList = requestList; - } + public void setRequestList(List<CloudOrchestrationResponse> requestList) { + this.requestList = requestList; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java index bd5167c395..7dc219407e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/CloudOrchestrationResponse.java @@ -25,14 +25,14 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(Include.NON_DEFAULT) public class CloudOrchestrationResponse { - - protected Request request; - - public Request getRequest() { - return request; - } - public void setRequest(Request request) { - this.request = request; - } + protected Request request; + + public Request getRequest() { + return request; + } + + public void setRequest(Request request) { + this.request = request; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java index b556178427..255d3a50f9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Distribution.java @@ -22,29 +22,29 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; -public class Distribution implements Serializable{ - - /** - * - */ - private static final long serialVersionUID = -529289171571892371L; - private Status status; - private String errorReason; - - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - public String getErrorReason() { - return errorReason; - } - - public void setErrorReason(String errorReason) { - this.errorReason = errorReason; - } +public class Distribution implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -529289171571892371L; + private Status status; + private String errorReason; + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public String getErrorReason() { + return errorReason; + } + + public void setErrorReason(String errorReason) { + this.errorReason = errorReason; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java index d54c6238ae..1b30b6fa14 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/DistributionStatus.java @@ -21,6 +21,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum DistributionStatus { - DISTRIBUTION_COMPLETE_OK, - DISTRIBUTION_COMPLETE_ERROR + DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java index 097660d9f3..34e219415b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/InstanceReferences.java @@ -29,32 +29,32 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class InstanceReferences { - private String operationalEnvironmentId; - private String operationalEnvName; - private String requestorId; - - public String getOperationalEnvironmentId() { - return operationalEnvironmentId; - } - - public void setOperationalEnvironmentId(String operationalEnvironmentId) { - this.operationalEnvironmentId = operationalEnvironmentId; - } - - public String getOperationalEnvName() { - return operationalEnvName; - } - - public void setOperationalEnvName(String operationalEnvName) { - this.operationalEnvName = operationalEnvName; - } - - public String getRequestorId() { - return requestorId; - } - - public void setRequestorId(String requestorId) { - this.requestorId = requestorId; - } - + private String operationalEnvironmentId; + private String operationalEnvName; + private String requestorId; + + public String getOperationalEnvironmentId() { + return operationalEnvironmentId; + } + + public void setOperationalEnvironmentId(String operationalEnvironmentId) { + this.operationalEnvironmentId = operationalEnvironmentId; + } + + public String getOperationalEnvName() { + return operationalEnvName; + } + + public void setOperationalEnvName(String operationalEnvName) { + this.operationalEnvName = operationalEnvName; + } + + public String getRequestorId() { + return requestorId; + } + + public void setRequestorId(String requestorId) { + this.requestorId = requestorId; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java index afb9ebdff3..4c66a3118e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Manifest.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; import java.util.ArrayList; import java.util.List; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -33,21 +32,21 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class Manifest implements Serializable { - private static final long serialVersionUID = -3460949513229380541L; - @JsonProperty("serviceModelList") - private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>(); - - public List<ServiceModelList> getServiceModelList() { - return serviceModelList; - } - - public void setServiceModelList(List<ServiceModelList> serviceModelList) { - this.serviceModelList = serviceModelList; - } - - @Override - public String toString() { - return "Manifest [serviceModelList=" + serviceModelList.toString() + "]"; - } - + private static final long serialVersionUID = -3460949513229380541L; + @JsonProperty("serviceModelList") + private List<ServiceModelList> serviceModelList = new ArrayList<ServiceModelList>(); + + public List<ServiceModelList> getServiceModelList() { + return serviceModelList; + } + + public void setServiceModelList(List<ServiceModelList> serviceModelList) { + this.serviceModelList = serviceModelList; + } + + @Override + public String toString() { + return "Manifest [serviceModelList=" + serviceModelList.toString() + "]"; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java index 61acc9f94c..d16093de04 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/OperationalEnvironment.java @@ -22,6 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum OperationalEnvironment { - ECOMP, - VNF + ECOMP, VNF } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java index f32c11f8a8..91d7aa2b89 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RecoveryAction.java @@ -22,7 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum RecoveryAction { - retry, - abort, - skip + retry, abort, skip } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java index 78faea7b8e..75f7e91742 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstance.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,39 +29,43 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName(value = "relatedInstance") @JsonInclude(Include.NON_DEFAULT) public class RelatedInstance implements Serializable { - - private static final long serialVersionUID = -6775477105573153067L; - @JsonProperty("instanceName") - protected String instanceName; - @JsonProperty("instanceId") - protected String instanceId; - @JsonProperty("resourceType") - protected ResourceType resourceType; - public String getInstanceName() { - return instanceName; - } - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } - public String getInstanceId() { - return instanceId; - } - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - public ResourceType getResourceType() { - return resourceType; - } - public void setResourceType(ResourceType resourceType) { - this.resourceType = resourceType; - } + private static final long serialVersionUID = -6775477105573153067L; + @JsonProperty("instanceName") + protected String instanceName; + @JsonProperty("instanceId") + protected String instanceId; + @JsonProperty("resourceType") + protected ResourceType resourceType; + + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public String getInstanceId() { + return instanceId; + } + + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + public ResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(ResourceType resourceType) { + this.resourceType = resourceType; + } + + @Override + public String toString() { + return "RelatedInstance [instanceName=" + instanceName + ", instanceId=" + instanceId + ", resourceType=" + + resourceType + "]"; + } - @Override - public String toString() { - return "RelatedInstance [instanceName=" + instanceName + - ", instanceId=" + instanceId + - ", resourceType=" + resourceType + "]"; - } - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java index ee54392e9d..73fb20660a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RelatedInstanceList.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,15 +30,15 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class RelatedInstanceList implements Serializable { - private static final long serialVersionUID = 1758713583807257102L; - @JsonProperty("relatedInstance") - protected RelatedInstance relatedInstance; + private static final long serialVersionUID = 1758713583807257102L; + @JsonProperty("relatedInstance") + protected RelatedInstance relatedInstance; - public RelatedInstance getRelatedInstance() { - return relatedInstance; - } + public RelatedInstance getRelatedInstance() { + return relatedInstance; + } - public void setRelatedInstance(RelatedInstance relatedInstance) { - this.relatedInstance = relatedInstance; - } + public void setRelatedInstance(RelatedInstance relatedInstance) { + this.relatedInstance = relatedInstance; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java index 7d927512e6..eb4e9384f5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Request.java @@ -36,55 +36,62 @@ public class Request { protected String requestType; protected RequestDetails requestDetails; protected RequestStatus requestStatus; - - - public String getRequestId() { - return requestId; - } - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getStartTime() { - return startTime; - } - public void setStartTime(String startTime) { - this.startTime = startTime; - } - - public String getRequestScope() { - return requestScope; - } - public void setRequestScope(String requestScope) { - this.requestScope = requestScope; - } - - public String getRequestType() { - return requestType; - } - public void setRequestType(String requestType) { - this.requestType = requestType; - } - - public RequestStatus getRequestStatus() { - return requestStatus; - } - public void setRequestStatus(RequestStatus requestStatus) { - this.requestStatus = requestStatus; - } - - public InstanceReferences getInstanceReferences() { - return instanceReferences; - } - public void setInstanceReferences(InstanceReferences instanceReferences) { - this.instanceReferences = instanceReferences; - } - - public RequestDetails getRequestDetails() { - return requestDetails; - } - public void setRequestDetails(RequestDetails requestDetails) { - this.requestDetails = requestDetails; - } - -}
\ No newline at end of file + + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getRequestScope() { + return requestScope; + } + + public void setRequestScope(String requestScope) { + this.requestScope = requestScope; + } + + public String getRequestType() { + return requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + public RequestStatus getRequestStatus() { + return requestStatus; + } + + public void setRequestStatus(RequestStatus requestStatus) { + this.requestStatus = requestStatus; + } + + public InstanceReferences getInstanceReferences() { + return instanceReferences; + } + + public void setInstanceReferences(InstanceReferences instanceReferences) { + this.instanceReferences = instanceReferences; + } + + public RequestDetails getRequestDetails() { + return requestDetails; + } + + public void setRequestDetails(RequestDetails requestDetails) { + this.requestDetails = requestDetails; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java index 36e3bf95e7..ff427c719f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestDetails.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; import java.util.Arrays; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -32,20 +31,18 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class RequestDetails implements Serializable { - private static final long serialVersionUID = -73080684945860609L; - @JsonProperty("requestInfo") + private static final long serialVersionUID = -73080684945860609L; + @JsonProperty("requestInfo") protected RequestInfo requestInfo; - @JsonProperty("relatedInstanceList") + @JsonProperty("relatedInstanceList") protected RelatedInstanceList[] relatedInstanceList; - @JsonProperty("requestParameters") + @JsonProperty("requestParameters") protected RequestParameters requestParameters; /** * Gets the value of the requestInfo property. * - * @return - * possible object is - * {@link RequestInfo } + * @return possible object is {@link RequestInfo } * */ public RequestInfo getRequestInfo() { @@ -55,9 +52,7 @@ public class RequestDetails implements Serializable { /** * Sets the value of the requestInfo property. * - * @param value - * allowed object is - * {@link RequestInfo } + * @param value allowed object is {@link RequestInfo } * */ public void setRequestInfo(RequestInfo value) { @@ -67,9 +62,7 @@ public class RequestDetails implements Serializable { /** * Gets the value of the requestParameters property. * - * @return - * possible object is - * {@link RequestParameters } + * @return possible object is {@link RequestParameters } * */ public RequestParameters getRequestParameters() { @@ -79,26 +72,24 @@ public class RequestDetails implements Serializable { /** * Sets the value of the requestParameters property. * - * @param value - * allowed object is - * {@link RequestParameters } + * @param value allowed object is {@link RequestParameters } * */ public void setRequestParameters(RequestParameters value) { this.requestParameters = value; } - public RelatedInstanceList[] getRelatedInstanceList() { - return relatedInstanceList; - } + public RelatedInstanceList[] getRelatedInstanceList() { + return relatedInstanceList; + } - public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) { - this.relatedInstanceList = relatedInstanceList; - } - @Override - public String toString() { - return "RequestDetails [requestInfo=" + requestInfo + - ", relatedInstanceList=" + Arrays.toString(relatedInstanceList) + - ", requestParameters=" + requestParameters + "]"; - } + public void setRelatedInstanceList(RelatedInstanceList[] relatedInstanceList) { + this.relatedInstanceList = relatedInstanceList; + } + + @Override + public String toString() { + return "RequestDetails [requestInfo=" + requestInfo + ", relatedInstanceList=" + + Arrays.toString(relatedInstanceList) + ", requestParameters=" + requestParameters + "]"; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java index d57d4bf366..b40fc3f07d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestInfo.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,22 +30,20 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class RequestInfo implements Serializable { - private static final long serialVersionUID = 1346372792555344857L; - @JsonProperty("resourceType") + private static final long serialVersionUID = 1346372792555344857L; + @JsonProperty("resourceType") protected ResourceType resourceType; - @JsonProperty("source") + @JsonProperty("source") protected String source; - @JsonProperty("instanceName") + @JsonProperty("instanceName") protected String instanceName; - @JsonProperty("requestorId") + @JsonProperty("requestorId") protected String requestorId; - /** + /** * Gets the value of the resourceType property. * - * @return - * possible object is - * {@link ResourceType } + * @return possible object is {@link ResourceType } * */ public ResourceType getResourceType() { @@ -56,9 +53,7 @@ public class RequestInfo implements Serializable { /** * Sets the value of the source property. * - * @param value - * allowed object is - * {@link ResourceType } + * @param value allowed object is {@link ResourceType } * */ public void setResourceType(ResourceType value) { @@ -69,9 +64,7 @@ public class RequestInfo implements Serializable { /** * Gets the value of the source property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getSource() { @@ -81,38 +74,34 @@ public class RequestInfo implements Serializable { /** * Sets the value of the source property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setSource(String value) { this.source = value; } - public String getInstanceName() { - return instanceName; - } - - public void setInstanceName(String instanceName) { - this.instanceName = instanceName; - } - - public String getRequestorId() { - return requestorId; - } - - public void setRequestorId(String requestorId) { - this.requestorId = requestorId; - } - - @Override - public String toString() { - return "RequestInfo [source=" + source - + ", instanceName=" + instanceName - + ", requestorId=" + requestorId - + ", resourceType=" + resourceType + "]"; - } + public String getInstanceName() { + return instanceName; + } + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + public String getRequestorId() { + return requestorId; + } + + public void setRequestorId(String requestorId) { + this.requestorId = requestorId; + } + + @Override + public String toString() { + return "RequestInfo [source=" + source + ", instanceName=" + instanceName + ", requestorId=" + requestorId + + ", resourceType=" + resourceType + "]"; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java index 170b5e7609..20021888c0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestList.java @@ -30,17 +30,15 @@ import com.fasterxml.jackson.annotation.JsonRootName; public class RequestList { - @JsonProperty("request") + @JsonProperty("request") protected Request request; - @JsonProperty("requestStatus") + @JsonProperty("requestStatus") protected RequestStatus requestStatus; /** * Gets the value of the request property. * - * @return - * possible object is - * {@link Request } + * @return possible object is {@link Request } * */ public Request getRequest() { @@ -50,9 +48,7 @@ public class RequestList { /** * Sets the value of the requestInfo property. * - * @param value - * allowed object is - * {@link Request } + * @param value allowed object is {@link Request } * */ public void setRequest(Request value) { @@ -62,22 +58,18 @@ public class RequestList { /** * Gets the value of the requestStatus property. * - * @return - * possible object is - * {@link RequestStatus } + * @return possible object is {@link RequestStatus } * */ public RequestStatus getRequestStatus() { return requestStatus; } - + /** * Sets the value of the requestStatus property. * - * @param value - * allowed object is - * {@link RequestStatus } + * @param value allowed object is {@link RequestStatus } * */ public void setRequestStatus(RequestStatus value) { @@ -85,9 +77,8 @@ public class RequestList { } - @Override - public String toString() { - return "RequestList [request=" + request + - ", requestStatus=" + requestStatus + "]"; - } -}
\ No newline at end of file + @Override + public String toString() { + return "RequestList [request=" + request + ", requestStatus=" + requestStatus + "]"; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java index 1a12c47d7d..299d177099 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestParameters.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,54 +30,52 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class RequestParameters implements Serializable { - private static final long serialVersionUID = 8530327178156183693L; - @JsonProperty("operationalEnvironmentType") - private OperationalEnvironment operationalEnvironmentType; - @JsonProperty("tenantContext") - private String tenantContext; - @JsonProperty("workloadContext") - private String workloadContext; - @JsonProperty("manifest") - private Manifest manifest; - - public OperationalEnvironment getOperationalEnvironmentType() { - return operationalEnvironmentType; - } + private static final long serialVersionUID = 8530327178156183693L; + @JsonProperty("operationalEnvironmentType") + private OperationalEnvironment operationalEnvironmentType; + @JsonProperty("tenantContext") + private String tenantContext; + @JsonProperty("workloadContext") + private String workloadContext; + @JsonProperty("manifest") + private Manifest manifest; + + public OperationalEnvironment getOperationalEnvironmentType() { + return operationalEnvironmentType; + } + + public void setOperationalEnvironmentType(OperationalEnvironment operationalEnvironmentType) { + this.operationalEnvironmentType = operationalEnvironmentType; + } + + public String getTenantContext() { + return tenantContext; + } + + public void setTenantContext(String tenantContext) { + this.tenantContext = tenantContext; + } - public void setOperationalEnvironmentType(OperationalEnvironment operationalEnvironmentType) { - this.operationalEnvironmentType = operationalEnvironmentType; - } + public String getWorkloadContext() { + return workloadContext; + } - public String getTenantContext() { - return tenantContext; - } + public void setWorkloadContext(String workloadContext) { + this.workloadContext = workloadContext; + } - public void setTenantContext(String tenantContext) { - this.tenantContext = tenantContext; - } - - public String getWorkloadContext() { - return workloadContext; - } + public Manifest getManifest() { + return manifest; + } - public void setWorkloadContext(String workloadContext) { - this.workloadContext = workloadContext; - } - - public Manifest getManifest() { - return manifest; - } + public void setManifest(Manifest manifest) { + this.manifest = manifest; + } - public void setManifest(Manifest manifest) { - this.manifest = manifest; - } - - @Override - public String toString() { - return "RequestParameters [operationalEnvironmentType=" + operationalEnvironmentType - + ", tenantContext=" + tenantContext - + ", workloadContext=" + workloadContext - + ", manifes=" + manifest +"]"; - } + @Override + public String toString() { + return "RequestParameters [operationalEnvironmentType=" + operationalEnvironmentType + ", tenantContext=" + + tenantContext + ", workloadContext=" + workloadContext + ", manifes=" + manifest + "]"; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java index 337de3c51d..d766bcf2dd 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestReferences.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,67 +29,58 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName(value = "requestReferences") @JsonInclude(Include.NON_DEFAULT) public class RequestReferences implements Serializable { - - private static final long serialVersionUID = 5873356773819905368L; - - @JsonProperty("requestId") - protected String requestId; - - @JsonProperty("instanceId") - String instanceId; + + private static final long serialVersionUID = 5873356773819905368L; + + @JsonProperty("requestId") + protected String requestId; + + @JsonProperty("instanceId") + String instanceId; /** * Gets the value of the requestId property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * - */ - public String getRequestId() { - return requestId; - } - + */ + public String getRequestId() { + return requestId; + } + /** * Sets the value of the requestId property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * - */ - public void setRequestId(String requestId) { - this.requestId = requestId; - } - + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + /** * Gets the value of the instanceId property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * - */ - public String getInstanceId() { - return instanceId; - } - + */ + public String getInstanceId() { + return instanceId; + } + /** * Sets the value of the instanceId property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + @Override + public String toString() { + return "RequestReferences [requestId=" + requestId + ", instanceId=" + instanceId + "]"; + } - @Override - public String toString() { - return "RequestReferences [requestId=" + requestId + - ", instanceId=" + instanceId + "]"; - } - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java index 6fd765b76f..f1f9417805 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/RequestStatus.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,39 +30,46 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class RequestStatus implements Serializable { - private static final long serialVersionUID = -1835437975187313144L; - @JsonProperty("requestState") - protected String requestState; - @JsonProperty("statusMessage") + private static final long serialVersionUID = -1835437975187313144L; + @JsonProperty("requestState") + protected String requestState; + @JsonProperty("statusMessage") protected String statusMessage; - @JsonProperty("percentProgress") + @JsonProperty("percentProgress") protected String percentProgress; - @JsonProperty("timestamp") + @JsonProperty("timestamp") protected String timeStamp; - public String getRequestState() { - return requestState; - } - public void setRequestState(String requestState) { - this.requestState = requestState; - } - public String getStatusMessage() { - return statusMessage; - } - public void setStatusMessage(String statusMessage) { - this.statusMessage = statusMessage; - } - public String getPercentProgress() { - return percentProgress; - } - public void setPercentProgress(String percentProgress) { - this.percentProgress = percentProgress; - } - public String getTimeStamp() { - return timeStamp; - } - public void setTimeStamp(String timeStamp) { - this.timeStamp = timeStamp; - } -}
\ No newline at end of file + public String getRequestState() { + return requestState; + } + + public void setRequestState(String requestState) { + this.requestState = requestState; + } + + public String getStatusMessage() { + return statusMessage; + } + + public void setStatusMessage(String statusMessage) { + this.statusMessage = statusMessage; + } + + public String getPercentProgress() { + return percentProgress; + } + + public void setPercentProgress(String percentProgress) { + this.percentProgress = percentProgress; + } + + public String getTimeStamp() { + return timeStamp; + } + + public void setTimeStamp(String timeStamp) { + this.timeStamp = timeStamp; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java index 835c2657d1..edeee56249 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ResourceType.java @@ -22,5 +22,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum ResourceType { - operationalEnvironment + operationalEnvironment } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java index 4dea3149ad..fbbd183380 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/ServiceModelList.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,29 +30,32 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class ServiceModelList implements Serializable { - private static final long serialVersionUID = 1758713583807257102L; - - @JsonProperty("serviceModelVersionId") - protected String serviceModelVersionId; - @JsonProperty("recoveryAction") - protected RecoveryAction recoveryAction; - - public String getServiceModelVersionId() { - return serviceModelVersionId; - } - public void setServiceModelVersionId(String serviceModelVersionId) { - this.serviceModelVersionId = serviceModelVersionId; - } - public RecoveryAction getRecoveryAction() { - return recoveryAction; - } - public void setRecoveryAction(RecoveryAction recoveryAction) { - this.recoveryAction = recoveryAction; - } - - @Override - public String toString() { - return "ServiceModelList [serviceModelVersionId=" + serviceModelVersionId + "," - + "recoveryAction=" + recoveryAction +"]"; - } + private static final long serialVersionUID = 1758713583807257102L; + + @JsonProperty("serviceModelVersionId") + protected String serviceModelVersionId; + @JsonProperty("recoveryAction") + protected RecoveryAction recoveryAction; + + public String getServiceModelVersionId() { + return serviceModelVersionId; + } + + public void setServiceModelVersionId(String serviceModelVersionId) { + this.serviceModelVersionId = serviceModelVersionId; + } + + public RecoveryAction getRecoveryAction() { + return recoveryAction; + } + + public void setRecoveryAction(RecoveryAction recoveryAction) { + this.recoveryAction = recoveryAction; + } + + @Override + public String toString() { + return "ServiceModelList [serviceModelVersionId=" + serviceModelVersionId + "," + "recoveryAction=" + + recoveryAction + "]"; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java index a7c6c67395..5182f448fe 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/Status.java @@ -21,6 +21,5 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public enum Status { - DISTRIBUTION_COMPLETE_OK, - DISTRIBUTION_COMPLETE_ERROR + DISTRIBUTION_COMPLETE_OK, DISTRIBUTION_COMPLETE_ERROR } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java index 003cb0815a..6d4c17519b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationRequest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -31,65 +30,72 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonInclude(Include.NON_DEFAULT) public class TenantIsolationRequest implements Serializable { - private static final long serialVersionUID = -210322298981798607L; - @JsonProperty("requestId") + private static final long serialVersionUID = -210322298981798607L; + @JsonProperty("requestId") protected String requestId; - @JsonProperty("startTime") + @JsonProperty("startTime") protected String startTime; - @JsonProperty("requestScope") + @JsonProperty("requestScope") protected String requestScope; - @JsonProperty("requestType") + @JsonProperty("requestType") protected String requestType; - @JsonProperty("requestDetails") + @JsonProperty("requestDetails") protected RequestDetails requestDetails; - @JsonProperty("requestStatus") + @JsonProperty("requestStatus") protected RequestStatus requestStatus; - - public String getRequestId() { - return requestId; - } - public void setRequestId(String requestId) { - this.requestId = requestId; - } - public String getStartTime() { - return startTime; - } - public void setStartTime(String startTime) { - this.startTime = startTime; - } - public String getRequestScope() { - return requestScope; - } - public void setRequestScope(String requestScope) { - this.requestScope = requestScope; - } - public String getRequestType() { - return requestType; - } - public void setRequestType(String requestType) { - this.requestType = requestType; - } - public RequestStatus getRequestStatus() { - return requestStatus; - } - public void setRequestStatus(RequestStatus requestStatus) { - this.requestStatus = requestStatus; - } - - public RequestDetails getRequestDetails() { - return requestDetails; - } - public void setRequestDetails(RequestDetails requestDetails) { - this.requestDetails = requestDetails; - } - - @Override - public String toString() { - return "Request [requestId=" + requestId + - ", startTime=" + startTime + - ", requestType=" + requestType + - ", requestDetails=" + requestDetails.toString() + - ", requestStatus=" + requestStatus.toString() + "]"; - } - + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getStartTime() { + return startTime; + } + + public void setStartTime(String startTime) { + this.startTime = startTime; + } + + public String getRequestScope() { + return requestScope; + } + + public void setRequestScope(String requestScope) { + this.requestScope = requestScope; + } + + public String getRequestType() { + return requestType; + } + + public void setRequestType(String requestType) { + this.requestType = requestType; + } + + public RequestStatus getRequestStatus() { + return requestStatus; + } + + public void setRequestStatus(RequestStatus requestStatus) { + this.requestStatus = requestStatus; + } + + public RequestDetails getRequestDetails() { + return requestDetails; + } + + public void setRequestDetails(RequestDetails requestDetails) { + this.requestDetails = requestDetails; + } + + @Override + public String toString() { + return "Request [requestId=" + requestId + ", startTime=" + startTime + ", requestType=" + requestType + + ", requestDetails=" + requestDetails.toString() + ", requestStatus=" + requestStatus.toString() + "]"; + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java index 15a0ab840c..b4ce83afca 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationResponse.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import java.io.Serializable; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; @@ -30,86 +29,74 @@ import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName(value = "tenantIsolationResponse") @JsonInclude(Include.NON_DEFAULT) public class TenantIsolationResponse implements Serializable { - - private static final long serialVersionUID = 756749312745898666L; - @JsonProperty("requestId") - protected String requestId; - @JsonProperty("status") - String status; - @JsonProperty("message") - String message; + + private static final long serialVersionUID = 756749312745898666L; + @JsonProperty("requestId") + protected String requestId; + @JsonProperty("status") + String status; + @JsonProperty("message") + String message; /** * Gets the value of the requestId property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * - */ - public String getRequestId() { - return requestId; - } - + */ + public String getRequestId() { + return requestId; + } + /** * Sets the value of the requestId property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * - */ - public void setRequestId(String requestId) { - this.requestId = requestId; - } - + */ + public void setRequestId(String requestId) { + this.requestId = requestId; + } + /** * Gets the value of the status property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * - */ - public String getStatus() { - return status; - } - + */ + public String getStatus() { + return status; + } + /** * Sets the value of the status property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * - */ - public void setStatus(String status) { - this.status = status; - } - - /** + */ + public void setStatus(String status) { + this.status = status; + } + + /** * Gets the value of the message property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * - */ - public String getMessage() { - return message; - } - + */ + public String getMessage() { + return message; + } + /** * Sets the value of the message property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * - */ - public void setMessage(String message) { - this.message = message; - } + */ + public void setMessage(String message) { + this.message = message; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java index 7281e1c708..0327232b43 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantSyncResponse.java @@ -21,15 +21,15 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; public class TenantSyncResponse { - - private RequestReferences requestReferences; - public RequestReferences getRequestReferences() { - return requestReferences; - } + private RequestReferences requestReferences; - public void setRequestReferences(RequestReferences requestReferences) { - this.requestReferences = requestReferences; - } + public RequestReferences getRequestReferences() { + return requestReferences; + } + + public void setRequestReferences(RequestReferences requestReferences) { + this.requestReferences = requestReferences; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java index 713a763321..45f85bf5d3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/tenantisolationbeans/package-info.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // package org.onap.so.apihandlerinfra.tenantisolationbeans; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java index 243bbf1474..07b2d4426f 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ApplyUpdatedConfigValidation.java @@ -25,25 +25,26 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; -public class ApplyUpdatedConfigValidation implements ValidationRule{ +public class ApplyUpdatedConfigValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); - RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); - - if(requestInfo == null){ - throw new ValidationException("requestInfo"); - }else if(empty(requestInfo.getRequestorId())) { - throw new ValidationException ("requestorId"); - }else if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source"); + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + + if (requestInfo == null) { + throw new ValidationException("requestInfo"); + } else if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId"); + } else if (empty(requestInfo.getSource())) { + throw new ValidationException("source"); + } + if (requestParameters == null) { + throw new ValidationException("requestParameters"); } - if(requestParameters == null){ - throw new ValidationException("requestParameters"); - } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java index 937ce19741..2207c52048 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CloudConfigurationValidation.java @@ -27,53 +27,61 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.ModelType; -public class CloudConfigurationValidation implements ValidationRule{ - public boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); - String requestScope = info.getRequestScope(); - int reqVersion = info.getReqVersion(); - Actions action = info.getAction(); - Boolean aLaCarteFlag = info.getALaCarteFlag(); - - if(!requestScope.equals(ModelType.instanceGroup.toString())){ - if(cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)){ - if((!requestScope.equalsIgnoreCase(ModelType.service.name()) && !requestScope.equalsIgnoreCase(ModelType.configuration.name())) && - (action == Action.createInstance || action == Action.deleteInstance || action == Action.updateInstance)){ - throw new ValidationException ("cloudConfiguration"); - } - if((requestScope.equalsIgnoreCase(ModelType.vnf.name()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) && - action == Action.replaceInstance){ - throw new ValidationException ("cloudConfiguration"); - } - if(requestScope.equalsIgnoreCase(ModelType.configuration.name()) && - (action == Action.enablePort || action == Action.disablePort || action == Action.activateInstance || action == Action.deactivateInstance)){ - throw new ValidationException ("cloudConfiguration"); - } - if(requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)){ - throw new ValidationException("cloudConfiguration"); - } - if(requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance){ - throw new ValidationException("cloudConfiguration", true); - } - } - } - - if (cloudConfiguration == null && ((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase (ModelType.service.name ()) && reqVersion < 5)) { - throw new ValidationException ("cloudConfiguration"); +public class CloudConfigurationValidation implements ValidationRule { + public boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); + String requestScope = info.getRequestScope(); + int reqVersion = info.getReqVersion(); + Actions action = info.getAction(); + Boolean aLaCarteFlag = info.getALaCarteFlag(); + + if (!requestScope.equals(ModelType.instanceGroup.toString())) { + if (cloudConfiguration == null && reqVersion >= 5 && (aLaCarteFlag != null && aLaCarteFlag)) { + if ((!requestScope.equalsIgnoreCase(ModelType.service.name()) + && !requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && (action == Action.createInstance || action == Action.deleteInstance + || action == Action.updateInstance)) { + throw new ValidationException("cloudConfiguration"); + } + if ((requestScope.equalsIgnoreCase(ModelType.vnf.name()) + || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) + && action == Action.replaceInstance) { + throw new ValidationException("cloudConfiguration"); + } + if (requestScope.equalsIgnoreCase(ModelType.configuration.name()) + && (action == Action.enablePort || action == Action.disablePort + || action == Action.activateInstance || action == Action.deactivateInstance)) { + throw new ValidationException("cloudConfiguration"); + } + if (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + && (action == Action.deactivateAndCloudDelete || action == Action.scaleOut)) { + throw new ValidationException("cloudConfiguration"); + } + if (requestScope.equals(ModelType.vnf.name()) && action == Action.recreateInstance) { + throw new ValidationException("cloudConfiguration", true); + } + } + } + + if (cloudConfiguration == null && ((aLaCarteFlag != null && !aLaCarteFlag) + && requestScope.equalsIgnoreCase(ModelType.service.name()) && reqVersion < 5)) { + throw new ValidationException("cloudConfiguration"); } if (cloudConfiguration != null) { - if (empty (cloudConfiguration.getLcpCloudRegionId ())) { - throw new ValidationException ("lcpCloudRegionId"); - } - if (empty (cloudConfiguration.getTenantId ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))) { - throw new ValidationException ("tenantId"); - } - } - return info; - } -}
\ No newline at end of file + if (empty(cloudConfiguration.getLcpCloudRegionId())) { + throw new ValidationException("lcpCloudRegionId"); + } + if (empty(cloudConfiguration.getTenantId()) + && !(requestScope.equalsIgnoreCase(ModelType.configuration.name()))) { + throw new ValidationException("tenantId"); + } + } + return info; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java index 8fdb43f20c..158de70309 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ConfigurationParametersValidation.java @@ -23,27 +23,28 @@ package org.onap.so.apihandlerinfra.validation; import java.util.List; import java.util.Map; - import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; -public class ConfigurationParametersValidation implements ValidationRule{ +public class ConfigurationParametersValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - ServiceInstancesRequest sir = info.getSir(); - List<Map<String, String>> configParams = sir.getRequestDetails().getConfigurationParameters(); - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - - if(configParams.isEmpty() && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut){ - throw new ValidationException("configuration parameters"); - } + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + ServiceInstancesRequest sir = info.getSir(); + List<Map<String, String>> configParams = sir.getRequestDetails().getConfigurationParameters(); + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + + if (configParams.isEmpty() && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + && action == Action.scaleOut) { + throw new ValidationException("configuration parameters"); + } return info; - } -}
\ No newline at end of file + } +} 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 new file mode 100644 index 0000000000..01e3de99ec --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidation.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.validation; + +import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.CloudConfiguration; +import org.onap.so.serviceinstancebeans.RequestParameters; +import com.google.common.base.Strings; + +public class CustomWorkflowValidation implements ValidationRule { + + @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"); + } + return info; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java index afbacb465d..6ffd9dcef8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InPlaceSoftwareUpdateValidation.java @@ -26,33 +26,34 @@ import org.onap.so.serviceinstancebeans.CloudConfiguration; import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; -public class InPlaceSoftwareUpdateValidation implements ValidationRule{ +public class InPlaceSoftwareUpdateValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); - CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails ().getCloudConfiguration(); - RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); - if (cloudConfiguration == null) { - throw new ValidationException ("cloudConfiguration"); - }else if (empty (cloudConfiguration.getLcpCloudRegionId ())) { - throw new ValidationException ("lcpCloudRegionId"); - }else if (empty (cloudConfiguration.getTenantId ())) { - throw new ValidationException ("tenantId"); - } - if(requestInfo == null){ - throw new ValidationException("requestInfo"); - }else if(empty(requestInfo.getRequestorId())) { - throw new ValidationException ("requestorId"); - }else if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source"); + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + RequestParameters requestParameters = info.getSir().getRequestDetails().getRequestParameters(); + CloudConfiguration cloudConfiguration = info.getSir().getRequestDetails().getCloudConfiguration(); + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + + if (cloudConfiguration == null) { + throw new ValidationException("cloudConfiguration"); + } else if (empty(cloudConfiguration.getLcpCloudRegionId())) { + throw new ValidationException("lcpCloudRegionId"); + } else if (empty(cloudConfiguration.getTenantId())) { + throw new ValidationException("tenantId"); + } + if (requestInfo == null) { + throw new ValidationException("requestInfo"); + } else if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId"); + } else if (empty(requestInfo.getSource())) { + throw new ValidationException("source"); + } + if (requestParameters == null) { + throw new ValidationException("requestParameters"); } - if(requestParameters == null){ - throw new ValidationException("requestParameters"); - } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java index fad11a5cc6..907bc942eb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/InstanceIdMapValidation.java @@ -22,68 +22,67 @@ package org.onap.so.apihandlerinfra.validation; import java.util.HashMap; - import org.onap.so.apihandler.common.CommonConstants; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.onap.so.utils.UUIDChecker; -public class InstanceIdMapValidation implements ValidationRule{ +public class InstanceIdMapValidation implements ValidationRule { + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + HashMap<String, String> instanceIdMap = info.getInstanceIdMap(); + ServiceInstancesRequest sir = info.getSir(); + if (instanceIdMap != null) { + if (instanceIdMap.get("serviceInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("serviceInstanceId"))) { + throw new ValidationException("serviceInstanceId"); + } + sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); + } + + if (instanceIdMap.get("vnfInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("vnfInstanceId"))) { + throw new ValidationException("vnfInstanceId"); + } + sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId")); + } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - HashMap<String, String> instanceIdMap = info.getInstanceIdMap(); - ServiceInstancesRequest sir = info.getSir(); - if(instanceIdMap != null){ - if(instanceIdMap.get("serviceInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("serviceInstanceId"))) { - throw new ValidationException ("serviceInstanceId"); - } - sir.setServiceInstanceId(instanceIdMap.get("serviceInstanceId")); - } + if (instanceIdMap.get("vfModuleInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("vfModuleInstanceId"))) { + throw new ValidationException("vfModuleInstanceId"); + } + sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId")); + } - if(instanceIdMap.get("vnfInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vnfInstanceId"))) { - throw new ValidationException ("vnfInstanceId"); - } - sir.setVnfInstanceId(instanceIdMap.get("vnfInstanceId")); - } + if (instanceIdMap.get("volumeGroupInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("volumeGroupInstanceId"))) { + throw new ValidationException("volumeGroupInstanceId"); + } + sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId")); + } - if(instanceIdMap.get("vfModuleInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("vfModuleInstanceId"))) { - throw new ValidationException ("vfModuleInstanceId"); - } - sir.setVfModuleInstanceId(instanceIdMap.get("vfModuleInstanceId")); - } + if (instanceIdMap.get("networkInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("networkInstanceId"))) { + throw new ValidationException("networkInstanceId"); + } + sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId")); + } - if(instanceIdMap.get("volumeGroupInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("volumeGroupInstanceId"))) { - throw new ValidationException ("volumeGroupInstanceId"); - } - sir.setVolumeGroupInstanceId(instanceIdMap.get("volumeGroupInstanceId")); - } + if (instanceIdMap.get("configurationInstanceId") != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get("configurationInstanceId"))) { + throw new ValidationException("configurationInstanceId"); + } + sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); + } - if(instanceIdMap.get("networkInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("networkInstanceId"))) { - throw new ValidationException ("networkInstanceId"); - } - sir.setNetworkInstanceId(instanceIdMap.get("networkInstanceId")); - } - - if(instanceIdMap.get("configurationInstanceId") != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get ("configurationInstanceId"))) { - throw new ValidationException ("configurationInstanceId"); - } - sir.setConfigurationId(instanceIdMap.get("configurationInstanceId")); - } - - if(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null){ - if (!UUIDChecker.isValidUUID (instanceIdMap.get (CommonConstants.INSTANCE_GROUP_INSTANCE_ID))) { - throw new ValidationException (CommonConstants.INSTANCE_GROUP_INSTANCE_ID, true); - } - sir.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); - } + if (instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID) != null) { + if (!UUIDChecker.isValidUUID(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID))) { + throw new ValidationException(CommonConstants.INSTANCE_GROUP_INSTANCE_ID, true); + } + sir.setInstanceGroupId(instanceIdMap.get(CommonConstants.INSTANCE_GROUP_INSTANCE_ID)); + } } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java index 89bb15dcb1..5e38979b89 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/MembersValidation.java @@ -27,43 +27,44 @@ import org.onap.so.serviceinstancebeans.RelatedInstance; import org.onap.so.serviceinstancebeans.RelatedInstanceList; import org.onap.so.serviceinstancebeans.RequestInfo; -public class MembersValidation implements ValidationRule{ +public class MembersValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); - RelatedInstanceList[] relatedInstanceList = info.getSir().getRequestDetails().getRelatedInstanceList(); - boolean vnfRelatedInstance = false; - - if(requestInfo == null){ - throw new ValidationException("requestInfo", true); - }else if(empty(requestInfo.getRequestorId())) { - throw new ValidationException ("requestorId", true); - }else if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source", true); + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + RelatedInstanceList[] relatedInstanceList = info.getSir().getRequestDetails().getRelatedInstanceList(); + boolean vnfRelatedInstance = false; + + if (requestInfo == null) { + throw new ValidationException("requestInfo", true); + } else if (empty(requestInfo.getRequestorId())) { + throw new ValidationException("requestorId", true); + } else if (empty(requestInfo.getSource())) { + throw new ValidationException("source", true); + } + if (relatedInstanceList == null) { + throw new ValidationException("related instances", true); + } else { + for (RelatedInstanceList instanceList : relatedInstanceList) { + RelatedInstance relatedInstance = instanceList.getRelatedInstance(); + ModelType modelType = relatedInstance.getModelInfo().getModelType(); + if (empty(relatedInstance.getInstanceId())) { + throw new ValidationException("instanceId in relatedInstances", true); + } + if (modelType == null) { + throw new ValidationException("modelType in relatedInstance", true); + } + if (modelType == ModelType.vnf) { + vnfRelatedInstance = true; + } + } + if (!vnfRelatedInstance) { + throw new ValidationException("vnf relatedInstance", true); + } } - if(relatedInstanceList == null){ - throw new ValidationException("related instances", true); - }else{ - for(RelatedInstanceList instanceList : relatedInstanceList){ - RelatedInstance relatedInstance = instanceList.getRelatedInstance(); - ModelType modelType = relatedInstance.getModelInfo().getModelType(); - if(empty(relatedInstance.getInstanceId())){ - throw new ValidationException("instanceId in relatedInstances", true); - } - if (modelType == null) { - throw new ValidationException("modelType in relatedInstance", true); - } - if(modelType == ModelType.vnf){ - vnfRelatedInstance = true; - } - } - if(!vnfRelatedInstance){ - throw new ValidationException("vnf relatedInstance", true); - } - } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java index e2a1bdc46a..ecc79c72e8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ModelInfoValidation.java @@ -29,109 +29,141 @@ import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.utils.UUIDChecker; -public class ModelInfoValidation implements ValidationRule{ - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); - RequestParameters requestParameters = info.getReqParameters(); - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - int reqVersion = info.getReqVersion(); - Boolean aLaCarteFlag = info.getALaCarteFlag(); - if(!requestScope.equals(ModelType.instanceGroup.toString())){ +public class ModelInfoValidation implements ValidationRule { + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } - if(!empty(modelInfo.getModelNameVersionId())){ - modelInfo.setModelVersionId(modelInfo.getModelNameVersionId()); - } - // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create - if(requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.createInstance && !requestParameters.isUsePreload()) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { - throw new ValidationException("modelCustomizationId"); - } - } + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); + RequestParameters requestParameters = info.getReqParameters(); + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + int reqVersion = info.getReqVersion(); + Boolean aLaCarteFlag = info.getALaCarteFlag(); - // modelCustomizationId is required for v5 and higher for VF Module Replace - if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.replaceInstance) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { - throw new ValidationException("modelCustomizationId"); - } - } + if (!requestScope.equals(ModelType.instanceGroup.toString())) { - // modelCustomizationId or modelCustomizationName are required for VNF Replace - if(requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.replaceInstance || action == Action.recreateInstance) { - if(!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) && modelInfo.getModelCustomizationName() == null) { - throw new ValidationException("modelCustomizationId or modelCustomizationName"); - } - } + if (!empty(modelInfo.getModelNameVersionId())) { + modelInfo.setModelVersionId(modelInfo.getModelNameVersionId()); + } + // modelCustomizationId is required when usePreLoad is false for v4 and higher for VF Module Create + if (requestParameters != null && reqVersion >= 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + && action == Action.createInstance && !requestParameters.isUsePreload()) { + if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { + throw new ValidationException("modelCustomizationId"); + } + } - //is required for serviceInstance delete macro when aLaCarte=false (v3) - //create and updates except for network (except v4) - if (empty (modelInfo.getModelInvariantId ()) && ((reqVersion >2 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || - !(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) && - (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || - (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { - throw new ValidationException ("modelInvariantId"); - } - if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ - throw new ValidationException("modelInvariantId"); - } - if(empty(modelInfo.getModelInvariantId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelInvariantId", true); - } - if (!empty (modelInfo.getModelInvariantId ()) && !UUIDChecker.isValidUUID (modelInfo.getModelInvariantId ())) { - throw new ValidationException ("modelInvariantId format"); - } + // modelCustomizationId is required for v5 and higher for VF Module Replace + if (requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + && action == Action.replaceInstance) { + if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { + throw new ValidationException("modelCustomizationId"); + } + } - if(reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && empty (modelInfo.getModelName ()) && (action == Action.createInstance || action == Action.updateInstance || - action == Action.addRelationships || action == Action.removeRelationships || action == Action.recreateInstance || ((action == Action.deleteInstance || action == Action.scaleOut) && (requestScope.equalsIgnoreCase (ModelType.vfModule.name ()))))){ - throw new ValidationException ("modelName", true); - } + // modelCustomizationId or modelCustomizationName are required for VNF Replace + if (requestParameters != null && reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) + && action == Action.replaceInstance || action == Action.recreateInstance) { + if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId()) + && modelInfo.getModelCustomizationName() == null) { + throw new ValidationException("modelCustomizationId or modelCustomizationName"); + } + } - if (empty (modelInfo.getModelVersion ()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) && - (!(reqVersion < 4 && requestScope.equalsIgnoreCase (ModelType.network.name ())) - && (action == Action.createInstance || action == Action.updateInstance || action == Action.addRelationships || action == Action.removeRelationships || action == Action.scaleOut))) { - throw new ValidationException ("modelVersion"); - } + // is required for serviceInstance delete macro when aLaCarte=false (v3) + // create and updates except for network (except v4) + if (empty(modelInfo.getModelInvariantId()) && ((reqVersion > 2 && (aLaCarteFlag != null && !aLaCarteFlag) + && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) + || !(reqVersion < 4 && requestScope.equalsIgnoreCase(ModelType.network.name())) + && (action == Action.createInstance || action == Action.updateInstance + || action == Action.enablePort || action == Action.disablePort + || action == Action.addRelationships || action == Action.removeRelationships + || (requestScope.equalsIgnoreCase(ModelType.configuration.name()) + && (action == Action.activateInstance + || action == Action.deactivateInstance))))) { + throw new ValidationException("modelInvariantId"); + } + if (empty(modelInfo.getModelInvariantId()) + && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)) { + throw new ValidationException("modelInvariantId"); + } + if (empty(modelInfo.getModelInvariantId()) + && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) { + throw new ValidationException("modelInvariantId", true); + } + if (!empty(modelInfo.getModelInvariantId()) && !UUIDChecker.isValidUUID(modelInfo.getModelInvariantId())) { + throw new ValidationException("modelInvariantId format"); + } - if(empty(modelInfo.getModelVersion()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelVersion", true); - } + if (reqVersion >= 4 && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && empty(modelInfo.getModelName()) + && (action == Action.createInstance || action == Action.updateInstance + || action == Action.addRelationships || action == Action.removeRelationships + || action == Action.recreateInstance + || ((action == Action.deleteInstance || action == Action.scaleOut) + && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()))))) { + throw new ValidationException("modelName", true); + } - // is required for serviceInstance delete macro when aLaCarte=false in v4 - if (reqVersion >= 4 && empty (modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) || - (action == Action.createInstance || action == Action.updateInstance || action == Action.enablePort || action == Action.disablePort || action == Action.addRelationships || action == Action.removeRelationships || - (requestScope.equalsIgnoreCase(ModelType.configuration.name()) && (action == Action.activateInstance || action == Action.deactivateInstance))))) { - throw new ValidationException ("modelVersionId"); - } - if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)){ - throw new ValidationException("modelVersionId", true); - } - if(empty(modelInfo.getModelVersionId()) && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)){ - throw new ValidationException("modelVersionId"); - } + if (empty(modelInfo.getModelVersion()) && !(requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && (!(reqVersion < 4 && requestScope.equalsIgnoreCase(ModelType.network.name())) + && (action == Action.createInstance || action == Action.updateInstance + || action == Action.addRelationships || action == Action.removeRelationships + || action == Action.scaleOut))) { + throw new ValidationException("modelVersion"); + } - if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance && empty (modelInfo.getModelCustomizationName ())) { - if (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) { - throw new ValidationException ("modelCustomizationId or modelCustomizationName"); - } - } + if (empty(modelInfo.getModelVersion()) + && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) { + throw new ValidationException("modelVersion", true); + } - if(reqVersion >= 4 && (!UUIDChecker.isValidUUID (modelInfo.getModelCustomizationId())) && (requestScope.equalsIgnoreCase (ModelType.network.name ()) || requestScope.equalsIgnoreCase(ModelType.configuration.name())) - && (action == Action.updateInstance || action == Action.createInstance)){ - throw new ValidationException ("modelCustomizationId"); - } - if(empty(modelInfo.getModelCustomizationId()) && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name() && requestParameters.isUsePreload() == true)){ - throw new ValidationException ("modelCustomizationId"); - } - }else{ - if(empty(modelInfo.getModelVersionId()) && action == Action.createInstance){ - throw new ValidationException("modelVersionId", true); - } - } - return info; - } + // is required for serviceInstance delete macro when aLaCarte=false in v4 + if (reqVersion >= 4 && empty(modelInfo.getModelVersionId()) && (((aLaCarteFlag != null && !aLaCarteFlag) + && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.deleteInstance) + || (action == Action.createInstance || action == Action.updateInstance + || action == Action.enablePort || action == Action.disablePort + || action == Action.addRelationships || action == Action.removeRelationships + || (requestScope.equalsIgnoreCase(ModelType.configuration.name()) + && (action == Action.activateInstance || action == Action.deactivateInstance))))) { + throw new ValidationException("modelVersionId"); + } + if (empty(modelInfo.getModelVersionId()) + && (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.recreateInstance)) { + throw new ValidationException("modelVersionId", true); + } + if (empty(modelInfo.getModelVersionId()) + && (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)) { + throw new ValidationException("modelVersionId"); + } + + if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action != Action.deleteInstance + && empty(modelInfo.getModelCustomizationName())) { + if (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) { + throw new ValidationException("modelCustomizationId or modelCustomizationName"); + } + } + + if (reqVersion >= 4 && (!UUIDChecker.isValidUUID(modelInfo.getModelCustomizationId())) + && (requestScope.equalsIgnoreCase(ModelType.network.name()) + || requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && (action == Action.updateInstance || action == Action.createInstance)) { + throw new ValidationException("modelCustomizationId"); + } + if (empty(modelInfo.getModelCustomizationId()) && requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + && action == Action.scaleOut && !(requestParameters.getTestApi() == TestApi.VNF_API.name() + && requestParameters.isUsePreload() == true)) { + throw new ValidationException("modelCustomizationId"); + } + } else { + if (empty(modelInfo.getModelVersionId()) && action == Action.createInstance) { + throw new ValidationException("modelVersionId", true); + } + } + return info; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java index 7c51f3e5ce..c80e89e21d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/PlatformLOBValidation.java @@ -28,33 +28,34 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.LineOfBusiness; import org.onap.so.serviceinstancebeans.Platform; -public class PlatformLOBValidation implements ValidationRule{ +public class PlatformLOBValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - int reqVersion = info.getReqVersion(); - Platform platform; - LineOfBusiness lineOfBusiness; - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - - platform = info.getSir().getRequestDetails().getPlatform(); - lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness(); - if(reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance){ - if(reqVersion > 5 && platform == null) { - throw new ValidationException("platform"); - } - if(platform != null && empty(platform.getPlatformName())){ - throw new ValidationException("platformName"); - } - if(lineOfBusiness != null && empty(lineOfBusiness.getLineOfBusinessName())){ - throw new ValidationException("lineOfBusinessName"); + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + int reqVersion = info.getReqVersion(); + Platform platform; + LineOfBusiness lineOfBusiness; + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + + platform = info.getSir().getRequestDetails().getPlatform(); + lineOfBusiness = info.getSir().getRequestDetails().getLineOfBusiness(); + if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) { + if (reqVersion > 5 && platform == null) { + throw new ValidationException("platform"); + } + if (platform != null && empty(platform.getPlatformName())) { + throw new ValidationException("platformName"); } - } + if (lineOfBusiness != null && empty(lineOfBusiness.getLineOfBusinessName())) { + throw new ValidationException("lineOfBusinessName"); + } + } info.setPlatform(platform); info.setLOB(lineOfBusiness); return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java index f6a3c03555..60e1274469 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ProjectOwningEntityValidation.java @@ -28,33 +28,35 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.OwningEntity; import org.onap.so.serviceinstancebeans.Project; -public class ProjectOwningEntityValidation implements ValidationRule{ +public class ProjectOwningEntityValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - int reqVersion = info.getReqVersion(); - Project project; - OwningEntity owningEntity; - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - - project = info.getSir().getRequestDetails().getProject(); - owningEntity = info.getSir().getRequestDetails().getOwningEntity(); - if(reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance || action == Action.assignInstance){ - if(reqVersion > 5 && owningEntity == null) { - throw new ValidationException("owningEntity"); - } - if(owningEntity != null && empty(owningEntity.getOwningEntityId())){ - throw new ValidationException("owningEntityId"); - } - if(project != null && empty(project.getProjectName())){ - throw new ValidationException("projectName"); - } - } - info.setProject(project); - info.setOE(owningEntity); + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + int reqVersion = info.getReqVersion(); + Project project; + OwningEntity owningEntity; + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + + project = info.getSir().getRequestDetails().getProject(); + owningEntity = info.getSir().getRequestDetails().getOwningEntity(); + if (reqVersion >= 5 && requestScope.equalsIgnoreCase(ModelType.service.name()) + && action == Action.createInstance || action == Action.assignInstance) { + if (reqVersion > 5 && owningEntity == null) { + throw new ValidationException("owningEntity"); + } + if (owningEntity != null && empty(owningEntity.getOwningEntityId())) { + throw new ValidationException("owningEntityId"); + } + if (project != null && empty(project.getProjectName())) { + throw new ValidationException("projectName"); + } + } + info.setProject(project); + info.setOE(owningEntity); return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java index 5eb3083003..b02bd95d97 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidation.java @@ -37,214 +37,238 @@ import org.onap.so.utils.UUIDChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class RelatedInstancesValidation implements ValidationRule{ - - private static Logger logger = LoggerFactory.getLogger(RelatedInstancesValidation.class); - - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); - } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - ServiceInstancesRequest sir = info.getSir(); - Actions action = info.getAction(); - int reqVersion = info.getReqVersion(); - String requestScope = info.getRequestScope(); - String serviceInstanceType = null; - String networkType = null; - String vnfType = null; - String vfModuleType = null; - String vfModuleModelName = null; - ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); - RelatedInstanceList[] instanceList = sir.getRequestDetails().getRelatedInstanceList(); - String serviceModelName = null; +public class RelatedInstancesValidation implements ValidationRule { + + private static Logger logger = LoggerFactory.getLogger(RelatedInstancesValidation.class); + + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); + } + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + ServiceInstancesRequest sir = info.getSir(); + Actions action = info.getAction(); + int reqVersion = info.getReqVersion(); + String requestScope = info.getRequestScope(); + String serviceInstanceType = null; + String networkType = null; + String vnfType = null; + String vfModuleType = null; + String vfModuleModelName = null; + ModelInfo modelInfo = info.getSir().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(requestScope.equalsIgnoreCase(ModelType.service.name())){ - serviceInstanceType = modelInfo.getModelName(); - info.setServiceInstanceType(serviceInstanceType); - } - if(requestScope.equalsIgnoreCase(ModelType.network.name())){ - networkType = modelInfo.getModelName(); - info.setNetworkType(networkType); - } - if (instanceList != null) { - for(RelatedInstanceList relatedInstanceList : instanceList){ - RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); - - ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo (); - if (relatedInstanceModelInfo == null) { - throw new ValidationException ("modelInfo in relatedInstance"); - } - - if (relatedInstanceModelInfo.getModelType () == null) { - throw new ValidationException ("modelType in relatedInstance"); - } - - if(empty(relatedInstance.getInstanceName ()) && ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) { - throw new ValidationException ("instanceName in relatedInstance for pnf modelType"); - } - - if (!empty (relatedInstance.getInstanceName ())) { - if (!relatedInstance.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) { - throw new ValidationException ("instanceName format in relatedInstance"); - } - } - - if (empty (relatedInstance.getInstanceId ()) && !ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) { - throw new ValidationException ("instanceId in relatedInstance"); - } - - if (!empty(relatedInstance.getInstanceId ()) && !UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) { - throw new ValidationException ("instanceId format in relatedInstance"); - } - if(empty(relatedInstanceModelInfo.getModelVersionId()) && requestScope.equals(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){ - throw new ValidationException("modelVersionId in relatedInstance", true); - } - if(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && relatedInstanceModelInfo.getModelType().equals(ModelType.service)){ - isRelatedServiceInstancePresent = true; - } - - if (action != Action.deleteInstance && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { - if(!( relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) || - relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) || - relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) || - relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) { - - if(empty (relatedInstanceModelInfo.getModelInvariantId ())) { - throw new ValidationException ("modelInvariantId in relatedInstance"); - } else if(reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelVersionId ())) { - throw new ValidationException("modelVersionId in relatedInstance"); - } else if(empty(relatedInstanceModelInfo.getModelName ())) { - throw new ValidationException ("modelName in relatedInstance"); - } else if (empty (relatedInstanceModelInfo.getModelVersion ())) { - throw new ValidationException ("modelVersion in relatedInstance"); - } - } - - if (!empty (relatedInstanceModelInfo.getModelInvariantId ()) && - !UUIDChecker.isValidUUID (relatedInstanceModelInfo.getModelInvariantId ())) { - throw new ValidationException ("modelInvariantId format in relatedInstance"); - } - - 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)))) { - isDestinationVnfPresent = true; - } - } - - if(ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - isConnectionPointPresent = true; - } - } - - if (empty (relatedInstanceModelInfo.getModelCustomizationName ()) && relatedInstanceModelInfo.getModelType ().equals (ModelType.vnf) ) { - if(reqVersion >=4 && empty (relatedInstanceModelInfo.getModelCustomizationId()) && action != Action.deleteInstance) { - throw new ValidationException ("modelCustomizationName or modelCustomizationId in relatedInstance of vnf"); - } - } - - if(relatedInstanceModelInfo.getModelType().equals(ModelType.service) && !(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance)) { - isRelatedServiceInstancePresent = true; - if (!relatedInstance.getInstanceId ().equals (sir.getServiceInstanceId ())) { - throw new ValidationException ("serviceInstanceId matching the serviceInstanceId in request URI"); - } - serviceModelName = relatedInstanceModelInfo.getModelName (); - asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion (); - } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { - isRelatedVnfInstancePresent = true; - if (!relatedInstance.getInstanceId ().equals (sir.getVnfInstanceId ())) { - throw new ValidationException ("vnfInstanceId matching the vnfInstanceId in request URI"); - } - vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); - } else if(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { - volumeGroupId = relatedInstance.getInstanceId (); - } - } - - if(action == Action.createInstance && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - if(!isSourceVnfPresent) { - throw new ValidationException ("source vnf relatedInstance for Port Configuration"); - } - - if(!isDestinationVnfPresent) { - throw new ValidationException ("destination vnf relatedInstance for Port Configuration"); - } - } - - if((action == Action.enablePort || action == Action.disablePort) && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { - if(!isConnectionPointPresent) { - throw new ValidationException ("connectionPoint relatedInstance for Port Configuration"); - } - } - if(requestScope.equals(ModelType.instanceGroup.toString())){ - if(!isRelatedServiceInstancePresent){ - throw new ValidationException("related service instance for instanceGroup request", true); - } - } - if(requestScope.equalsIgnoreCase (ModelType.volumeGroup.name ())) { - if (!isRelatedServiceInstancePresent) { - throw new ValidationException ("related service instance for volumeGroup request"); - } - if (!isRelatedVnfInstancePresent) { - throw new ValidationException ("related vnf instance for volumeGroup request"); - } - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - info.setServiceInstanceType(serviceInstanceType); - info.setVnfType(vnfType); - } - else if(requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) { - if (!isRelatedServiceInstancePresent) { - throw new ValidationException ("related service instance for vfModule request"); - } - if (!isRelatedVnfInstancePresent) { - throw new ValidationException ("related vnf instance for vfModule request"); - } - vfModuleModelName = modelInfo.getModelName (); - serviceInstanceType = serviceModelName; - vnfType = serviceModelName + "/" + vnfModelName; - vfModuleType = vnfType + "::" + vfModuleModelName; - sir.setVolumeGroupInstanceId (volumeGroupId); - info.setVfModuleModelName(vfModuleModelName); - info.setVnfType(vnfType); - info.setServiceInstanceType(serviceInstanceType); - info.setVfModuleType(vfModuleType); - } - else if (requestScope.equalsIgnoreCase (ModelType.vnf.name ())) { - if (!isRelatedServiceInstancePresent) { - throw new ValidationException ("related service instance for vnf request"); - } - vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName(); - info.setVnfType(vnfType); - } + boolean isSourceVnfPresent = false; + boolean isDestinationVnfPresent = false; + boolean isConnectionPointPresent = false; + + if (requestScope.equalsIgnoreCase(ModelType.service.name())) { + serviceInstanceType = modelInfo.getModelName(); + info.setServiceInstanceType(serviceInstanceType); + } + if (requestScope.equalsIgnoreCase(ModelType.network.name())) { + networkType = modelInfo.getModelName(); + info.setNetworkType(networkType); + } + if (instanceList != null) { + for (RelatedInstanceList relatedInstanceList : instanceList) { + RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance(); + + ModelInfo relatedInstanceModelInfo = relatedInstance.getModelInfo(); + if (relatedInstanceModelInfo == null) { + throw new ValidationException("modelInfo in relatedInstance"); + } + + if (relatedInstanceModelInfo.getModelType() == null) { + throw new ValidationException("modelType in relatedInstance"); + } + + if (empty(relatedInstance.getInstanceName()) + && ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceName in relatedInstance for pnf modelType"); + } + + if (!empty(relatedInstance.getInstanceName())) { + if (!relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { + throw new ValidationException("instanceName format in relatedInstance"); + } + } + + if (empty(relatedInstance.getInstanceId()) + && !ModelType.pnf.equals(relatedInstanceModelInfo.getModelType())) { + throw new ValidationException("instanceId in relatedInstance"); + } + + if (!empty(relatedInstance.getInstanceId()) + && !UUIDChecker.isValidUUID(relatedInstance.getInstanceId())) { + throw new ValidationException("instanceId format in relatedInstance"); + } + if (empty(relatedInstanceModelInfo.getModelVersionId()) + && requestScope.equals(ModelType.instanceGroup.toString()) + && relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + throw new ValidationException("modelVersionId in relatedInstance", true); + } + if (requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) + && relatedInstanceModelInfo.getModelType().equals(ModelType.service)) { + isRelatedServiceInstancePresent = true; + } + + if (action != Action.deleteInstance + && !requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString())) { + if (!(relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup) + || relatedInstanceModelInfo.getModelType().equals(ModelType.connectionPoint) + || relatedInstanceModelInfo.getModelType().equals(ModelType.pnf) + || relatedInstanceModelInfo.getModelType().equals(ModelType.networkInstanceGroup))) { + + if (empty(relatedInstanceModelInfo.getModelInvariantId())) { + throw new ValidationException("modelInvariantId in relatedInstance"); + } else if (reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelVersionId())) { + throw new ValidationException("modelVersionId in relatedInstance"); + } else if (empty(relatedInstanceModelInfo.getModelName())) { + throw new ValidationException("modelName in relatedInstance"); + } else if (empty(relatedInstanceModelInfo.getModelVersion())) { + throw new ValidationException("modelVersion in relatedInstance"); + } + } + + if (!empty(relatedInstanceModelInfo.getModelInvariantId()) + && !UUIDChecker.isValidUUID(relatedInstanceModelInfo.getModelInvariantId())) { + throw new ValidationException("modelInvariantId format in relatedInstance"); + } + + 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)))) { + isDestinationVnfPresent = true; + } + } + + if (ModelType.connectionPoint.equals(relatedInstanceModelInfo.getModelType()) + && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + isConnectionPointPresent = true; + } + } + + if (empty(relatedInstanceModelInfo.getModelCustomizationName()) + && relatedInstanceModelInfo.getModelType().equals(ModelType.vnf)) { + if (reqVersion >= 4 && empty(relatedInstanceModelInfo.getModelCustomizationId()) + && action != Action.deleteInstance) { + throw new ValidationException( + "modelCustomizationName or modelCustomizationId in relatedInstance of vnf"); + } + } + + if (relatedInstanceModelInfo.getModelType().equals(ModelType.service) + && !(requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) + && action == Action.createInstance)) { + isRelatedServiceInstancePresent = true; + if (!relatedInstance.getInstanceId().equals(sir.getServiceInstanceId())) { + throw new ValidationException( + "serviceInstanceId matching the serviceInstanceId in request URI"); + } + serviceModelName = relatedInstanceModelInfo.getModelName(); + asdcServiceModelVersion = relatedInstanceModelInfo.getModelVersion(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.vnf) + && !(ModelType.configuration.name().equalsIgnoreCase(requestScope))) { + isRelatedVnfInstancePresent = true; + if (!relatedInstance.getInstanceId().equals(sir.getVnfInstanceId())) { + throw new ValidationException("vnfInstanceId matching the vnfInstanceId in request URI"); + } + vnfModelName = relatedInstanceModelInfo.getModelCustomizationName(); + } else if (relatedInstanceModelInfo.getModelType().equals(ModelType.volumeGroup)) { + volumeGroupId = relatedInstance.getInstanceId(); + } + } + + if (action == Action.createInstance && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + if (!isSourceVnfPresent) { + throw new ValidationException("source vnf relatedInstance for Port Configuration"); + } + + if (!isDestinationVnfPresent) { + throw new ValidationException("destination vnf relatedInstance for Port Configuration"); + } + } + + if ((action == Action.enablePort || action == Action.disablePort) + && ModelType.configuration.name().equalsIgnoreCase(requestScope)) { + if (!isConnectionPointPresent) { + throw new ValidationException("connectionPoint relatedInstance for Port Configuration"); + } + } + if (requestScope.equals(ModelType.instanceGroup.toString())) { + if (!isRelatedServiceInstancePresent) { + throw new ValidationException("related service instance for instanceGroup request", true); + } + } + if (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name())) { + if (!isRelatedServiceInstancePresent) { + throw new ValidationException("related service instance for volumeGroup request"); + } + if (!isRelatedVnfInstancePresent) { + throw new ValidationException("related vnf instance for volumeGroup request"); + } + serviceInstanceType = serviceModelName; + vnfType = serviceModelName + "/" + vnfModelName; + info.setServiceInstanceType(serviceInstanceType); + info.setVnfType(vnfType); + } else if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { + if (!isRelatedServiceInstancePresent) { + throw new ValidationException("related service instance for vfModule request"); + } + if (!isRelatedVnfInstancePresent) { + throw new ValidationException("related vnf instance for vfModule request"); + } + vfModuleModelName = modelInfo.getModelName(); + serviceInstanceType = serviceModelName; + vnfType = serviceModelName + "/" + vnfModelName; + vfModuleType = vnfType + "::" + vfModuleModelName; + sir.setVolumeGroupInstanceId(volumeGroupId); + info.setVfModuleModelName(vfModuleModelName); + info.setVnfType(vnfType); + info.setServiceInstanceType(serviceInstanceType); + info.setVfModuleType(vfModuleType); + } else if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) { + if (!isRelatedServiceInstancePresent) { + throw new ValidationException("related service instance for vnf request"); + } + vnfType = serviceModelName + "/" + sir.getRequestDetails().getModelInfo().getModelCustomizationName(); + info.setVnfType(vnfType); + } + } else if (((requestScope.equalsIgnoreCase(ModelType.vnf.name()) + || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name()) + || requestScope.equalsIgnoreCase(ModelType.vfModule.name()) + || requestScope.equalsIgnoreCase(ModelType.configuration.name())) + && (action == Action.createInstance || action == Action.enablePort || action == Action.disablePort)) + || (reqVersion >= 4 + && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name()) + || requestScope.equalsIgnoreCase(ModelType.vfModule.name())) + && action == Action.updateInstance + || (requestScope.equalsIgnoreCase(ModelType.vfModule.name()) && action == Action.scaleOut)) + || (requestScope.equalsIgnoreCase(ModelType.service.name()) + && (action.equals(Action.addRelationships) || action.equals(Action.removeRelationships)))) { + logger.debug("related instance exception"); + throw new ValidationException("related instances"); } - else if ((( requestScope.equalsIgnoreCase(ModelType.vnf.name ()) || requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) - || requestScope.equalsIgnoreCase(ModelType.configuration.name())) && (action == Action.createInstance || action == Action.enablePort || action == Action.disablePort)) || - (reqVersion >= 4 && (requestScope.equalsIgnoreCase(ModelType.volumeGroup.name ()) || requestScope.equalsIgnoreCase(ModelType.vfModule.name ())) && action == Action.updateInstance || - (requestScope.equalsIgnoreCase(ModelType.vfModule.name ()) && action == Action.scaleOut)) || - (requestScope.equalsIgnoreCase(ModelType.service.name()) && (action.equals(Action.addRelationships) || action.equals(Action.removeRelationships)))){ - logger.debug("related instance exception"); - throw new ValidationException ("related instances"); + if (instanceList == null && requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) + && action == Action.createInstance) { + throw new ValidationException("relatedInstanceList", true); } - if(instanceList == null && requestScope.equalsIgnoreCase(ModelType.instanceGroup.toString()) && action == Action.createInstance){ - throw new ValidationException("relatedInstanceList", true); - } - info.setVfModuleModelName(vfModuleModelName); - info.setServiceInstanceType(serviceInstanceType); - info.setVnfType(vnfType); - info.setAsdcServiceModelVersion(asdcServiceModelVersion); - info.setVfModuleType(vfModuleType); - return info; - } + info.setVfModuleModelName(vfModuleModelName); + info.setServiceInstanceType(serviceInstanceType); + info.setVnfType(vnfType); + info.setAsdcServiceModelVersion(asdcServiceModelVersion); + info.setVfModuleType(vfModuleType); + return info; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java index bdc9649ecc..483c9db81b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestInfoValidation.java @@ -28,40 +28,44 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestInfo; -public class RequestInfoValidation implements ValidationRule{ +public class RequestInfoValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); - int reqVersion = info.getReqVersion(); - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - Boolean aLaCarteFlag = info.getALaCarteFlag(); - - //required for all operations in V4 - if(empty(requestInfo.getRequestorId()) && reqVersion >= 4) { - throw new ValidationException ("requestorId"); + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + int reqVersion = info.getReqVersion(); + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + Boolean aLaCarteFlag = info.getALaCarteFlag(); + + // required for all operations in V4 + if (empty(requestInfo.getRequestorId()) && reqVersion >= 4) { + throw new ValidationException("requestorId"); } - if (empty (requestInfo.getSource ())) { - throw new ValidationException ("source"); + if (empty(requestInfo.getSource())) { + throw new ValidationException("source"); } - if (!empty (requestInfo.getInstanceName ())) { - if (!requestInfo.getInstanceName ().matches (Constants.VALID_INSTANCE_NAME_FORMAT)) { - throw new ValidationException ("instanceName format"); - } + if (!empty(requestInfo.getInstanceName())) { + if (!requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) { + throw new ValidationException("instanceName format"); + } } - if (empty (requestInfo.getProductFamilyId ())) { - // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update - //Mandatory for macro request create service instance - if((requestScope.equalsIgnoreCase (ModelType.vnf.name ()) && action == Action.createInstance) || - (requestScope.equalsIgnoreCase (ModelType.network.name ()) && (action == Action.createInstance || action == Action.updateInstance)) || - (reqVersion > 3 && (aLaCarteFlag != null && !aLaCarteFlag) && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance)) { - throw new ValidationException ("productFamilyId"); - } + if (empty(requestInfo.getProductFamilyId())) { + // Mandatory for vnf Create(aLaCarte=true), Network Create(aLaCarte=true) and network update + // Mandatory for macro request create service instance + if ((requestScope.equalsIgnoreCase(ModelType.vnf.name()) && action == Action.createInstance) + || (requestScope.equalsIgnoreCase(ModelType.network.name()) + && (action == Action.createInstance || action == Action.updateInstance)) + || (reqVersion > 3 && (aLaCarteFlag != null && !aLaCarteFlag) + && requestScope.equalsIgnoreCase(ModelType.service.name()) + && action == Action.createInstance)) { + throw new ValidationException("productFamilyId"); + } } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java index 8e1a6f5d35..edf48227f1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidation.java @@ -27,99 +27,98 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.RequestParameters; -public class RequestParametersValidation implements ValidationRule{ - private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); +public class RequestParametersValidation implements ValidationRule { + private static boolean empty(String s) { + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - int reqVersion = info.getReqVersion(); - String requestScope = info.getRequestScope(); - Actions action = info.getAction(); - RequestParameters requestParameters = info.getReqParameters(); - - if (requestScope.equalsIgnoreCase(ModelType.service.name()) && (action == Action.createInstance || action == Action.assignInstance)) { - if (requestParameters == null) { - throw new ValidationException ("requestParameters"); - } - if (empty (requestParameters.getSubscriptionServiceType())) { - throw new ValidationException ("subscriptionServiceType"); - } + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + int reqVersion = info.getReqVersion(); + String requestScope = info.getRequestScope(); + Actions action = info.getAction(); + RequestParameters requestParameters = info.getReqParameters(); + + if (requestScope.equalsIgnoreCase(ModelType.service.name()) + && (action == Action.createInstance || action == Action.assignInstance)) { + if (requestParameters == null) { + throw new ValidationException("requestParameters"); + } + if (empty(requestParameters.getSubscriptionServiceType())) { + throw new ValidationException("subscriptionServiceType"); + } } - if(reqVersion >= 4){ - if(Action.addRelationships.equals(action) || Action.removeRelationships.equals(action)) { - if(requestParameters == null || requestParameters.getALaCarte() == null) { - throw new ValidationException ("aLaCarte in requestParameters"); - } - } + if (reqVersion >= 4) { + if (Action.addRelationships.equals(action) || Action.removeRelationships.equals(action)) { + if (requestParameters == null || requestParameters.getALaCarte() == null) { + throw new ValidationException("aLaCarte in requestParameters"); + } + } } - if(requestParameters == null && !requestScope.equalsIgnoreCase(ModelType.service.name())){ - info.setALaCarteFlag(true); - } - if(requestParameters != null){ - if(requestScope.equalsIgnoreCase(ModelType.vnf.name())){ - if(action == Action.updateInstance){ - if(requestParameters.isUsePreload() == null){ - requestParameters.setUsePreload(true); - } - } - if(action == Action.replaceInstance){ - if(requestParameters.getRebuildVolumeGroups() == null){ - requestParameters.setRebuildVolumeGroups(false); - } - } - } - if(requestScope.equalsIgnoreCase(ModelType.vfModule.name())){ - if(action == Action.createInstance || action == Action.updateInstance){ - if(requestParameters.isUsePreload() == null){ - if(reqVersion >= 4){ - if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == true) { - requestParameters.setUsePreload(true); - } - else { - requestParameters.setUsePreload(false); - } - } - else { - requestParameters.setUsePreload(true); - } - } - } - } - if(requestScope.equalsIgnoreCase(ModelType.service.name())){ - if(action == Action.createInstance){ - if(requestParameters.isUsePreload() == null){ - if(reqVersion >= 4){ - if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == false) { - requestParameters.setUsePreload(false); - } - else { - requestParameters.setUsePreload(true); - } - } - else { - requestParameters.setUsePreload(true); - } - } - } - } - if(reqVersion >= 4){ - if(requestParameters.getALaCarte() != null){ - info.setALaCarteFlag(requestParameters.getALaCarte()); - }else if(requestScope.equalsIgnoreCase(ModelType.service.name())){ - if(action == Action.createInstance || action == Action.deleteInstance || action == Action.activateInstance || action == Action.deactivateInstance){ - if(requestParameters.getALaCarte() == null){ - requestParameters.setaLaCarte(false); - info.setALaCarteFlag(requestParameters.getALaCarte()); - } - } - }else{ - info.setALaCarteFlag(true); - } - }else{ - info.setALaCarteFlag(true); - } + if (requestParameters == null && !requestScope.equalsIgnoreCase(ModelType.service.name())) { + info.setALaCarteFlag(true); } - return info; - } -}
\ No newline at end of file + if (requestParameters != null) { + if (requestScope.equalsIgnoreCase(ModelType.vnf.name())) { + if (action == Action.updateInstance) { + if (requestParameters.isUsePreload() == null) { + requestParameters.setUsePreload(true); + } + } + if (action == Action.replaceInstance) { + if (requestParameters.getRebuildVolumeGroups() == null) { + requestParameters.setRebuildVolumeGroups(false); + } + } + } + if (requestScope.equalsIgnoreCase(ModelType.vfModule.name())) { + if (action == Action.createInstance || action == Action.updateInstance) { + if (requestParameters.isUsePreload() == null) { + if (reqVersion >= 4) { + if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == true) { + requestParameters.setUsePreload(true); + } else { + requestParameters.setUsePreload(false); + } + } else { + requestParameters.setUsePreload(true); + } + } + } + } + if (requestScope.equalsIgnoreCase(ModelType.service.name())) { + if (action == Action.createInstance) { + if (requestParameters.isUsePreload() == null) { + if (reqVersion >= 4) { + if (requestParameters.getALaCarte() == null || requestParameters.getALaCarte() == false) { + requestParameters.setUsePreload(false); + } else { + requestParameters.setUsePreload(true); + } + } else { + requestParameters.setUsePreload(true); + } + } + } + } + if (reqVersion >= 4) { + if (requestParameters.getALaCarte() != null) { + info.setALaCarteFlag(requestParameters.getALaCarte()); + } else if (requestScope.equalsIgnoreCase(ModelType.service.name())) { + if (action == Action.createInstance || action == Action.deleteInstance + || action == Action.activateInstance || action == Action.deactivateInstance) { + if (requestParameters.getALaCarte() == null) { + requestParameters.setaLaCarte(false); + info.setALaCarteFlag(requestParameters.getALaCarte()); + } + } + } else { + info.setALaCarteFlag(true); + } + } else { + info.setALaCarteFlag(true); + } + } + return info; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java index 51a9afe200..635a715558 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/RequestScopeValidation.java @@ -25,25 +25,25 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ModelInfo; import org.onap.so.serviceinstancebeans.RequestInfo; -public class RequestScopeValidation implements ValidationRule{ - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); - RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); - String requestScope; - +public class RequestScopeValidation implements ValidationRule { + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + ModelInfo modelInfo = info.getSir().getRequestDetails().getModelInfo(); + RequestInfo requestInfo = info.getSir().getRequestDetails().getRequestInfo(); + String requestScope; + if (modelInfo == null) { - throw new ValidationException ("model-info"); + throw new ValidationException("model-info"); + } + if (requestInfo == null) { + throw new ValidationException("requestInfo"); } - if (requestInfo == null) { - throw new ValidationException ("requestInfo"); - } - info.setRequestInfo(requestInfo); - if (modelInfo.getModelType () == null) { - throw new ValidationException ("modelType"); + info.setRequestInfo(requestInfo); + if (modelInfo.getModelType() == null) { + throw new ValidationException("modelType"); } requestScope = info.getSir().getRequestDetails().getModelInfo().getModelType().name(); info.setRequestScope(requestScope); return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java index d9298f5f4e..4f68ef319c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/SubscriberInfoValidation.java @@ -27,25 +27,27 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ModelType; import org.onap.so.serviceinstancebeans.SubscriberInfo; -public class SubscriberInfoValidation implements ValidationRule{ +public class SubscriberInfoValidation implements ValidationRule { private static boolean empty(String s) { - return (s == null || s.trim().isEmpty()); + return (s == null || s.trim().isEmpty()); } - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - String requestScope = info.getRequestScope(); - int reqVersion = info.getReqVersion(); - Actions action = info.getAction(); - - if (reqVersion > 4 && requestScope.equalsIgnoreCase (ModelType.service.name ()) && action == Action.createInstance || action == Action.assignInstance) { - SubscriberInfo subscriberInfo = info.getSir().getRequestDetails ().getSubscriberInfo(); - if (subscriberInfo == null) { - throw new ValidationException ("subscriberInfo"); - } - if (empty (subscriberInfo.getGlobalSubscriberId ())) { - throw new ValidationException ("globalSubscriberId"); - } + + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + String requestScope = info.getRequestScope(); + int reqVersion = info.getReqVersion(); + Actions action = info.getAction(); + + if (reqVersion > 4 && requestScope.equalsIgnoreCase(ModelType.service.name()) && action == Action.createInstance + || action == Action.assignInstance) { + SubscriberInfo subscriberInfo = info.getSir().getRequestDetails().getSubscriberInfo(); + if (subscriberInfo == null) { + throw new ValidationException("subscriberInfo"); + } + if (empty(subscriberInfo.getGlobalSubscriberId())) { + throw new ValidationException("globalSubscriberId"); + } } return info; - } -}
\ No newline at end of file + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java index 894e488e92..067e8611d0 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/UserParamsValidation.java @@ -23,7 +23,6 @@ package org.onap.so.apihandlerinfra.validation; import java.util.ArrayList; import java.util.List; - import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.Actions; import org.onap.so.exceptions.ValidationException; @@ -33,103 +32,107 @@ import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.VfModules; import org.onap.so.serviceinstancebeans.Vnfs; -public class UserParamsValidation implements ValidationRule{ - @Override - public ValidationInformation validate(ValidationInformation info) throws ValidationException{ - Service validate = info.getUserParams(); - Actions action = info.getAction(); - - if(validate.getModelInfo() == null){ - throw new ValidationException ("modelInfo in userParams", true); - }else if(validate.getModelInfo().getModelType() == null){ - throw new ValidationException("modelType in userParams service modelInfo", true); - }else if(validate.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams service modelInfo", true); - } - modelInfoValidation(info.getSir().getRequestDetails().getModelInfo(), validate.getModelInfo()); - if(validate.getInstanceName() != null && info.getRequestInfo().getInstanceName() != null){ - instanceNameValidation(info, validate); - } - for(Vnfs vnf : validate.getResources().getVnfs()){ - if(vnf.getModelInfo() == null){ - throw new ValidationException ("modelInfo in userParams vnf resources", true); - }else if(vnf.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams vnf resources", true); - }else if(vnf.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams vnf resources", true); - } - if(vnf.getCloudConfiguration() == null){ - throw new ValidationException ("cloudConfiguration in userParams vnf resources", true); - } - if(action == Action.createInstance || action == Action.assignInstance){ - if(vnf.getPlatform() == null){ - throw new ValidationException ("platform in userParams vnf resources", true); - }if(vnf.getProductFamilyId() == null){ - throw new ValidationException ("productFamilyId in userParams vnf resources", true); - } - } - if (vnf.getPlatform() != null && vnf.getPlatform().getPlatformName() == null){ - throw new ValidationException ("platformName in userParams vnf resources", true); - } - if(vnf.getVfModules().isEmpty()){ - throw new ValidationException ("vfModules in userParams vnf resources", true); - } - for(VfModules vfModules : vnf.getVfModules()){ - if(vfModules.getModelInfo() == null){ - throw new ValidationException ("modelInfo in userParams vfModules resources", true); - }else if(vfModules.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams vfModule resources", true); - }else if(vfModules.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams vfModule resources", true); - } - } - } - - List<Networks> validateNetworks = new ArrayList<>(); - validateNetworks = validate.getResources().getNetworks(); - if(validateNetworks != null){ - for(Networks networks : validateNetworks){ - if(networks.getModelInfo() == null){ - throw new ValidationException ("modelInfo in userParams network resources", true); - }else if(networks.getModelInfo().getModelCustomizationId() == null){ - throw new ValidationException ("modelCustomizationId in userParams network resources", true); - }else if(networks.getModelInfo().getModelVersionId() == null){ - throw new ValidationException("modelVersionId in userParams network resources", true); - } - if(networks.getCloudConfiguration() == null){ - throw new ValidationException ("cloudConfiguration in userParams network resources", true); - } - } - } - return info; - } - public void instanceNameValidation(ValidationInformation info, Service validate) throws ValidationException{ - if(!info.getRequestInfo().getInstanceName().equals(validate.getInstanceName())){ - throw new ValidationException("instanceName in requestInfo", "instanceName in userParams service"); - } - } - public void modelInfoValidation(ModelInfo info, ModelInfo userParamInfo) throws ValidationException{ - if(!info.getModelType().equals(userParamInfo.getModelType())){ - throw new ValidationException("modelType in modelInfo", "modelType in userParams service"); - } - if((info.getModelInvariantId() != null && userParamInfo.getModelInvariantId() != null) && - (!info.getModelInvariantId().equals(userParamInfo.getModelInvariantId()))){ - throw new ValidationException("modelInvariantId in modelInfo", "modelInvariantId in userParams service"); - } - if(!info.getModelVersionId().equals(userParamInfo.getModelVersionId())){ - throw new ValidationException("modelVersionId in modelInfo", "modelVersionId in userParams service"); - } - if((info.getModelName() != null && userParamInfo.getModelName() != null) && - (!info.getModelName().equals(userParamInfo.getModelName()))){ - throw new ValidationException("modelName in modelInfo", "modelName in userParams service"); - } - if((info.getModelVersion() != null && userParamInfo.getModelVersion() != null) && - (!info.getModelVersion().equals(userParamInfo.getModelVersion()))){ - throw new ValidationException("modelVersion in modelInfo", "modelVersion in userParams service"); - } - if((info.getModelCustomizationId() != null && userParamInfo.getModelCustomizationId() != null) && - (!info.getModelCustomizationId().equals(userParamInfo.getModelCustomizationId()))){ - throw new ValidationException("modelCustomizationId in modelInfo", "modelCustomizationId in userParams service"); - } - } -}
\ No newline at end of file +public class UserParamsValidation implements ValidationRule { + @Override + public ValidationInformation validate(ValidationInformation info) throws ValidationException { + Service validate = info.getUserParams(); + Actions action = info.getAction(); + + if (validate.getModelInfo() == null) { + throw new ValidationException("modelInfo in userParams", true); + } else if (validate.getModelInfo().getModelType() == null) { + throw new ValidationException("modelType in userParams service modelInfo", true); + } else if (validate.getModelInfo().getModelVersionId() == null) { + throw new ValidationException("modelVersionId in userParams service modelInfo", true); + } + modelInfoValidation(info.getSir().getRequestDetails().getModelInfo(), validate.getModelInfo()); + if (validate.getInstanceName() != null && info.getRequestInfo().getInstanceName() != null) { + instanceNameValidation(info, validate); + } + for (Vnfs vnf : validate.getResources().getVnfs()) { + if (vnf.getModelInfo() == null) { + throw new ValidationException("modelInfo in userParams vnf resources", true); + } else if (vnf.getModelInfo().getModelCustomizationId() == null) { + throw new ValidationException("modelCustomizationId in userParams vnf resources", true); + } else if (vnf.getModelInfo().getModelVersionId() == null) { + throw new ValidationException("modelVersionId in userParams vnf resources", true); + } + if (vnf.getCloudConfiguration() == null) { + throw new ValidationException("cloudConfiguration in userParams vnf resources", true); + } + if (action == Action.createInstance || action == Action.assignInstance) { + if (vnf.getPlatform() == null) { + throw new ValidationException("platform in userParams vnf resources", true); + } + if (vnf.getProductFamilyId() == null) { + throw new ValidationException("productFamilyId in userParams vnf resources", true); + } + } + if (vnf.getPlatform() != null && vnf.getPlatform().getPlatformName() == null) { + throw new ValidationException("platformName in userParams vnf resources", true); + } + if (vnf.getVfModules().isEmpty()) { + throw new ValidationException("vfModules in userParams vnf resources", true); + } + for (VfModules vfModules : vnf.getVfModules()) { + if (vfModules.getModelInfo() == null) { + throw new ValidationException("modelInfo in userParams vfModules resources", true); + } else if (vfModules.getModelInfo().getModelCustomizationId() == null) { + throw new ValidationException("modelCustomizationId in userParams vfModule resources", true); + } else if (vfModules.getModelInfo().getModelVersionId() == null) { + throw new ValidationException("modelVersionId in userParams vfModule resources", true); + } + } + } + + List<Networks> validateNetworks = new ArrayList<>(); + validateNetworks = validate.getResources().getNetworks(); + if (validateNetworks != null) { + for (Networks networks : validateNetworks) { + if (networks.getModelInfo() == null) { + throw new ValidationException("modelInfo in userParams network resources", true); + } else if (networks.getModelInfo().getModelCustomizationId() == null) { + throw new ValidationException("modelCustomizationId in userParams network resources", true); + } else if (networks.getModelInfo().getModelVersionId() == null) { + throw new ValidationException("modelVersionId in userParams network resources", true); + } + if (networks.getCloudConfiguration() == null) { + throw new ValidationException("cloudConfiguration in userParams network resources", true); + } + } + } + return info; + } + + public void instanceNameValidation(ValidationInformation info, Service validate) throws ValidationException { + if (!info.getRequestInfo().getInstanceName().equals(validate.getInstanceName())) { + throw new ValidationException("instanceName in requestInfo", "instanceName in userParams service"); + } + } + + public void modelInfoValidation(ModelInfo info, ModelInfo userParamInfo) throws ValidationException { + if (!info.getModelType().equals(userParamInfo.getModelType())) { + throw new ValidationException("modelType in modelInfo", "modelType in userParams service"); + } + if ((info.getModelInvariantId() != null && userParamInfo.getModelInvariantId() != null) + && (!info.getModelInvariantId().equals(userParamInfo.getModelInvariantId()))) { + throw new ValidationException("modelInvariantId in modelInfo", "modelInvariantId in userParams service"); + } + if (!info.getModelVersionId().equals(userParamInfo.getModelVersionId())) { + throw new ValidationException("modelVersionId in modelInfo", "modelVersionId in userParams service"); + } + if ((info.getModelName() != null && userParamInfo.getModelName() != null) + && (!info.getModelName().equals(userParamInfo.getModelName()))) { + throw new ValidationException("modelName in modelInfo", "modelName in userParams service"); + } + if ((info.getModelVersion() != null && userParamInfo.getModelVersion() != null) + && (!info.getModelVersion().equals(userParamInfo.getModelVersion()))) { + throw new ValidationException("modelVersion in modelInfo", "modelVersion in userParams service"); + } + if ((info.getModelCustomizationId() != null && userParamInfo.getModelCustomizationId() != null) + && (!info.getModelCustomizationId().equals(userParamInfo.getModelCustomizationId()))) { + throw new ValidationException("modelCustomizationId in modelInfo", + "modelCustomizationId in userParams service"); + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java index 7fc9567123..68b2a78a85 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationInformation.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.validation; import java.util.HashMap; - import org.onap.so.apihandlerinfra.Actions; import org.onap.so.serviceinstancebeans.LineOfBusiness; import org.onap.so.serviceinstancebeans.OwningEntity; @@ -33,148 +32,186 @@ import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; -public class ValidationInformation{ - ServiceInstancesRequest sir; - HashMap<String,String> instanceIdMap; - Actions action; - int reqVersion; - String requestScope; - Boolean aLaCarteFlag; - RequestParameters requestParameters; - RequestInfo requestInfo; - String serviceInstanceType; - String vfModuleModelName; - String vnfType; - String asdcServiceModelVersion; - String vfModuleType; - String networkType; - Platform platform; - LineOfBusiness lob; - Project project; - OwningEntity owningEntity; - Service userParams; - - public ValidationInformation(ServiceInstancesRequest sir, HashMap<String,String> instanceIdMap, - Actions action, int reqVersion, Boolean aLaCarteFlag, RequestParameters requestParameters){ - this.sir = sir; - this.instanceIdMap = instanceIdMap; - this.action = action; - this.reqVersion = reqVersion; - this.aLaCarteFlag = aLaCarteFlag; - this.requestParameters = requestParameters; - } - public ServiceInstancesRequest getSir(){ - return this.sir; - } - public void setSir(ServiceInstancesRequest value){ - this.sir = value; - } - public HashMap<String, String> getInstanceIdMap(){ - return this.instanceIdMap; - } - public void setInstanceIdMap(HashMap<String, String> value){ - this.instanceIdMap = value; - } - public Actions getAction(){ - return this.action; - } - public void setAction(Actions value){ - this.action = value; - } - public RequestInfo getRequestInfo(){ - return this.requestInfo; - } - public void setRequestInfo(RequestInfo value){ - this.requestInfo = value; - } - public int getReqVersion(){ - return this.reqVersion; - } - public void setReqVersion(int value){ - this.reqVersion = value; - } - public String getRequestScope(){ - return this.requestScope; - } - public void setRequestScope(String value){ - this.requestScope = value; - } - public Boolean getALaCarteFlag(){ - return this.aLaCarteFlag; - } - public void setALaCarteFlag(Boolean value){ - this.aLaCarteFlag = value; - } - public RequestParameters getReqParameters(){ - return this.requestParameters; - } - public void setReqParameters(RequestParameters value){ - this.requestParameters = value; - } - public String getServiceInstanceType(){ - return this.serviceInstanceType; - } - public void setServiceInstanceType(String value){ - this.serviceInstanceType = value; - } - public String getVfModuleModelName(){ - return this.vfModuleModelName; - } - public void setVfModuleModelName(String value){ - this.vfModuleModelName = value; - } - public String getVnfType(){ - return this.vnfType; - } - public void setVnfType(String value){ - this.vnfType = value; - } - public String getAsdcServiceModelVersion(){ - return this.asdcServiceModelVersion; - } - public void setAsdcServiceModelVersion(String value){ - this.asdcServiceModelVersion = value; - } - public String getVfModuleType(){ - return this.vfModuleType; - } - public void setVfModuleType(String value){ - this.vfModuleType = value; - } - public String getNetworkType(){ - return this.networkType; - } - public void setNetworkType(String value){ - this.networkType = value; - } - public Platform getPlatform(){ - return this.platform; - } - public void setPlatform(Platform value){ - this.platform = value; - } - public LineOfBusiness getLOB(){ - return this.lob; - } - public void setLOB(LineOfBusiness value){ - this.lob = value; - } - public Project getProject(){ - return this.project; - } - public void setProject(Project value){ - this.project = value; - } - public OwningEntity getOE(){ - return this.owningEntity; - } - public void setOE(OwningEntity value){ - this.owningEntity = value; - } - public Service getUserParams(){ - return this.userParams; - } - public void setUserParams(Service value){ - this.userParams = value; - } -}
\ No newline at end of file +public class ValidationInformation { + ServiceInstancesRequest sir; + HashMap<String, String> instanceIdMap; + Actions action; + int reqVersion; + String requestScope; + Boolean aLaCarteFlag; + RequestParameters requestParameters; + RequestInfo requestInfo; + String serviceInstanceType; + String vfModuleModelName; + String vnfType; + String asdcServiceModelVersion; + String vfModuleType; + String networkType; + Platform platform; + LineOfBusiness lob; + Project project; + OwningEntity owningEntity; + Service userParams; + + public ValidationInformation(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Actions action, + int reqVersion, Boolean aLaCarteFlag, RequestParameters requestParameters) { + this.sir = sir; + this.instanceIdMap = instanceIdMap; + this.action = action; + this.reqVersion = reqVersion; + this.aLaCarteFlag = aLaCarteFlag; + this.requestParameters = requestParameters; + } + + public ServiceInstancesRequest getSir() { + return this.sir; + } + + public void setSir(ServiceInstancesRequest value) { + this.sir = value; + } + + public HashMap<String, String> getInstanceIdMap() { + return this.instanceIdMap; + } + + public void setInstanceIdMap(HashMap<String, String> value) { + this.instanceIdMap = value; + } + + public Actions getAction() { + return this.action; + } + + public void setAction(Actions value) { + this.action = value; + } + + public RequestInfo getRequestInfo() { + return this.requestInfo; + } + + public void setRequestInfo(RequestInfo value) { + this.requestInfo = value; + } + + public int getReqVersion() { + return this.reqVersion; + } + + public void setReqVersion(int value) { + this.reqVersion = value; + } + + public String getRequestScope() { + return this.requestScope; + } + + public void setRequestScope(String value) { + this.requestScope = value; + } + + public Boolean getALaCarteFlag() { + return this.aLaCarteFlag; + } + + public void setALaCarteFlag(Boolean value) { + this.aLaCarteFlag = value; + } + + public RequestParameters getReqParameters() { + return this.requestParameters; + } + + public void setReqParameters(RequestParameters value) { + this.requestParameters = value; + } + + public String getServiceInstanceType() { + return this.serviceInstanceType; + } + + public void setServiceInstanceType(String value) { + this.serviceInstanceType = value; + } + + public String getVfModuleModelName() { + return this.vfModuleModelName; + } + + public void setVfModuleModelName(String value) { + this.vfModuleModelName = value; + } + + public String getVnfType() { + return this.vnfType; + } + + public void setVnfType(String value) { + this.vnfType = value; + } + + public String getAsdcServiceModelVersion() { + return this.asdcServiceModelVersion; + } + + public void setAsdcServiceModelVersion(String value) { + this.asdcServiceModelVersion = value; + } + + public String getVfModuleType() { + return this.vfModuleType; + } + + public void setVfModuleType(String value) { + this.vfModuleType = value; + } + + public String getNetworkType() { + return this.networkType; + } + + public void setNetworkType(String value) { + this.networkType = value; + } + + public Platform getPlatform() { + return this.platform; + } + + public void setPlatform(Platform value) { + this.platform = value; + } + + public LineOfBusiness getLOB() { + return this.lob; + } + + public void setLOB(LineOfBusiness value) { + this.lob = value; + } + + public Project getProject() { + return this.project; + } + + public void setProject(Project value) { + this.project = value; + } + + public OwningEntity getOE() { + return this.owningEntity; + } + + public void setOE(OwningEntity value) { + this.owningEntity = value; + } + + public Service getUserParams() { + return this.userParams; + } + + public void setUserParams(Service value) { + this.userParams = value; + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java index a5d85f6533..e8073bd1d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/validation/ValidationRule.java @@ -23,6 +23,6 @@ package org.onap.so.apihandlerinfra.validation; import org.onap.so.exceptions.ValidationException; -public interface ValidationRule{ - ValidationInformation validate(ValidationInformation info)throws ValidationException; -}
\ No newline at end of file +public interface ValidationRule { + ValidationInformation validate(ValidationInformation info) throws ValidationException; +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java index 15fe0a5be3..796db8c32a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ActionType.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -34,10 +34,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for action-type. + * <p> + * Java class for action-type. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="action-type"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -59,15 +62,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum ActionType { - CREATE, - SETSTATUS, - REPLACE, - UPDATE, - DELETE, - CREATE_VF_MODULE, - UPDATE_VF_MODULE, - DELETE_VF_MODULE, - NOT_PROVIDED; + CREATE, SETSTATUS, REPLACE, UPDATE, DELETE, CREATE_VF_MODULE, UPDATE_VF_MODULE, DELETE_VF_MODULE, NOT_PROVIDED; public String value() { return name(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java index 3f708c49d5..e24ecd4eac 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ModelType.java @@ -22,11 +22,7 @@ package org.onap.so.apihandlerinfra.vnfbeans; /* * Enum for Status values returned by API Handler to Tail-F -*/ + */ public enum ModelType { - service, - vnf, - vfModule, - volumeGroup, - network + service, vnf, vfModule, volumeGroup, network } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java index 72be61105b..2236b09f2a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/ObjectFactory.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -36,31 +36,28 @@ import javax.xml.namespace.QName; /** - * This object contains factory methods for each - * Java content interface and Java element interface - * generated in the org.onap.so.apihandlerinfra.vnfbeans1 package. - * <p>An ObjectFactory allows you to programatically - * construct new instances of the Java representation - * for XML content. The Java representation of XML - * content can consist of schema derived interfaces - * and classes representing the binding of schema - * type definitions, element declarations and model - * groups. Factory methods for each of these are - * provided in this class. + * This object contains factory methods for each Java content interface and Java element interface generated in the + * org.onap.so.apihandlerinfra.vnfbeans1 package. + * <p> + * An ObjectFactory allows you to programatically construct new instances of the Java representation for XML content. + * The Java representation of XML content can consist of schema derived interfaces and classes representing the binding + * of schema type definitions, element declarations and model groups. Factory methods for each of these are provided in + * this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _VnfParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "vnf-params"); - private final static QName _NetworkParams_QNAME = new QName("http://org.onap/so/infra/vnf-request/v1", "network-params"); + private final static QName _NetworkParams_QNAME = + new QName("http://org.onap/so/infra/vnf-request/v1", "network-params"); /** - * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.onap.so.apihandlerinfra.vnfbeans1 + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: + * org.onap.so.apihandlerinfra.vnfbeans1 * */ - public ObjectFactory() { - } + public ObjectFactory() {} /** * Create an instance of {@link VnfInputs } @@ -102,7 +99,7 @@ public class ObjectFactory { return new VnfRequest(); } - + /** * Create an instance of {@link VnfTypes } * @@ -118,7 +115,7 @@ public class ObjectFactory { public VnfRequests createVnfRequests() { return new VnfRequests(); } - + /** * Create an instance of {@link VfModuleModelName } * @@ -126,7 +123,7 @@ public class ObjectFactory { public VfModuleModelName createVfModuleModelName() { return new VfModuleModelName(); } - + /** * Create an instance of {@link VfModuleModelNames } * @@ -135,9 +132,8 @@ public class ObjectFactory { return new VfModuleModelNames(); } - - - + + /** * Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}} * diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java index dc8457c6a4..2af0a02d17 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestInfo.java @@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -63,16 +65,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestId", - "action", - "requestStatus", - "statusMessage", - "progress", - "startTime", - "endTime", - "source" -}) +@XmlType(name = "", propOrder = {"requestId", "action", "requestStatus", "statusMessage", "progress", "startTime", + "endTime", "source"}) @XmlRootElement(name = "request-info") public class RequestInfo { @@ -94,9 +88,7 @@ public class RequestInfo { /** * Gets the value of the requestId property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getRequestId() { @@ -106,9 +98,7 @@ public class RequestInfo { /** * Sets the value of the requestId property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setRequestId(String value) { @@ -118,9 +108,7 @@ public class RequestInfo { /** * Gets the value of the action property. * - * @return - * possible object is - * {@link ActionType } + * @return possible object is {@link ActionType } * */ public ActionType getAction() { @@ -130,9 +118,7 @@ public class RequestInfo { /** * Sets the value of the action property. * - * @param value - * allowed object is - * {@link ActionType } + * @param value allowed object is {@link ActionType } * */ public void setAction(ActionType value) { @@ -142,9 +128,7 @@ public class RequestInfo { /** * Gets the value of the requestStatus property. * - * @return - * possible object is - * {@link RequestStatusType } + * @return possible object is {@link RequestStatusType } * */ public RequestStatusType getRequestStatus() { @@ -154,9 +138,7 @@ public class RequestInfo { /** * Sets the value of the requestStatus property. * - * @param value - * allowed object is - * {@link RequestStatusType } + * @param value allowed object is {@link RequestStatusType } * */ public void setRequestStatus(RequestStatusType value) { @@ -166,9 +148,7 @@ public class RequestInfo { /** * Gets the value of the statusMessage property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getStatusMessage() { @@ -178,9 +158,7 @@ public class RequestInfo { /** * Sets the value of the statusMessage property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setStatusMessage(String value) { @@ -190,9 +168,7 @@ public class RequestInfo { /** * Gets the value of the progress property. * - * @return - * possible object is - * {@link Integer } + * @return possible object is {@link Integer } * */ public String getProgress() { @@ -202,9 +178,7 @@ public class RequestInfo { /** * Sets the value of the progress property. * - * @param value - * allowed object is - * {@link Integer } + * @param value allowed object is {@link Integer } * */ public void setProgress(String value) { @@ -214,9 +188,7 @@ public class RequestInfo { /** * Gets the value of the startTime property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getStartTime() { @@ -226,9 +198,7 @@ public class RequestInfo { /** * Sets the value of the startTime property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setStartTime(String value) { @@ -238,9 +208,7 @@ public class RequestInfo { /** * Gets the value of the endTime property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getEndTime() { @@ -250,9 +218,7 @@ public class RequestInfo { /** * Sets the value of the endTime property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setEndTime(String value) { @@ -262,9 +228,7 @@ public class RequestInfo { /** * Gets the value of the source property. * - * @return - * possible object is - * {@link String } + * @return possible object is {@link String } * */ public String getSource() { @@ -274,9 +238,7 @@ public class RequestInfo { /** * Sets the value of the source property. * - * @param value - * allowed object is - * {@link String } + * @param value allowed object is {@link String } * */ public void setSource(String value) { diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java index 8c98b9f801..d7250c6ebf 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/RequestStatusType.java @@ -34,10 +34,13 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for request-status-type. + * <p> + * Java class for request-status-type. * - * <p>The following schema fragment specifies the expected content contained within this class. * <p> + * The following schema fragment specifies the expected content contained within this class. + * <p> + * * <pre> * <simpleType name="request-status-type"> * <restriction base="{http://www.w3.org/2001/XMLSchema}string"> @@ -53,12 +56,7 @@ import javax.xml.bind.annotation.XmlType; @XmlEnum public enum RequestStatusType { - COMPLETE, - FAILED, - IN_PROGRESS, - PENDING, - TIMEOUT, - UNLOCKED; + COMPLETE, FAILED, IN_PROGRESS, PENDING, TIMEOUT, UNLOCKED; public String value() { return name(); diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java index 74065482f8..1bf99b1362 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelName.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -38,9 +38,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -63,40 +65,31 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "modelName", - "modelVersion", - "modelInvariantUuid", - "isBase", - "id", - "description", - "asdcServiceModelVersion" -}) +@XmlType(name = "", propOrder = {"modelName", "modelVersion", "modelInvariantUuid", "isBase", "id", "description", + "asdcServiceModelVersion"}) @XmlRootElement(name = "vf-module-model-name") public class VfModuleModelName { - @XmlElement(name="model-name", required = true) + @XmlElement(name = "model-name", required = true) protected String modelName; - @XmlElement(name="model-version", required = true) + @XmlElement(name = "model-version", required = true) protected String modelVersion; - @XmlElement(name="model-invariant-uuid", required = true) + @XmlElement(name = "model-invariant-uuid", required = true) protected String modelInvariantUuid; - @XmlElement(name="is-base", required = true) + @XmlElement(name = "is-base", required = true) protected Boolean isBase; - @XmlElement(name="id", required = true) + @XmlElement(name = "id", required = true) protected String id; - @XmlElement(name="description", required = true) + @XmlElement(name = "description", required = true) protected String description; - @XmlElement(name="asdc-service-model-version", required = true) + @XmlElement(name = "asdc-service-model-version", required = true) protected String asdcServiceModelVersion; /** * Gets the value of the modelName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getModelName() { return modelName; @@ -105,22 +98,18 @@ public class VfModuleModelName { /** * Sets the value of the modelName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setModelName(String value) { this.modelName = value; } - + /** * Gets the value of the modelVersion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getModelVersion() { return modelVersion; @@ -129,22 +118,18 @@ public class VfModuleModelName { /** * Sets the value of the modelVersion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setModelVersion(String value) { this.modelVersion = value; } - + /** * Gets the value of the modelInvariantUuid property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getModelInvariantUuid() { return modelInvariantUuid; @@ -153,22 +138,18 @@ public class VfModuleModelName { /** * Sets the value of the modelInvariantUuid property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setModelInvariantUuid(String value) { this.modelInvariantUuid = value; } - + /** * Gets the value of the isBase property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean getIsBase() { return isBase; @@ -177,10 +158,8 @@ public class VfModuleModelName { /** * Sets the value of the isBase property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setIsBase(Boolean value) { this.isBase = value; @@ -189,10 +168,8 @@ public class VfModuleModelName { /** * Gets the value of the id property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getId() { return id; @@ -201,10 +178,8 @@ public class VfModuleModelName { /** * Sets the value of the id property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setId(String value) { this.id = value; @@ -213,10 +188,8 @@ public class VfModuleModelName { /** * Gets the value of the description property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getDescription() { return description; @@ -225,22 +198,18 @@ public class VfModuleModelName { /** * Sets the value of the description property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setDescription(String value) { this.description = value; } - + /** * Gets the value of the asdcServiceModelVersion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAsdcServiceModelVersion() { return asdcServiceModelVersion; @@ -249,10 +218,8 @@ public class VfModuleModelName { /** * Sets the value of the asdcServiceModelVersion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setAsdcServiceModelVersion(String value) { this.asdcServiceModelVersion = value; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java index 9904884620..2b334f262d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VfModuleModelNames.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vfModuleModelName" -}) +@XmlType(name = "", propOrder = {"vfModuleModelName"}) @XmlRootElement(name = "vf-module-model-names") public class VfModuleModelNames { @@ -72,21 +71,20 @@ public class VfModuleModelNames { * Gets the value of the vfModuleModelName property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the vnfType property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to + * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for + * the vnfType property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getVfModuleModelName().add(newItem); + * getVfModuleModelName().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link VfModuleModelName } + * Objects of the following type(s) are allowed in the list {@link VfModuleModelName } * * */ @@ -96,9 +94,9 @@ public class VfModuleModelNames { } return this.vfModuleModelName; } - + public void setVfModuleModelName(List<VfModuleModelName> vfModuleModelName) { - this.vfModuleModelName=vfModuleModelName; + this.vfModuleModelName = vfModuleModelName; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java index 8816d0d4fc..f6b539dbe5 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfInputs.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -81,32 +83,14 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfId", - "vfModuleId", - "vnfName", - "vfModuleName", - "vnfType", - "vfModuleModelName", - "asdcServiceModelVersion", - "serviceInstanceId", - "backoutOnFailure", - "serviceType", - "serviceId", - "aicNodeClli", - "aicCloudRegion", - "tenantId", - "provStatus", - "volumeGroupName", - "volumeGroupId", - // BEGIN - elements valid only on BPMN interface - "personaModelId", - "personaModelVersion", - "isBaseVfModule", - "vnfPersonaModelId", - "vnfPersonaModelVersion" - // END - elements valid only on BPMN interface -}) +@XmlType(name = "", + propOrder = {"vnfId", "vfModuleId", "vnfName", "vfModuleName", "vnfType", "vfModuleModelName", + "asdcServiceModelVersion", "serviceInstanceId", "backoutOnFailure", "serviceType", "serviceId", + "aicNodeClli", "aicCloudRegion", "tenantId", "provStatus", "volumeGroupName", "volumeGroupId", + // BEGIN - elements valid only on BPMN interface + "personaModelId", "personaModelVersion", "isBaseVfModule", "vnfPersonaModelId", "vnfPersonaModelVersion" + // END - elements valid only on BPMN interface + }) @XmlRootElement(name = "vnf-inputs") public class VnfInputs { @@ -158,10 +142,8 @@ public class VnfInputs { /** * Gets the value of the vnfId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfId() { return vnfId; @@ -170,10 +152,8 @@ public class VnfInputs { /** * Sets the value of the vnfId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfId(String value) { this.vnfId = value; @@ -182,10 +162,8 @@ public class VnfInputs { /** * Gets the value of the vnfName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfName() { return vnfName; @@ -194,10 +172,8 @@ public class VnfInputs { /** * Sets the value of the vnfName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfName(String value) { this.vnfName = value; @@ -206,10 +182,8 @@ public class VnfInputs { /** * Gets the value of the vnfType property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfType() { return vnfType; @@ -218,22 +192,18 @@ public class VnfInputs { /** * Sets the value of the vnfType property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfType(String value) { this.vnfType = value; } - + /** * Gets the value of the serviceInstanceId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getServiceInstanceId() { return serviceInstanceId; @@ -242,10 +212,8 @@ public class VnfInputs { /** * Sets the value of the serviceInstanceId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setServiceInstanceId(String value) { this.serviceInstanceId = value; @@ -254,10 +222,8 @@ public class VnfInputs { /** * Gets the value of the serviceType property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getServiceType() { return serviceType; @@ -266,22 +232,18 @@ public class VnfInputs { /** * Sets the value of the serviceType property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setServiceType(String value) { this.serviceType = value; } - + /** * Gets the value of the serviceId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getServiceId() { return serviceId; @@ -290,12 +252,10 @@ public class VnfInputs { /** * Sets the value of the serviceId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ - public void setServiceId (String value) { + public void setServiceId(String value) { this.serviceId = value; } @@ -303,10 +263,8 @@ public class VnfInputs { /** * Gets the value of the aicNodeClli property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAicNodeClli() { return aicNodeClli; @@ -315,22 +273,18 @@ public class VnfInputs { /** * Sets the value of the aicNodeClli property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setAicNodeClli(String value) { this.aicNodeClli = value; } - + /** * Gets the value of the aicCloudRegion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAicCloudRegion() { return aicCloudRegion; @@ -339,10 +293,8 @@ public class VnfInputs { /** * Sets the value of the aicCloudRegion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setAicCloudRegion(String value) { this.aicCloudRegion = value; @@ -351,10 +303,8 @@ public class VnfInputs { /** * Gets the value of the tenantId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTenantId() { return tenantId; @@ -363,10 +313,8 @@ public class VnfInputs { /** * Sets the value of the tenantId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTenantId(String value) { this.tenantId = value; @@ -375,10 +323,8 @@ public class VnfInputs { /** * Gets the value of the provStatus property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getProvStatus() { return provStatus; @@ -387,22 +333,18 @@ public class VnfInputs { /** * Sets the value of the provStatus property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setProvStatus(String value) { this.provStatus = value; } - + /** * Gets the value of the volumeGroupName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVolumeGroupName() { return volumeGroupName; @@ -411,22 +353,18 @@ public class VnfInputs { /** * Sets the value of the volumeGroupName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVolumeGroupName(String value) { this.volumeGroupName = value; } - + /** * Gets the value of the volumeGroupId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVolumeGroupId() { return volumeGroupId; @@ -435,22 +373,18 @@ public class VnfInputs { /** * Sets the value of the volumeGroupId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVolumeGroupId(String value) { this.volumeGroupId = value; } - + /** * Gets the value of the vfModuleId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVfModuleId() { return vfModuleId; @@ -459,22 +393,18 @@ public class VnfInputs { /** * Sets the value of the vfModuleId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVfModuleId(String value) { this.vfModuleId = value; } - + /** * Gets the value of the vfModuleName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVfModuleName() { return vfModuleName; @@ -483,22 +413,18 @@ public class VnfInputs { /** * Sets the value of the vfModuleName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVfModuleName(String value) { this.vfModuleName = value; } - + /** * Gets the value of the vfModuleModelName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVfModuleModelName() { return vfModuleModelName; @@ -507,22 +433,18 @@ public class VnfInputs { /** * Sets the value of the vfModuleModelName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVfModuleModelName(String value) { this.vfModuleModelName = value; } - + /** * Gets the value of the asdcServiceModelVersion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAsdcServiceModelVersion() { return asdcServiceModelVersion; @@ -531,22 +453,18 @@ public class VnfInputs { /** * Sets the value of the asdcServiceModelVersion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setAsdcServiceModelVersion(String value) { this.asdcServiceModelVersion = value; } - + /** * Gets the value of the backoutOnFailure property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean getBackoutOnFailure() { return backoutOnFailure; @@ -555,22 +473,18 @@ public class VnfInputs { /** * Sets the value of the backoutOnFailure property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setBackoutOnFailure(Boolean value) { this.backoutOnFailure = value; } - + /** * Gets the value of the personaModelId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getPersonaModelId() { return personaModelId; @@ -579,22 +493,18 @@ public class VnfInputs { /** * Sets the value of the personaModelId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setPersonaModelId(String value) { this.personaModelId = value; } - + /** * Gets the value of the personaModelVersion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getPersonaModelVersion() { return personaModelVersion; @@ -603,23 +513,19 @@ public class VnfInputs { /** * Sets the value of the personaModelVersion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setPersonaModelVersion(String value) { this.personaModelVersion = value; } - - + + /** * Gets the value of the isBaseVfModule property. * - * @return - * possible object is - * {@link Boolean } - * + * @return possible object is {@link Boolean } + * */ public Boolean getIsBaseVfModule() { return isBaseVfModule; @@ -628,22 +534,18 @@ public class VnfInputs { /** * Sets the value of the isBaseVfModule property. * - * @param value - * allowed object is - * {@link Boolean } - * + * @param value allowed object is {@link Boolean } + * */ public void setIsBaseVfModule(Boolean value) { this.isBaseVfModule = value; } - + /** * Gets the value of the vnfPersonaModelId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfPersonaModelId() { return vnfPersonaModelId; @@ -652,22 +554,18 @@ public class VnfInputs { /** * Sets the value of the vnfPersonaModelId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfPersonaModelId(String value) { this.vnfPersonaModelId = value; } - + /** * Gets the value of the vnfPersonaModelVersion property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfPersonaModelVersion() { return vnfPersonaModelVersion; @@ -676,14 +574,12 @@ public class VnfInputs { /** * Sets the value of the vnfPersonaModelVersion property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfPersonaModelVersion(String value) { this.vnfPersonaModelVersion = value; - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java index 114a3ae137..051dcce5d3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfOutputs.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -63,16 +65,8 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfId", - "vfModuleId", - "vnfName", - "vfModuleName", - "aicNodeClli", - "tenantId", - "volumeGroupName", - "volumeGroupId" -}) +@XmlType(name = "", propOrder = {"vnfId", "vfModuleId", "vnfName", "vfModuleName", "aicNodeClli", "tenantId", + "volumeGroupName", "volumeGroupId"}) @XmlRootElement(name = "vnf-outputs") public class VnfOutputs { @@ -96,10 +90,8 @@ public class VnfOutputs { /** * Gets the value of the vnfId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfId() { return vnfId; @@ -108,22 +100,18 @@ public class VnfOutputs { /** * Sets the value of the vnfId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfId(String value) { this.vnfId = value; } - + /** * Gets the value of the vfModuleId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVfModuleId() { return vfModuleId; @@ -132,10 +120,8 @@ public class VnfOutputs { /** * Sets the value of the vfModuleId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVfModuleId(String value) { this.vfModuleId = value; @@ -146,10 +132,8 @@ public class VnfOutputs { /** * Gets the value of the vnfName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVnfName() { return vnfName; @@ -158,22 +142,18 @@ public class VnfOutputs { /** * Sets the value of the vnfName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVnfName(String value) { this.vnfName = value; } - + /** * Gets the value of the vfModuleName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVfModuleName() { return vfModuleName; @@ -182,10 +162,8 @@ public class VnfOutputs { /** * Sets the value of the vfModuleName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVfModuleName(String value) { this.vfModuleName = value; @@ -195,10 +173,8 @@ public class VnfOutputs { /** * Gets the value of the aicNodeClli property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getAicNodeClli() { return aicNodeClli; @@ -207,10 +183,8 @@ public class VnfOutputs { /** * Sets the value of the aicNodeClli property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setAicNodeClli(String value) { this.aicNodeClli = value; @@ -219,10 +193,8 @@ public class VnfOutputs { /** * Gets the value of the tenantId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getTenantId() { return tenantId; @@ -231,22 +203,18 @@ public class VnfOutputs { /** * Sets the value of the tenantId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setTenantId(String value) { this.tenantId = value; } - + /** * Gets the value of the volumeGroupName property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVolumeGroupName() { return volumeGroupName; @@ -255,22 +223,18 @@ public class VnfOutputs { /** * Sets the value of the volumeGroupName property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVolumeGroupName(String value) { this.volumeGroupName = value; } - + /** * Gets the value of the volumeGroupId property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getVolumeGroupId() { return volumeGroupId; @@ -279,10 +243,8 @@ public class VnfOutputs { /** * Sets the value of the volumeGroupId property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setVolumeGroupId(String value) { this.volumeGroupId = value; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java index 07b186e149..9007f7c97b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequest.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -61,12 +63,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "requestInfo", - "vnfInputs", - "vnfParams", - "vnfOutputs" -}) +@XmlType(name = "", propOrder = {"requestInfo", "vnfInputs", "vnfParams", "vnfOutputs"}) @XmlRootElement(name = "vnf-request") public class VnfRequest { @@ -78,15 +75,13 @@ public class VnfRequest { protected Object vnfParams; @XmlElement(name = "vnf-outputs") protected VnfOutputs vnfOutputs; - + /** * Gets the value of the requestInfo property. * - * @return - * possible object is - * {@link RequestInfo } - * + * @return possible object is {@link RequestInfo } + * */ public RequestInfo getRequestInfo() { return requestInfo; @@ -95,10 +90,8 @@ public class VnfRequest { /** * Sets the value of the requestInfo property. * - * @param value - * allowed object is - * {@link RequestInfo } - * + * @param value allowed object is {@link RequestInfo } + * */ public void setRequestInfo(RequestInfo value) { this.requestInfo = value; @@ -107,10 +100,8 @@ public class VnfRequest { /** * Gets the value of the vnfInputs property. * - * @return - * possible object is - * {@link VnfInputs } - * + * @return possible object is {@link VnfInputs } + * */ public VnfInputs getVnfInputs() { return vnfInputs; @@ -119,10 +110,8 @@ public class VnfRequest { /** * Sets the value of the vnfInputs property. * - * @param value - * allowed object is - * {@link VnfInputs } - * + * @param value allowed object is {@link VnfInputs } + * */ public void setVnfInputs(VnfInputs value) { this.vnfInputs = value; @@ -131,10 +120,8 @@ public class VnfRequest { /** * Gets the value of the vnfParams property. * - * @return - * possible object is - * {@link Object } - * + * @return possible object is {@link Object } + * */ public Object getVnfParams() { return vnfParams; @@ -143,10 +130,8 @@ public class VnfRequest { /** * Sets the value of the vnfParams property. * - * @param value - * allowed object is - * {@link Object } - * + * @param value allowed object is {@link Object } + * */ public void setVnfParams(Object value) { this.vnfParams = value; @@ -155,10 +140,8 @@ public class VnfRequest { /** * Gets the value of the vnfOutputs property. * - * @return - * possible object is - * {@link VnfOutputs } - * + * @return possible object is {@link VnfOutputs } + * */ public VnfOutputs getVnfOutputs() { return vnfOutputs; @@ -167,13 +150,11 @@ public class VnfRequest { /** * Sets the value of the vnfOutputs property. * - * @param value - * allowed object is - * {@link VnfOutputs } - * + * @param value allowed object is {@link VnfOutputs } + * */ public void setVnfOutputs(VnfOutputs value) { this.vnfOutputs = value; } - } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java index caa0cae84d..677b983205 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfRequests.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfRequest" -}) +@XmlType(name = "", propOrder = {"vnfRequest"}) @XmlRootElement(name = "vnf-requests") public class VnfRequests { @@ -72,21 +71,20 @@ public class VnfRequests { * Gets the value of the vnfRequest property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the vnfRequest property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to + * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for + * the vnfRequest property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getVnfRequest().add(newItem); + * getVnfRequest().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link VnfRequest } + * Objects of the following type(s) are allowed in the list {@link VnfRequest } * * */ @@ -98,6 +96,6 @@ public class VnfRequests { } public void setVnfRequest(List<VnfRequest> vnfRequest) { - this.vnfRequest=vnfRequest; + this.vnfRequest = vnfRequest; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java index dd556a7c34..1917839b47 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfType.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -37,9 +37,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -58,11 +60,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "type", - "id", - "description" -}) +@XmlType(name = "", propOrder = {"type", "id", "description"}) @XmlRootElement(name = "vnf-type") public class VnfType { @@ -76,10 +74,8 @@ public class VnfType { /** * Gets the value of the type property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getType() { return type; @@ -88,10 +84,8 @@ public class VnfType { /** * Sets the value of the type property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setType(String value) { this.type = value; @@ -100,10 +94,8 @@ public class VnfType { /** * Gets the value of the id property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getId() { return id; @@ -112,10 +104,8 @@ public class VnfType { /** * Sets the value of the id property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setId(String value) { this.id = value; @@ -124,10 +114,8 @@ public class VnfType { /** * Gets the value of the description property. * - * @return - * possible object is - * {@link String } - * + * @return possible object is {@link String } + * */ public String getDescription() { return description; @@ -136,10 +124,8 @@ public class VnfType { /** * Sets the value of the description property. * - * @param value - * allowed object is - * {@link String } - * + * @param value allowed object is {@link String } + * */ public void setDescription(String value) { this.description = value; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java index 6728c69172..7ce179de8e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/VnfTypes.java @@ -19,10 +19,10 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // @@ -31,7 +31,6 @@ package org.onap.so.apihandlerinfra.vnfbeans; import java.util.ArrayList; import java.util.List; - import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; @@ -40,9 +39,11 @@ import javax.xml.bind.annotation.XmlType; /** - * <p>Java class for anonymous complex type. + * <p> + * Java class for anonymous complex type. * - * <p>The following schema fragment specifies the expected content contained within this class. + * <p> + * The following schema fragment specifies the expected content contained within this class. * * <pre> * <complexType> @@ -59,9 +60,7 @@ import javax.xml.bind.annotation.XmlType; * */ @XmlAccessorType(XmlAccessType.FIELD) -@XmlType(name = "", propOrder = { - "vnfType" -}) +@XmlType(name = "", propOrder = {"vnfType"}) @XmlRootElement(name = "vnf-types") public class VnfTypes { @@ -72,21 +71,20 @@ public class VnfTypes { * Gets the value of the vnfType property. * * <p> - * This accessor method returns a reference to the live list, - * not a snapshot. Therefore any modification you make to the - * returned list will be present inside the JAXB object. - * This is why there is not a <CODE>set</CODE> method for the vnfType property. + * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to + * the returned list will be present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for + * the vnfType property. * * <p> * For example, to add a new item, do as follows: + * * <pre> - * getVnfType().add(newItem); + * getVnfType().add(newItem); * </pre> * * * <p> - * Objects of the following type(s) are allowed in the list - * {@link VnfType } + * Objects of the following type(s) are allowed in the list {@link VnfType } * * */ @@ -96,9 +94,9 @@ public class VnfTypes { } return this.vnfType; } - - public void setVnfType( List<VnfType> vnfType) { - this.vnfType=vnfType; + + public void setVnfType(List<VnfType> vnfType) { + this.vnfType = vnfType; } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java index 3eb84299f4..efcfecffce 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/vnfbeans/package-info.java @@ -19,12 +19,13 @@ */ // -// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 -// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> -// Any modifications to this file will be lost upon recompilation of the source schema. -// Generated on: 2015.09.03 at 02:02:13 PM EDT +// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 +// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> +// Any modifications to this file will be lost upon recompilation of the source schema. +// Generated on: 2015.09.03 at 02:02:13 PM EDT // -@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/infra/vnf-request/v1", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +@javax.xml.bind.annotation.XmlSchema(namespace = "http://org.onap/so/infra/vnf-request/v1", + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package org.onap.so.apihandlerinfra.vnfbeans; diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java new file mode 100644 index 0000000000..75cc1ecec6 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ActivitySequence.java @@ -0,0 +1,82 @@ +/*- + * ============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.workflowspecificationbeans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"name", "description"}) +public class ActivitySequence { + + @JsonProperty("name") + private String name; + @JsonProperty("description") + private String description; + + /** + * No args constructor for use in serialization + * + */ + public ActivitySequence() {} + + /** + * + * @param description + * @param name + */ + public ActivitySequence(String name, String description) { + super(); + this.name = name; + this.description = description; + } + + @JsonProperty("name") + public String getName() { + return name; + } + + @JsonProperty("name") + public void setName(String name) { + this.name = name; + } + + public ActivitySequence withName(String name) { + this.name = name; + return this; + } + + @JsonProperty("description") + public String getDescription() { + return description; + } + + @JsonProperty("description") + public void setDescription(String description) { + this.description = description; + } + + public ActivitySequence withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java new file mode 100644 index 0000000000..26f37c1319 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/ArtifactInfo.java @@ -0,0 +1,218 @@ +/*- + * ============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.workflowspecificationbeans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"artifactType", "artifactUuid", "artifactName", "artifactVersion", "artifactDescription", + "workflowName", "operationName", "workflowSource", "workflowResourceTarget"}) +public class ArtifactInfo { + + @JsonProperty("artifactType") + private String artifactType; + @JsonProperty("artifactUuid") + private String artifactUuid; + @JsonProperty("artifactName") + private String artifactName; + @JsonProperty("artifactVersion") + private String artifactVersion; + @JsonProperty("artifactDescription") + private String artifactDescription; + @JsonProperty("workflowName") + private String workflowName; + @JsonProperty("operationName") + private String operationName; + @JsonProperty("workflowSource") + private String workflowSource; + @JsonProperty("workflowResourceTarget") + private String workflowResourceTarget; + + /** + * No args constructor for use in serialization + * + */ + public ArtifactInfo() {} + + /** + * + * @param artifactName + * @param workflowName + * @param artifactType + * @param operationName + * @param artifactVersion + * @param workflowResourceTarget + * @param workflowSource + * @param artifactUuid + * @param artifactDescription + */ + public ArtifactInfo(String artifactType, String artifactUuid, String artifactName, String artifactVersion, + String artifactDescription, String workflowName, String operationName, String workflowSource, + String workflowResourceTarget) { + super(); + this.artifactType = artifactType; + this.artifactUuid = artifactUuid; + this.artifactName = artifactName; + this.artifactVersion = artifactVersion; + this.artifactDescription = artifactDescription; + this.workflowName = workflowName; + this.operationName = operationName; + this.workflowSource = workflowSource; + this.workflowResourceTarget = workflowResourceTarget; + } + + @JsonProperty("artifactType") + public String getArtifactType() { + return artifactType; + } + + @JsonProperty("artifactType") + public void setArtifactType(String artifactType) { + this.artifactType = artifactType; + } + + public ArtifactInfo withArtifactType(String artifactType) { + this.artifactType = artifactType; + return this; + } + + @JsonProperty("artifactUuid") + public String getArtifactUuid() { + return artifactUuid; + } + + @JsonProperty("artifactUuid") + public void setArtifactUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + } + + public ArtifactInfo withArtifactUuid(String artifactUuid) { + this.artifactUuid = artifactUuid; + return this; + } + + @JsonProperty("artifactName") + public String getArtifactName() { + return artifactName; + } + + @JsonProperty("artifactName") + public void setArtifactName(String artifactName) { + this.artifactName = artifactName; + } + + public ArtifactInfo withArtifactName(String artifactName) { + this.artifactName = artifactName; + return this; + } + + @JsonProperty("artifactVersion") + public String getArtifactVersion() { + return artifactVersion; + } + + @JsonProperty("artifactVersion") + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public ArtifactInfo withArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + return this; + } + + @JsonProperty("artifactDescription") + public String getArtifactDescription() { + return artifactDescription; + } + + @JsonProperty("artifactDescription") + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public ArtifactInfo withArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + return this; + } + + @JsonProperty("workflowName") + public String getWorkflowName() { + return workflowName; + } + + @JsonProperty("workflowName") + public void setWorkflowName(String workflowName) { + this.workflowName = workflowName; + } + + public ArtifactInfo withWorkflowName(String workflowName) { + this.workflowName = workflowName; + return this; + } + + @JsonProperty("operationName") + public String getOperationName() { + return operationName; + } + + @JsonProperty("operationName") + public void setOperationName(String operationName) { + this.operationName = operationName; + } + + public ArtifactInfo withOperationName(String operationName) { + this.operationName = operationName; + return this; + } + + @JsonProperty("workflowSource") + public String getWorkflowSource() { + return workflowSource; + } + + @JsonProperty("workflowSource") + public void setWorkflowSource(String workflowSource) { + this.workflowSource = workflowSource; + } + + public ArtifactInfo withWorkflowSource(String workflowSource) { + this.workflowSource = workflowSource; + return this; + } + + @JsonProperty("workflowResourceTarget") + public String getWorkflowResourceTarget() { + return workflowResourceTarget; + } + + @JsonProperty("workflowResourceTarget") + public void setWorkflowResourceTarget(String workflowResourceTarget) { + this.workflowResourceTarget = workflowResourceTarget; + } + + public ArtifactInfo withWorkflowResourceTarget(String workflowResourceTarget) { + this.workflowResourceTarget = workflowResourceTarget; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java new file mode 100644 index 0000000000..324f368c26 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/Validation.java @@ -0,0 +1,82 @@ +/*- + * ============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.workflowspecificationbeans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"maxLength", "allowableChars"}) +public class Validation { + + @JsonProperty("maxLength") + private String maxLength; + @JsonProperty("allowableChars") + private String allowableChars; + + /** + * No args constructor for use in serialization + * + */ + public Validation() {} + + /** + * + * @param maxLength + * @param allowableChars + */ + public Validation(String maxLength, String allowableChars) { + super(); + this.maxLength = maxLength; + this.allowableChars = allowableChars; + } + + @JsonProperty("maxLength") + public String getMaxLength() { + return maxLength; + } + + @JsonProperty("maxLength") + public void setMaxLength(String maxLength) { + this.maxLength = maxLength; + } + + public Validation withMaxLength(String maxLength) { + this.maxLength = maxLength; + return this; + } + + @JsonProperty("allowableChars") + public String getAllowableChars() { + return allowableChars; + } + + @JsonProperty("allowableChars") + public void setAllowableChars(String allowableChars) { + this.allowableChars = allowableChars; + } + + public Validation withAllowableChars(String allowableChars) { + this.allowableChars = allowableChars; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java new file mode 100644 index 0000000000..8cbd622667 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowInputParameter.java @@ -0,0 +1,160 @@ +/*- + * ============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.workflowspecificationbeans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"label", "inputType", "required", "validation", "soFieldName", "soPayloadLocation"}) +public class WorkflowInputParameter { + + @JsonProperty("label") + private String label; + @JsonProperty("inputType") + private String inputType; + @JsonProperty("required") + private Boolean required; + @JsonProperty("validation") + private List<Validation> validation = null; + @JsonProperty("soFieldName") + private String soFieldName; + @JsonProperty("soPayloadLocation") + private String soPayloadLocation; + + /** + * No args constructor for use in serialization + * + */ + public WorkflowInputParameter() {} + + /** + * + * @param validation + * @param inputType + * @param soPayloadLocation + * @param label + * @param required + * @param soFieldName + */ + public WorkflowInputParameter(String label, String inputType, Boolean required, List<Validation> validation, + String soFieldName, String soPayloadLocation) { + super(); + this.label = label; + this.inputType = inputType; + this.required = required; + this.validation = validation; + this.soFieldName = soFieldName; + this.soPayloadLocation = soPayloadLocation; + } + + @JsonProperty("label") + public String getLabel() { + return label; + } + + @JsonProperty("label") + public void setLabel(String label) { + this.label = label; + } + + public WorkflowInputParameter withLabel(String label) { + this.label = label; + return this; + } + + @JsonProperty("inputType") + public String getInputType() { + return inputType; + } + + @JsonProperty("inputType") + public void setInputType(String inputType) { + this.inputType = inputType; + } + + public WorkflowInputParameter withInputType(String inputType) { + this.inputType = inputType; + return this; + } + + @JsonProperty("required") + public Boolean getRequired() { + return required; + } + + @JsonProperty("required") + public void setRequired(Boolean required) { + this.required = required; + } + + public WorkflowInputParameter withRequired(Boolean required) { + this.required = required; + return this; + } + + @JsonProperty("validation") + public List<Validation> getValidation() { + return validation; + } + + @JsonProperty("validation") + public void setValidation(List<Validation> validation) { + this.validation = validation; + } + + public WorkflowInputParameter withValidation(List<Validation> validation) { + this.validation = validation; + return this; + } + + @JsonProperty("soFieldName") + public String getSoFieldName() { + return soFieldName; + } + + @JsonProperty("soFieldName") + public void setSoFieldName(String soFieldName) { + this.soFieldName = soFieldName; + } + + public WorkflowInputParameter withSoFieldName(String soFieldName) { + this.soFieldName = soFieldName; + return this; + } + + @JsonProperty("soPayloadLocation") + public String getSoPayloadLocation() { + return soPayloadLocation; + } + + @JsonProperty("soPayloadLocation") + public void setSoPayloadLocation(String soPayloadLocation) { + this.soPayloadLocation = soPayloadLocation; + } + + public WorkflowInputParameter withSoPayloadLocation(String soPayloadLocation) { + this.soPayloadLocation = soPayloadLocation; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java new file mode 100644 index 0000000000..d8a0a8b662 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecification.java @@ -0,0 +1,103 @@ +/*- + * ============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.workflowspecificationbeans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"artifactInfo", "activitySequence", "workflowInputParameters"}) +public class WorkflowSpecification { + + @JsonProperty("artifactInfo") + private ArtifactInfo artifactInfo; + @JsonProperty("activitySequence") + private List<ActivitySequence> activitySequence = null; + @JsonProperty("workflowInputParameters") + private List<WorkflowInputParameter> workflowInputParameters = null; + + /** + * No args constructor for use in serialization + * + */ + public WorkflowSpecification() {} + + /** + * + * @param activitySequence + * @param artifactInfo + * @param workflowInputParameters + */ + public WorkflowSpecification(ArtifactInfo artifactInfo, List<ActivitySequence> activitySequence, + List<WorkflowInputParameter> workflowInputParameters) { + super(); + this.artifactInfo = artifactInfo; + this.activitySequence = activitySequence; + this.workflowInputParameters = workflowInputParameters; + } + + @JsonProperty("artifactInfo") + public ArtifactInfo getArtifactInfo() { + return artifactInfo; + } + + @JsonProperty("artifactInfo") + public void setArtifactInfo(ArtifactInfo artifactInfo) { + this.artifactInfo = artifactInfo; + } + + public WorkflowSpecification withArtifactInfo(ArtifactInfo artifactInfo) { + this.artifactInfo = artifactInfo; + return this; + } + + @JsonProperty("activitySequence") + public List<ActivitySequence> getActivitySequence() { + return activitySequence; + } + + @JsonProperty("activitySequence") + public void setActivitySequence(List<ActivitySequence> activitySequence) { + this.activitySequence = activitySequence; + } + + public WorkflowSpecification withActivitySequence(List<ActivitySequence> activitySequence) { + this.activitySequence = activitySequence; + return this; + } + + @JsonProperty("workflowInputParameters") + public List<WorkflowInputParameter> getWorkflowInputParameters() { + return workflowInputParameters; + } + + @JsonProperty("workflowInputParameters") + public void setWorkflowInputParameters(List<WorkflowInputParameter> workflowInputParameters) { + this.workflowInputParameters = workflowInputParameters; + } + + public WorkflowSpecification withWorkflowInputParameters(List<WorkflowInputParameter> workflowInputParameters) { + this.workflowInputParameters = workflowInputParameters; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java new file mode 100644 index 0000000000..ba54e7271a --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationList.java @@ -0,0 +1,63 @@ +/*- + * ============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.workflowspecificationbeans; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"workflowSpecification"}) +public class WorkflowSpecificationList { + + @JsonProperty("workflowSpecification") + private WorkflowSpecification workflowSpecification; + + /** + * No args constructor for use in serialization + * + */ + public WorkflowSpecificationList() {} + + /** + * + * @param workflowSpecification + */ + public WorkflowSpecificationList(WorkflowSpecification workflowSpecification) { + super(); + this.workflowSpecification = workflowSpecification; + } + + @JsonProperty("workflowSpecification") + public WorkflowSpecification getWorkflowSpecification() { + return workflowSpecification; + } + + @JsonProperty("workflowSpecification") + public void setWorkflowSpecification(WorkflowSpecification workflowSpecification) { + this.workflowSpecification = workflowSpecification; + } + + public WorkflowSpecificationList withWorkflowSpecification(WorkflowSpecification workflowSpecification) { + this.workflowSpecification = workflowSpecification; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java new file mode 100644 index 0000000000..922f5601d5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/main/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecifications.java @@ -0,0 +1,65 @@ +/*- + * ============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.workflowspecificationbeans; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"workflowSpecificationList"}) +public class WorkflowSpecifications { + + @JsonProperty("workflowSpecificationList") + private List<WorkflowSpecificationList> workflowSpecificationList = null; + + /** + * No args constructor for use in serialization + * + */ + public WorkflowSpecifications() {} + + /** + * + * @param workflowSpecificationList + */ + public WorkflowSpecifications(List<WorkflowSpecificationList> workflowSpecificationList) { + super(); + this.workflowSpecificationList = workflowSpecificationList; + } + + @JsonProperty("workflowSpecificationList") + public List<WorkflowSpecificationList> getWorkflowSpecificationList() { + return workflowSpecificationList; + } + + @JsonProperty("workflowSpecificationList") + public void setWorkflowSpecificationList(List<WorkflowSpecificationList> workflowSpecificationList) { + this.workflowSpecificationList = workflowSpecificationList; + } + + public WorkflowSpecifications withWorkflowSpecificationList( + List<WorkflowSpecificationList> workflowSpecificationList) { + this.workflowSpecificationList = workflowSpecificationList; + return this; + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java index 8a45752949..b8a2f22566 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/common/ResponseBuilderTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandler.common; import static org.junit.Assert.assertEquals; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; @@ -33,41 +31,41 @@ import org.springframework.beans.factory.annotation.Autowired; public class ResponseBuilderTest extends BaseTest { - @Autowired - private ResponseBuilder builder; - + @Autowired + private ResponseBuilder builder; + @Test - public void testBuildResponseResponse () throws ApiException { - - String requestId = null; - String apiVersion = "1"; - String jsonResponse = "Successfully started the process"; - + public void testBuildResponseResponse() throws ApiException { + + String requestId = null; + String apiVersion = "1"; + String jsonResponse = "Successfully started the process"; + Response response = builder.buildResponse(HttpStatus.SC_ACCEPTED, requestId, jsonResponse, apiVersion); - + assertEquals(202, response.getStatus()); 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 testBuildResponseVersion () throws ApiException { - - String requestId = "123456-67889"; - String apiVersion = "v5"; - String jsonResponse = "Successfully started the process"; - + public void testBuildResponseVersion() throws ApiException { + + String requestId = "123456-67889"; + String apiVersion = "v5"; + String jsonResponse = "Successfully started the process"; + Response response = builder.buildResponse(HttpStatus.SC_CREATED, requestId, jsonResponse, apiVersion); - + assertEquals(201, response.getStatus()); 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("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - + } - + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java index db3dcb5af5..276b438529 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/filters/RequestUriFilterTest.java @@ -23,35 +23,33 @@ package org.onap.so.apihandler.filters; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; - import java.io.IOException; import java.net.URI; - import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.UriInfo; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class RequestUriFilterTest extends BaseTest{ - - @Test - public void filterTest() throws IOException { - RequestUriFilter URIFilter = new RequestUriFilter(); - URI baseURI = URI.create("http://localhost:58879/"); - String requestURI = "onap/so/infra/serviceInstances/v5"; - - ContainerRequestContext mockContext = mock(ContainerRequestContext.class); - UriInfo mockInfo = mock(UriInfo.class); - - when(mockContext.getUriInfo()).thenReturn(mockInfo); - when(mockInfo.getBaseUri()).thenReturn(baseURI); - when(mockInfo.getPath()).thenReturn(requestURI); - - - URIFilter.filter(mockContext); - assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances", URIFilter.getRequestUri()); - } +public class RequestUriFilterTest extends BaseTest { + + @Test + public void filterTest() throws IOException { + RequestUriFilter URIFilter = new RequestUriFilter(); + URI baseURI = URI.create("http://localhost:58879/"); + String requestURI = "onap/so/infra/serviceInstances/v5"; + + ContainerRequestContext mockContext = mock(ContainerRequestContext.class); + UriInfo mockInfo = mock(UriInfo.class); + + when(mockContext.getUriInfo()).thenReturn(mockInfo); + when(mockInfo.getBaseUri()).thenReturn(baseURI); + when(mockInfo.getPath()).thenReturn(requestURI); + + + URIFilter.filter(mockContext); + assertEquals("http://localhost:58879/onap/so/infra/serviceInstantiation/v5/serviceInstances", + URIFilter.getRequestUri()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java index 564121b7b5..9065a1a9ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandler/recipe/CamundaClientErrorHandlerTest.java @@ -1,30 +1,23 @@ /* - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 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 + * ============LICENSE_START======================================================= ONAP - SO + * ================================================================================ Copyright (C) 2018 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 + * 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. + * 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.apihandler.recipe; import static org.junit.Assert.assertEquals; - import java.io.ByteArrayInputStream; import java.io.IOException; - import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.junit.Before; @@ -32,41 +25,41 @@ import org.junit.Test; import org.mockito.Mockito; public class CamundaClientErrorHandlerTest { - - private ClientHttpResponse clientHttpResponse; - private CamundaClientErrorHandler clientErrorHandler; - - @Before - public void before() { - clientHttpResponse = Mockito.mock(ClientHttpResponse.class); - clientErrorHandler = new CamundaClientErrorHandler(); - } - - @Test - public void handleError_SERVER_ERROR_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(true, serverHasError); - } - - @Test - public void handleError_CLIENT_ERROR_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(true, clientHasError); - } - - @Test - public void handleError_SUCCESS_Test() throws IOException { - Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); - Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); - clientErrorHandler.handleError(clientHttpResponse); - boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse); - assertEquals(false, hasNoError); - } - -}
\ No newline at end of file + + private ClientHttpResponse clientHttpResponse; + private CamundaClientErrorHandler clientErrorHandler; + + @Before + public void before() { + clientHttpResponse = Mockito.mock(ClientHttpResponse.class); + clientErrorHandler = new CamundaClientErrorHandler(); + } + + @Test + public void handleError_SERVER_ERROR_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.INTERNAL_SERVER_ERROR); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean serverHasError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(true, serverHasError); + } + + @Test + public void handleError_CLIENT_ERROR_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.BAD_REQUEST); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean clientHasError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(true, clientHasError); + } + + @Test + public void handleError_SUCCESS_Test() throws IOException { + Mockito.when(clientHttpResponse.getStatusCode()).thenReturn(HttpStatus.ACCEPTED); + Mockito.when(clientHttpResponse.getBody()).thenReturn(new ByteArrayInputStream("{}".getBytes())); + clientErrorHandler.handleError(clientHttpResponse); + boolean hasNoError = clientErrorHandler.hasError(clientHttpResponse); + assertEquals(false, hasNoError); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java index 68869b77d4..75a6eeea7d 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/AllTestsTestSuite.java @@ -19,14 +19,14 @@ */ package org.onap.so.apihandlerinfra; -import org.junit.runner.RunWith; +import org.junit.runner.RunWith; import com.googlecode.junittoolbox.SuiteClasses; import com.googlecode.junittoolbox.WildcardPatternSuite; @RunWith(WildcardPatternSuite.class) @SuiteClasses("**/*Test.class") public class AllTestsTestSuite { - // the class remains empty, - // used only as a holder for the above annotations + // the class remains empty, + // used only as a holder for the above annotations } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java index 6efcdc47e5..bc867503f2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ApiExceptionTest.java @@ -26,15 +26,12 @@ import org.junit.Test; import org.junit.rules.ExpectedException; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.exceptions.*; - import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; - import java.io.IOException; import java.util.LinkedList; import java.util.List; - import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; @@ -52,7 +49,8 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage("Message rewritten"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build(); + RecipeNotFoundException testException = new RecipeNotFoundException.Builder("Test Message", + HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).message("Message rewritten").build(); throw testException; } @@ -65,8 +63,9 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage(startsWith("Request Failed due to BPEL error with HTTP Status =")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - thrown.expect(hasProperty("variables",sameBeanAs(testVariables))); - BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build(); + thrown.expect(hasProperty("variables", sameBeanAs(testVariables))); + BPMNFailureException testException = new BPMNFailureException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_BAD_PARAMETER).variables(testVariables).build(); throw testException; } @@ -81,33 +80,40 @@ public class ApiExceptionTest extends BaseTest { thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); thrown.expect(hasProperty("cause", sameBeanAs(ioException))); - ClientConnectionException testException = new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).cause(ioException).build(); + ClientConnectionException testException = + new ClientConnectionException.Builder("test", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER) + .cause(ioException).build(); throw testException; } @Test public void testDuplicateRequestException() throws ApiException { - ErrorLoggerInfo testLog = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); + ErrorLoggerInfo testLog = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError) + .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build(); thrown.expect(DuplicateRequestException.class); thrown.expectMessage(startsWith("Error: Locked instance")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); thrown.expect(hasProperty("errorLoggerInfo", sameBeanAs(testLog))); - DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2","Test3","Test4", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build(); + DuplicateRequestException testException = new DuplicateRequestException.Builder("Test1", "Test2", "Test3", + "Test4", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(testLog).build(); throw testException; } @Test public void testValidateException() throws ApiException { - + thrown.expect(ValidateException.class); thrown.expectMessage("Test Message"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_NOT_FOUND))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); - ValidateException testException = new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); + ValidateException testException = + new ValidateException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_BAD_PARAMETER) + .messageID(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).build(); throw testException; } @@ -118,7 +124,9 @@ public class ApiExceptionTest extends BaseTest { thrown.expectMessage("Test Message"); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_CONFLICT))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); - VfModuleNotFoundException testException = new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND,ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build(); + VfModuleNotFoundException testException = + new VfModuleNotFoundException.Builder("Test Message", HttpStatus.SC_NOT_FOUND, + ErrorNumbers.SVC_BAD_PARAMETER).httpResponseCode(HttpStatus.SC_CONFLICT).build(); throw testException; } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java index 54e7b27168..da37be98b2 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BaseTest.java @@ -22,26 +22,25 @@ package org.onap.so.apihandlerinfra; -import com.github.tomakehurst.wiremock.client.WireMock; +import java.nio.file.Files; +import java.nio.file.Paths; +import javax.transaction.Transactional; import org.junit.After; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.web.server.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.boot.web.server.LocalServerPort; import org.springframework.cloud.contract.wiremock.AutoConfigureWireMock; import org.springframework.core.env.Environment; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; - -import javax.transaction.Transactional; - -import java.nio.file.Files; -import java.nio.file.Paths; +import com.github.tomakehurst.wiremock.WireMockServer; +import com.github.tomakehurst.wiremock.client.WireMock; @RunWith(SpringRunner.class) @SpringBootTest(classes = ApiHandlerApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -50,39 +49,46 @@ import java.nio.file.Paths; @Transactional @AutoConfigureWireMock(port = 0) public abstract class BaseTest { - protected Logger logger = LoggerFactory.getLogger(BaseTest.class); - protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + protected Logger logger = LoggerFactory.getLogger(BaseTest.class); + protected TestRestTemplate restTemplate = new TestRestTemplate("test", "test"); + + @Autowired + protected Environment env; + + @LocalServerPort + private int port; + + @Autowired + protected WireMockServer wireMockServer; + + protected String createURLWithPort(String uri) { + return "http://localhost:" + port + uri; + } + + protected String createURLWithPort(String uri, int iPort) { + return "http://localhost:" + iPort + uri; + } - @Autowired - protected Environment env; + @After + public void tearDown() { + wireMockServer.resetAll(); + } - @LocalServerPort - private int port; - - protected String createURLWithPort(String uri) { - return "http://localhost:" + port + uri; - } - - protected String createURLWithPort(String uri, int iPort) { - return "http://localhost:" + iPort + uri; - } - - @After - public void tearDown(){ - WireMock.reset(); - } + public static String getResponseTemplate; + public static String getResponseTemplateNoBody; + public static String infraActivePost; - public static String getResponseTemplate; - public static String getResponseTemplateNoBody; - public static String infraActivePost; - @BeforeClass - public static void setupTest() throws Exception { - getResponseTemplate = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json"))); - getResponseTemplateNoBody = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json"))); - infraActivePost = new String(Files.readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json"))); - } + @BeforeClass + public static void setupTest() throws Exception { + getResponseTemplate = new String(Files + .readAllBytes(Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequest.json"))); + getResponseTemplateNoBody = new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/InfraActiveRequests/getInfraActiveRequestNoBody.json"))); + infraActivePost = new String(Files.readAllBytes( + Paths.get("src/test/resources/__files/InfraActiveRequests/createInfraActiveRequests.json"))); + } - public String getTestUrl(String requestId) { - return "/infraActiveRequests/" + requestId; - } + public String getTestUrl(String requestId) { + return "/infraActiveRequests/" + requestId; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java index 68c5c918ba..53982ca9d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/BeanMultiTest.java @@ -1,4 +1,5 @@ package org.onap.so.apihandlerinfra; + /*- * ============LICENSE_START======================================================= * ONAP - SO @@ -20,7 +21,6 @@ package org.onap.so.apihandlerinfra; */ import org.junit.Before; import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.PojoClassFilter; import com.openpojo.reflection.filters.FilterEnum; @@ -33,35 +33,34 @@ import com.openpojo.validation.test.impl.SetterTester; public class BeanMultiTest { - Validator validator; - PojoClassFilter enumFilter; - private PojoClassFilter filterTestClasses = new FilterTestClasses(); + Validator validator; + PojoClassFilter enumFilter; + private PojoClassFilter filterTestClasses = new FilterTestClasses(); + + @Before + public void setup() { + enumFilter = new FilterEnum(); + validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + } + + @Test + public void validateBeansMsoApihandlerBeans() { + test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans"); + test("org.onap.so.apihandlerinfra.tasksbeans"); + test("org.onap.so.apihandlerinfra.vnfbeans"); + test("org.onap.so.apihandlerinfra.tenantisolationbeans"); + test("org.onap.so.apihandlerinfra.workflowspecificationbeans"); + } - @Before - public void setup(){ - enumFilter = new FilterEnum(); - validator = ValidatorBuilder.create() - .with(new SetterMustExistRule(), - new GetterMustExistRule()) - .with(new SetterTester(), - new GetterTester()) - .build(); - } - @Test - public void validateBeansMsoApihandlerBeans() { - test("org.onap.so.apihandlerinfra.e2eserviceinstancebeans"); - test("org.onap.so.apihandlerinfra.tasksbeans"); - test("org.onap.so.apihandlerinfra.vnfbeans"); - test("org.onap.so.apihandlerinfra.tenantisolationbeans"); - } + private void test(String packageName) { + validator.validate(packageName, enumFilter, filterTestClasses); - private void test(String packageName) { - validator.validate(packageName, enumFilter, filterTestClasses); + } - } - private static class FilterTestClasses implements PojoClassFilter { - public boolean include(PojoClass pojoClass) { - return !pojoClass.getSourcePath().contains("/test-classes/"); - } - } + private static class FilterTestClasses implements PojoClassFilter { + public boolean include(PojoClass pojoClass) { + return !pojoClass.getSourcePath().contains("/test-classes/"); + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java index 8d5539cf8a..7ddab572e3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/E2EServiceInstancesTest.java @@ -24,20 +24,16 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -51,224 +47,239 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; public class E2EServiceInstancesTest extends BaseTest { -private final ObjectMapper mapper = new ObjectMapper(); - - private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/"; - - - @Before - public void init() throws JsonProcessingException { - stubFor(post(urlPathEqualTo("/testOrchestrationUri")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson("{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setServiceModelUUID(defaultService.getModelUUID()); - serviceRecipe.setAction(Action.scaleInstance.name()); - serviceRecipe.setRecipeTimeout(180); - serviceRecipe.setOrchestrationUri("/testOrchestrationUri"); - - stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - } - public String inputStream(String JsonInput)throws IOException{ - JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput; - return new String(Files.readAllBytes(Paths.get(JsonInput))); - } - public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type",MediaType.APPLICATION_JSON); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath)); - HttpEntity<String> request = new HttpEntity<>(requestJson, headers); - - return restTemplate.exchange(builder.toUriString(), - reqMethod, request, String.class); - } - - @Test - public void createE2EServiceInstanceNoRequestInfo() throws IOException{ - String uri = e2eServInstancesUri + "v3"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void updateE2EServiceInstanceJSONMappingError() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void updateE2EServiceInstanceNoRequestorId() throws IOException{ - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC0002"); - exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); - } - @Test - public void deleteE2EServiceInstance() throws IOException{ - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC1000"); - exception.setText("No communication to catalog DB null"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void deleteE2EServiceInstanceNotValid() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void getE2EServiceInstanceNullOperationalStatus() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET); - - assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void scaleE2EServiceInstanceMappingError() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void scaleE2EServiceInstance() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; - ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void updateE2EServiceInstance() throws IOException{ - String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - } - - @Test - public void getE2EServiceInstance() throws IOException{ - OperationStatus status = new OperationStatus(); - status.setOperationId("operationId"); - status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e"); - stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(status)) - .withStatus(HttpStatus.SC_OK))); - String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId"; - ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET); - assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - } - @Test - public void compareModelWithTargetVersionBadRequest() throws IOException{ - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); - } - @Test - public void compareModelWithTargetVersion() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("Camunda/SuccessfulResponse.json").withStatus(org.apache.http.HttpStatus.SC_ACCEPTED))); - - String expectedResponse = "success"; - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - String actualResponse = response.getBody(); - assertEquals(expectedResponse, actualResponse); - } - @Test - public void compareModelWithTargetVersionEmptyResponse() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); - - RequestError expectedResponse = new RequestError(); - ServiceException exception = new ServiceException(); - exception.setMessageId("SVC1000"); - exception.setText("Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond"); - expectedResponse.setServiceException(exception); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); - } - @Test - public void compareModelWithTargetVersionBadBpelResponse() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status")); - } - @Test - public void compareModelWithTargetVersionNoBPELResponse() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBody("{}").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - - String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; - ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); - - assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("Request Failed due to BPEL error with HTTP Status")); - } -}
\ No newline at end of file + private final ObjectMapper mapper = new ObjectMapper(); + + private final String e2eServInstancesUri = "/onap/so/infra/e2eServiceInstances/"; + + + @Before + public void init() throws JsonProcessingException { + wireMockServer.stubFor(post(urlPathEqualTo("/testOrchestrationUri")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(equalToJson( + "{\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"Error parsing request: No valid requestorId is specified\",\"progress\":100,\"startTime\":1533541051247,\"endTime\":1533541051247,\"source\":null,\"vnfId\":null,\"vnfName\":null,\"vnfType\":null,\"serviceType\":null,\"aicNodeClli\":null,\"tenantId\":null,\"provStatus\":null,\"vnfParams\":null,\"vnfOutputs\":null,\"requestBody\":\"{\\r\\n \\\"service\\\":{\\r\\n \\\"name\\\":\\\"so_test4\\\",\\r\\n \\\"description\\\":\\\"so_test2\\\",\\r\\n \\\"serviceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561519\\\",\\r\\n \\\"serviceUuid\\\":\\\"592f9437-a9c0-4303-b9f6-c445bb7e9814\\\",\\r\\n \\\"globalSubscriberId\\\":\\\"123457\\\",\\r\\n \\\"serviceType\\\":\\\"voLTE\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"resources\\\":[\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vIMS\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vBAS-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-vMME-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"vEPC\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"61c3e96e-0970-4871-b6e0-3b6de7561516\\\",\\r\\n \\\"resourceUuid\\\":\\\"62c3e96e-0970-4871-b6e0-3b6de7561512\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n {\\r\\n \\\"vnfProfileId\\\":\\\"zte-CSCF-1.0\\\",\\r\\n \\\"locationConstraints\\\":{\\r\\n \\\"vimId\\\":\\\"4050083f-465f-4838-af1e-47a545222ad1\\\"\\r\\n }\\r\\n }\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"underlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561513\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561514\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n },\\r\\n {\\r\\n \\\"resourceName\\\":\\\"overlayvpn\\\",\\r\\n \\\"resourceInvariantUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561517\\\",\\r\\n \\\"resourceUuid\\\":\\\"60c3e96e-0970-4871-b6e0-3b6de7561518\\\",\\r\\n \\\"parameters\\\":{\\r\\n \\\"locationConstraints\\\":[\\r\\n\\r\\n ]\\r\\n }\\r\\n }\\r\\n ],\\r\\n \\\"requestInputs\\\":{\\r\\n \\\"externalDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"m6000_mng_ip\\\":\\\"181.18.20.2\\\",\\r\\n \\\"externalCompanyFtpDataNetworkName\\\":\\\"Flow_out_net\\\",\\r\\n \\\"externalPluginManageNetworkName\\\":\\\"plugin_net_2014\\\",\\r\\n \\\"externalManageNetworkName\\\":\\\"mng_net_2017\\\",\\r\\n \\\"sfc_data_network\\\":\\\"sfc_data_net_2016\\\",\\r\\n \\\"NatIpRange\\\":\\\"210.1.1.10-210.1.1.20\\\",\\r\\n \\\"location\\\":\\\"4050083f-465f-4838-af1e-47a545222ad0\\\",\\r\\n \\\"sdncontroller\\\":\\\"9b9f02c0-298b-458a-bc9c-be3692e4f35e\\\"\\r\\n }\\r\\n }\\r\\n\\r\\n }\\r\\n\\r\\n}\",\"responseBody\":null,\"lastModifiedBy\":\"APIH\",\"modifyTime\":null,\"requestType\":null,\"volumeGroupId\":null,\"volumeGroupName\":null,\"vfModuleId\":null,\"vfModuleName\":null,\"vfModuleModelName\":null,\"aaiServiceId\":null,\"aicCloudRegion\":null,\"callBackUrl\":null,\"correlator\":null,\"serviceInstanceId\":null,\"serviceInstanceName\":null,\"requestScope\":\"service\",\"requestAction\":\"createInstance\",\"networkId\":null,\"networkName\":null,\"networkType\":null,\"requestorId\":null,\"configurationId\":null,\"configurationName\":null,\"operationalEnvId\":null,\"operationalEnvName\":null,\"requestURI\":\"d167c9d0-1785-4e93-b319-996ebbcc3272\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setServiceModelUUID(defaultService.getModelUUID()); + serviceRecipe.setAction(Action.scaleInstance.name()); + serviceRecipe.setRecipeTimeout(180); + serviceRecipe.setOrchestrationUri("/testOrchestrationUri"); + + wireMockServer.stubFor(get(urlPathEqualTo("/service/search/findFirstByModelNameOrderByModelVersionDesc")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/serviceRecipe/search/findFirstByServiceModelUUIDAndAction")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + } + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/E2EServiceInstancesTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath)); + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class); + } + + @Test + public void createE2EServiceInstanceNoRequestInfo() throws IOException { + String uri = e2eServInstancesUri + "v3"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void updateE2EServiceInstanceJSONMappingError() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.PUT); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void updateE2EServiceInstanceNoRequestorId() throws IOException { + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC0002"); + exception.setText("Error parsing request. Error parsing request: No valid requestorId is specified"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); + } + + @Test + public void deleteE2EServiceInstance() throws IOException { + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC1000"); + exception.setText("No communication to catalog DB null"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/DeleteRequest.json"), uri, HttpMethod.DELETE); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void deleteE2EServiceInstanceNotValid() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.DELETE); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void getE2EServiceInstanceNullOperationalStatus() throws IOException { + String uri = e2eServInstancesUri + + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.GET); + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void scaleE2EServiceInstanceMappingError() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void scaleE2EServiceInstance() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/scale"; + ResponseEntity<String> response = sendRequest(inputStream("/ScaleRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void updateE2EServiceInstance() throws IOException { + String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.PUT); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void getE2EServiceInstance() throws IOException { + OperationStatus status = new OperationStatus(); + status.setOperationId("operationId"); + status.setServiceId("9b9f02c0-298b-458a-bc9c-be3692e4f35e"); + wireMockServer.stubFor(get(urlPathEqualTo("/operationStatus/search/findOneByServiceIdAndOperationId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(status)).withStatus(HttpStatus.SC_OK))); + String uri = e2eServInstancesUri + "v3/9b9f02c0-298b-458a-bc9c-be3692e4f35e/operations/operationId"; + ResponseEntity<String> response = sendRequest("", uri, HttpMethod.GET); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); + } + + @Test + public void compareModelWithTargetVersionBadRequest() throws IOException { + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/Request.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText().contains("Mapping of request to JSON object failed")); + } + + @Test + public void compareModelWithTargetVersion() throws IOException { + wireMockServer.stubFor( + post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn(aResponse() + .withHeader("Content-Type", "application/json").withBodyFile("Camunda/SuccessfulResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_ACCEPTED))); + + String expectedResponse = "success"; + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + String actualResponse = response.getBody(); + assertEquals(expectedResponse, actualResponse); + } + + @Test + public void compareModelWithTargetVersionEmptyResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) + .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); + + RequestError expectedResponse = new RequestError(); + ServiceException exception = new ServiceException(); + exception.setMessageId("SVC1000"); + exception.setText( + "Failed calling bpmn localhost:" + env.getProperty("wiremock.server.port") + " failed to respond"); + expectedResponse.setServiceException(exception); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); + } + + @Test + public void compareModelWithTargetVersionBadBpelResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/TestResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText() + .contains("Request Failed due to BPEL error with HTTP Status")); + } + + @Test + public void compareModelWithTargetVersionNoBPELResponse() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CompareModelofE2EServiceInstance")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody("{}") + .withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + + String uri = e2eServInstancesUri + "v5/9b9f02c0-298b-458a-bc9c-be3692e4f35e/modeldifferences"; + ResponseEntity<String> response = sendRequest(inputStream("/CompareModelRequest.json"), uri, HttpMethod.POST); + + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); + assertTrue(realResponse.getServiceException().getText() + .contains("Request Failed due to BPEL error with HTTP Status")); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java index 1e4b99d4ff..5d0fb298d9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedCatalogDbConfig.java @@ -19,10 +19,10 @@ */ package org.onap.so.apihandlerinfra; + import ch.vorburger.exec.ManagedProcessException; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.jdbc.DataSourceBuilder; @@ -36,17 +36,14 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; - import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @Profile({"test"}) @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "entityManagerFactory", - basePackages = {"org.onap.so.db.catalog.data.repository"} - ) +@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory", + basePackages = {"org.onap.so.db.catalog.data.repository"}) public class EmbeddedCatalogDbConfig { @Bean @@ -54,49 +51,36 @@ public class EmbeddedCatalogDbConfig { return new MariaDB4jSpringService(); } - @Primary - @Bean(name = "dataSource") + @Primary + @Bean(name = "dataSource") DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, - @Value("${mariaDB4j.databaseName}") String databaseName, - @Value("${spring.datasource.username}") String datasourceUsername, - @Value("${spring.datasource.password}") String datasourcePassword, - @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { - //Create our database with default root user and no password + @Value("${mariaDB4j.databaseName}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + // Create our database with default root user and no password mariaDB4jSpringService.getDB().createDB(databaseName); DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); - return DataSourceBuilder - .create() - .username(datasourceUsername) - .password(datasourcePassword) - .url(config.getURL(databaseName)) - .driverClassName(datasourceDriver) - .build(); + return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword) + .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build(); } - - @Primary - @Bean(name = "entityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("dataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.catalog.beans") - .persistenceUnit("catalogDB") - .build(); - } - @Primary - @Bean(name = "transactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("entityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Primary + @Bean(name = "entityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("dataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.catalog.beans").persistenceUnit("catalogDB") + .build(); + } + + @Primary + @Bean(name = "transactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java index 00efb6b410..0ec06177c8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/EmbeddedRequestDbConfig.java @@ -19,10 +19,10 @@ */ package org.onap.so.apihandlerinfra; + import ch.vorburger.exec.ManagedProcessException; import ch.vorburger.mariadb4j.DBConfigurationBuilder; import ch.vorburger.mariadb4j.springframework.MariaDB4jSpringService; - import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.jdbc.DataSourceBuilder; @@ -37,17 +37,14 @@ import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; - import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; @Configuration @Profile({"test"}) @EnableTransactionManagement -@EnableJpaRepositories( - entityManagerFactoryRef = "requestEntityManagerFactory",transactionManagerRef = "requestTransactionManager", - basePackages = { "org.onap.so.db.request.data.repository" } - ) +@EnableJpaRepositories(entityManagerFactoryRef = "requestEntityManagerFactory", + transactionManagerRef = "requestTransactionManager", basePackages = {"org.onap.so.db.request.data.repository"}) public class EmbeddedRequestDbConfig { @Bean @@ -56,47 +53,34 @@ public class EmbeddedRequestDbConfig { } - @Bean(name = "requestDataSource") - @ConfigurationProperties(prefix = "request.datasource") + @Bean(name = "requestDataSource") + @ConfigurationProperties(prefix = "request.datasource") DataSource dataSource(MariaDB4jSpringService mariaDB4jSpringService, - @Value("${mariaDB4j.databaseName2}") String databaseName, - @Value("${spring.datasource.username}") String datasourceUsername, - @Value("${spring.datasource.password}") String datasourcePassword, - @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { - //Create our database with default root user and no password + @Value("${mariaDB4j.databaseName2}") String databaseName, + @Value("${spring.datasource.username}") String datasourceUsername, + @Value("${spring.datasource.password}") String datasourcePassword, + @Value("${spring.datasource.driver-class-name}") String datasourceDriver) throws ManagedProcessException { + // Create our database with default root user and no password mariaDB4jSpringService.getDB().createDB(databaseName); DBConfigurationBuilder config = mariaDB4jSpringService.getConfiguration(); - return DataSourceBuilder - .create() - .username(datasourceUsername) - .password(datasourcePassword) - .url(config.getURL(databaseName)) - .driverClassName(datasourceDriver) - .build(); + return DataSourceBuilder.create().username(datasourceUsername).password(datasourcePassword) + .url(config.getURL(databaseName)).driverClassName(datasourceDriver).build(); } - @Bean(name = "requestEntityManagerFactory") - public LocalContainerEntityManagerFactoryBean - entityManagerFactory( - EntityManagerFactoryBuilder builder, - @Qualifier("requestDataSource") DataSource dataSource - ) { - return builder - .dataSource(dataSource) - .packages("org.onap.so.db.request.beans") - .persistenceUnit("requestDB") - .build(); - } + @Bean(name = "requestEntityManagerFactory") + public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, + @Qualifier("requestDataSource") DataSource dataSource) { + return builder.dataSource(dataSource).packages("org.onap.so.db.request.beans").persistenceUnit("requestDB") + .build(); + } - @Bean(name = "requestTransactionManager") - public PlatformTransactionManager transactionManager( - @Qualifier("requestEntityManagerFactory") EntityManagerFactory - entityManagerFactory - ) { - return new JpaTransactionManager(entityManagerFactory); - } + @Bean(name = "requestTransactionManager") + public PlatformTransactionManager transactionManager( + @Qualifier("requestEntityManagerFactory") EntityManagerFactory entityManagerFactory) { + return new JpaTransactionManager(entityManagerFactory); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java index 45fadb540a..928b488f6a 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/GlobalHealthcheckHandlerTest.java @@ -25,18 +25,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; - import static org.mockito.ArgumentMatchers.anyObject; import static org.mockito.ArgumentMatchers.anyString; import java.net.URI; import java.util.Collections; import java.util.List; - import org.springframework.test.util.ReflectionTestUtils; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; - import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; @@ -62,175 +59,170 @@ public class GlobalHealthcheckHandlerTest { @Mock ContainerRequestContext requestContext; - + @InjectMocks @Spy - GlobalHealthcheckHandler globalhealth; - - @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - + GlobalHealthcheckHandler globalhealth; + + @Rule + public MockitoRule mockitoRule = MockitoJUnit.rule(); + + @Test + public void testQuerySubsystemHealthNullResult() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080"); + + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(null); + + String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN); + System.out.println(result); + assertEquals(HealthcheckStatus.DOWN.toString(), result); + } + + @Test + public void testQuerySubsystemHealthNotNullResult() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + subSystemResponse.setStatus("UP"); + ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r); + + String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC); + System.out.println(result); + assertEquals(HealthcheckStatus.UP.toString(), result); + } + + private Response globalHealthcheck(String status) { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); + ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); + ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); + + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + + subSystemResponse.setStatus(status); + ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), ArgumentMatchers.any(HttpMethod.class), + ArgumentMatchers.<HttpEntity<?>>any(), ArgumentMatchers.<Class<Object>>any())).thenReturn(r); + + Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890"); + Response response = globalhealth.globalHealthcheck(true, requestContext); + + return response; + } + + @Test + public void globalHealthcheckAllUPTest() throws JSONException { + Response response = globalHealthcheck("UP"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthcheckResponse root; + root = (HealthcheckResponse) response.getEntity(); + String apistatus = root.getApih(); + assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String bpmnstatus = root.getBpmn(); + assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String sdncstatus = root.getSdncAdapter(); + assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String asdcstatus = root.getAsdcController(); + assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String catastatus = root.getCatalogdbAdapter(); + assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String reqdbstatus = root.getRequestdbAdapter(); + assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String openstatus = root.getOpenstackAdapter(); + assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String reqdbattstatus = root.getRequestdbAdapterAttsvc(); + assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + } + + @Test + public void globalHealthcheckAllDOWNTest() throws JSONException { + Response response = globalHealthcheck("DOWN"); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + HealthcheckResponse root; + root = (HealthcheckResponse) response.getEntity(); + String apistatus = root.getApih(); + assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); + + String bpmnstatus = root.getBpmn(); + assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String sdncstatus = root.getSdncAdapter(); + assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String asdcstatus = root.getAsdcController(); + assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String catastatus = root.getCatalogdbAdapter(); + assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String reqdbstatus = root.getRequestdbAdapter(); + assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String openstatus = root.getOpenstackAdapter(); + assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + + String reqdbattstatus = root.getRequestdbAdapterAttsvc(); + assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); + } + @Test - public void testQuerySubsystemHealthNullResult(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8080"); - - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(null); - - String result = globalhealth.querySubsystemHealth(MsoSubsystems.BPMN); - System.out.println(result); - assertEquals(HealthcheckStatus.DOWN.toString(),result); + public void buildHttpEntityForRequestTest() { + HttpEntity<String> he = globalhealth.buildHttpEntityForRequest(); + assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getAccept().get(0)); + assertEquals(MediaType.APPLICATION_JSON, he.getHeaders().getContentType()); } - + @Test - public void testQuerySubsystemHealthNotNullResult(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - subSystemResponse.setStatus("UP"); - ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(r); - - String result = globalhealth.querySubsystemHealth(MsoSubsystems.ASDC); - System.out.println(result); - assertEquals(HealthcheckStatus.UP.toString(),result); + public void getEndpointUrlForSubsystemEnumTest() { + ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); + ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); + ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); + ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); + ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); + ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); + ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); + + String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC); + assertEquals("http://localhost:8080", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC); + assertEquals("http://localhost:8081", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN); + assertEquals("http://localhost:8082", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB); + assertEquals("http://localhost:8083", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK); + assertEquals("http://localhost:8084", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB); + assertEquals("http://localhost:8085", result); + result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT); + assertEquals("http://localhost:8086", result); } - - private Response globalHealthcheck (String status){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); - - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - - subSystemResponse.setStatus(status); - ResponseEntity<Object> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - Mockito.when(restTemplate.exchange(ArgumentMatchers.any(URI.class), - ArgumentMatchers.any(HttpMethod.class), - ArgumentMatchers.<HttpEntity<?>> any(), - ArgumentMatchers.<Class<Object>> any())).thenReturn(r); - - Mockito.when(requestContext.getProperty(anyString())).thenReturn("1234567890"); - Response response = globalhealth.globalHealthcheck(true, requestContext); - - return response; + + @Test + public void processResponseFromSubsystemTest() { + SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); + subSystemResponse.setStatus("UP"); + ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse, HttpStatus.OK); + String result = globalhealth.processResponseFromSubsystem(r, MsoSubsystems.BPMN); + assertEquals("UP", result); } - - @Test - public void globalHealthcheckAllUPTest() throws JSONException { - Response response = globalHealthcheck("UP"); - assertEquals(Response.Status.OK.getStatusCode(),response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - } - - @Test - public void globalHealthcheckAllDOWNTest() throws JSONException { - Response response = globalHealthcheck("DOWN"); - assertEquals(Response.Status.OK.getStatusCode(),response.getStatus()); - HealthcheckResponse root; - root = (HealthcheckResponse) response.getEntity(); - String apistatus = root.getApih(); - assertTrue(apistatus.equalsIgnoreCase(HealthcheckStatus.UP.toString())); - - String bpmnstatus = root.getBpmn(); - assertTrue(bpmnstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String sdncstatus = root.getSdncAdapter(); - assertTrue(sdncstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String asdcstatus = root.getAsdcController(); - assertTrue(asdcstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String catastatus = root.getCatalogdbAdapter(); - assertTrue(catastatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbstatus = root.getRequestdbAdapter(); - assertTrue(reqdbstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String openstatus = root.getOpenstackAdapter(); - assertTrue(openstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - - String reqdbattstatus = root.getRequestdbAdapterAttsvc(); - assertTrue(reqdbattstatus.equalsIgnoreCase(HealthcheckStatus.DOWN.toString())); - } - - @Test - public void buildHttpEntityForRequestTest(){ - HttpEntity<String> he = globalhealth.buildHttpEntityForRequest(); - assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getAccept().get(0)); - assertEquals (MediaType.APPLICATION_JSON,he.getHeaders().getContentType()); - } - - @Test - public void getEndpointUrlForSubsystemEnumTest(){ - ReflectionTestUtils.setField(globalhealth, "actuatorContextPath", "/manage"); - ReflectionTestUtils.setField(globalhealth, "endpointAsdc", "http://localhost:8080"); - ReflectionTestUtils.setField(globalhealth, "endpointSdnc", "http://localhost:8081"); - ReflectionTestUtils.setField(globalhealth, "endpointBpmn", "http://localhost:8082"); - ReflectionTestUtils.setField(globalhealth, "endpointCatalogdb", "http://localhost:8083"); - ReflectionTestUtils.setField(globalhealth, "endpointOpenstack", "http://localhost:8084"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdb", "http://localhost:8085"); - ReflectionTestUtils.setField(globalhealth, "endpointRequestdbAttsvc", "http://localhost:8086"); - - String result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.ASDC); - assertEquals("http://localhost:8080", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.SDNC); - assertEquals("http://localhost:8081", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.BPMN); - assertEquals("http://localhost:8082", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.CATALOGDB); - assertEquals("http://localhost:8083", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.OPENSTACK); - assertEquals("http://localhost:8084", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDB); - assertEquals("http://localhost:8085", result); - result = globalhealth.getEndpointUrlForSubsystemEnum(MsoSubsystems.REQUESTDBATT); - assertEquals("http://localhost:8086", result); - } - - @Test - public void processResponseFromSubsystemTest(){ - SubsystemHealthcheckResponse subSystemResponse = new SubsystemHealthcheckResponse(); - subSystemResponse.setStatus("UP"); - ResponseEntity<SubsystemHealthcheckResponse> r = new ResponseEntity<>(subSystemResponse,HttpStatus.OK); - String result = globalhealth.processResponseFromSubsystem(r,MsoSubsystems.BPMN); - assertEquals("UP",result); - } - -}
\ No newline at end of file + +} 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 new file mode 100644 index 0000000000..9fc9e4a51b --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/InstanceManagementTest.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 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.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.MdcConstants.CLIENT_ID; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.serviceinstancebeans.RequestReferences; +import org.onap.so.serviceinstancebeans.ServiceInstancesResponse; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +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.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class InstanceManagementTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); + + @Value("${wiremock.server.port}") + private String wiremockPort; + + private final String instanceManagementUri = "/onap/so/infra/instanceManagement/"; + + private String uri; + private URL selfLink; + private URL initialUrl; + private int initialPort; + private HttpHeaders headers; + + @Before + public void beforeClass() { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + // set headers + headers = new HttpHeaders(); + headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); + headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(CLIENT_ID, "VID"); + headers.set(REQUESTOR_ID, "xxxxxx"); + try { // generate one-time port number to avoid RANDOM port number later. + initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); + initialPort = initialUrl.getPort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + } + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + private URL createExpectedSelfLink(String version, String requestId) { + System.out.println("createdUrl: " + initialUrl.toString()); + try { + selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId)); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return selfLink; + } + + private String getWiremockResponseForCatalogdb(String file) { + try { + File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file); + return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090", + "localhost:" + wiremockPort); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, + HttpHeaders headers) { + + if (!headers.containsKey(HttpHeaders.ACCEPT)) { + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + } + if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + } + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort)); + + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); + } + + @Test + public void executeCustomWorkflow() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/testingWorkflow")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/workflow/search/findByArtifactUUID[?]artifactUUID=71526781-e55c-4cb7-adb3-97e09d9c76be")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("workflow_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response + ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); + RequestReferences requestReferences = new RequestReferences(); + requestReferences.setInstanceId("1882939"); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v1", "32807a28-1a14-4b88-b7b3-2950918aa76d")); + expectedResponse.setRequestReferences(requestReferences); + uri = instanceManagementUri + "v1" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/workflows/71526781-e55c-4cb7-adb3-97e09d9c76be"; + ResponseEntity<String> response = + sendRequest(inputStream("/ExecuteCustomWorkflow.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/ManualTasksTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java index 1943b42404..ad0a878931 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ManualTasksTest.java @@ -22,12 +22,11 @@ package org.onap.so.apihandlerinfra; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static org.onap.so.logger.MdcConstants.ECOMP_REQUEST_ID; import static org.onap.so.logger.MdcConstants.ENDTIME; @@ -38,13 +37,10 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; import static org.onap.so.logger.MdcConstants.CLIENT_ID; - import java.io.IOException; import java.util.Map; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; @@ -60,22 +56,20 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class ManualTasksTest extends BaseTest{ +public class ManualTasksTest extends BaseTest { private final String basePath = "/tasks/v1/"; @Test public void testCreateOpEnvObjectMapperError() throws IOException { TestAppender.events.clear(); - stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")) + wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")) .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_OK))); String taskId = "55"; @@ -83,14 +77,14 @@ public class ManualTasksTest extends BaseTest{ RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); reqInfo.setRequestorId("testId"); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); - //expected response + // expected response TaskRequestReference expectedResponse = new TaskRequestReference(); - expectedResponse.setTaskId(taskId); + expectedResponse.setTaskId(taskId); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -98,10 +92,10 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); @@ -111,32 +105,31 @@ public class ManualTasksTest extends BaseTest{ TaskRequestReference realResponse = mapper.readValue(response.getBody(), TaskRequestReference.class); - //then - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - assertThat(realResponse, sameBeanAs(expectedResponse)); - - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + // then + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + assertThat(realResponse, sameBeanAs(expectedResponse)); + + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS",mdc.get(STATUSCODE)); - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); + assertEquals("INPROGRESS", mdc.get(STATUSCODE)); + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ENDTIME)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202",mdc.get(RESPONSECODE)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("tasks/v1/55/complete",mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE",mdc.get(STATUSCODE)); + assertEquals("202", mdc.get(RESPONSECODE)); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("tasks/v1/55/complete", mdc.get(SERVICE_NAME)); + assertEquals("COMPLETE", mdc.get(STATUSCODE)); assertNotNull(mdc.get(RESPONSEDESC)); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); @@ -144,6 +137,7 @@ public class ManualTasksTest extends BaseTest{ assertEquals("1.0.0", response.getHeaders().get("X-LatestVersion").get(0)); } } + @Test public void completeTaskMappingError() throws IOException { String invalidRequest = "test"; @@ -151,9 +145,9 @@ public class ManualTasksTest extends BaseTest{ ServiceException se = new ServiceException(); se.setMessageId("SVC0002"); se.setText("Mapping of request to JSON object failed: Unrecognized token \'test\': " - + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]"); + + "was expecting \'null\', \'true\', \'false\' or NaN\n at [Source: (String)\"test\"; line: 1, column: 9]"); expectedResponse.setServiceException(se); - + HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -161,26 +155,27 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<String> entity = new HttpEntity<String>(invalidRequest, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + "55" + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - + RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } + @Test public void completeTaskValidationError() throws IOException { String taskId = "55"; TasksRequest taskReq = new TasksRequest(); RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); @@ -197,30 +192,31 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } + @Test public void completeTaskBpelResponseError() throws IOException { - stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE))); + wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task/55/complete")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withFault(Fault.EMPTY_RESPONSE))); String taskId = "55"; TasksRequest taskReq = new TasksRequest(); RequestDetails reqDetail = new RequestDetails(); RequestInfo reqInfo = new RequestInfo(); reqInfo.setRequestorId("testId"); - reqInfo.setSource("testSource"); + reqInfo.setSource("testSource"); reqInfo.setResponseValue(ValidResponses.skip); reqDetail.setRequestInfo(reqInfo); taskReq.setRequestDetails(reqDetail); @@ -237,10 +233,10 @@ public class ManualTasksTest extends BaseTest{ headers.set(CLIENT_ID, "VID"); HttpEntity<TasksRequest> entity = new HttpEntity<TasksRequest>(taskReq, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath) + taskId + "/complete"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); ObjectMapper mapper = new ObjectMapper(); @@ -248,7 +244,7 @@ public class ManualTasksTest extends BaseTest{ mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); RequestError realResponse = mapper.readValue(response.getBody(), RequestError.class); - assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); assertThat(realResponse, sameBeanAs(expectedResponse)); } } 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 ee98accfdc..c30b9dedf2 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,7 +22,6 @@ package org.onap.so.apihandlerinfra; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.io.IOException; import java.io.StringReader; import java.net.URL; @@ -32,12 +31,10 @@ import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Optional; - import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; - import org.apache.http.HttpStatus; import org.junit.ClassRule; import org.junit.Rule; @@ -49,11 +46,9 @@ import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; import org.springframework.test.context.junit4.rules.SpringClassRule; import org.springframework.test.context.junit4.rules.SpringMethodRule; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; - import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.w3c.dom.Document; @@ -61,442 +56,977 @@ import org.xml.sax.InputSource; @RunWith(JUnitParamsRunner.class) public class MsoRequestTest extends BaseTest { - private ObjectMapper mapper = new ObjectMapper(); - private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>(); - private ServiceInstancesRequest sir; - private MsoRequest msoRequest; - private Action action; - private String version; - private int reqVersion; - private String originalRequestJSON; - private String requestJSON; - private boolean expected; - private String expectedException; - - @ClassRule + private ObjectMapper mapper = new ObjectMapper(); + private HashMap<String, String> instanceIdMapTest = new HashMap<String, String>(); + private ServiceInstancesRequest sir; + private MsoRequest msoRequest; + private Action action; + private String version; + private int reqVersion; + private String originalRequestJSON; + private String requestJSON; + private boolean expected; + private String expectedException; + + @ClassRule public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule(); @Rule public final SpringMethodRule springMethodRule = new SpringMethodRule(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public String inputStream(String JsonInput)throws IOException{ - JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; - String input = new String(Files.readAllBytes(Paths.get(JsonInput))); - return input; - } - //Tests for successful validation of incoming JSON requests through the parse method - @Test - @Parameters(method = "successParameters") - public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) throws ValidationException, IOException{ - this.sir = sir; - this.instanceIdMapTest = instanceIdMapTest; - this.action = action; - this.reqVersion = reqVersion; - this.version = "v" + reqVersion; - this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Parameters - private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException{ - return Arrays.asList(new Object[][]{ - {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, - {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, - {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "3"}, - {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"}, - {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"}, - {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "6"}, - {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, - {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"}, - {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "5"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, - {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"} - }); - } - @Test - @Parameters(method = "aLaCarteParameters") - public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) throws JsonParseException, IOException, ValidationException{ - this.expected = expected; - this.sir = sir; - this.msoRequest = new MsoRequest(); - assertEquals(expected, msoRequest.getAlacarteFlag(sir)); - } - @Parameters - private Collection<Object[]> aLaCarteParameters() throws IOException{ - return Arrays.asList(new Object[][] { - {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class)}, - {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"), ServiceInstancesRequest.class)} - }); - } - //Tests various scenarios ensuring that requests containing missing or invalid information will throw a ValidationException - @Test - @Parameters(method = "validationParameters") - public void validationFailureTest(String expectedException, ServiceInstancesRequest sir, HashMap<String,String> instanceIdMapTest, Action action, int reqVersion) throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.expectedException = expectedException; - this.sir = sir; - this.instanceIdMapTest = instanceIdMapTest; - this.action = action; - this.reqVersion = reqVersion; - this.version = "v" + reqVersion; - this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); - thrown.expect(ValidationException.class); - thrown.expectMessage(expectedException); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Parameters - private Collection<Object[]> validationParameters() throws IOException{ - return Arrays.asList(new Object[][] { - //ValidationException for CloudConfiguration - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateAndCloudDelete, 7}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid cloudConfiguration is specified", mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid lcpCloudRegionId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid tenantId is specified", mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - //ValidationException for ModelInfo - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 4}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 6}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 6}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, 5}, - {"No valid modelCustomizationId or modelCustomizationName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelCustomizationId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid model-info is specified", mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId format is specified", mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 3}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 5}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelInvariantId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 4}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelName is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelType is specified", mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelVersion is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 4}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, 4}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.recreateInstance, 7}, - {"No valid modelVersionId is specified", mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - //ValidationException for Platform and LineOfBusiness - {"No valid lineOfBusinessName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid platform is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6}, - {"No valid platformName is specified", mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - //ValidationException for Project and OwningEntity - {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 6}, - {"No valid owningEntityId is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid projectName is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid owningEntity is specified", mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //ValidationException for RelatedInstances - {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 5}, - {"No valid connectionPoint relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid destination vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceName format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 6}, - {"No valid instanceName in relatedInstance for pnf modelType is specified", mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 6}, - {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid modelInfo in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId format in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelInvariantId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelName in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersion in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeRelationships, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, 2}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 4}, - {"No valid related instances is specified", mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid related service instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related service instance for vnf request is specified", mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related service instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related vnf instance for vfModule request is specified", mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid related vnf instance for volumeGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, 6}, - {"No valid source vnf relatedInstance for Port Configuration is specified", mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified", mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, 5}, - {"No valid instanceName format is specified", mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 2}, - {"No valid relatedInstanceList is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - {"No valid related service instance for instanceGroup request is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - {"No valid modelVersionId in relatedInstance is specified", mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 7}, - //ValidationException for RequestInfo - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, 3}, - {"No valid productFamilyId is specified", mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - //ValidationException for RequestParameters - {"No valid aLaCarte in requestParameters", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, 4}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, 6}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, - {"No valid requestParameters is specified", mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //ValidationException for SubscriberInfo - {"No valid globalSubscriberId is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriptionServiceType is specified", mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, 5}, - {"No valid subscriberInfo is specified", mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //Validation for UserParams - {"No valid cloudConfiguration in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid cloudConfiguration in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams service modelInfo is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelVersionId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid platform in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid platformName in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid productFamilyId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid vfModules in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModules.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams vfModules resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelInfo in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams vfModule resources is specified", mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams vnf resources is specified", mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - {"No valid modelCustomizationId in userParams network resources is specified", mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, 7}, - //Validation for ConfigurationParameters - {"No valid configuration parameters is specified", mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.scaleOut, 7}, - //Validation for Add and Remove Members - {"No valid vnf relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid related instances is specified", mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid requestInfo is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid requestorId is specified", mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid source is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid instanceId in relatedInstances is specified", mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.addMembers, 7}, - {"No valid modelType in relatedInstance is specified", mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"), ServiceInstancesRequest.class), instanceIdMapTest, Action.removeMembers, 7} - }); - } - @Test - public void nullInstanceIdMapTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest = null; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(NullPointerException.class); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - - @Test - public void serviceInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void vnfInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("vnfInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid vnfInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void vfModuleInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("vfModuleInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid vfModuleInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void volumeGroupInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("volumeGroupInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid volumeGroupInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void networkInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("networkInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid networkInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void configurationInstanceIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("configurationInstanceId", "test"); - this.action = Action.createInstance; - thrown.expect(ValidationException.class); - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expectMessage("No valid configurationInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void instanceGroupIdHashMapFailureTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("instanceGroupInstanceId", "test"); - this.action = Action.createInstance; - thrown.expect(ValidationException.class); - this.reqVersion = 7; - this.version = "v" + reqVersion; - thrown.expectMessage("No valid instanceGroupInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - } - @Test - public void testVfModuleV4UsePreLoad() throws JsonParseException, JsonMappingException, IOException, ValidationException { - this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json"); - this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.reqVersion = 4; - this.version = "v" + reqVersion; - this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); - this.msoRequest = new MsoRequest (); - msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false); - - this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json"); - this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); - this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); - msoRequest = new MsoRequest (); - msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, false); - } - @Test - public void buildServiceErrorResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.ServiceException, "Mapping of request to JSON object failed. ", - ErrorNumbers.SVC_BAD_PARAMETER, null, version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/MsoRequestTest" + JsonInput; + String input = new String(Files.readAllBytes(Paths.get(JsonInput))); + return input; + } + + // Tests for successful validation of incoming JSON requests through the parse method + @Test + @Parameters(method = "successParameters") + public void successTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, Action action, + int reqVersion) throws ValidationException, IOException { + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vfModuleInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("volumeGroupInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("networkInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("configurationInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> successParameters() throws JsonParseException, JsonMappingException, IOException { + return Arrays.asList(new Object[][] { + {mapper.readValue(inputStream("/CloudConfiguration/EmptyCloudConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, + {mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityName.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, + {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/OptionalLineOfBusiness.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/ProjectAndOwningEntity/OptionalProject.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/PlatformAndLineOfBusiness/PlatformTest.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, "3"}, + {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdFlag.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyIdUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ModelCustomizationIdUsingPreload.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfigurationDelete.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "4"}, + {mapper.readValue(inputStream("/ModelInfo/ModelVersionNetwork.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdEmpty.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationNameNull.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationTest.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnActivate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "2"}, + {mapper.readValue(inputStream("/ModelInfo/ServiceModelNameEmptyOnDelete.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "2"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "4"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/ModelInfo/ValidModelCustomizationIdService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.replaceInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstances.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVfModule.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceInPlaceSoftwareUpdate.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.applyUpdatedConfig, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableService.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/VnfActivate.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, "6"}, + {mapper.readValue(inputStream("/RequestParameters/VnfRequestParameters.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v3DeleteNetwork.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deleteInstance, "3"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v3UpdateNetwork.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.updateInstance, "3"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5CreateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v6CreateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.createInstance, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.enablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5EnableConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.disablePort, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5ActivateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/v5ActivateNoRelatedInstance.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.activateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v5DeactivateConfiguration.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, + {mapper.readValue(inputStream("/RelatedInstances/v5DeactivateNoRelatedInstance.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.deactivateInstance, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/v6AddRelationships.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.addRelationships, "6"}, + {mapper.readValue(inputStream("/SuccessfulValidation/UserParams.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, "5"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceAssign.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.assignInstance, "7"}, + {mapper.readValue(inputStream("/SuccessfulValidation/ServiceUnassign.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.unassignInstance, "7"}}); + } + + @Test + @Parameters(method = "customWorkflowSuccessParameters") + public void customWorkflowSuccessTest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMapTest, + Action action, int reqVersion) throws ValidationException, IOException { + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("workflowUuid", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> customWorkflowSuccessParameters() + throws JsonParseException, JsonMappingException, IOException { + return Arrays.asList( + new Object[][] {{mapper.readValue(inputStream("/SuccessfulValidation/v1ExecuteCustomWorkflow.json"), + ServiceInstancesRequest.class), instanceIdMapTest, Action.inPlaceSoftwareUpdate, "1"} + + }); + } + + @Test + @Parameters(method = "aLaCarteParameters") + public void aLaCarteFlagTest(boolean expected, ServiceInstancesRequest sir) + throws JsonParseException, IOException, ValidationException { + this.expected = expected; + this.sir = sir; + this.msoRequest = new MsoRequest(); + assertEquals(expected, msoRequest.getAlacarteFlag(sir)); + } + + @Parameters + private Collection<Object[]> aLaCarteParameters() throws IOException { + return Arrays.asList(new Object[][] { + {false, mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class)}, + {true, mapper.readValue(inputStream("/RequestParameters/RequestParametersALaCarteTrue.json"), + ServiceInstancesRequest.class)}}); + } + + // Tests various scenarios ensuring that requests containing missing or invalid information will throw a + // ValidationException + @Test + @Parameters(method = "validationParameters") + public void validationFailureTest(String expectedException, ServiceInstancesRequest sir, + HashMap<String, String> instanceIdMapTest, Action action, int reqVersion) + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.expectedException = expectedException; + this.sir = sir; + this.instanceIdMapTest = instanceIdMapTest; + this.action = action; + this.reqVersion = reqVersion; + this.version = "v" + reqVersion; + this.instanceIdMapTest.put("serviceInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("vnfInstanceId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + this.instanceIdMapTest.put("instanceGroupId", "ff305d54-75b4-431b-adb2-eb6b9e5ff000"); + thrown.expect(ValidationException.class); + thrown.expectMessage(expectedException); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Parameters + private Collection<Object[]> validationParameters() throws IOException { + return Arrays.asList(new Object[][] { + // ValidationException for CloudConfiguration + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 4}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/CloudConfigurationConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid cloudConfiguration is specified", + mapper.readValue( + inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid cloudConfiguration is specified", + mapper.readValue( + inputStream("/CloudConfiguration/DeactivateAndCloudDeleteCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateAndCloudDelete, 7}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/ScaleOutNoCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid cloudConfiguration is specified", + mapper.readValue(inputStream("/CloudConfiguration/VnfRecreateCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid lcpCloudRegionId is specified", + mapper.readValue(inputStream("/CloudConfiguration/EmptyLcpCloudConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid lcpCloudRegionId is specified", + mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateCloudRegionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid tenantId is specified", + mapper.readValue(inputStream("/CloudConfiguration/EmptyTenantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid tenantId is specified", + mapper.readValue(inputStream("/CloudConfiguration/InPlaceSoftwareUpdateTenantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + // ValidationException for ModelInfo + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/v5CreateConfigurationModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/v4CreateVfModuleMissingModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 4}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationIdPreload.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomizationName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 6}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/ModelCustomization.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 6}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.replaceInstance, 5}, + {"No valid modelCustomizationId or modelCustomizationName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateNoModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelCustomizationId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid model-info is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInfoNull.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId format is specified", + mapper.readValue(inputStream("/ModelInfo/InvalidModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 2}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 4}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdNetwork.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ModelInvariantIdDisablePort.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelInvariantIdConfiguration.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 3}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v5DeactivateModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 5}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/v3UpdateNetworkBad.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 4}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelInvariantId is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/VfModuleModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, 4}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelName is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelType is specified", + mapper.readValue(inputStream("/ModelInfo/ModelTypeNull.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionVfModule.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionServiceCreate.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelVersion is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ConfigurationModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 4}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deactivateInstance, 4}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v2ModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ModelVersionIdCreate.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/v5ActivateModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/ScaleOutNoModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/VnfRecreateModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.recreateInstance, 7}, + {"No valid modelVersionId is specified", + mapper.readValue(inputStream("/ModelInfo/CreateInstanceGroupNoModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + // ValidationException for Platform and LineOfBusiness + {"No valid lineOfBusinessName is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyLineOfBusiness.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid platform is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/Platform.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 6}, + {"No valid platformName is specified", + mapper.readValue(inputStream("/PlatformAndLineOfBusiness/EmptyPlatformName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + // ValidationException for Project and OwningEntity + {"No valid owningEntity is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/OwningEntity.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 6}, + {"No valid owningEntityId is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyOwningEntityId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid projectName is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/EmptyProjectName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid owningEntity is specified", + mapper.readValue(inputStream("/ProjectAndOwningEntity/ServiceAssignNoOE.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // ValidationException for RelatedInstances + {"No valid connectionPoint relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 5}, + {"No valid connectionPoint relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoConnectionPoint.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid destination vnf relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoDestinationRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceId format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesIdFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceName format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesNameFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid instanceName in relatedInstance for pnf modelType is specified", + mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeRelationships, 6}, + {"No valid instanceName in relatedInstance for pnf modelType is specified", + mapper.readValue(inputStream("/RelatedInstances/v6AddRelationshipsInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 6}, + {"No valid modelCustomizationName or modelCustomizationId in relatedInstance of vnf is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid modelInfo in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId format in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantIdFormat.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelInvariantId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelInvariantId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelName in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersion in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersion.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid modelVersionId in relatedInstance is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ServiceNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeRelationships, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.disablePort, 2}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5EnablePortNoRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.enablePort, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/v4RelatedInstancesNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 4}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/RelatedInstances/ScaleOutNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid related service instance for vfModule request is specified", + mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related service instance for vnf request is specified", + mapper.readValue(inputStream("/RelatedInstances/VnfRelatedInstancesService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related service instance for volumeGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesServiceInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related vnf instance for vfModule request is specified", + mapper.readValue(inputStream("/RelatedInstances/VfModuleRelatedInstancesVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid related vnf instance for volumeGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid serviceInstanceId matching the serviceInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/v6VnfDeleteInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.deleteInstance, 6}, + {"No valid source vnf relatedInstance for Port Configuration is specified", + mapper.readValue(inputStream("/RelatedInstances/v5CreateNoSourceRelatedInstance.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid vnfInstanceId matching the vnfInstanceId in request URI is specified", + mapper.readValue(inputStream("/RelatedInstances/RelatedInstancesVnfInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.activateInstance, 5}, + {"No valid instanceName format is specified", + mapper.readValue(inputStream("/RelatedInstances/InvalidInstanceName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 2}, + {"No valid relatedInstanceList is specified", + mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupNoRelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid related service instance for instanceGroup request is specified", + mapper.readValue(inputStream("/RelatedInstances/CreateInstanceGroupService.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + {"No valid modelVersionId in relatedInstance is specified", + mapper.readValue( + inputStream("/RelatedInstances/CreateInstanceGroupRelatedInstanceModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 7}, + // ValidationException for RequestInfo + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfoNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/RequestInfo.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/RequestInfo/ScaleOutNoRequestInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/VnfProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/NetworkProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.updateInstance, 3}, + {"No valid productFamilyId is specified", + mapper.readValue(inputStream("/RequestInfo/ServiceProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/EmptyRequestorId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/RequestInfo/RequestorId.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + // ValidationException for RequestParameters + {"No valid aLaCarte in requestParameters", + mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addRelationships, 4}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.applyUpdatedConfig, 6}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/RequestParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.inPlaceSoftwareUpdate, 6}, + {"No valid requestParameters is specified", + mapper.readValue(inputStream("/RequestParameters/AssignEmptyReqParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // ValidationException for SubscriberInfo + {"No valid globalSubscriberId is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptyGlobalSubscriberId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriberInfo is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriberInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriptionServiceType is specified", + mapper.readValue(inputStream("/SubscriberInfo/EmptySubscriptionServiceType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.createInstance, 5}, + {"No valid subscriberInfo is specified", + mapper.readValue(inputStream("/SubscriberInfo/AssignEmptySubscriberInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // Validation for UserParams + {"No valid cloudConfiguration in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/AssignCloudConfigVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid cloudConfiguration in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkCloudConfig.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsVnfModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams service modelInfo is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VnfModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams vfModule resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModuleModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelVersionId in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkModelVersionId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid platform in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsPlatform.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid platformName in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/UserParamsPlatformName.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid productFamilyId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/ProductFamilyId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid vfModules in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModules.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams vfModules resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModulesModelInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelInfo in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/Network.json"), ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams vfModule resources is specified", + mapper.readValue(inputStream("/RequestParameters/VfModuleModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams vnf resources is specified", + mapper.readValue(inputStream("/RequestParameters/VnfModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + {"No valid modelCustomizationId in userParams network resources is specified", + mapper.readValue(inputStream("/RequestParameters/NetworkModelCustomizationId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.assignInstance, 7}, + // Validation for ConfigurationParameters + {"No valid configuration parameters is specified", + mapper.readValue(inputStream("/ConfigurationParameters/NoConfigurationParameters.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.scaleOut, 7}, + // Validation for Add and Remove Members + {"No valid vnf relatedInstance is specified", + mapper.readValue(inputStream("/MembersValidation/RelatedInstancesVnf.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid related instances is specified", + mapper.readValue(inputStream("/MembersValidation/RelatedInstances.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid requestInfo is specified", + mapper.readValue(inputStream("/MembersValidation/MembersRequestInfo.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid requestorId is specified", + mapper.readValue(inputStream("/MembersValidation/MembersRequestorId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid source is specified", + mapper.readValue(inputStream("/MembersValidation/AddMembersSource.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid instanceId in relatedInstances is specified", + mapper.readValue(inputStream("/MembersValidation/AddMembersInstanceId.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.addMembers, 7}, + {"No valid modelType in relatedInstance is specified", + mapper.readValue(inputStream("/MembersValidation/DeleteMembersModelType.json"), + ServiceInstancesRequest.class), + instanceIdMapTest, Action.removeMembers, 7}}); + } + + @Test + public void nullInstanceIdMapTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/RequestParameters/RequestParametersNull.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest = null; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(NullPointerException.class); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void serviceInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void vnfInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("vnfInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid vnfInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void vfModuleInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("vfModuleInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid vfModuleInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void volumeGroupInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("volumeGroupInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid volumeGroupInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void networkInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("networkInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid networkInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void configurationInstanceIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("configurationInstanceId", "test"); + this.action = Action.createInstance; + thrown.expect(ValidationException.class); + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expectMessage("No valid configurationInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void instanceGroupIdHashMapFailureTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("instanceGroupInstanceId", "test"); + this.action = Action.createInstance; + thrown.expect(ValidationException.class); + this.reqVersion = 7; + this.version = "v" + reqVersion; + thrown.expectMessage("No valid instanceGroupInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + } + + @Test + public void testVfModuleV4UsePreLoad() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.requestJSON = inputStream("/SuccessfulValidation/v4CreateVfModule.json"); + this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.reqVersion = 4; + this.version = "v" + reqVersion; + this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); + this.msoRequest = new MsoRequest(); + msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, + false); + + this.requestJSON = inputStream("/ModelInfo/v4CreateVfModuleNoCustomizationId.json"); + this.instanceIdMapTest.put("serviceInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.instanceIdMapTest.put("vnfInstanceId", "3eecada1-83a4-4f33-9ed2-7937e7b8dbbc"); + this.sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class); + msoRequest = new MsoRequest(); + msoRequest.parse(sir, instanceIdMapTest, Action.createInstance, version, originalRequestJSON, reqVersion, + false); + } + + @Test + public void buildServiceErrorResponseTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException, + "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version); 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("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } - @Test - public void buildServiceErrorPolicyExceptionResponseTest() throws JsonParseException, JsonMappingException, IOException, ValidationException{ - this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), ServiceInstancesRequest.class); - this.instanceIdMapTest.put("serviceInstanceId", "test"); - this.action = Action.createInstance; - this.reqVersion = 5; - this.version = "v" + reqVersion; - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid serviceInstanceId is specified"); - this.msoRequest = new MsoRequest(); - - - this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); - Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, - MsoException.PolicyException, "Mapping of request to JSON object failed. ", - ErrorNumbers.SVC_BAD_PARAMETER, null, version); + } + + @Test + public void buildServiceErrorPolicyExceptionResponseTest() + throws JsonParseException, JsonMappingException, IOException, ValidationException { + this.sir = mapper.readValue(inputStream("/SuccessfulValidation/InstanceIdHashMap.json"), + ServiceInstancesRequest.class); + this.instanceIdMapTest.put("serviceInstanceId", "test"); + this.action = Action.createInstance; + this.reqVersion = 5; + this.version = "v" + reqVersion; + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid serviceInstanceId is specified"); + this.msoRequest = new MsoRequest(); + + + this.msoRequest.parse(sir, instanceIdMapTest, action, version, originalRequestJSON, reqVersion, false); + Response response = + msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.PolicyException, + "Mapping of request to JSON object failed. ", ErrorNumbers.SVC_BAD_PARAMETER, null, version); 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("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); - } + } @Test public void domToStrTest() throws Exception { @@ -510,17 +1040,18 @@ public class MsoRequestTest extends BaseTest { @Test public void buildSelfLinkUrlTest() throws Exception { - // v - version - String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; - String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1"; - this.msoRequest = new MsoRequest(); - Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId); - assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); - // V - Version - String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; - String expectedSelfLinkV = "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; - Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId); - assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString()); - } -}
\ No newline at end of file + // v - version + String incomingUrl = "http://localhost:8080/onap/infra/so/serviceInstantiation/v7/serviceInstances"; + String expectedSelfLink = "http://localhost:8080/orchestrationRequests/v7/efce3167-5e45-4666-9d4d-22e23648e5d1"; + String requestId = "efce3167-5e45-4666-9d4d-22e23648e5d1"; + this.msoRequest = new MsoRequest(); + Optional<URL> actualSelfLinkUrl = msoRequest.buildSelfLinkUrl(incomingUrl, requestId); + assertEquals(expectedSelfLink, actualSelfLinkUrl.get().toString()); + // V - Version + String incomingUrlV = "http://localhost:8080/onap/infra/so/serviceInstantiation/V7/serviceInstances"; + String expectedSelfLinkV = + "http://localhost:8080/orchestrationRequests/V7/efce3167-5e45-4666-9d4d-22e23648e5d1"; + Optional<URL> actualSelfLinkUrlV = msoRequest.buildSelfLinkUrl(incomingUrlV, requestId); + assertEquals(expectedSelfLinkV, actualSelfLinkUrlV.get().toString()); + } +} 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 28797d247b..321ea3ac7d 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 @@ -26,13 +26,11 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.equalToJson; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -41,10 +39,8 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; 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; @@ -64,7 +60,6 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -74,8 +69,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class OrchestrationRequestsTest extends BaseTest { @Autowired private RequestsDbClient requestsDbClient; - - @Autowired + + @Autowired private OrchestrationRequests orchReq; private static final GetOrchestrationListResponse ORCHESTRATION_LIST = generateOrchestrationList(); @@ -114,13 +109,12 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + 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)); @@ -128,7 +122,7 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("00032ab7-na18-42e5-965d-8ea592502018", response.getHeaders().get("X-TransactionID").get(0)); assertNotNull(response.getBody().getRequest().getFinishTime()); } - + @Test public void testGetOrchestrationRequestInstanceGroup() throws Exception { setupTestGetOrchestrationRequestInstanceGroup(); @@ -146,19 +140,18 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("request.startTime") + .ignoring("request.finishTime").ignoring("request.requestStatus.timeStamp")); } @Test public void testGetOrchestrationRequestRequestDetails() throws Exception { setupTestGetOrchestrationRequestRequestDetails("00032ab7-3fb3-42e5-965d-8ea592502017", "COMPLETED"); - //Test request with modelInfo request body + // Test request with modelInfo request body GetOrchestrationResponse testResponse = new GetOrchestrationResponse(); Request request = ORCHESTRATION_LIST.getRequestList().get(0).getRequest(); @@ -173,13 +166,12 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + testRequestId)); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("request.startTime").ignoring("request.finishTime") - .ignoring("request.requestStatus.timeStamp")); + 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)); @@ -189,12 +181,12 @@ public class OrchestrationRequestsTest extends BaseTest { @Test public void testGetOrchestrationRequestNoRequestID() { - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", "application/json; charset=UTF-8"); - headers.set("Content-Type", "application/json; charset=UTF-8"); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", "application/json; charset=UTF-8"); + headers.set("Content-Type", "application/json; charset=UTF-8"); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/")); + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6/")); ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationListResponse.class); @@ -207,10 +199,11 @@ public class OrchestrationRequestsTest extends BaseTest { List<String> values = new ArrayList<>(); values.add("EQUALS"); values.add("vfModule"); - + ObjectMapper mapper = new ObjectMapper(); - GetOrchestrationListResponse testResponse = mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"), - GetOrchestrationListResponse.class); + GetOrchestrationListResponse testResponse = + mapper.readValue(new File("src/test/resources/OrchestrationRequest/OrchestrationFilterResponse.json"), + GetOrchestrationListResponse.class); Map<String, List<String>> orchestrationMap = new HashMap<>(); orchestrationMap.put("modelType", values); @@ -220,18 +213,17 @@ public class OrchestrationRequestsTest extends BaseTest { HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); HttpEntity<Request> entity = new HttpEntity<Request>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder - .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule")); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort("/onap/so/infra/orchestrationRequests/v6?filter=modelType:EQUALS:vfModule")); ResponseEntity<GetOrchestrationListResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationListResponse.class); - assertThat(response.getBody(), - sameBeanAs(testResponse).ignoring("requestList.request.startTime").ignoring("requestList.request.finishTime") - .ignoring("requestList.request.requestStatus.timeStamp")); + assertThat(response.getBody(), sameBeanAs(testResponse).ignoring("requestList.request.startTime") + .ignoring("requestList.request.finishTime").ignoring("requestList.request.requestStatus.timeStamp")); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals(requests.size(), response.getBody().getRequestList().size()); - + } @Test @@ -239,7 +231,8 @@ public class OrchestrationRequestsTest extends BaseTest { setupTestUnlockOrchestrationRequest("0017f68c-eb2d-45bb-b7c7-ec31b37dc349", "UNLOCKED"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -255,11 +248,12 @@ public class OrchestrationRequestsTest extends BaseTest { expectedRequestError = new RequestError(); se = new ServiceException(); se.setMessageId(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); - se.setText("Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked"); + se.setText( + "Orchestration RequestId 0017f68c-eb2d-45bb-b7c7-ec31b37dc349 has a status of UNLOCKED and can not be unlocked"); expectedRequestError.setServiceException(se); - builder = UriComponentsBuilder.fromHttpUrl( - createURLWithPort("/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock")); + builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/onap/so/infra/orchestrationRequests/v6/0017f68c-eb2d-45bb-b7c7-ec31b37dc349/unlock")); response = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); actualRequestError = mapper.readValue(response.getBody(), RequestError.class); @@ -273,7 +267,8 @@ public class OrchestrationRequestsTest extends BaseTest { setupTestUnlockOrchestrationRequest_invalid_Json(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -307,7 +302,8 @@ public class OrchestrationRequestsTest extends BaseTest { throws JsonParseException, JsonMappingException, IOException, ValidationException { setupTestUnlockOrchestrationRequest_Valid_Status("5ffbabd6-b793-4377-a1ab-082670fbc7ac", "PENDING"); ObjectMapper mapper = new ObjectMapper(); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); + String requestJSON = + new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/Request.json"))); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -319,14 +315,15 @@ public class OrchestrationRequestsTest extends BaseTest { // Test valid status request = ORCHESTRATION_LIST.getRequestList().get(1).getRequest(); - builder = UriComponentsBuilder.fromHttpUrl( - createURLWithPort("/onap/so/infra/orchestrationRequests/v7/" + "5ffbabd6-b793-4377-a1ab-082670fbc7ac" + "/unlock")); + builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort( + "/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 properly called to update. + // Cannot assert anything further here, already have a wiremock in place which ensures that the post was + // properly called to update. } - @Ignore //What is this testing? + @Ignore // What is this testing? @Test public void testGetOrchestrationRequestRequestDetailsWhiteSpace() throws Exception { InfraActiveRequests requests = new InfraActiveRequests(); @@ -347,8 +344,8 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -358,19 +355,20 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); } - @Ignore //What is this testing? + @Ignore // What is this testing? @Test public void testGetOrchestrationRequestRequestDetailsAlaCarte() throws IOException { InfraActiveRequests requests = new InfraActiveRequests(); - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); + String requestJSON = new String( + Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/AlaCarteRequest.json"))); requests.setAction("create"); requests.setRequestBody(requestJSON); requests.setRequestId("requestId"); requests.setRequestScope("service"); requests.setRequestType("createInstance"); -// iar.save(requests); + // iar.save(requests); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON); headers.set("Content-Type", MediaType.APPLICATION_JSON); @@ -379,8 +377,8 @@ public class OrchestrationRequestsTest extends BaseTest { UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(createURLWithPort("/onap/so/infra/orchestrationRequests/v7/requestId")); - ResponseEntity<GetOrchestrationResponse> response = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, - entity, GetOrchestrationResponse.class); + ResponseEntity<GetOrchestrationResponse> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, GetOrchestrationResponse.class); assertEquals(Response.Status.OK.getStatusCode(), response.getStatusCode().value()); assertEquals("application/json", response.getHeaders().get(HttpHeaders.CONTENT_TYPE).get(0)); @@ -389,96 +387,112 @@ public class OrchestrationRequestsTest extends BaseTest { assertEquals("7.0.0", response.getHeaders().get("X-LatestVersion").get(0)); assertEquals("requestId", response.getHeaders().get("X-TransactionID").get(0)); } + @Test - public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException{ - RequestProcessingData entry = new RequestProcessingData(); - RequestProcessingData secondEntry = new RequestProcessingData(); - List<HashMap<String, String>> expectedList = new ArrayList<>(); - HashMap<String, String> expectedMap = new HashMap<>(); - List<HashMap<String, String>> secondExpectedList = new ArrayList<>(); - HashMap<String, String> secondExpectedMap = new HashMap<>(); - List<RequestProcessingData> expectedDataList = new ArrayList<>(); - entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); - entry.setTag("pincFabricConfigRequest"); - expectedMap.put("requestAction", "assign"); - expectedMap.put("pincFabricId", "testId"); - expectedList.add(expectedMap); - entry.setDataPairs(expectedList); - secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715"); - secondEntry.setTag("pincFabricConfig"); - secondExpectedMap.put("requestAction", "unassign"); - secondExpectedList.add(secondExpectedMap); - secondEntry.setDataPairs(secondExpectedList); - expectedDataList.add(entry); - expectedDataList.add(secondEntry); - - List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>(); - List<RequestProcessingData> actualProcessingData = new ArrayList<>(); - ObjectMapper mapper = new ObjectMapper(); - processingData = mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"), - new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>(){}); + public void mapRequestProcessingDataTest() throws JsonParseException, JsonMappingException, IOException { + RequestProcessingData entry = new RequestProcessingData(); + RequestProcessingData secondEntry = new RequestProcessingData(); + List<HashMap<String, String>> expectedList = new ArrayList<>(); + HashMap<String, String> expectedMap = new HashMap<>(); + List<HashMap<String, String>> secondExpectedList = new ArrayList<>(); + HashMap<String, String> secondExpectedMap = new HashMap<>(); + List<RequestProcessingData> expectedDataList = new ArrayList<>(); + entry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca714"); + entry.setTag("pincFabricConfigRequest"); + expectedMap.put("requestAction", "assign"); + expectedMap.put("pincFabricId", "testId"); + expectedList.add(expectedMap); + entry.setDataPairs(expectedList); + secondEntry.setGroupingId("7d2e8c07-4d10-456d-bddc-37abf38ca715"); + secondEntry.setTag("pincFabricConfig"); + secondExpectedMap.put("requestAction", "unassign"); + secondExpectedList.add(secondExpectedMap); + secondEntry.setDataPairs(secondExpectedList); + expectedDataList.add(entry); + expectedDataList.add(secondEntry); + + List<org.onap.so.db.request.beans.RequestProcessingData> processingData = new ArrayList<>(); + List<RequestProcessingData> actualProcessingData = new ArrayList<>(); + ObjectMapper mapper = new ObjectMapper(); + processingData = + mapper.readValue(new File("src/test/resources/OrchestrationRequest/RequestProcessingData.json"), + new TypeReference<List<org.onap.so.db.request.beans.RequestProcessingData>>() {}); actualProcessingData = orchReq.mapRequestProcessingData(processingData); - assertThat(actualProcessingData,sameBeanAs(expectedDataList)); + assertThat(actualProcessingData, sameBeanAs(expectedDataList)); } - public void setupTestGetOrchestrationRequest() throws Exception{ - //For testGetOrchestrationRequest - stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) - .withStatus(HttpStatus.SC_OK))); + public void setupTestGetOrchestrationRequest() throws Exception { + // For testGetOrchestrationRequest + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequest.json")))) + .withStatus(HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) + .withStatus(HttpStatus.SC_OK))); } - public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception{ - //For testGetOrchestrationRequest - stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) - .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) - .withStatus(HttpStatus.SC_OK))); + + public void setupTestGetOrchestrationRequestInstanceGroup() throws Exception { + // For testGetOrchestrationRequest + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths.get( + "src/test/resources/OrchestrationRequest/getOrchestrationRequestInstanceGroup.json")))) + .withStatus(HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlPathEqualTo("/requestProcessingData/search/findBySoRequestIdOrderByGroupingIdDesc/")) + .withQueryParam("SO_REQUEST_ID", equalTo("00032ab7-na18-42e5-965d-8ea592502018")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes(Paths + .get("src/test/resources/OrchestrationRequest/getRequestProcessingData.json")))) + .withStatus(HttpStatus.SC_OK))); } - private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception{ - stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json")))) + private void setupTestGetOrchestrationRequestRequestDetails(String requestId, String status) throws Exception { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getOrchestrationRequestDetails.json")))) .withStatus(HttpStatus.SC_OK))); } private void setupTestUnlockOrchestrationRequest(String requestId, String status) { - stubFor(get(urlPathEqualTo(getTestUrl(requestId))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, requestId, status)) - .withStatus(HttpStatus.SC_OK))); + 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() { - stubFor(get(urlPathEqualTo(getTestUrl(INVALID_REQUEST_ID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + 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) { - stubFor(get(urlPathEqualTo(getTestUrl(requestID))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, requestID, status)) - .withStatus(HttpStatus.SC_OK))); + 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))); - stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(infraActivePost, requestID)) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(infraActivePost, requestID)).withStatus(HttpStatus.SC_OK))); } - private void setupTestGetOrchestrationRequestFilter() throws Exception{ - //for testGetOrchestrationRequestFilter(); - stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/")).withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}")).willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(new String(Files.readAllBytes(Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json")))) - .withStatus(HttpStatus.SC_OK))); + private void setupTestGetOrchestrationRequestFilter() throws Exception { + // for testGetOrchestrationRequestFilter(); + wireMockServer.stubFor(any(urlPathEqualTo("/infraActiveRequests/getOrchestrationFiltersFromInfraActive/")) + .withRequestBody(equalToJson("{\"modelType\":[\"EQUALS\",\"vfModule\"]}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(new String(Files.readAllBytes( + Paths.get("src/test/resources/OrchestrationRequest/getRequestDetailsFilter.json")))) + .withStatus(HttpStatus.SC_OK))); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java new file mode 100644 index 0000000000..dc0cd473c2 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/RequestHandlerUtilsTest.java @@ -0,0 +1,339 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 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.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; +import static org.onap.so.logger.HttpHeadersConstants.REQUESTOR_ID; +import static org.onap.so.logger.MdcConstants.CLIENT_ID; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.List; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.MediaType; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; +import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; +import org.onap.so.db.catalog.beans.Service; +import org.onap.so.db.request.beans.InfraActiveRequests; +import org.onap.so.logger.HttpHeadersConstants; +import org.onap.so.serviceinstancebeans.ModelInfo; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.onap.so.serviceinstancebeans.RequestInfo; +import org.onap.so.serviceinstancebeans.RequestParameters; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.util.UriComponentsBuilder; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class RequestHandlerUtilsTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); + + @Autowired + private RequestHandlerUtils requestHandlerUtils; + + @Value("${wiremock.server.port}") + private String wiremockPort; + + private URL initialUrl; + private int initialPort; + private HttpHeaders headers; + + @Before + public void beforeClass() { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + // set headers + headers = new HttpHeaders(); + headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); + headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers.set(CLIENT_ID, "VID"); + headers.set(REQUESTOR_ID, "xxxxxx"); + try { // generate one-time port number to avoid RANDOM port number later. + initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); + initialPort = initialUrl.getPort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + } + + public String inputStream(String JsonInput) throws IOException { + JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput; + return new String(Files.readAllBytes(Paths.get(JsonInput))); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, + HttpHeaders headers) { + + if (!headers.containsKey(HttpHeaders.ACCEPT)) { + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + } + if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + } + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort)); + + HttpEntity<String> request = new HttpEntity<>(requestJson, headers); + + return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class); + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); + } + + @Test + public void test_mapJSONtoMSOStyle() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + String testRequest = inputStream("/ServiceInstanceDefault.json"); + String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, null, false, null); + ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class); + ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796", modelInfo.getModelCustomizationUuid()); + assertEquals("modelInstanceName", modelInfo.getModelInstanceName()); + assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965", modelInfo.getModelInvariantUuid()); + assertEquals("10", modelInfo.getModelUuid()); + + } + + + @Test + public void test_mapJSONtoMSOStyleUsePreload() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_NULL); + String testRequest = inputStream("/ServiceInstanceDefault.json"); + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails rd = new RequestDetails(); + RequestParameters rp = new RequestParameters(); + rp.setUsePreload(true); + rd.setRequestParameters(rp); + sir.setRequestDetails(rd); + String resultString = requestHandlerUtils.mapJSONtoMSOStyle(testRequest, sir, false, null); + ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class); + assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload()); + } + + @Test + public void setServiceTypeTestALaCarte() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = true; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + requestInfo.setSource("VID"); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceTypeALaCarte"); + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceTypeALaCarte"); + } + + @Test + public void setServiceTypeTest() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestDefault() throws JsonProcessingException { + String requestScope = ModelType.service.toString(); + Boolean aLaCarteFlag = false; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + Service defaultService = new Service(); + defaultService.setServiceType("testServiceType"); + + wireMockServer.stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "testServiceType"); + } + + @Test + public void setServiceTypeTestNetwork() throws JsonProcessingException { + String requestScope = ModelType.network.toString(); + Boolean aLaCarteFlag = null; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + RequestDetails requestDetails = new RequestDetails(); + RequestInfo requestInfo = new RequestInfo(); + ModelInfo modelInfo = new ModelInfo(); + modelInfo.setModelName("networkModelName"); + requestInfo.setSource("VID"); + requestDetails.setModelInfo(modelInfo); + requestDetails.setRequestInfo(requestInfo); + sir.setRequestDetails(requestDetails); + + String serviceType = requestHandlerUtils.getServiceType(requestScope, sir, aLaCarteFlag); + assertEquals(serviceType, "networkModelName"); + } + + @Test + public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException { + String requestScope = "instanceGroup"; + ServiceInstancesRequest sir = + mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); + assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", + requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void setServiceInstanceIdReturnNullTest() { + String requestScope = "vnf"; + ServiceInstancesRequest sir = new ServiceInstancesRequest(); + assertNull(requestHandlerUtils.setServiceInstanceId(requestScope, sir)); + } + + @Test + public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertTrue(inProgress); + } + + @Test + public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void camundaHistoryCheckNotInProgressTest() throws ContactCamundaException, RequestDbFailureException { + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponseCompleted.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + InfraActiveRequests duplicateRecord = new InfraActiveRequests(); + duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); + boolean inProgress = false; + inProgress = requestHandlerUtils.camundaHistoryCheck(duplicateRecord, null); + assertFalse(inProgress); + } + + @Test + public void setCamundaHeadersTest() throws ContactCamundaException, RequestDbFailureException { + String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password + String key = "07a7159d3bf51a0e53be7a8f89699be7"; + HttpHeaders headers = requestHandlerUtils.setCamundaHeaders(encryptedAuth, key); + List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); + String expectedAcceptedType = "application/json"; + assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); + String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); + String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; + assertEquals(expectedBasicAuth, basicAuth); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java index 33d9d413d6..328414930e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/ServiceInstanceBeansTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra; import java.util.List; - import org.junit.Before; import org.junit.Test; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.filters.FilterEnum; import com.openpojo.reflection.impl.PojoClassFactory; @@ -34,17 +32,19 @@ import com.openpojo.validation.rule.impl.*; import com.openpojo.validation.test.impl.*; -public class ServiceInstanceBeansTest extends BaseTest{ - List<PojoClass> pojoClasses; - @Before - public void setup() { - pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum()); - } - @Test - public void validateGettersAndSetters() { - Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) - .with(new SetterTester(), new GetterTester()).build(); - validator.validate(pojoClasses); - } +public class ServiceInstanceBeansTest extends BaseTest { + List<PojoClass> pojoClasses; + + @Before + public void setup() { + pojoClasses = PojoClassFactory.getPojoClassesRecursively("org.onap.so.serviceinstancebeans", new FilterEnum()); + } + + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate(pojoClasses); + } } 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 17fa011c93..1bb3932cff 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 @@ -24,14 +24,11 @@ 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.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.logger.HttpHeadersConstants.ONAP_REQUEST_ID; @@ -45,38 +42,26 @@ import static org.onap.so.logger.MdcConstants.RESPONSEDESC; import static org.onap.so.logger.MdcConstants.SERVICE_NAME; import static org.onap.so.logger.MdcConstants.STATUSCODE; import static org.onap.so.logger.HttpHeadersConstants.TRANSACTION_ID; - - import java.io.File; import java.io.IOException; import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.Map; - import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.apihandlerinfra.exceptions.ContactCamundaException; -import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException; import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceRecipe; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.HttpHeadersConstants; import org.onap.so.serviceinstancebeans.CloudConfiguration; -import org.onap.so.serviceinstancebeans.ModelInfo; -import org.onap.so.serviceinstancebeans.RequestDetails; import org.onap.so.serviceinstancebeans.RequestError; -import org.onap.so.serviceinstancebeans.RequestInfo; import org.onap.so.serviceinstancebeans.RequestParameters; import org.onap.so.serviceinstancebeans.RequestReferences; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; @@ -89,7 +74,6 @@ 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.annotation.JsonInclude.Include; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -97,20 +81,19 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.tomakehurst.wiremock.http.Fault; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class ServiceInstancesTest extends BaseTest{ +public class ServiceInstancesTest extends BaseTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private ObjectMapper errorMapper = new ObjectMapper(); - private final ObjectMapper mapper = new ObjectMapper(); - private ObjectMapper errorMapper = new ObjectMapper(); - @Autowired private ServiceInstances servInstances; - @Value("${wiremock.server.port}") - private String wiremockPort; + @Value("${wiremock.server.port}") + private String wiremockPort; private final String servInstanceuri = "/onap/so/infra/serviceInstantiation/"; private final String servInstanceUriPrev7 = "/onap/so/infra/serviceInstances/"; @@ -120,111 +103,79 @@ public class ServiceInstancesTest extends BaseTest{ private int initialPort; private HttpHeaders headers; - @Before - public void beforeClass() { - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); + @Before + public void beforeClass() { + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + errorMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); // set headers - headers = new HttpHeaders(); - headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); - headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + headers = new HttpHeaders(); + headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "test_name"); + headers.set(HttpHeadersConstants.TRANSACTION_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAP_REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(ONAPLogConstants.MDCs.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); headers.set(CLIENT_ID, "VID"); headers.set(REQUESTOR_ID, "xxxxxx"); - try { // generate one-time port number to avoid RANDOM port number later. - initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); - initialPort = initialUrl.getPort(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - stubFor(post(urlMatching(".*/infraActiveRequests.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - - public String inputStream(String JsonInput)throws IOException{ + try { // generate one-time port number to avoid RANDOM port number later. + initialUrl = new URL(createURLWithPort(Constants.ORCHESTRATION_REQUESTS_PATH)); + initialPort = initialUrl.getPort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests.*")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + } + + public String inputStream(String JsonInput) throws IOException { JsonInput = "src/test/resources/ServiceInstanceTest" + JsonInput; return new String(Files.readAllBytes(Paths.get(JsonInput))); } private URL createExpectedSelfLink(String version, String requestId) { - System.out.println("createdUrl: " + initialUrl.toString()); - try { - selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId)); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - return selfLink; - } - - private String getWiremockResponseForCatalogdb(String file) { - try { - File resource= ResourceUtils.getFile("classpath:__files/catalogdb/"+file); - return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090","localhost:"+wiremockPort); - } catch (IOException e) { - e.printStackTrace(); - return null; - } - - } - - public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, HttpHeaders headers){ - - if (!headers.containsKey(HttpHeaders.ACCEPT)) { - headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); - } - if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { - headers.set(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON); - } + System.out.println("createdUrl: " + initialUrl.toString()); + try { + selfLink = new URL(initialUrl.toString().concat("/").concat(version).concat("/").concat(requestId)); + } catch (MalformedURLException e) { + e.printStackTrace(); + } + return selfLink; + } + + private String getWiremockResponseForCatalogdb(String file) { + try { + File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file); + return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090", + "localhost:" + wiremockPort); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + + } + + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod, + HttpHeaders headers) { + + if (!headers.containsKey(HttpHeaders.ACCEPT)) { + headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON); + } + if (!headers.containsKey(HttpHeaders.CONTENT_TYPE)) { + headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON); + } UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(uriPath, initialPort)); HttpEntity<String> request = new HttpEntity<>(requestJson, headers); - return restTemplate.exchange(builder.toUriString(), - reqMethod, request, String.class); + return restTemplate.exchange(builder.toUriString(), reqMethod, request, String.class); } - - public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod){ - return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); - } - - @Test - public void test_mapJSONtoMSOStyle() throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); - String resultString = servInstances.mapJSONtoMSOStyle(testRequest, null, false, null); - ServiceInstancesRequest sir = mapper.readValue(resultString, ServiceInstancesRequest.class); - ModelInfo modelInfo = sir.getRequestDetails().getModelInfo(); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a796",modelInfo.getModelCustomizationUuid()); - assertEquals("modelInstanceName",modelInfo.getModelInstanceName()); - assertEquals("f7ce78bb-423b-11e7-93f8-0050569a7965",modelInfo.getModelInvariantUuid()); - assertEquals("10",modelInfo.getModelUuid()); + public ResponseEntity<String> sendRequest(String requestJson, String uriPath, HttpMethod reqMethod) { + return sendRequest(requestJson, uriPath, reqMethod, new HttpHeaders()); } - - + @Test - public void test_mapJSONtoMSOStyleUsePreload() throws IOException{ - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(Include.NON_NULL); - String testRequest= inputStream("/ServiceInstanceDefault.json"); - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails rd = new RequestDetails(); - RequestParameters rp = new RequestParameters(); - rp.setUsePreload(true); - rd.setRequestParameters(rp); - sir.setRequestDetails(rd); - String resultString = servInstances.mapJSONtoMSOStyle(testRequest, sir, false, null); - ServiceInstancesRequest sir1 = mapper.readValue(resultString, ServiceInstancesRequest.class); - assertTrue(sir1.getRequestDetails().getRequestParameters().getUsePreload()); - } - - @Test - public void createServiceInstanceVIDDefault() throws IOException{ + public void createServiceInstanceVIDDefault() throws IOException { TestAppender.events.clear(); ServiceRecipe serviceRecipe = new ServiceRecipe(); @@ -235,68 +186,67 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/search/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); - - - - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + + + + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS",mdc.get(STATUSCODE)); - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME)); + assertEquals("INPROGRESS", mdc.get(STATUSCODE)); + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("EXIT")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ENDTIME)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("202",mdc.get(RESPONSECODE)); - assertEquals("UNKNOWN",mdc.get(PARTNERNAME)); - assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances",mdc.get(SERVICE_NAME)); - assertEquals("COMPLETE",mdc.get(STATUSCODE)); + assertEquals("202", mdc.get(RESPONSECODE)); + assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("onap/so/infra/serviceInstantiation/v5/serviceInstances", mdc.get(SERVICE_NAME)); + assertEquals("COMPLETE", mdc.get(STATUSCODE)); assertNotNull(mdc.get(RESPONSEDESC)); assertEquals("0", response.getHeaders().get("X-MinorVersion").get(0)); assertEquals("0", response.getHeaders().get("X-PatchVersion").get(0)); assertEquals("5.0.0", response.getHeaders().get("X-LatestVersion").get(0)); } } + @Test - public void createServiceInstanceServiceInstancesUri() throws IOException{ + public void createServiceInstanceServiceInstancesUri() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/CreateGenericALaCarteServiceInstance"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -305,37 +255,37 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/CreateGenericALaCarteServiceInstance")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateGenericALaCarteServiceInstance")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/search/.*")) + + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expect + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceUriPrev7 + "v5"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePrev7.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void createServiceInstanceBpelStatusError() throws IOException{ + public void createServiceInstanceBpelStatusError() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -346,1025 +296,1126 @@ public class ServiceInstancesTest extends BaseTest{ defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); - + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY))); + - stubFor(get(urlMatching(".*/service/search/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceStatusError.json"), uri, HttpMethod.POST); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createServiceInstanceBadGateway() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void createServiceInstanceBadGateway() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withStatus(org.apache.http.HttpStatus.SC_BAD_GATEWAY).withBody("{}"))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceBadGateway.json"), uri, HttpMethod.POST); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createServiceInstanceEmptyResponse() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void createServiceInstanceEmptyResponse() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withFault(Fault.EMPTY_RESPONSE))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEmpty.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_GATEWAY.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstanceNoRecipeALaCarte() throws IOException{ - TestAppender.events.clear(); + public void activateServiceInstanceNoRecipeALaCarte() throws IOException { + TestAppender.events.clear(); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; - HttpHeaders requestIDheaders = new HttpHeaders(); - requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri, HttpMethod.POST, requestIDheaders); + HttpHeaders requestIDheaders = new HttpHeaders(); + requestIDheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "32807a28-1a14-4b88-b7b3-2950918aa76d"); + ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceALaCarteTrueNoRecipe.json"), uri, + HttpMethod.POST, requestIDheaders); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance")) + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); + + + wireMockServer.stubFor(get(urlMatching( + ".*/serviceRecipe/search/findFirstByServiceModelUUIDAndAction?serviceModelUUID=d88da85c-d9e8-4f73-b837-3a72a431622a&action=activateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstanceNoRecipe() throws IOException{ + public void activateServiceInstanceNoRecipe() throws IOException { uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(get(urlMatching(".*/service/search/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/search/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST); + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search/.*")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_NOT_FOUND))); + + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceNoRecipe.json"), uri, HttpMethod.POST); assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatusCode().value()); } + @Test - public void activateServiceInstance() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void activateServiceInstance() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .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))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceActivate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deactivateServiceInstance() throws IOException{ + public void deactivateServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/deactivate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDeactivate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a8868/"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDelete.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void assignServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/assign"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceAssign.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceAssign.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void unassignServiceInstance() throws IOException { - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).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))); + + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/unassign"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceUnassign.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceUnassign.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createPortConfiguration() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePortConfiguration.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createPortConfigurationEmptyProductFamilyId() throws IOException { uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST); - assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void deletePortConfiguration() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void enablePort() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceEnablePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/enablePort"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceEnablePort.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")); } + @Test public void disablePort() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDisablePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/disablePort"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDisablePort.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")); } + @Test public void activatePort() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceActivatePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/activate"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceActivatePort.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")); } + @Test public void deactivatePort() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDeactivatePort.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations/f7ce78bb-423b-11e7-93f8-0050569a7970/deactivate"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDeactivatePort.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")); } + @Test public void addRelationships() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/addRelationships"; - ResponseEntity<String> response = sendRequest(inputStream("/AddRelationships.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/AddRelationships.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void removeRelationships() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/removeRelationships"; - ResponseEntity<String> response = sendRequest(inputStream("/RemoveRelationships.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/RemoveRelationships.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVnfInstanceNoALaCarte() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomization_ReplaceVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/49585b36-2b5a-443a-8b10-c75d34bb5e46/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfCreateDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfCreateDefault.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVnfInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/5df8b6de-2083-11e7-93ae-92361f002672")) + wireMockServer.stubFor(get(urlMatching(".*/service/5df8b6de-2083-11e7-93ae-92361f002672")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("serviceVnf_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/5df8b6de-2083-11e7-93ae-92361f002672/vnfCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/service/5df8b6de-2083-11e7-93ae-92361f002672/vnfCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationsList_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002672/vnfResources")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourcesCreateVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeCreateInstance_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstance.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfWithServiceRelatedInstance.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createVnfWithServiceRelatedInstanceFail() throws IOException { uri = servInstanceUriPrev7 + "v6" + "/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/VnfWithServiceRelatedInstanceFail.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test - public void createVnfInstanceInvalidVnfResource() throws IOException { + public void createVnfInstanceInvalidVnfResource() throws IOException { uri = servInstanceuri + "v7" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs"; ResponseEntity<String> response = sendRequest(inputStream("/NoVnfResource.json"), uri, HttpMethod.POST); - + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vnfResource is specified", realResponse.getServiceException().getText()); } + @Test public void replaceVnfInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_ReplaceVnf_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomization_ReplaceVnf_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/1/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_ReplaceVnf_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeReplaceInstance_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnf.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void replaceVnfRecreateInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/RecreateInfraVce")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/RecreateInfraVce")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=TEST&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; - ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + ResponseEntity<String> response = + sendRequest(inputStream("/ReplaceVnfRecreate.json"), uri, HttpMethod.POST, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void recreateVnfInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]nfRole=GR-API-DEFAULT&action=recreateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipe_ResponseWorkflowAction.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/recreate"; ResponseEntity<String> response = sendRequest(inputStream("/VnfRecreate.json"), uri, HttpMethod.POST, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void updateVnfInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void updateVnfInstance() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=68dc9a92-214c-11e7-93ae-92361f002674")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateVnf.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void applyUpdatedConfig() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/VnfConfigUpdate")) + public void applyUpdatedConfig() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfConfigUpdate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=applyUpdatedConfig")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeApplyUpdatedConfig_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig"; - ResponseEntity<String> response = sendRequest(inputStream("/ApplyUpdatedConfig.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/applyUpdatedConfig"; + ResponseEntity<String> response = + sendRequest(inputStream("/ApplyUpdatedConfig.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVnfInstanceV5() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeDelete_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v5" + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v5" + + "/serviceInstances/e446b97d-9c35-437a-95a2-6b4c542c4507/vnfs/49befbfe-fccb-421d-bb4c-0734a43f5ea0"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVnfV5.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVfModuleInstance() throws IOException { - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching("/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) + wireMockServer.stubFor(get(urlMatching("/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) + + wireMockServer.stubFor(get(urlMatching( + "/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc\\?MODEL_CUSTOMIZATION_UUID=20c4431c-246d-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + "/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=20c4431c-246d-11e7-93ae-92361f002671&vnfComponentType=vfModule&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleWithRelatedInstances.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleWithRelatedInstances.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void createVfModuleInstanceNoModelCustomization() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateVfModuleInfra")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResource/fe6478e4-ea33-3346-ac12-ab121484a3fe")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResource/fe6478e4-ea33-3346-ac12-ab121484a3fe")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + - "[?]modelInstanceName=test&vnfResourceModelUUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" + - "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDAndVfModuleModelUUIDOrderByCreatedDesc[?]" + + "MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672&MODEL_UUID=066de97e-253e-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/066de97e-253e-11e7-93ae-92361f002672")) + wireMockServer.stubFor(get(urlMatching(".*/vfModule/066de97e-253e-11e7-93ae-92361f002672")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction" + - "[?]vnfComponentType=vfModule&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVNF_API_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVnfComponentTypeAndAction" + + "[?]vnfComponentType=vfModule&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVNF_API_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoModelCustomization.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ObjectMapper mapper = new ObjectMapper(); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVfModuleInstanceNoMatchingModelUUD() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResource/.*")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResource/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/2/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/066de97e-253e-11e7-93ae-92361f002672")) + wireMockServer.stubFor(get(urlMatching(".*/vfModule/066de97e-253e-11e7-93ae-92361f002672")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModulePCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoMatchingModelUUID.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ObjectMapper mapper = new ObjectMapper(); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVfModuleInstanceNoRecipe() throws IOException { - stubFor(get(urlMatching(".*/vnfResource/fe6478e4-ea33-3346-ac12-ab121484a3fe")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResource/fe6478e4-ea33-3346-ac12-ab121484a3fe")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResourceForVfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + - "[?]modelInstanceName=test&vnfResourceModelUUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomizationForVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer + .stubFor(get(urlMatching(".*/vnfResourceCustomization/search/findByModelInstanceNameAndVnfResources" + + "[?]MODEL_INSTANCE_NAME=test&VNF_RESOURCE_MODEL_UUID=fe6478e4-ea33-3346-ac12-ab121484a3fe")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfResourceCustomizationForVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vfModuleCustomizations")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/3/vfModuleCustomizations")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationsPCM_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" + - "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationPCM_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - uri = servInstanceuri + "v6" + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers); - + wireMockServer.stubFor( + get(urlMatching(".*/vfModuleCustomization/search/findByModelCustomizationUUIDAndVfModuleModelUUID[?]" + + "modelCustomizationUUID=b4ea86b4-253f-11e7-93ae-92361f002672&vfModuleModelUUID=066de97e-253e-11e7-93ae-92361f002672")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vfModuleCustomizationPCM_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + uri = servInstanceuri + "v6" + + "/serviceInstances/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules"; + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleInvalid.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); assertEquals("No valid vfModuleCustomization is specified", realResponse.getServiceException().getText()); } + @Test public void replaceVfModuleInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=replaceInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; - ResponseEntity<String> response = sendRequest(inputStream("/ReplaceVfModule.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/replace"; + ResponseEntity<String> response = + sendRequest(inputStream("/ReplaceVfModule.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateVfModuleInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) + wireMockServer.stubFor(get(urlMatching(".*/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipe_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipe_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/UpdateVfModule.json"), uri, HttpMethod.PUT, headers); logger.debug(response.getBody()); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void createVfModuleNoModelType() throws IOException{ + public void createVfModuleNoModelType() throws IOException { InfraActiveRequests expectedRecord = new InfraActiveRequests(); expectedRecord.setRequestStatus("FAILED"); expectedRecord.setAction("createInstance"); @@ -1379,371 +1430,423 @@ public class ServiceInstancesTest extends BaseTest{ expectedRecord.setRequestAction("createInstance"); expectedRecord.setRequestorId("zz9999"); expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d"); - //VnfType is not sent in this request, should be blank in db + // VnfType is not sent in this request, should be blank in db expectedRecord.setVnfType(""); - uri = servInstanceuri + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules"; + uri = servInstanceuri + + "v5/serviceInstances/32807a28-1a14-4b88-b7b3-2950918aa76d/vnfs/32807a28-1a14-4b88-b7b3-2950918aa76d/vfModules"; - ResponseEntity<String> response = sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers); - //ActualRecord + ResponseEntity<String> response = + sendRequest(inputStream("/VfModuleNoModelType.json"), uri, HttpMethod.POST, headers); + // ActualRecord assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void inPlaceSoftwareUpdate() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/VnfInPlaceUpdate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" + - "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction[?]" + + "nfRole=GR-API-DEFAULT&action=inPlaceSoftwareUpdate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfRecipeInPlaceUpdate_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate"; - ResponseEntity<String> response = sendRequest(inputStream("/InPlaceSoftwareUpdate.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/inPlaceSoftwareUpdate"; + ResponseEntity<String> response = + sendRequest(inputStream("/InPlaceSoftwareUpdate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } - + @Test public void deleteVfModuleInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVfModule.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVfModuleNoModelInvariantId() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeleteVfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=VNF-API-DEFAULT&vnfComponentType=vfModule&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeleteVfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/196b4a84-0858-4317-a1f6-497e2e52ae43/vnfs/36e4f902-ec32-451e-8d53-e3edc19e40a4/vfModules/09f3a38d-933f-450a-8784-9e6c4dec3f72"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVfModuleNoModelInvariantId.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deactivateAndCloudDeleteVfModuleInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + - "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeDeactivate_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer + .stubFor(get(urlMatching(".*/vfModule/search/findFirstVfModuleByModelInvariantUUIDAndModelVersion[?]" + + "modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671&modelVersion=2")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=deactivateAndCloudDelete")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeDeactivate_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete"; - ResponseEntity<String> response = sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.json"), uri, HttpMethod.POST, headers); - + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/vfModules/ff305d54-75b4-431b-adb2-eb6b9e5ff000/deactivateAndCloudDelete"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeactivateAndCloudDeleteVfModule.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createVolumeGroupInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups"; ResponseEntity<String> response = sendRequest(inputStream("/VolumeGroup.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void updateVolumeGroupInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/UpdateVolumeGroup.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteVolumeGroupInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=b4ea86b4-253f-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomizationVolGrp_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModuleVolGroup_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVolGrp_GRAPI_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=volumeGroup&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVolGrp_GRAPI_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; - ResponseEntity<String> response = sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers); - + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/vnfs/ff305d54-75b4-431b-adb2-eb6b9e5ff000/volumeGroups/ff305d54-75b4-431b-adb2-eb6b9e5ff000"; + ResponseEntity<String> response = + sendRequest(inputStream("/DeleteVolumeGroup.json"), uri, HttpMethod.DELETE, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void createNetworkInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreate.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreate.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateNetworkInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test public void deleteNetworkInstance() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteNetworkInstanceNoReqParams() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v6","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v6", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstanceNoReqParams.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void convertJsonToServiceInstanceRequestFail() throws IOException { - //ExpectedRecord + // ExpectedRecord InfraActiveRequests expectedRecord = new InfraActiveRequests(); expectedRecord.setRequestStatus("FAILED"); expectedRecord.setStatusMessage("Error mapping request: "); @@ -1754,16 +1857,20 @@ public class ServiceInstancesTest extends BaseTest{ expectedRecord.setRequestAction("deleteInstance"); expectedRecord.setRequestId("32807a28-1a14-4b88-b7b3-2950918aa76d"); - uri = servInstanceuri + "v6" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v6" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.DELETE, headers); - //ActualRecord + // ActualRecord assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); } + @Test public void convertJsonToServiceInstanceRequestConfigurationFail() throws IOException { - uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort"; + uri = servInstanceuri + "v5" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/configurations/test/enablePort"; ResponseEntity<String> response = sendRequest(inputStream("/ConvertRequestFail.json"), uri, HttpMethod.POST); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); @@ -1771,7 +1878,7 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void creatServiceInstanceGRTestApiNoCustomRecipeFound() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); @@ -1783,79 +1890,81 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(get(urlMatching(".*/service/.*")) + + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceMacro.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void createNetworkInstanceTestApiUndefinedUsePropertiesDefault() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateAlternateInstanceName.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void createNetworkInstanceTestApiIncorrectUsePropertiesDefault() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiIncorrect.json"), uri, HttpMethod.POST); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); @@ -1866,80 +1975,84 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void createNetworkInstanceTestApiGrApi() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=GR-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=GR-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiGrApi.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void createNetworkInstanceTestApiVnfApi() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/CreateNetworkInstance")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateNetworkInstance")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("networkResourceCustomization_Response.json")) .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=createInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - + wireMockServer.stubFor( + get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac/networkResource")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkResource_Response.json")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=createInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipeVNF_API_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkCreateTestApiVnfApi.json"), uri, HttpMethod.POST, headers); - //expected response + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test - public void activateServiceInstanceRequestStatus() throws IOException{ + public void activateServiceInstanceRequestStatus() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -1948,33 +2061,32 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - //expect + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7999/activate"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePrev8.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePrev8.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test @@ -1983,13 +2095,15 @@ public class ServiceInstancesTest extends BaseTest{ HttpHeaders ivalidRequestIdHeaders = new HttpHeaders(); ivalidRequestIdHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, illegalRequestId); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, ivalidRequestIdHeaders); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); assertTrue(response.getBody().contains("Request Id " + illegalRequestId + " is not a valid UUID")); } + @Test - public void invalidBPELResponse() throws IOException{ + public void invalidBPELResponse() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -1999,30 +2113,31 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid2.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", realResponse.getServiceException().getText()); + assertEquals("Request Failed due to BPEL error with HTTP Status = 202{\"instanceId\": \"1882939\"}", + realResponse.getServiceException().getText()); } + @Test - public void unauthorizedBPELResponse() throws IOException{ + public void unauthorizedBPELResponse() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -2032,31 +2147,32 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/UnauthorizedResponse.json").withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED))); + .withBodyFile("Camunda/UnauthorizedResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_UNAUTHORIZED))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); + assertEquals("Exception caught mapping Camunda JSON response to object", + realResponse.getServiceException().getText()); } @Test - public void invalidBPELResponse2() throws IOException{ + public void invalidBPELResponse2() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); @@ -2066,30 +2182,30 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertTrue(realResponse.getServiceException().getText().contains("<aetgt:ErrorMessage>Exception in create execution list 500")); + assertTrue(realResponse.getServiceException().getText() + .contains("<aetgt:ErrorMessage>Exception in create execution list 500")); } @Test - public void createMacroServiceInstance() throws IOException{ + public void createMacroServiceInstance() throws IOException { ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/CreateMacroServiceNetworkVnf"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); @@ -2098,44 +2214,44 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf")) + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/CreateMacroServiceNetworkVnf")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestResponseInvalid.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v5","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v5", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceUriPrev7 + "v5"; - ResponseEntity<String> response = sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/MacroServiceInstance.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } @Test public void testUserParams() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); RequestParameters requestParameters = request.getRequestDetails().getRequestParameters(); String userParamsTxt = inputStream("/userParams.txt"); @@ -2150,8 +2266,10 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void testConfigureCloudConfig() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); - CloudConfiguration cloudConfig = servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters()); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + CloudConfiguration cloudConfig = + servInstances.configureCloudConfig(request.getRequestDetails().getRequestParameters()); assertEquals("mdt25b", cloudConfig.getLcpCloudRegionId()); assertEquals("aefb697db6524ddebfe4915591b0a347", cloudConfig.getTenantId()); @@ -2160,153 +2278,184 @@ public class ServiceInstancesTest extends BaseTest{ @Test public void testMapToLegacyRequest() throws IOException { ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest request = mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); - ServiceInstancesRequest expected = mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest request = + mapper.readValue(inputStream("/MacroServiceInstance.json"), ServiceInstancesRequest.class); + ServiceInstancesRequest expected = + mapper.readValue(inputStream("/LegacyMacroServiceInstance.json"), ServiceInstancesRequest.class); servInstances.mapToLegacyRequest(request.getRequestDetails()); System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(request)); assertThat(request, sameBeanAs(expected)); } + @Test public void scaleOutVfModule() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vfModuleCustomization/search/findFirstByModelCustomizationUUIDOrderByCreatedDesc[?]MODEL_CUSTOMIZATION_UUID=cb82ffd8-252a-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModuleCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/vfModule")) + wireMockServer.stubFor(get(urlMatching(".*/vfModuleCustomization/1/vfModule")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) + wireMockServer.stubFor(get(urlMatching(".*/vfModule/20c4431c-246d-11e7-93ae-92361f002671")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vfModule_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + - "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfComponentRecipeVfModuleScaleOut_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_Response.json")).withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching( + ".*/vnfComponentsRecipe/search/findFirstVnfComponentsRecipeByVfModuleModelUUIDAndVnfComponentTypeAndAction" + + "[?]vfModuleModelUUID=GR-API-DEFAULT&vnfComponentType=vfModule&action=scaleOut")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb( + "vnfComponentRecipeVfModuleScaleOut_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching( + ".*/vfModule/search/findByModelInvariantUUIDOrderByModelVersionDesc[?]modelInvariantUUID=78ca26d0-246d-11e7-93ae-92361f002671")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vfModulesListByInvariantId_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut"; - ResponseEntity<String> response = sendRequest(inputStream("/ScaleOutRequest.json"), uri, HttpMethod.POST, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/7a88cbeb-0ec8-4765-a271-4f9e90c3da7b/vnfs/cbba721b-4803-4df7-9347-307c9a955426/vfModules/scaleOut"; + ResponseEntity<String> response = + sendRequest(inputStream("/ScaleOutRequest.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")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertTrue(response.getBody().contains("1882939")); } + @Test - public void createServiceInstanceBadResponse() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); - serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); - serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - serviceRecipe.setAction(Action.createInstance.toString()); - serviceRecipe.setId(1); - serviceRecipe.setRecipeTimeout(180); - Service defaultService = new Service(); - defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/service/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - - uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - - assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value()); - RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Exception caught mapping Camunda JSON response to object", realResponse.getServiceException().getText()); - } - @Test - public void createServiceInstanceDuplicateError() throws IOException{ - stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + public void createServiceInstanceBadResponse() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); + serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); + serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + serviceRecipe.setAction(Action.createInstance.toString()); + serviceRecipe.setId(1); + serviceRecipe.setRecipeTimeout(180); + Service defaultService = new Service(); + defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); + + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/TestBadResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).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))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + + assertEquals(Response.Status.NOT_ACCEPTABLE.getStatusCode(), response.getStatusCode().value()); + RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); + assertEquals("Exception caught mapping Camunda JSON response to object", + realResponse.getServiceException().getText()); + } + + @Test + public void createServiceInstanceDuplicateError() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + + uri = servInstanceuri + "v5/serviceInstances"; + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicateHistoryCheck() throws IOException{ - stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") - .withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + public void createServiceInstanceDuplicateHistoryCheck() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - + .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBodyFile("Camunda/HistoryCheckResponse.json") + .withStatus(org.apache.http.HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.CONFLICT.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.", realResponse.getServiceException().getText()); + assertEquals( + "Error: Locked instance - This service (testService9) already has a request being worked with a status of UNLOCKED (RequestId - f0a35706-efc4-4e27-80ea-a995d7a2a40f). The existing request must finish or be cleaned up before proceeding.", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicateHistoryCheckException() throws IOException{ - stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") - .withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + public void createServiceInstanceDuplicateHistoryCheckException() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + .withBodyFile("InfraActiveRequests/createInfraActiveRequests.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get( + ("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(org.apache.http.HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to get process-instance history from Camunda for requestId: f0a35706-efc4-4e27-80ea-a995d7a2a40f due to error: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void createServiceInstanceDuplicate() throws IOException{ - stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + public void createServiceInstanceDuplicate() throws IOException { + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/checkInstanceNameDuplicate")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to check for duplicate instance due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } - + @Test - public void createServiceInstanceSaveError() throws IOException{ - ServiceRecipe serviceRecipe = new ServiceRecipe(); + public void createServiceInstanceSaveError() throws IOException { + ServiceRecipe serviceRecipe = new ServiceRecipe(); serviceRecipe.setOrchestrationUri("/mso/async/services/WorkflowActionBB"); serviceRecipe.setServiceModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); serviceRecipe.setAction(Action.createInstance.toString()); @@ -2314,415 +2463,288 @@ public class ServiceInstancesTest extends BaseTest{ serviceRecipe.setRecipeTimeout(180); Service defaultService = new Service(); defaultService.setModelUUID("d88da85c-d9e8-4f73-b837-3a72a431622a"); - stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - stubFor(get(urlMatching(".*/service/.*")) + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + wireMockServer.stubFor(get(urlMatching(".*/service/.*")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(defaultService)).withStatus(HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/serviceRecipe/search.*")) + wireMockServer.stubFor(get(urlMatching(".*/serviceRecipe/search.*")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceRecipe)) - .withStatus(HttpStatus.SC_OK))); - + .withBody(mapper.writeValueAsString(serviceRecipe)).withStatus(HttpStatus.SC_OK))); + uri = servInstanceuri + "v5/serviceInstances"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceDefault.json"), uri, HttpMethod.POST, headers); assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test public void createPortConfigurationSaveError() throws IOException { - stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/ALaCarteOrchestrator")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - + uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstancePortConfiguration.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test public void createPortConfigDbUpdateError() throws IOException { - stubFor(post(urlMatching(".*/infraActiveRequests/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); - + wireMockServer.stubFor(post(urlMatching(".*/infraActiveRequests/")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR))); + uri = servInstanceuri + "v5" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7968/configurations"; - ResponseEntity<String> response = sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers); - + ResponseEntity<String> response = + sendRequest(inputStream("/ServiceInstanceParseFail.json"), uri, HttpMethod.POST, headers); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals("Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", realResponse.getServiceException().getText()); + assertEquals( + "Unable to save instance to db due to error contacting requestDb: org.springframework.web.client.HttpServerErrorException: 500 Server Error", + realResponse.getServiceException().getText()); } + @Test - public void vnfUpdateWithNetworkInstanceGroup() throws IOException{ - TestAppender.events.clear(); - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void vnfUpdateWithNetworkInstanceGroup() throws IOException { + TestAppender.events.clear(); + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/2ccae1b4-7d9e-46fa-a452-9180ce008d17")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlMatching( + ".*/vnfResourceCustomization/search/findByModelCustomizationUUID[?]MODEL_CUSTOMIZATION_UUID=2ccae1b4-7d9e-46fa-a452-9180ce008d17")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("vnfResourceCustomization_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfResources")) + wireMockServer.stubFor(get(urlMatching(".*/vnfResourceCustomization/4/vnfResources")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBody(getWiremockResponseForCatalogdb("vnfResources_Response.json")) .withStatus(org.apache.http.HttpStatus.SC_OK))); - - stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + - "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlMatching(".*/vnfRecipe/search/findFirstVnfRecipeByNfRoleAndAction" + + "[?]nfRole=GR-API-DEFAULT&action=updateInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("UpdateVnfRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); headers.set(ONAPLogConstants.Headers.PARTNER_NAME, "VID"); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca"; - ResponseEntity<String> response = sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers); - //then + uri = servInstanceuri + + "v7/serviceInstances/e05864f0-ab35-47d0-8be4-56fd9619ba3c/vnfs/f501ce76-a9bc-4601-9837-74fd9f4d5eca"; + ResponseEntity<String> response = + sendRequest(inputStream("/VnfwithNeteworkInstanceGroup.json"), uri, HttpMethod.PUT, headers); + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); assertEquals(response.getHeaders().get(TRANSACTION_ID).get(0), "32807a28-1a14-4b88-b7b3-2950918aa76d"); - - for(ILoggingEvent logEvent : TestAppender.events){ - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); - assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertEquals("VID",mdc.get(PARTNERNAME)); + + for (ILoggingEvent logEvent : TestAppender.events) { + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("ENTRY")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("32807a28-1a14-4b88-b7b3-2950918aa76d", mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals("VID", mdc.get(PARTNERNAME)); } } } + @Test - public void createInstanceGroup() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void createInstanceGroup() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expect + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups"; - ResponseEntity<String> response = sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/CreateInstanceGroup.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deleteInstanceGroup() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void deleteInstanceGroup() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expect + + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void deleteInstanceGroupNoRequestIdHeader() throws IOException{ + public void deleteInstanceGroupNoRequestIdHeader() throws IOException { uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE); - //then + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-RequestID header is specified"); } + @Test - public void deleteInstanceGroupNoPartnerNameHeader() throws IOException{ - HttpHeaders noPartnerHeaders = new HttpHeaders(); - noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx"); + public void deleteInstanceGroupNoPartnerNameHeader() throws IOException { + HttpHeaders noPartnerHeaders = new HttpHeaders(); + noPartnerHeaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); + noPartnerHeaders.set(REQUESTOR_ID, "xxxxxx"); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noPartnerHeaders); - //then + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-ONAP-PartnerName header is specified"); } + @Test - public void deleteInstanceGroupNoRquestorIdHeader() throws IOException{ + public void deleteInstanceGroupNoRquestorIdHeader() throws IOException { HttpHeaders noRequestorIdHheaders = new HttpHeaders(); noRequestorIdHheaders.set(ONAPLogConstants.Headers.REQUEST_ID, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); - //expect + noRequestorIdHheaders.set(ONAPLogConstants.Headers.PARTNER_NAME, "eca3a1b1-43ab-457e-ab1c-367263d148b4"); + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c"; ResponseEntity<String> response = sendRequest(null, uri, HttpMethod.DELETE, noRequestorIdHheaders); - - //then + + // then assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified"); + assertEquals(realResponse.getServiceException().getText(), "No valid X-RequestorID header is specified"); } + @Test - public void addMembers() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void addMembers() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/addMembers"; ResponseEntity<String> response = sendRequest(inputStream("/AddMembers.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test - public void removeMembers() throws IOException{ - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + public void removeMembers() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - //expect + // expect ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); uri = servInstanceuri + "/v7/instanceGroups/e05864f0-ab35-47d0-8be4-56fd9619ba3c/removeMembers"; - ResponseEntity<String> response = sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers); + ResponseEntity<String> response = + sendRequest(inputStream("/RemoveMembers.json"), uri, HttpMethod.POST, headers); - //then + // then assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void deleteNetworkInstanceNoCustomizationEntry() throws IOException { - stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) + wireMockServer.stubFor(post(urlPathEqualTo("/mso/async/services/WorkflowActionBB")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withBodyFile("Camunda/TestResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_NOT_FOUND))); - stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + - "modelName=VNF-API-DEFAULT&action=deleteInstance")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) - .withStatus(org.apache.http.HttpStatus.SC_OK))); - - //expected response + wireMockServer.stubFor(get(urlMatching(".*/networkRecipe/search/findFirstByModelNameAndAction[?]" + + "modelName=VNF-API-DEFAULT&action=deleteInstance")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("networkRecipe_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + // expected response ServiceInstancesResponse expectedResponse = new ServiceInstancesResponse(); RequestReferences requestReferences = new RequestReferences(); requestReferences.setInstanceId("1882939"); - requestReferences.setRequestSelfLink(createExpectedSelfLink("v7","32807a28-1a14-4b88-b7b3-2950918aa76d")); + requestReferences.setRequestSelfLink(createExpectedSelfLink("v7", "32807a28-1a14-4b88-b7b3-2950918aa76d")); expectedResponse.setRequestReferences(requestReferences); - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; - ResponseEntity<String> response = sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + ResponseEntity<String> response = + sendRequest(inputStream("/NetworkInstance.json"), uri, HttpMethod.DELETE, headers); assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); ServiceInstancesResponse realResponse = mapper.readValue(response.getBody(), ServiceInstancesResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); + assertThat(realResponse, sameBeanAs(expectedResponse).ignoring("requestReferences.requestId")); } + @Test public void updateNetworkInstanceNoCustomizationEntry() throws IOException { - stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) + wireMockServer.stubFor(get(urlMatching(".*/networkResourceCustomization/3bdbb104-476c-483e-9f8b-c095b3d308ac")) .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) .withStatus(HttpStatus.SC_NOT_FOUND))); - - uri = servInstanceuri + "v7" + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; + + uri = servInstanceuri + "v7" + + "/serviceInstances/f7ce78bb-423b-11e7-93f8-0050569a7969/networks/1710966e-097c-4d63-afda-e0d3bb7015fb"; ResponseEntity<String> response = sendRequest(inputStream("/UpdateNetwork.json"), uri, HttpMethod.PUT, headers); - + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatusCode().value()); RequestError realResponse = errorMapper.readValue(response.getBody(), RequestError.class); - assertEquals(realResponse.getServiceException().getText(), "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); - } - - @Test - public void setServiceTypeTestALaCarte() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = true; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - requestInfo.setSource("VID"); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceTypeALaCarte"); - - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceTypeALaCarte"); - } - @Test - public void setServiceTypeTest() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); - } - @Test - public void setServiceTypeTestDefault() throws JsonProcessingException{ - String requestScope = ModelType.service.toString(); - Boolean aLaCarteFlag = false; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelVersionId("0dd91181-49da-446b-b839-cd959a96f04a"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - Service defaultService = new Service(); - defaultService.setServiceType("testServiceType"); - - stubFor(get(urlMatching(".*/service/0dd91181-49da-446b-b839-cd959a96f04a")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - stubFor(get(urlMatching(".*/service/search/.*")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(defaultService)) - .withStatus(HttpStatus.SC_OK))); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "testServiceType"); - } - @Test - public void setServiceTypeTestNetwork() throws JsonProcessingException{ - String requestScope = ModelType.network.toString(); - Boolean aLaCarteFlag = null; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - RequestDetails requestDetails = new RequestDetails(); - RequestInfo requestInfo = new RequestInfo(); - ModelInfo modelInfo = new ModelInfo(); - modelInfo.setModelName("networkModelName"); - requestInfo.setSource("VID"); - requestDetails.setModelInfo(modelInfo); - requestDetails.setRequestInfo(requestInfo); - sir.setRequestDetails(requestDetails); - - String serviceType = servInstances.getServiceType(requestScope, sir, aLaCarteFlag); - assertEquals(serviceType, "networkModelName"); - } - @Test - public void setServiceInstanceIdInstanceGroupTest() throws JsonParseException, JsonMappingException, IOException{ - String requestScope = "instanceGroup"; - ServiceInstancesRequest sir = mapper.readValue(inputStream("/CreateInstanceGroup.json"), ServiceInstancesRequest.class); - assertEquals("ddcbbf3d-f2c1-4ca0-8852-76a807285efc", servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void setServiceInstanceIdTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - sir.setServiceInstanceId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - assertEquals("f0a35706-efc4-4e27-80ea-a995d7a2a40f", servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void setServiceInstanceIdReturnNullTest(){ - String requestScope = "vnf"; - ServiceInstancesRequest sir = new ServiceInstancesRequest(); - assertNull(servInstances.setServiceInstanceId(requestScope, sir)); - } - @Test - public void camundaHistoryCheckTest() throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponse.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertTrue(inProgress); - } - @Test - public void camundaHistoryCheckNoneFoundTest() throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody("[]").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); - } - @Test - public void camundaHistoryCheckNotInProgressTest()throws ContactCamundaException, RequestDbFailureException{ - stubFor(get(("/sobpmnengine/history/process-instance?variables=mso-request-id_eq_f0a35706-efc4-4e27-80ea-a995d7a2a40f")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBodyFile("Camunda/HistoryCheckResponseCompleted.json").withStatus(org.apache.http.HttpStatus.SC_OK))); - - InfraActiveRequests duplicateRecord = new InfraActiveRequests(); - duplicateRecord.setRequestId("f0a35706-efc4-4e27-80ea-a995d7a2a40f"); - boolean inProgress = false; - inProgress = servInstances.camundaHistoryCheck(duplicateRecord, null); - assertFalse(inProgress); - } - @Test - public void setCamundaHeadersTest()throws ContactCamundaException, RequestDbFailureException{ - String encryptedAuth = "015E7ACF706C6BBF85F2079378BDD2896E226E09D13DC2784BA309E27D59AB9FAD3A5E039DF0BB8408"; // user:password - String key = "07a7159d3bf51a0e53be7a8f89699be7"; - HttpHeaders headers = servInstances.setCamundaHeaders(encryptedAuth, key); - List<org.springframework.http.MediaType> acceptedType = headers.getAccept(); - String expectedAcceptedType = "application/json"; - assertEquals(expectedAcceptedType, acceptedType.get(0).toString()); - String basicAuth = headers.getFirst(HttpHeaders.AUTHORIZATION); - String expectedBasicAuth = "Basic dXNlcjpwYXNzd29yZA=="; - assertEquals(expectedBasicAuth, basicAuth); - } + assertEquals(realResponse.getServiceException().getText(), + "No valid modelCustomizationId for networkResourceCustomization lookup is specified"); + } + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java index 5c6fd31422..77d6f68de9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TasksHandlerTest.java @@ -23,20 +23,16 @@ 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.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; - import java.io.IOException; 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 org.apache.http.HttpStatus; import org.json.JSONException; import org.junit.Test; @@ -48,78 +44,80 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; 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; -public class TasksHandlerTest extends BaseTest{ - - private final String basePath = "onap/so/infra/tasks/v1"; - - @Test - public void getTasksTestByOriginalRequestId() throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException{ - stubFor(post(urlPathEqualTo("/sobpmnengine/task")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK))); - - String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a"; - - //expected response - TasksGetResponse expectedResponse = new TasksGetResponse(); - - List<TaskList> taskList = new ArrayList<TaskList>(); - TaskList taskList1 = new TaskList(); - List<String> validEntries = new ArrayList<String>(); - validEntries.add(ValidResponses.rollback.toString()); - validEntries.add(ValidResponses.skip.toString()); - validEntries.add(ValidResponses.manual.toString()); - validEntries.add(ValidResponses.abort.toString()); - taskList1.setBuildingBlockName("UpdateConfigurationState"); - taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check"); - taskList1.setErrorCode("1002"); - taskList1.setErrorSource("SDNO"); - taskList1.setErrorMessage("SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found"); - taskList1.setNfRole("VPROBE"); - taskList1.setType("fallout"); - taskList1.setOriginalRequestId(requestId); - taskList1.setOriginalRequestorId("VID"); - taskList1.setSubscriptionServiceType("PORT-MIRROR"); - taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52"); - taskList1.setDescription("test task"); - taskList1.setTimeout("PT3000S"); - taskList1.setValidResponses(validEntries); - taskList.add(taskList1); - - expectedResponse.setTaskList(taskList); - 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); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) - .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - ObjectMapper mapper = new ObjectMapper(); - - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - - - //then - assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); - TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class); - assertThat(realResponse, sameBeanAs(expectedResponse)); +public class TasksHandlerTest extends BaseTest { + + private final String basePath = "onap/so/infra/tasks/v1"; + + @Test + public void getTasksTestByOriginalRequestId() + throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + wireMockServer.stubFor(post(urlPathEqualTo("/sobpmnengine/task")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("Camunda/GetTaskResponse.json").withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/sobpmnengine/task/b5fa707a-f55a-11e7-a796-005056856d52/variables")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("Camunda/GetTaskVariablesResponse.json").withStatus(HttpStatus.SC_OK))); + + String requestId = "4f6fe9ac-800c-4540-a93e-10d179fa1b0a"; + + // expected response + TasksGetResponse expectedResponse = new TasksGetResponse(); + + List<TaskList> taskList = new ArrayList<TaskList>(); + TaskList taskList1 = new TaskList(); + List<String> validEntries = new ArrayList<String>(); + validEntries.add(ValidResponses.rollback.toString()); + validEntries.add(ValidResponses.skip.toString()); + validEntries.add(ValidResponses.manual.toString()); + validEntries.add(ValidResponses.abort.toString()); + taskList1.setBuildingBlockName("UpdateConfigurationState"); + taskList1.setBuildingBlockStep("Configurationactivate SDNO Post-Check"); + taskList1.setErrorCode("1002"); + taskList1.setErrorSource("SDNO"); + taskList1.setErrorMessage( + "SDN-O exception: failed with message FAIL - AnsibleOperations exception: Failed : HTTP error code : 400 - Error Msg : no node list provided and no inventory file found"); + taskList1.setNfRole("VPROBE"); + taskList1.setType("fallout"); + taskList1.setOriginalRequestId(requestId); + taskList1.setOriginalRequestorId("VID"); + taskList1.setSubscriptionServiceType("PORT-MIRROR"); + taskList1.setTaskId("b5fa707a-f55a-11e7-a796-005056856d52"); + taskList1.setDescription("test task"); + taskList1.setTimeout("PT3000S"); + taskList1.setValidResponses(validEntries); + taskList.add(taskList1); + + expectedResponse.setTaskList(taskList); + 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); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + .queryParam("taskId", "b5fa707a-f55a-11e7-a796-005056856d52"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + ObjectMapper mapper = new ObjectMapper(); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + + // then + assertEquals(Response.Status.ACCEPTED.getStatusCode(), response.getStatusCode().value()); + TasksGetResponse realResponse = mapper.readValue(response.getBody(), TasksGetResponse.class); + assertThat(realResponse, sameBeanAs(expectedResponse)); 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)); - } + } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java index 48711a2595..1beb3b37a7 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/TestAppender.java @@ -27,11 +27,11 @@ import ch.qos.logback.core.AppenderBase; -public class TestAppender extends AppenderBase<ILoggingEvent> { +public class TestAppender extends AppenderBase<ILoggingEvent> { public static List<ILoggingEvent> events = new ArrayList<>(); - - @Override - protected void append(ILoggingEvent loggingEvent) { - events.add(loggingEvent); - } + + @Override + protected void append(ILoggingEvent loggingEvent) { + events.add(loggingEvent); + } } 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 new file mode 100644 index 0000000000..48abeacbc5 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/WorkflowSpecificationsHandlerTest.java @@ -0,0 +1,266 @@ +/*- + * ============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.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 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.skyscreamer.jsonassert.JSONAssert; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +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; + +public class WorkflowSpecificationsHandlerTest extends BaseTest { + @Autowired + WorkflowSpecificationsHandler workflowSpecificationsHandler; + + @Value("${wiremock.server.port}") + private String wiremockPort; + + private final String basePath = "onap/so/infra/workflowSpecifications/v1/workflows"; + + @Test + public void queryWorkflowSpecifications_Test_Success() + throws ParseException, JSONException, JsonParseException, JsonMappingException, IOException { + + 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")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(getWiremockResponseForCatalogdb("WorkflowSpecificationsQuery_Response.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("WorkflowActivitySpecSequence_Response.json")) + .withStatus(org.apache.http.HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(basePath)) + .queryParam("vnfModelVersionId", "b5fa707a-f55a-11e7-a796-005056856d52"); + + 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/WorkflowSpecifications.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 mapWorkflowsToWorkflowSpecifications_Test_Success() throws Exception { + List<Workflow> workflows = new ArrayList<Workflow>(); + Workflow workflow = new Workflow(); + workflow.setArtifactUUID("ab6478e4-ea33-3346-ac12-ab121484a333"); + workflow.setArtifactName("inPlaceSoftwareUpdate-1_0.bpmn"); + workflow.setVersion(1.0); + workflow.setDescription("xyz xyz"); + workflow.setName("inPlaceSoftwareUpdate"); + workflow.setOperationName("inPlaceSoftwareUpdate"); + workflow.setSource("sdc"); + workflow.setResourceTarget("vnf"); + + UserParameters userParameter1 = new UserParameters(); + userParameter1.setLabel("Operations Timeout"); + userParameter1.setType("text"); + userParameter1.setIsRequried(true); + userParameter1.setMaxLength(50); + userParameter1.setAllowableChars("someRegEx"); + userParameter1.setName("operations_timeout"); + userParameter1.setPayloadLocation("userParams"); + + UserParameters userParameter2 = new UserParameters(); + userParameter2.setLabel("Existing Software Version"); + userParameter2.setType("text"); + userParameter2.setIsRequried(true); + userParameter2.setMaxLength(50); + userParameter2.setAllowableChars("someRegEx"); + userParameter2.setName("existing_software_version"); + userParameter2.setPayloadLocation("userParams"); + + UserParameters userParameter3 = new UserParameters(); + userParameter3.setLabel("Cloud Owner"); + userParameter3.setType("text"); + userParameter3.setIsRequried(true); + userParameter3.setMaxLength(7); + userParameter3.setAllowableChars("someRegEx"); + userParameter3.setName("cloudOwner"); + userParameter3.setPayloadLocation("cloudConfiguration"); + + UserParameters userParameter4 = new UserParameters(); + userParameter4.setLabel("Tenant/Project ID"); + userParameter4.setType("text"); + userParameter4.setIsRequried(true); + userParameter4.setMaxLength(36); + userParameter4.setAllowableChars("someRegEx"); + userParameter4.setName("tenantId"); + userParameter4.setPayloadLocation("cloudConfiguration"); + + UserParameters userParameter5 = new UserParameters(); + userParameter5.setLabel("New Software Version"); + userParameter5.setType("text"); + userParameter5.setIsRequried(true); + userParameter5.setMaxLength(50); + userParameter5.setAllowableChars("someRegEx"); + userParameter5.setName("new_software_version"); + userParameter5.setPayloadLocation("userParams"); + + UserParameters userParameter6 = new UserParameters(); + userParameter6.setLabel("Cloud Region ID"); + userParameter6.setType("text"); + userParameter6.setIsRequried(true); + userParameter6.setMaxLength(7); + userParameter6.setAllowableChars("someRegEx"); + userParameter6.setName("lcpCloudRegionId"); + userParameter6.setPayloadLocation("cloudConfiguration"); + + + List<ActivitySpecUserParameters> activitySpecUserParameters = new ArrayList<ActivitySpecUserParameters>(); + + ActivitySpecUserParameters activitySpecUserParameter1 = new ActivitySpecUserParameters(); + activitySpecUserParameter1.setUserParameters(userParameter1); + activitySpecUserParameters.add(activitySpecUserParameter1); + + ActivitySpecUserParameters activitySpecUserParameter2 = new ActivitySpecUserParameters(); + activitySpecUserParameter2.setUserParameters(userParameter2); + activitySpecUserParameters.add(activitySpecUserParameter2); + + ActivitySpecUserParameters activitySpecUserParameter3 = new ActivitySpecUserParameters(); + activitySpecUserParameter3.setUserParameters(userParameter3); + activitySpecUserParameters.add(activitySpecUserParameter3); + + + ActivitySpecUserParameters activitySpecUserParameter4 = new ActivitySpecUserParameters(); + activitySpecUserParameter4.setUserParameters(userParameter4); + activitySpecUserParameters.add(activitySpecUserParameter4); + + ActivitySpecUserParameters activitySpecUserParameter5 = new ActivitySpecUserParameters(); + activitySpecUserParameter5.setUserParameters(userParameter5); + activitySpecUserParameters.add(activitySpecUserParameter5); + + ActivitySpecUserParameters activitySpecUserParameter6 = new ActivitySpecUserParameters(); + activitySpecUserParameter6.setUserParameters(userParameter6); + activitySpecUserParameters.add(activitySpecUserParameter6); + + List<WorkflowActivitySpecSequence> workflowActivitySpecSequences = + new ArrayList<WorkflowActivitySpecSequence>(); + + ActivitySpec activitySpec1 = new ActivitySpec(); + activitySpec1.setName("VNFQuiesceTrafficActivity"); + activitySpec1.setDescription("Activity to QuiesceTraffic on VNF"); + activitySpec1.setActivitySpecUserParameters(activitySpecUserParameters); + WorkflowActivitySpecSequence workflowActivitySpecSequence1 = new WorkflowActivitySpecSequence(); + workflowActivitySpecSequence1.setActivitySpec(activitySpec1); + workflowActivitySpecSequences.add(workflowActivitySpecSequence1); + + ActivitySpec activitySpec2 = new ActivitySpec(); + activitySpec2.setName("VNFHealthCheckActivity"); + activitySpec2.setDescription("Activity to HealthCheck VNF"); + activitySpec2.setActivitySpecUserParameters(activitySpecUserParameters); + WorkflowActivitySpecSequence workflowActivitySpecSequence2 = new WorkflowActivitySpecSequence(); + workflowActivitySpecSequence2.setActivitySpec(activitySpec2); + workflowActivitySpecSequences.add(workflowActivitySpecSequence2); + + ActivitySpec activitySpec3 = new ActivitySpec(); + activitySpec3.setName("FlowCompleteActivity"); + activitySpec3.setDescription("Activity to Complete the BPMN Flow"); + activitySpec3.setActivitySpecUserParameters(activitySpecUserParameters); + WorkflowActivitySpecSequence workflowActivitySpecSequence3 = new WorkflowActivitySpecSequence(); + workflowActivitySpecSequence3.setActivitySpec(activitySpec3); + workflowActivitySpecSequences.add(workflowActivitySpecSequence3); + + workflow.setWorkflowActivitySpecSequence(workflowActivitySpecSequences); + workflows.add(workflow); + + WorkflowSpecifications workflowSpecifications = + workflowSpecificationsHandler.mapWorkflowsToWorkflowSpecifications(workflows); + ObjectMapper mapper = new ObjectMapper(); + + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + String workflowSpecificationsJson = mapper.writeValueAsString(workflowSpecifications); + WorkflowSpecifications expectedResult = mapper.readValue( + new String(Files + .readAllBytes(Paths.get("src/test/resources/__files/catalogdb/WorkflowSpecifications.json"))), + WorkflowSpecifications.class); + String expectedResultJson = mapper.writeValueAsString(expectedResult); + + JSONAssert.assertEquals(expectedResultJson, workflowSpecificationsJson, false); + assertThat(expectedResult, sameBeanAs(workflowSpecifications).ignoring(WorkflowInputParameter.class)); + } + + private String getWiremockResponseForCatalogdb(String file) { + try { + File resource = ResourceUtils.getFile("classpath:__files/catalogdb/" + file); + return new String(Files.readAllBytes(resource.toPath())).replaceAll("localhost:8090", + "localhost:" + wiremockPort); + } catch (IOException e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java index 96ac02ae75..bc5869e416 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/DelE2ESvcRespTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class DelE2ESvcRespTest { @@ -31,7 +30,7 @@ public class DelE2ESvcRespTest { @Test public void verifyDelE2ESvcResp() throws Exception { test.setOperationId("operationId"); - assertEquals(test.getOperationId(),"operationId"); + assertEquals(test.getOperationId(), "operationId"); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java index 7cfee66d48..cbc835dfbb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2ERequestTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class E2ERequestTest { @@ -32,23 +31,23 @@ public class E2ERequestTest { public void verifyE2ERequest() throws Exception { test.setOperationId("operationId"); - assertEquals(test.getOperationId(),"operationId"); + assertEquals(test.getOperationId(), "operationId"); test.setOperation("operation"); - assertEquals(test.getOperation(),"operation"); + assertEquals(test.getOperation(), "operation"); test.setResult("result"); - assertEquals(test.getResult(),"result"); + assertEquals(test.getResult(), "result"); test.setReason("test"); - assertEquals(test.getReason(),"test"); + assertEquals(test.getReason(), "test"); test.setUserId("userId"); - assertEquals(test.getUserId(),"userId"); + assertEquals(test.getUserId(), "userId"); test.setOperationContent("operation"); - assertEquals(test.getOperationContent(),"operation"); + assertEquals(test.getOperationContent(), "operation"); test.setProgress(123); - assertEquals(test.getProgress(),123); + assertEquals(test.getProgress(), 123); test.setOperateAt("operate"); - assertEquals(test.getOperateAt(),"operate"); + assertEquals(test.getOperateAt(), "operate"); test.setFinishedAt("finished"); - assertEquals(test.getFinishedAt(),"finished"); + assertEquals(test.getFinishedAt(), "finished"); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java index a3bab01dfd..8dfe6dc006 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EServiceInstanceDeleteRequestTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import static org.junit.Assert.assertEquals; public class E2EServiceInstanceDeleteRequestTest { @@ -33,9 +32,9 @@ public class E2EServiceInstanceDeleteRequestTest { public void verifyE2ESerInstanceDelReq() throws Exception { test.setGlobalSubscriberId("id"); - assertEquals(test.getGlobalSubscriberId(),"id"); + assertEquals(test.getGlobalSubscriberId(), "id"); test.setServiceType("type"); - assertEquals(test.getServiceType(),"type"); + assertEquals(test.getServiceType(), "type"); } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java index 59bfa2a1d2..bb331904ca 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/E2EUserParamTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import java.util.HashMap; import java.util.Map; - import static org.junit.Assert.assertEquals; public class E2EUserParamTest { @@ -35,13 +33,13 @@ public class E2EUserParamTest { public void verifyE2EParam() throws Exception { test.setName("name"); - assertEquals(test.getName(),"name"); + assertEquals(test.getName(), "name"); test.setValue("value"); - assertEquals(test.getValue(),"value"); + assertEquals(test.getValue(), "value"); Map<String, Object> additionalProperties = new HashMap<>(); additionalProperties.put("name", test); - test.setAdditionalProperty("name",test); - assertEquals(test.getAdditionalProperties(),additionalProperties); + test.setAdditionalProperty("name", test); + assertEquals(test.getAdditionalProperties(), additionalProperties); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java index 59e10b3938..5b09cefc85 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/e2eserviceinstancebeans/NsParametersTest.java @@ -21,12 +21,10 @@ package org.onap.so.apihandlerinfra.e2eserviceinstancebeans; import org.junit.Test; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; - import static org.junit.Assert.assertEquals; public class NsParametersTest { @@ -37,15 +35,15 @@ public class NsParametersTest { @Test public void verifyNsParameters() throws Exception { - LocationConstraint obj =new LocationConstraint(); + LocationConstraint obj = new LocationConstraint(); List<LocationConstraint> locationConstraints = new ArrayList<LocationConstraint>(); locationConstraints.add(obj); test.setLocationConstraints(locationConstraints); - assertEquals(test.getLocationConstraints(),locationConstraints); - Map<String, Object> additionalParamForNs = new HashMap<String,Object>(); - additionalParamForNs.put("1",test); + assertEquals(test.getLocationConstraints(), locationConstraints); + Map<String, Object> additionalParamForNs = new HashMap<String, Object>(); + additionalParamForNs.put("1", test); test.setAdditionalParamForNs(additionalParamForNs); - assertEquals(test.getAdditionalParamForNs(),additionalParamForNs); + assertEquals(test.getAdditionalParamForNs(), additionalParamForNs); } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java index cbdfe6b831..9c7fd37d28 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tasksbeans/TasksBeansTest.java @@ -22,7 +22,6 @@ package org.onap.so.apihandlerinfra.tasksbeans; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; - import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.validation.Validator; import com.openpojo.validation.ValidatorBuilder; @@ -31,11 +30,11 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; -public class TasksBeansTest extends BaseTest{ - @Test - public void validateGettersAndSetters() { - Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) - .with(new SetterTester(), new GetterTester()).build(); - validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); - } +public class TasksBeansTest extends BaseTest { + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java index 1e11b74215..9ae1e5b232 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudOrchestrationTest.java @@ -20,7 +20,16 @@ package org.onap.so.apihandlerinfra.tenantisolation; -import com.fasterxml.jackson.databind.ObjectMapper; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.io.File; +import java.io.IOException; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Ignore; @@ -35,213 +44,242 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; +import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.MediaType; -import java.io.File; -import java.io.IOException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +public class CloudOrchestrationTest extends BaseTest { + private static final String path = "/onap/so/infra/cloudResources/v1"; -public class CloudOrchestrationTest extends BaseTest { - - private static final String path = "/onap/so/infra/cloudResources/v1"; - - private HttpHeaders headers = new HttpHeaders(); - - @Before - public void setupTestClass() throws Exception{ - stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED))); - } - - @Test - public void testCreateOpEnvObjectMapperError() throws IOException { - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody().toString(); - assertTrue(body.contains("Mapping of request to JSON object failed.")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testCreateOpEnvError() throws IOException { - - String request = "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"}," - + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody().toString(); - assertTrue(body.contains("Mapping of request to JSON object failed")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException { - stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "123", "PENDING")) - .withStatus(HttpStatus.SC_OK))); - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(409, response.getStatusCodeValue()); - } - - @Test - public void testCreateOperationalEnvironment() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - headers.set("X-TransactionID", "987654321"); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testCreateVNFDuplicateCheck() throws IOException { - stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString())) - .withStatus(HttpStatus.SC_OK))); - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(409, response.getStatusCodeValue()); - } - - @Test - public void testCreateVNF() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); - stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testActivate() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"), TenantIsolationRequest.class); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate"); - stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_NOT_FOUND))); - - stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); - } - - @Test - public void testDeactivate() throws IOException { - ObjectMapper mapper = new ObjectMapper(); - TenantIsolationRequest request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), TenantIsolationRequest.class); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); - - -// stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) -// .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa", Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); - } - - - @Test - @Ignore - public void testDeactivateDupCheck() throws IOException { - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestId"); - iar.setOperationalEnvName("myVnfOpEnv"); - iar.setRequestStatus(Status.IN_PROGRESS.toString()); - iar.setAction(Action.create.toString()); - iar.setRequestAction(Action.create.toString()); - iar.setRequestScope("UNKNOWN"); - //iarRepo.saveAndFlush(iar); - ObjectMapper mapper = new ObjectMapper(); - String request = mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(request, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - assertEquals(409, response.getStatusCodeValue()); - } - -}
\ No newline at end of file + private HttpHeaders headers = new HttpHeaders(); + + @Before + public void setupTestClass() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_CREATED))); + } + + @Test + public void testCreateOpEnvObjectMapperError() throws IOException { + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody().toString(); + assertTrue(body.contains("Mapping of request to JSON object failed.")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testCreateOpEnvError() throws IOException { + + String request = + "{\"requestDetails\":{\"requestInfo\":{\"resourceType\":\"operationalEnvironment\",\"instanceName\": \"myOpEnv\",\"source\": \"VID\",\"requestorId\": \"xxxxxx\"}," + + " \"requestParameters\": {\"tenantContext\": \"Test\",\"workloadContext\": \"ECOMP_E2E-IST\"}}}"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody().toString(); + assertTrue(body.contains("Mapping of request to JSON object failed")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testCreateOpEnvReqRecordDuplicateCheck() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "123", "PENDING")).withStatus(HttpStatus.SC_OK))); + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(409, response.getStatusCodeValue()); + } + + @Test + public void testCreateOperationalEnvironment() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + headers.set("X-TransactionID", "987654321"); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testCreateVNFDuplicateCheck() throws IOException { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestId", Status.IN_PROGRESS.toString())) + .withStatus(HttpStatus.SC_OK))); + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(409, response.getStatusCodeValue()); + } + + @Test + public void testCreateVNF() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/operationalEnvironments"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":null,\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testActivate() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"), + TenantIsolationRequest.class); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/activate"); + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo( + "{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7ff\"},\"instanceName\":\"myVnfOpEnv\",\"requestScope\":\"operationalEnvironment\"}")) + .willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_NOT_FOUND))); + + wireMockServer.stubFor( + get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7ff"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testDeactivate() throws IOException { + ObjectMapper mapper = new ObjectMapper(); + TenantIsolationRequest request = + mapper.readValue(new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), + TenantIsolationRequest.class); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<TenantIsolationRequest> entity = new HttpEntity<TenantIsolationRequest>(request, headers); + + + // wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl("checkInstanceNameDuplicate"))).withRequestBody(equalTo("{\"instanceIdMap\":{\"operationalEnvironmentId\":\"ff3514e3-5a33-55df-13ab-12abad84e7fa\"},\"instanceName\":null,\"requestScope\":\"operationalEnvironment\"}")).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, + // MediaType.APPLICATION_JSON) + // .withBodyFile((String.format(getResponseTemplate, "ff3514e3-5a33-55df-13ab-12abad84e7fa", + // Status.COMPLETE.toString()))).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathEqualTo(getTestUrl("checkVnfIdStatus/ff3514e3-5a33-55df-13ab-12abad84e7fa"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7fa/deactivate"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); + } + + + @Test + @Ignore + public void testDeactivateDupCheck() throws IOException { + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestId"); + iar.setOperationalEnvName("myVnfOpEnv"); + iar.setRequestStatus(Status.IN_PROGRESS.toString()); + iar.setAction(Action.create.toString()); + iar.setRequestAction(Action.create.toString()); + iar.setRequestScope("UNKNOWN"); + // iarRepo.saveAndFlush(iar); + ObjectMapper mapper = new ObjectMapper(); + String request = mapper.readValue( + new File("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"), String.class); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(request, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl( + createURLWithPort(path) + "/operationalEnvironments/ff3514e3-5a33-55df-13ab-12abad84e7ff/deactivate"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + assertEquals(409, response.getStatusCodeValue()); + } + +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java index 8ac84d6598..5f12060059 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/CloudResourcesOrchestrationTest.java @@ -20,6 +20,14 @@ package org.onap.so.apihandlerinfra.tenantisolation; +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.post; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import java.text.ParseException; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -31,280 +39,284 @@ import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; -import javax.ws.rs.core.MediaType; -import java.text.ParseException; -import static com.github.tomakehurst.wiremock.client.WireMock.*; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +public class CloudResourcesOrchestrationTest extends BaseTest { + + private String requestJSON = + "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }"; + private static final String path = "/onap/so/infra/cloudResourcesRequests"; + + HttpHeaders headers = new HttpHeaders(); + + @Before + public void setupTestClass() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_CREATED))); + } + + @Test + public void testUnlockFailObjectMapping() { + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + + String body = response.getBody(); + assertTrue(body.contains("Mapping of request to JSON object failed.")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError1() { + String requestJSON = "{\"requestDetails\": null }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid requestDetails is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError2() { + String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid source is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testParseOrchestrationError3() { + String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }"; + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("No valid requestorId is specified")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testGetInfraActiveRequestNull() { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody(); + assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB")); + assertEquals(400, response.getStatusCodeValue()); + + } + + @Test + public void testUnlock() throws ParseException { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS")) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock"); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); -public class CloudResourcesOrchestrationTest extends BaseTest{ - - private String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"xxxxxx\" } } }"; - private static final String path = "/onap/so/infra/cloudResourcesRequests"; - - HttpHeaders headers = new HttpHeaders(); - @Before - public void setupTestClass() throws Exception{ - stubFor(post(urlPathEqualTo(getTestUrl(""))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_CREATED))); - } - @Test - public void testUnlockFailObjectMapping() { - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - String body = response.getBody(); - assertTrue(body.contains("Mapping of request to JSON object failed.")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError1() { - String requestJSON = "{\"requestDetails\": null }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid requestDetails is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError2() { - String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"\",\"requestorId\":\"xxxxxx\" } } }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid source is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testParseOrchestrationError3() { - String requestJSON = "{\"requestDetails\":{\"requestInfo\":{\"source\":\"VID\",\"requestorId\":\"\" } } }"; - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/test/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("No valid requestorId is specified")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testGetInfraActiveRequestNull() { - stubFor(get(urlPathEqualTo(getTestUrl("request-id-null-check"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<String>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/request-id-null-check/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody(); - assertTrue(body.contains("Orchestration RequestId request-id-null-check is not found in DB")); - assertEquals(400, response.getStatusCodeValue()); - - } - - @Test - public void testUnlock() throws ParseException { - stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlock"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestUnlock", "IN_PROGRESS")) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlock/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - - assertEquals(204, response.getStatusCodeValue()); - } - - @Test - public void testUnlockComplete() throws ParseException { - stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.POST, entity, String.class); - String body = response.getBody().toString(); - assertTrue(body.contains("Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked")); - assertEquals(400, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvFilter() { - stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "not-there"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - //204s cannot have a body - //assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB")); - assertEquals(204, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvSuccess() throws ParseException { - stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplateNoBody, "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>("", headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); + assertEquals(204, response.getStatusCodeValue()); + } + + @Test + public void testUnlockComplete() throws ParseException { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestUnlockComplete"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, "requestIdtestUnlockComplete", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(requestJSON, headers); + + UriComponentsBuilder builder = + UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1/requestIdtestUnlockComplete/unlock"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.POST, entity, String.class); + String body = response.getBody().toString(); + assertTrue(body.contains( + "Orchestration RequestId requestIdtestUnlockComplete has a status of COMPLETE and can not be unlocked")); + assertEquals(400, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilter() { + wireMockServer.stubFor(get(urlPathEqualTo(getTestUrl("not-there"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "not-there"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + // 204s cannot have a body + // assertTrue(response.getBody().contains("Orchestration RequestId not-there is not found in DB")); + assertEquals(204, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvSuccess() throws ParseException { + wireMockServer + .stubFor(get(urlPathEqualTo(getTestUrl("90c56827-1c78-4827-bc4d-6afcdb37a51f"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplateNoBody, + "90c56827-1c78-4827-bc4d-6afcdb37a51f", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>("", headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "90c56827-1c78-4827-bc4d-6afcdb37a51f"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); 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)); assertEquals("90c56827-1c78-4827-bc4d-6afcdb37a51f", response.getHeaders().get("X-TransactionID").get(0)); - } - - @Test - public void testGetOperationalEnvFilterSuccess() throws ParseException { - stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(String.format(getResponseTemplate, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody("{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}") - .withBody("["+String.format(getResponseTemplateNoBody, "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")+"]") - .withStatus(HttpStatus.SC_OK))); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess"); - builder.queryParam("operationalEnvironmentName", "myVnfOpEnv"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - assertEquals(200, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilterSuccess() throws ParseException { + wireMockServer + .stubFor(get(urlPathEqualTo(getTestUrl("requestIdtestGetOperationalEnvFilterSuccess"))).willReturn( + aResponse().withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(String.format(getResponseTemplate, + "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE")) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + post(urlPathEqualTo(getTestUrl("getCloudOrchestrationFiltersFromInfraActive"))).willReturn(aResponse() + .withHeader(javax.ws.rs.core.HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody( + "{\"requestId\":\"getCloudOrchestrationFiltersFromInfraActive\", \"operationalEnvironmentName\":\"myVnfOpEnv\"}") + .withBody("[" + String.format(getResponseTemplateNoBody, + "requestIdtestGetOperationalEnvFilterSuccess", "COMPLETE") + "]") + .withStatus(HttpStatus.SC_OK))); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("requestId", "requestIdtestGetOperationalEnvFilterSuccess"); + builder.queryParam("operationalEnvironmentName", "myVnfOpEnv"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + assertEquals(200, response.getStatusCodeValue()); 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 testGetOperationalEnvFilterException1() throws ParseException { - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestId-getOpEnvFilterEx1"); - iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); - iar.setOperationalEnvId("operationalEnvironmentId"); - iar.setOperationalEnvName("operationalEnvName"); - iar.setRequestorId("xxxxxx"); - iar.setRequestBody(""); - iar.setRequestStatus("COMPLETE"); - iar.setRequestAction("TEST"); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>("", headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv"); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - assertEquals(500, response.getStatusCodeValue()); - } - - @Test - public void testGetOperationalEnvFilterException2() throws ParseException { - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("requestIdFilterException2"); - iar.setRequestScope("requestScope"); - iar.setRequestType("requestType"); - iar.setOperationalEnvId("operationalEnvId"); - iar.setOperationalEnvName("operationalEnvName"); - iar.setRequestorId("xxxxxx"); - iar.setRequestBody(""); - iar.setRequestStatus("COMPLETE"); - iar.setRequestAction("TEST"); - - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<String> entity = new HttpEntity<>(null, headers); - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); - - builder.queryParam("operationalEnvironmentName", ""); - - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.GET, entity, String.class); - - - assertEquals(500, response.getStatusCodeValue()); - assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified")); - } + } + + @Test + public void testGetOperationalEnvFilterException1() throws ParseException { + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestId-getOpEnvFilterEx1"); + iar.setRequestScope("requestScope"); + iar.setRequestType("requestType"); + iar.setOperationalEnvId("operationalEnvironmentId"); + iar.setOperationalEnvName("operationalEnvName"); + iar.setRequestorId("xxxxxx"); + iar.setRequestBody(""); + iar.setRequestStatus("COMPLETE"); + iar.setRequestAction("TEST"); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>("", headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("filter", "operationalEnvironmentName:EQUALS:myVnfOpEnv"); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + assertEquals(500, response.getStatusCodeValue()); + } + + @Test + public void testGetOperationalEnvFilterException2() throws ParseException { + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("requestIdFilterException2"); + iar.setRequestScope("requestScope"); + iar.setRequestType("requestType"); + iar.setOperationalEnvId("operationalEnvId"); + iar.setOperationalEnvName("operationalEnvName"); + iar.setRequestorId("xxxxxx"); + iar.setRequestBody(""); + iar.setRequestStatus("COMPLETE"); + iar.setRequestAction("TEST"); + + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<String> entity = new HttpEntity<>(null, headers); + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path) + "/v1"); + + builder.queryParam("operationalEnvironmentName", ""); + + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class); + + + assertEquals(500, response.getStatusCodeValue()); + assertTrue(response.getBody().toString().contains("No valid operationalEnvironmentName value is specified")); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java index 4e5cfaba48..e9237f604e 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/ModelDistributionRequestTest.java @@ -28,13 +28,10 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.contains; import static org.mockito.Mockito.doNothing; - import java.io.IOException; - import javax.inject.Provider; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; - import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Rule; @@ -55,82 +52,82 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.web.util.UriComponentsBuilder; - import com.fasterxml.jackson.databind.ObjectMapper; -public class ModelDistributionRequestTest extends BaseTest{ +public class ModelDistributionRequestTest extends BaseTest { - private static final String requestJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }"; + private static final String requestJSON = + "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\", \"errorReason\": \"Distribution failed in AAI\" }"; @Rule public ExpectedException thrown = ExpectedException.none(); - @Mock - private Provider<TenantIsolationRunnable> thread; - @InjectMocks - @Spy - private ModelDistributionRequest request = new ModelDistributionRequest(); - @Mock - private TenantIsolationRunnable runnable = new TenantIsolationRunnable(); - - @Before - public void beforeTest() { - Mockito.when(thread.get()).thenReturn(runnable); - } - - @Test - public void testObjectMapperError() throws ApiException{ + @Mock + private Provider<TenantIsolationRunnable> thread; + @InjectMocks + @Spy + private ModelDistributionRequest request = new ModelDistributionRequest(); + @Mock + private TenantIsolationRunnable runnable = new TenantIsolationRunnable(); + + @Before + public void beforeTest() { + Mockito.when(thread.get()).thenReturn(runnable); + } + + @Test + public void testObjectMapperError() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("Mapping of request to JSON object failed")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); request.updateModelDistributionStatus("", null, null); - } - - @Test - public void testParseError1() throws ApiException{ + } + + @Test + public void testParseError1() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("No valid status is specified")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); String requestErrorJSON = "{\"errorReason\": \"Distribution failed in AAI\" }"; request.updateModelDistributionStatus(requestErrorJSON, null, null); - } - - @Test - public void testParseError2() throws ApiException{ + } + + @Test + public void testParseError2() throws ApiException { thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("No valid errorReason is specified")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_BAD_PARAMETER))); String requestErrorJSON = "{\"status\": \"DISTRIBUTION_COMPLETE_ERROR\"}"; request.updateModelDistributionStatus(requestErrorJSON, null, null); - } - - @Test - public void testSuccess() throws ApiException{ - doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class), anyString()); - - Response response = request.updateModelDistributionStatus(requestJSON, null, null); - - assertEquals(200, response.getStatus()); - } - - @Test - public void testSuccess_PATCH() throws ApiException, IOException{ - String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa"; - ObjectMapper mapper = new ObjectMapper(); - Distribution distRequest = mapper.readValue(requestJSON, Distribution.class); - HttpHeaders headers = new HttpHeaders(); - headers.set("Accept", MediaType.APPLICATION_JSON); - headers.set("Content-Type", MediaType.APPLICATION_JSON); - HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers); - - UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path)); - ResponseEntity<String> response = restTemplate.exchange( - builder.toUriString(), - HttpMethod.PATCH, entity, String.class); - assertEquals(200, response.getStatusCodeValue()); - - } - + } + + @Test + public void testSuccess() throws ApiException { + doNothing().when(runnable).run(any(Action.class), anyString(), any(CloudOrchestrationRequest.class), + anyString()); + + Response response = request.updateModelDistributionStatus(requestJSON, null, null); + + assertEquals(200, response.getStatus()); + } + + @Test + public void testSuccess_PATCH() throws ApiException, IOException { + String path = "/onap/so/infra/modelDistributions/v1/distributions/ff3514e3-5a33-55df-13ab-12abad84e7fa"; + ObjectMapper mapper = new ObjectMapper(); + Distribution distRequest = mapper.readValue(requestJSON, Distribution.class); + HttpHeaders headers = new HttpHeaders(); + headers.set("Accept", MediaType.APPLICATION_JSON); + headers.set("Content-Type", MediaType.APPLICATION_JSON); + HttpEntity<Distribution> entity = new HttpEntity<Distribution>(distRequest, headers); + + UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(createURLWithPort(path)); + ResponseEntity<String> response = + restTemplate.exchange(builder.toUriString(), HttpMethod.PATCH, entity, String.class); + assertEquals(200, response.getStatusCodeValue()); + + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java index 426be98486..d983d1eca8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/TenantIsolationRequestTest.java @@ -22,11 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolation; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -34,110 +32,116 @@ import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.tenantisolationbeans.Action; import org.onap.so.exceptions.ValidationException; import org.springframework.test.context.ActiveProfiles; - import com.fasterxml.jackson.databind.ObjectMapper; -public class TenantIsolationRequestTest extends BaseTest{ +public class TenantIsolationRequestTest extends BaseTest { + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Test + public void testParseCloudResourceECOMP() throws Exception { + try { + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseCloudResourceVNF() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseCloudResourceVNFInvalid() throws Exception { + expectedException.expect(ValidationException.class); + + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.create); + assertNotNull(request.getRequestId()); + } + + @Test + public void testParseActivateCloudResource() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.activate); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseActivateCloudResourceInvalid() throws Exception { + expectedException.expect(ValidationException.class); + + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.activate); + assertNotNull(request.getRequestId()); + } + + @Test + public void testParseDeactivateCloudResource() throws Exception { + try { + String requestJSON = new String(Files + .readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.deactivate); + assertNotNull(request.getRequestId()); + } catch (ValidationException e) { + fail(e.getMessage()); + } + } + + @Test + public void testParseDeactivateCloudResourceInvalid() throws Exception { + expectedException.expect(ValidationException.class); - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Test - public void testParseCloudResourceECOMP() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ECOMPOperationEnvironmentCreate.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseCloudResourceVNF() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreate.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseCloudResourceVNFInvalid() throws Exception { - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/VNFOperationEnvironmentCreateInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.create); - assertNotNull(request.getRequestId()); - } - - @Test - public void testParseActivateCloudResource() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironment.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.activate); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseActivateCloudResourceInvalid() throws Exception{ - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/ActivateOperationEnvironmentInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.activate); - assertNotNull(request.getRequestId()); - } - - @Test - public void testParseDeactivateCloudResource() throws Exception{ - try { - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironment.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.deactivate); - assertNotNull(request.getRequestId()); - } catch(ValidationException e) { - fail(e.getMessage()); - } - } - - @Test - public void testParseDeactivateCloudResourceInvalid() throws Exception{ - expectedException.expect(ValidationException.class); - - String requestJSON = new String(Files.readAllBytes(Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json"))); - ObjectMapper mapper = new ObjectMapper(); - HashMap<String, String> instanceIdMap = new HashMap<String,String>(); - CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); - TenantIsolationRequest request = new TenantIsolationRequest ("1234"); - request.parse(cor, instanceIdMap, Action.deactivate); - assertNotNull(request.getRequestId()); - } + String requestJSON = new String(Files.readAllBytes( + Paths.get("src/test/resources/TenantIsolation/DeactivateOperationEnvironmentInvalid.json"))); + ObjectMapper mapper = new ObjectMapper(); + HashMap<String, String> instanceIdMap = new HashMap<String, String>(); + CloudOrchestrationRequest cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class); + TenantIsolationRequest request = new TenantIsolationRequest("1234"); + request.parse(cor, instanceIdMap, Action.deactivate); + assertNotNull(request.getRequestId()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java index ef57fa1a76..34f9c04b82 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/DmaapOperationalEnvClientTest.java @@ -21,12 +21,10 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.text.ParseException; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.apihandlerinfra.ApiHandlerApplication; @@ -36,37 +34,37 @@ 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 com.fasterxml.jackson.databind.ObjectMapper; -public class DmaapOperationalEnvClientTest extends BaseTest{ - - private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; - private static final String operationalEnvironmentId = "28122015552391"; - private static final String operationalEnvironmentName = "OpEnv-name"; - private static final String operationalEnvironmentType = "VNF"; - private static final String tenantContext = "Test"; - private static final String workloadContext = "VNF_E2E-IST"; - private static final String action = "Create"; - @Autowired - private DmaapOperationalEnvClient client; - - @Test - public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException { - String content = this.getJson("ecomp-openv-request.json"); - ObjectMapper mapper = new ObjectMapper(); - CreateEcompOperationEnvironmentBean expected = mapper.readValue(content, CreateEcompOperationEnvironmentBean.class); - - String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName, operationalEnvironmentType, - tenantContext, workloadContext, action); - - assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual); - } - - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); - } - +public class DmaapOperationalEnvClientTest extends BaseTest { + + private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; + private static final String operationalEnvironmentId = "28122015552391"; + private static final String operationalEnvironmentName = "OpEnv-name"; + private static final String operationalEnvironmentType = "VNF"; + private static final String tenantContext = "Test"; + private static final String workloadContext = "VNF_E2E-IST"; + private static final String action = "Create"; + @Autowired + private DmaapOperationalEnvClient client; + + @Test + public void verifyCreateEcompOperationEnvironmentRequest() throws IOException, ApiException { + String content = this.getJson("ecomp-openv-request.json"); + ObjectMapper mapper = new ObjectMapper(); + CreateEcompOperationEnvironmentBean expected = + mapper.readValue(content, CreateEcompOperationEnvironmentBean.class); + + String actual = client.buildRequest(operationalEnvironmentId, operationalEnvironmentName, + operationalEnvironmentType, tenantContext, workloadContext, action); + + assertEquals("payloads are equal", mapper.writeValueAsString(expected), actual); + } + + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get(fileLocation + filename))); + } + } - + diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java index 7329f313a5..4263bbdee1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/OperationalEnvironmentPublisherTest.java @@ -21,10 +21,8 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.FileNotFoundException; import java.io.IOException; - import org.junit.Test; import org.junit.runner.RunWith; import org.onap.so.apihandlerinfra.ApiHandlerApplication; @@ -37,15 +35,17 @@ import org.springframework.test.context.junit4.SpringRunner; public class OperationalEnvironmentPublisherTest extends BaseTest { - @Autowired - private OperationalEnvironmentPublisher publisher; - - @Test - public void getProperties() throws FileNotFoundException, IOException { - - assertEquals("B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0", publisher.getAuth()); - assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey()); - assertEquals("test.operationalEnvironmentEvent", publisher.getTopic()); - assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get()); - } + @Autowired + private OperationalEnvironmentPublisher publisher; + + @Test + public void getProperties() throws FileNotFoundException, IOException { + + assertEquals( + "B3705D6C2D521257CC2422ACCF03B001811ACC49F564DDB3A2CF2A1378B6D35A23CDCB696F2E1EDFBE6758DFE7C74B94F4A7DF84A0E2BB904935AC4D900D5597DF981ADE6CE1FF3AF993BED0", + publisher.getAuth()); + assertEquals("07a7159d3bf51a0e53be7a8f89699be7", publisher.getKey()); + assertEquals("test.operationalEnvironmentEvent", publisher.getTopic()); + assertEquals("http://localhost:" + env.getProperty("wiremock.server.port"), publisher.getHost().get()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java index 3fcfa5dfa8..cb977607ea 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/dmaap/SDCDmaapClientTest.java @@ -21,50 +21,48 @@ package org.onap.so.apihandlerinfra.tenantisolation.dmaap; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.text.ParseException; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.tenantisolation.dmaap.CreateEcompOperationEnvironmentBean; - import com.fasterxml.jackson.databind.ObjectMapper; -public class SDCDmaapClientTest extends BaseTest{ - - private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; - - private static final String operationalEnvironmentId = "28122015552391"; - private static final String operationalEnvironmentName = "Operational Environment Name"; - private static final String operationalEnvironmentType = "ECOMP"; - private static final String tenantContext = "TEST"; - private static final String workloadContext = "ECOMP_E2E-IST"; - private static final String action = "Create" ; - - - - @Test - public void verifyasdcCreateoeRequest() throws IOException, ParseException{ - - ObjectMapper mapper = new ObjectMapper(); - - String expected = "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}"; - - - CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean(); - cBean.setOperationalEnvironmentId(operationalEnvironmentId); - cBean.setoperationalEnvironmentName(operationalEnvironmentName); - cBean.setoperationalEnvironmentType(operationalEnvironmentType); - cBean.settenantContext(tenantContext); - cBean.setworkloadContext(workloadContext); - cBean.setaction(action); - - String actual = mapper.writeValueAsString(cBean); - - assertEquals("payloads are equal", expected, actual); - } - - - +public class SDCDmaapClientTest extends BaseTest { + + private final String fileLocation = "src/test/resources/org/onap/so/client/asdc/create-ecompoe/"; + + private static final String operationalEnvironmentId = "28122015552391"; + private static final String operationalEnvironmentName = "Operational Environment Name"; + private static final String operationalEnvironmentType = "ECOMP"; + private static final String tenantContext = "TEST"; + private static final String workloadContext = "ECOMP_E2E-IST"; + private static final String action = "Create"; + + + + @Test + public void verifyasdcCreateoeRequest() throws IOException, ParseException { + + ObjectMapper mapper = new ObjectMapper(); + + String expected = + "{\"operationalEnvironmentId\":\"28122015552391\",\"operationalEnvironmentName\":\"Operational Environment Name\",\"operationalEnvironmentType\":\"ECOMP\",\"tenantContext\":\"TEST\",\"workloadContext\":\"ECOMP_E2E-IST\",\"action\":\"Create\"}"; + + + CreateEcompOperationEnvironmentBean cBean = new CreateEcompOperationEnvironmentBean(); + cBean.setOperationalEnvironmentId(operationalEnvironmentId); + cBean.setoperationalEnvironmentName(operationalEnvironmentName); + cBean.setoperationalEnvironmentType(operationalEnvironmentType); + cBean.settenantContext(tenantContext); + cBean.setworkloadContext(workloadContext); + cBean.setaction(action); + + String actual = mapper.writeValueAsString(cBean); + + assertEquals("payloads are equal", expected, actual); + } + + + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java index 2cb02e9666..8918b015e9 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/AAIClientCallFailedTest.java @@ -20,7 +20,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java index 5ee2eeaeba..7ad55ded48 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/SDCClientCallFailedTest.java @@ -21,25 +21,24 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class SDCClientCallFailedTest extends BaseTest{ - - @Test - public void testAsdcException() { - SDCClientCallFailed asdc = new SDCClientCallFailed("failed"); - - assertEquals("failed", asdc.getMessage()); - } - - @Test - public void testAsdcExceptionWithCause() { - SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable")); - - assertEquals("failed", asdc.getMessage()); - assertEquals("throwable", asdc.getCause().getMessage()); - } +public class SDCClientCallFailedTest extends BaseTest { + + @Test + public void testAsdcException() { + SDCClientCallFailed asdc = new SDCClientCallFailed("failed"); + + assertEquals("failed", asdc.getMessage()); + } + + @Test + public void testAsdcExceptionWithCause() { + SDCClientCallFailed asdc = new SDCClientCallFailed("failed", new Throwable("throwable")); + + assertEquals("failed", asdc.getMessage()); + assertEquals("throwable", asdc.getCause().getMessage()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java index f73a194a7b..db5d15a998 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/exceptions/TenantIsolationExceptionTest.java @@ -22,24 +22,23 @@ package org.onap.so.apihandlerinfra.tenantisolation.exceptions; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; -public class TenantIsolationExceptionTest extends BaseTest{ - - @Test - public void testTenantIsolation() { - TenantIsolationException exception = new TenantIsolationException(); - - assertNotNull(exception); - } - - @Test - public void testTenantIsolationException() { - TenantIsolationException exception = new TenantIsolationException("exception"); - - assertEquals("Tenant Isolation error: exception", exception.getMessage()); - } +public class TenantIsolationExceptionTest extends BaseTest { + + @Test + public void testTenantIsolation() { + TenantIsolationException exception = new TenantIsolationException(); + + assertNotNull(exception); + } + + @Test + public void testTenantIsolationException() { + TenantIsolationException exception = new TenantIsolationException("exception"); + + assertEquals("Tenant Isolation error: exception", exception.getMessage()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java index 78315e9fad..3a389ce227 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientHelperTest.java @@ -24,7 +24,6 @@ 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.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -34,11 +33,9 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; - import java.util.HashMap; import java.util.Map; import java.util.Optional; - import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.aai.domain.yang.OperationalEnvironment; @@ -49,100 +46,112 @@ import org.springframework.beans.factory.annotation.Autowired; -public class AAIClientHelperTest extends BaseTest{ - - @Autowired - private AAIClientHelper clientHelper; - - @Test - public void testGetAaiOperationalEnvironmentSuccess() throws Exception { - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - - AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); - Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class); - assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId()); - } - - @Test - public void testUpdateSuccess() { - stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class), any(OperationalEnvironment.class)); - clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv); - - verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testUpdateMapSuccess() { - stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - Map<String, String> payload = new HashMap<String, String>(); - payload.put("tenant-context", "Test"); - payload.put("workload-context", "ECOMPL_PSL"); - payload.put("operational-environment-status", "ACTIVE"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload); - clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload); - - verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testCreateSuccess() { - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setOperationalEnvironmentId("opeEvnId"); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class)); - clientHelper.createOperationalEnvironment(ecompEnv); - - verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } - - @Test - public void testcreateRelationshipSuccess() { - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - - try { - AAIClientHelper clientHelper = mock(AAIClientHelper.class); - doNothing().when(clientHelper).createRelationship(anyString(), anyString()); - clientHelper.createRelationship("managingEcomp", "vnfOp"); - - verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp"); - } catch(Exception e) { - fail("shouldn't reach here"); - } - } +public class AAIClientHelperTest extends BaseTest { + + @Autowired + private AAIClientHelper clientHelper; + + @Test + public void testGetAaiOperationalEnvironmentSuccess() throws Exception { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); + Optional<OperationalEnvironment> aaiOpEnv = wrapper.asBean(OperationalEnvironment.class); + assertEquals("EMOE-001", aaiOpEnv.get().getOperationalEnvironmentId()); + } + + @Test + public void testUpdateSuccess() { + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).updateAaiOperationalEnvironment(any(String.class), + any(OperationalEnvironment.class)); + clientHelper.updateAaiOperationalEnvironment("EMOE-001", ecompEnv); + + verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", ecompEnv); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testUpdateMapSuccess() { + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + Map<String, String> payload = new HashMap<String, String>(); + payload.put("tenant-context", "Test"); + payload.put("workload-context", "ECOMPL_PSL"); + payload.put("operational-environment-status", "ACTIVE"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).updateAaiOperationalEnvironment("EMOE-001", payload); + clientHelper.updateAaiOperationalEnvironment("EMOE-001", payload); + + verify(clientHelper, times(1)).updateAaiOperationalEnvironment("EMOE-001", payload); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testCreateSuccess() { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setOperationalEnvironmentId("opeEvnId"); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).createOperationalEnvironment(any(OperationalEnvironment.class)); + clientHelper.createOperationalEnvironment(ecompEnv); + + verify(clientHelper, times(1)).createOperationalEnvironment(ecompEnv); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } + + @Test + public void testcreateRelationshipSuccess() { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + + try { + AAIClientHelper clientHelper = mock(AAIClientHelper.class); + doNothing().when(clientHelper).createRelationship(anyString(), anyString()); + clientHelper.createRelationship("managingEcomp", "vnfOp"); + + verify(clientHelper, times(1)).createRelationship("managingEcomp", "vnfOp"); + } catch (Exception e) { + fail("shouldn't reach here"); + } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java index 3915fc8928..4a602345d3 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/AAIClientObjectBuilderTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import static org.junit.Assert.assertEquals; - import org.junit.Before; import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; @@ -30,43 +29,43 @@ import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestInfo; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters; - import com.fasterxml.jackson.databind.ObjectMapper; -public class AAIClientObjectBuilderTest extends BaseTest{ +public class AAIClientObjectBuilderTest extends BaseTest { - private CloudOrchestrationRequest request; - private ObjectMapper mapper = new ObjectMapper(); - - @Before + private CloudOrchestrationRequest request; + private ObjectMapper mapper = new ObjectMapper(); + + @Before public void testSetUp() { - request = getCloudOrchestrationRequest(); - } + request = getCloudOrchestrationRequest(); + } + + public CloudOrchestrationRequest getCloudOrchestrationRequest() { + CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); + RequestDetails reqDetails = new RequestDetails(); + RequestInfo reqInfo = new RequestInfo(); + RequestParameters reqParams = new RequestParameters(); + reqParams.setTenantContext("TEST"); + reqParams.setWorkloadContext("ECOMP_TEST"); + reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); + reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); + reqDetails.setRequestInfo(reqInfo); + reqDetails.setRequestParameters(reqParams); + cor.setRequestDetails(reqDetails); + return cor; + } - public CloudOrchestrationRequest getCloudOrchestrationRequest() { - CloudOrchestrationRequest cor = new CloudOrchestrationRequest(); - RequestDetails reqDetails = new RequestDetails(); - RequestInfo reqInfo = new RequestInfo(); - RequestParameters reqParams = new RequestParameters(); - reqParams.setTenantContext("TEST"); - reqParams.setWorkloadContext("ECOMP_TEST"); - reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); - reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); - reqDetails.setRequestInfo(reqInfo); - reqDetails.setRequestParameters(reqParams); - cor.setRequestDetails(reqDetails); - return cor; - } - - @Test - public void testGetAaiClientObjectBuilder() throws Exception { - AAIClientObjectBuilder builder = new AAIClientObjectBuilder(); - org.onap.aai.domain.yang.OperationalEnvironment operEnv = builder.buildAAIOperationalEnvironment("Active", request); - assertEquals("TEST", operEnv.getTenantContext()); - assertEquals("ECOMP_TEST", operEnv.getWorkloadContext()); - assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName()); - assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType()); - } + @Test + public void testGetAaiClientObjectBuilder() throws Exception { + AAIClientObjectBuilder builder = new AAIClientObjectBuilder(); + org.onap.aai.domain.yang.OperationalEnvironment operEnv = + builder.buildAAIOperationalEnvironment("Active", request); + assertEquals("TEST", operEnv.getTenantContext()); + assertEquals("ECOMP_TEST", operEnv.getWorkloadContext()); + assertEquals("TEST_ECOMP_ENVIRONMENT", operEnv.getOperationalEnvironmentName()); + assertEquals(OperationalEnvironment.ECOMP.toString(), operEnv.getOperationalEnvironmentType()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java index 6fda6afc50..800fb37039 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/ActivateVnfDBHelperTest.java @@ -21,7 +21,6 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import static org.junit.Assert.assertThat; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -34,112 +33,96 @@ 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 static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -public class ActivateVnfDBHelperTest extends BaseTest{ - - String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; - String requestId = "TEST_requestId"; - String origRequestId = "TEST_requestId"; - - String workloadContext1 = "TEST_workloadContext1"; - String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; - String distributionId1 = "TEST_distributionId1"; - String errorReason = "ABORTED"; - int retryCountThree = 3; - int retryCountZero = 0; - String recoveryActionRetry = "RETRY"; - String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); - String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); - String statusSent = "SENT"; - - OperationalEnvDistributionStatus expectedDistStatus; - OperationalEnvServiceModelStatus expectedServiceModelStatus; - - @Autowired - private ActivateVnfDBHelper dbHelper; - - @Before - public void testSetUp() { - // prepare expected OperationalEnvDistributionStatus object - expectedDistStatus = new OperationalEnvDistributionStatus(); - expectedDistStatus.setDistributionId(distributionId1); - expectedDistStatus.setOperationalEnvId(operationalEnvironmentId); - expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1); - expectedDistStatus.setDistributionIdStatus(statusOk); - expectedDistStatus.setRequestId(requestId); - expectedDistStatus.setDistributionIdErrorReason(""); - - // prepare expected OperationalEnvServiceModelStatus object - expectedServiceModelStatus = new OperationalEnvServiceModelStatus(); - expectedServiceModelStatus.setRequestId(requestId); - expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId); - expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1); - expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk); - expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry); - expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree)); - expectedServiceModelStatus.setWorkloadContext(workloadContext1); - expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - } - - @Test - public void testOperationalEnvDistributionStatusDbMethods() throws Exception { - - // test insert method - OperationalEnvDistributionStatus distStatus1 = - dbHelper.insertRecordToOperationalEnvDistributionStatus(distributionId1, - operationalEnvironmentId, - serviceModelVersionId1, - requestId, - statusOk, - ""); - assertThat(distStatus1, sameBeanAs(expectedDistStatus)); - - // prepare updated expected object - OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus; - expectedUpdatedDistStatus.setDistributionIdStatus(statusError); - expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason); - - // test update method - statusOk to statusError - OperationalEnvDistributionStatus distStatus2 = - dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1, - statusError, - errorReason - ); - assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus)); - - } - - @Test - public void testOperationalEnvServiceModelStatusDbMethods() throws Exception { - - // test insert method - OperationalEnvServiceModelStatus serviceModelStatus1 = - dbHelper.insertRecordToOperationalEnvServiceModelStatus(requestId, - operationalEnvironmentId, - serviceModelVersionId1, - statusOk, - recoveryActionRetry, - retryCountThree, - workloadContext1, - vnfOperationalEnvironmentId); - assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus)); - - // prepare updated expected object - OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1; - expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError); - expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero)); - - // test update method - update statusOk to statusError & retryCountThree to retryCountZero - OperationalEnvServiceModelStatus serviceModelStatus2 = - dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1, - statusError, - retryCountZero); - assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus)); - - } - +public class ActivateVnfDBHelperTest extends BaseTest { + + String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; + String requestId = "TEST_requestId"; + String origRequestId = "TEST_requestId"; + + String workloadContext1 = "TEST_workloadContext1"; + String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; + String distributionId1 = "TEST_distributionId1"; + String errorReason = "ABORTED"; + int retryCountThree = 3; + int retryCountZero = 0; + String recoveryActionRetry = "RETRY"; + String statusOk = DistributionStatus.DISTRIBUTION_COMPLETE_OK.toString(); + String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + String statusSent = "SENT"; + + OperationalEnvDistributionStatus expectedDistStatus; + OperationalEnvServiceModelStatus expectedServiceModelStatus; + + @Autowired + private ActivateVnfDBHelper dbHelper; + + @Before + public void testSetUp() { + // prepare expected OperationalEnvDistributionStatus object + expectedDistStatus = new OperationalEnvDistributionStatus(); + expectedDistStatus.setDistributionId(distributionId1); + expectedDistStatus.setOperationalEnvId(operationalEnvironmentId); + expectedDistStatus.setServiceModelVersionId(serviceModelVersionId1); + expectedDistStatus.setDistributionIdStatus(statusOk); + expectedDistStatus.setRequestId(requestId); + expectedDistStatus.setDistributionIdErrorReason(""); + + // prepare expected OperationalEnvServiceModelStatus object + expectedServiceModelStatus = new OperationalEnvServiceModelStatus(); + expectedServiceModelStatus.setRequestId(requestId); + expectedServiceModelStatus.setOperationalEnvId(operationalEnvironmentId); + expectedServiceModelStatus.setServiceModelVersionId(serviceModelVersionId1); + expectedServiceModelStatus.setServiceModelVersionDistrStatus(statusOk); + expectedServiceModelStatus.setRecoveryAction(recoveryActionRetry); + expectedServiceModelStatus.setRetryCount(new Integer(retryCountThree)); + expectedServiceModelStatus.setWorkloadContext(workloadContext1); + expectedServiceModelStatus.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + } + + @Test + public void testOperationalEnvDistributionStatusDbMethods() throws Exception { + + // test insert method + OperationalEnvDistributionStatus distStatus1 = dbHelper.insertRecordToOperationalEnvDistributionStatus( + distributionId1, operationalEnvironmentId, serviceModelVersionId1, requestId, statusOk, ""); + assertThat(distStatus1, sameBeanAs(expectedDistStatus)); + + // prepare updated expected object + OperationalEnvDistributionStatus expectedUpdatedDistStatus = expectedDistStatus; + expectedUpdatedDistStatus.setDistributionIdStatus(statusError); + expectedUpdatedDistStatus.setDistributionIdErrorReason(errorReason); + + // test update method - statusOk to statusError + OperationalEnvDistributionStatus distStatus2 = + dbHelper.updateStatusInOperationalEnvDistributionStatus(distStatus1, statusError, errorReason); + assertThat(distStatus2, sameBeanAs(expectedUpdatedDistStatus)); + + } + + @Test + public void testOperationalEnvServiceModelStatusDbMethods() throws Exception { + + // test insert method + OperationalEnvServiceModelStatus serviceModelStatus1 = dbHelper.insertRecordToOperationalEnvServiceModelStatus( + requestId, operationalEnvironmentId, serviceModelVersionId1, statusOk, recoveryActionRetry, + retryCountThree, workloadContext1, vnfOperationalEnvironmentId); + assertThat(serviceModelStatus1, sameBeanAs(expectedServiceModelStatus)); + + // prepare updated expected object + OperationalEnvServiceModelStatus expectedUpdatedServiceModelStatus = serviceModelStatus1; + expectedUpdatedServiceModelStatus.setServiceModelVersionDistrStatus(statusError); + expectedUpdatedServiceModelStatus.setRetryCount(new Integer(retryCountZero)); + + // test update method - update statusOk to statusError & retryCountThree to retryCountZero + OperationalEnvServiceModelStatus serviceModelStatus2 = + dbHelper.updateRetryCountAndStatusInOperationalEnvServiceModelStatus(serviceModelStatus1, statusError, + retryCountZero); + assertThat(serviceModelStatus2, sameBeanAs(expectedUpdatedServiceModelStatus)); + + } + } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java index 76bf0b0dbc..063902152c 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/helpers/SDCClientHelperTest.java @@ -22,11 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolation.helpers; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; - import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; @@ -35,160 +33,169 @@ import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.springframework.beans.factory.annotation.Autowired; -public class SDCClientHelperTest extends BaseTest{ +public class SDCClientHelperTest extends BaseTest { - String serviceModelVersionId = "TEST_uuid1"; - String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - String workloadContext = "TEST_workloadContext"; + String serviceModelVersionId = "TEST_uuid1"; + String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + String workloadContext = "TEST_workloadContext"; - @Autowired - private SDCClientHelper sdcClientUtils; + @Autowired + private SDCClientHelper sdcClientUtils; - @Test - public void postActivateOperationalEnvironment_Test() throws ApiException { + @Test + public void postActivateOperationalEnvironment_Test() throws ApiException { - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", "TEST_distributionId"); + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", "TEST_distributionId"); - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); - JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext); + JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, + operationalEnvironmentId, workloadContext); - assertEquals("202", jsonResponse.get("statusCode")); - assertEquals("Success", jsonResponse.get("message")); + assertEquals("202", jsonResponse.get("statusCode")); + assertEquals("Success", jsonResponse.get("message")); - } + } - @Test - public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException { + @Test + public void postActivateOperationalEnvironment_InvalidJson_Test() throws ApiException { - // ERROR in asdc response, invalid json object - JSONObject jsonErrorResponse = new JSONObject(); - jsonErrorResponse.put("requestError", ""); + // ERROR in asdc response, invalid json object + JSONObject jsonErrorResponse = new JSONObject(); + jsonErrorResponse.put("requestError", ""); - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_uuid1/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_BAD_REQUEST))); - JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, operationalEnvironmentId, workloadContext); + JSONObject jsonResponse = sdcClientUtils.postActivateOperationalEnvironment(serviceModelVersionId, + operationalEnvironmentId, workloadContext); - assertEquals("500", jsonResponse.get("statusCode")); - assertEquals("", jsonResponse.get("messageId")); - assertEquals(" Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.", jsonResponse.get("message")); + assertEquals("500", jsonResponse.get("statusCode")); + assertEquals("", jsonResponse.get("messageId")); + assertEquals( + " Encountered Error while calling SDC POST Activate. JSONObject[\"requestError\"] is not a JSONObject.", + jsonResponse.get("message")); - } + } - @Test - public void buildUriBuilderTest() { + @Test + public void buildUriBuilderTest() { - try { - String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); - assertEquals("http://localhost:" + env.getProperty("wiremock.server.port") + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate", url); + try { + String url = sdcClientUtils.buildUriBuilder(serviceModelVersionId, operationalEnvironmentId); + assertEquals( + "http://localhost:" + env.getProperty("wiremock.server.port") + + "/sdc/v1/catalog/services/TEST_uuid1/distribution/TEST_operationalEnvironmentId/activate", + url); - } catch (Exception e) { - fail("Exception caught: " + e.getMessage()); + } catch (Exception e) { + fail("Exception caught: " + e.getMessage()); - } - } + } + } - @Test - public void buildJsonWorkloadContextTest() throws JSONException { + @Test + public void buildJsonWorkloadContextTest() throws JSONException { - String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext); - assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload); + String jsonPayload = sdcClientUtils.buildJsonWorkloadContext(workloadContext); + assertEquals("{\"workloadContext\":\"TEST_workloadContext\"}", jsonPayload); - } + } - @Test - public void enhanceJsonResponseTest_Success() throws JSONException { + @Test + public void enhanceJsonResponseTest_Success() throws JSONException { - // build success response data - JSONObject sdcResponseJsonObj = new JSONObject(); - sdcResponseJsonObj.put("distributionId", "TEST_distributionId"); + // build success response data + JSONObject sdcResponseJsonObj = new JSONObject(); + sdcResponseJsonObj.put("distributionId", "TEST_distributionId"); - int statusCode = 202; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + int statusCode = 202; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("202", sdcResponseJsonObj.getString("statusCode")); - assertEquals("", sdcResponseJsonObj.getString("messageId")); - assertEquals("Success", sdcResponseJsonObj.getString("message")); - assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId")); + assertEquals("202", sdcResponseJsonObj.getString("statusCode")); + assertEquals("", sdcResponseJsonObj.getString("messageId")); + assertEquals("Success", sdcResponseJsonObj.getString("message")); + assertEquals("TEST_distributionId", sdcResponseJsonObj.getString("distributionId")); - } + } - @Test - public void enhanceJsonResponseTest_Error() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 409; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 409; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("409", sdcResponseJsonObj.getString("statusCode")); - assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId")); - assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message")); + assertEquals("409", sdcResponseJsonObj.getString("statusCode")); + assertEquals("SVC4675", sdcResponseJsonObj.getString("messageId")); + assertEquals("Error: Service state is invalid for this action.", sdcResponseJsonObj.getString("message")); - } + } - @Test - public void enhanceJsonResponseTest_Error_policyException() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error_policyException() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "POL5003"); - jsonMessages.put("text", "Error: Not authorized to use the API."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "POL5003"); + jsonMessages.put("text", "Error: Not authorized to use the API."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 403; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 403; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("403", sdcResponseJsonObj.getString("statusCode")); - assertEquals("POL5003", sdcResponseJsonObj.getString("messageId")); - assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message")); + assertEquals("403", sdcResponseJsonObj.getString("statusCode")); + assertEquals("POL5003", sdcResponseJsonObj.getString("messageId")); + assertEquals("Error: Not authorized to use the API.", sdcResponseJsonObj.getString("message")); - } + } - @Test - public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException { + @Test + public void enhanceJsonResponseTest_Error_UnexpectedFormat() throws JSONException { - // build error response data - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("messageId", "POL5003"); - jsonMessages.put("text", "Error: Not authorized to use the API."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("unexpectedResponseTag", jsonServException); + // build error response data + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("messageId", "POL5003"); + jsonMessages.put("text", "Error: Not authorized to use the API."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("unexpectedResponseTag", jsonServException); - String responseData = jsonErrorRequest.toString(); + String responseData = jsonErrorRequest.toString(); - JSONObject sdcResponseJsonObj = new JSONObject(responseData); - int statusCode = 403; - sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); + JSONObject sdcResponseJsonObj = new JSONObject(responseData); + int statusCode = 403; + sdcResponseJsonObj = sdcClientUtils.enhanceJsonResponse(sdcResponseJsonObj, statusCode); - assertEquals("500", sdcResponseJsonObj.getString("statusCode")); - assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId")); - assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message")); + assertEquals("500", sdcResponseJsonObj.getString("statusCode")); + assertEquals("Undefined Error Message!", sdcResponseJsonObj.getString("messageId")); + assertEquals("Unexpected response format from SDC.", sdcResponseJsonObj.getString("message")); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java index 418ed4270a..feebbd49d1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfOperationalEnvironmentTest.java @@ -21,21 +21,18 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.util.ArrayList; import java.util.List; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.json.JSONObject; import org.junit.Before; @@ -48,165 +45,176 @@ import org.onap.so.apihandlerinfra.exceptions.ApiException; import org.onap.so.apihandlerinfra.exceptions.ValidateException; import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; import org.onap.so.apihandlerinfra.tenantisolation.helpers.AAIClientHelper; +import org.onap.so.apihandlerinfra.tenantisolationbeans.Manifest; +import org.onap.so.apihandlerinfra.tenantisolationbeans.RecoveryAction; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails; import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters; import org.onap.so.apihandlerinfra.tenantisolationbeans.ServiceModelList; -import org.onap.so.apihandlerinfra.tenantisolationbeans.RecoveryAction; -import org.onap.so.apihandlerinfra.tenantisolationbeans.Manifest; import org.onap.so.client.aai.AAIVersion; import org.onap.so.client.aai.entities.AAIResultWrapper; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +public class ActivateVnfOperationalEnvironmentTest extends BaseTest { + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Autowired + private ActivateVnfOperationalEnvironment activateVnf; + @Autowired + private AAIClientHelper clientHelper; + + private final String requestId = "TEST_requestId"; + private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d"; + private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d"; + private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private final String workloadContext = "PVT"; + String recoveryActionRetry = "RETRY"; + private final String serviceModelVersionId = "TEST_serviceModelVersionId"; + int retryCount = 3; + private final String sdcDistributionId = "TEST_distributionId"; + private final String statusSent = "SENT"; + private final ObjectMapper mapper = new ObjectMapper(); + + @Before + public void init() { + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + + @Test + public void getAAIOperationalEnvironmentTest() { + + OperationalEnvironment aaiOpEnv; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); + aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get(); + assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId()); + assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0) + .getRelationshipData().get(0).getRelationshipValue()); + assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)); + assertEquals("EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId) + .asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId()); + + } + + @Test + public void executionTest() throws Exception { + + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + RequestDetails requestDetails = new RequestDetails(); + RequestParameters requestParameters = new RequestParameters(); + Manifest manifest = new Manifest(); + manifest.setServiceModelList(serviceModelVersionIdList); + requestParameters.setManifest(manifest); + requestParameters.setWorkloadContext(workloadContext); + requestDetails.setRequestParameters(requestParameters); + + request.setOperationalEnvironmentId(vnfOperationalEnvironmentId); + request.setRequestDetails(requestDetails); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + activateVnf.execute(requestId, request); + } + + @Test + public void processActivateSDCRequestTest_202() throws Exception { + + String distributionId = "TEST_distributionId"; + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", distributionId); + + // prepare request detail + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, + workloadContext, vnfOperationalEnvironmentId); + } + + @Test + public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException { + + // ERROR in asdc + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("message", "Failure"); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("policyException", jsonMessages); + // jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorResponse = new JSONObject(); + jsonErrorResponse.put("requestError", jsonServException); + + // prepare request detail + List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); + ServiceModelList serviceModelList1 = new ServiceModelList(); + serviceModelList1.setRecoveryAction(RecoveryAction.retry); + serviceModelList1.setServiceModelVersionId(serviceModelVersionId); + serviceModelVersionIdList.add(serviceModelList1); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setRequestStatus("PENDING"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + thrown.expect(ValidateException.class); + + activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, + workloadContext, vnfOperationalEnvironmentId); + } -public class ActivateVnfOperationalEnvironmentTest extends BaseTest{ - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - @Autowired - private ActivateVnfOperationalEnvironment activateVnf; - @Autowired - private AAIClientHelper clientHelper; - - private final String requestId = "TEST_requestId"; - private final String operationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e55d"; - private final String vnfOperationalEnvironmentId = "1dfe7154-eae0-44f2-8e7a-8e5e7882e66d"; - private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private final String workloadContext = "PVT"; - String recoveryActionRetry = "RETRY"; - private final String serviceModelVersionId = "TEST_serviceModelVersionId"; - int retryCount = 3; - private final String sdcDistributionId = "TEST_distributionId"; - private final String statusSent = "SENT"; - private final ObjectMapper mapper = new ObjectMapper(); - - @Before - public void init(){ - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":3,\"workloadContext\":\"PVT\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e66d\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestId\",\"distributionIdStatus\":\"SENT\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - - - @Test - public void getAAIOperationalEnvironmentTest() { - - OperationalEnvironment aaiOpEnv; - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED))); - - AAIResultWrapper wrapper = clientHelper.getAaiOperationalEnvironment("EMOE-001"); - aaiOpEnv = wrapper.asBean(OperationalEnvironment.class).get(); - assertEquals("EMOE-001", aaiOpEnv.getOperationalEnvironmentId()); - assertEquals("1dfe7154-eae0-44f2-8e7a-8e5e7882e55d", aaiOpEnv.getRelationshipList().getRelationship().get(0).getRelationshipData().get(0).getRelationshipValue()); - assertNotNull(activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId)); - assertEquals( "EMOE-001", activateVnf.getAAIOperationalEnvironment(operationalEnvironmentId).asBean(OperationalEnvironment.class).get().getOperationalEnvironmentId()); - - } - - @Test - public void executionTest() throws Exception { - - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - RequestDetails requestDetails = new RequestDetails(); - RequestParameters requestParameters = new RequestParameters(); - Manifest manifest = new Manifest(); - manifest.setServiceModelList(serviceModelVersionIdList); - requestParameters.setManifest(manifest); - requestParameters.setWorkloadContext(workloadContext); - requestDetails.setRequestParameters(requestParameters); - - request.setOperationalEnvironmentId(vnfOperationalEnvironmentId); - request.setRequestDetails(requestDetails); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/activateOperationalEnvironmentWithRelationship.json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - activateVnf.execute(requestId, request); - } - - @Test - public void processActivateSDCRequestTest_202() throws Exception { - - String distributionId = "TEST_distributionId"; - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", distributionId); - - // prepare request detail - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId); - } - - @Test - public void processActivateSDCRequestTest_409() throws ApiException, JsonProcessingException { - - // ERROR in asdc - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("message", "Failure"); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("policyException", jsonMessages); - //jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorResponse = new JSONObject(); - jsonErrorResponse.put("requestError", jsonServException); - - // prepare request detail - List<ServiceModelList> serviceModelVersionIdList = new ArrayList<>(); - ServiceModelList serviceModelList1 = new ServiceModelList(); - serviceModelList1.setRecoveryAction(RecoveryAction.retry); - serviceModelList1.setServiceModelVersionId(serviceModelVersionId); - serviceModelVersionIdList.add(serviceModelList1); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setRequestStatus("PENDING"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonErrorResponse.toString()).withStatus(HttpStatus.SC_CONFLICT))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("operationalEnvId\":\"1dfe7154-eae0-44f2-8e7a-8e5e7882e55d\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - thrown.expect(ValidateException.class); - - activateVnf.processActivateSDCRequest(requestId, operationalEnvironmentId, serviceModelVersionIdList, workloadContext, vnfOperationalEnvironmentId); - } - } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java index 6722941f95..9100e82beb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/ActivateVnfStatusOperationalEnvironmentTest.java @@ -21,26 +21,23 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; -import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.hamcrest.Matchers.startsWith; import static org.junit.Assert.assertEquals; - import static org.junit.Assert.assertThat; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.json.JSONObject; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; -import org.junit.Ignore; import org.junit.rules.ExpectedException; import org.onap.so.apihandler.common.ErrorNumbers; import org.onap.so.apihandlerinfra.BaseTest; @@ -54,606 +51,619 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.beans.OperationalEnvDistributionStatus; import org.onap.so.db.request.beans.OperationalEnvServiceModelStatus; import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - -public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest{ +public class ActivateVnfStatusOperationalEnvironmentTest extends BaseTest { - @Autowired - private ActivateVnfStatusOperationalEnvironment activateVnfStatus; + @Autowired + private ActivateVnfStatusOperationalEnvironment activateVnfStatus; @Rule public ExpectedException thrown = ExpectedException.none(); - private final String requestId = "TEST_requestId"; - private final String requestIdOrig = "TEST_requestIdOrig"; - private final String operationalEnvironmentId = "TEST_operationalEnvironmentId"; - private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; - private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private final String workloadContext = "TEST_workloadContext"; - private final String recoveryActionRetry = "RETRY"; - private final String recoveryActionAbort = "ABORT"; - private final String recoveryActionSkip = "SKIP"; - private final String serviceModelVersionId = "TEST_serviceModelVersionId"; - private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; - private final int retryCountThree = 3; - private final int retryCountTwo = 2; - private final int retryCountZero = 0; - private final String sdcDistributionId1 = "TEST_distributionId1"; - private final String sdcDistributionId = "TEST_distributionId"; - private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString(); - private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); - private final String statusSent = "SENT"; - String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; - - private final ObjectMapper mapper = new ObjectMapper(); - - @Test - public void checkOrUpdateOverallStatusTest_Ok() throws Exception { - - // two entries, both status Ok & retry 0 - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusOk); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId1); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusOk); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - - // overall is success - } - - @Test - public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); + private final String requestId = "TEST_requestId"; + private final String requestIdOrig = "TEST_requestIdOrig"; + private final String operationalEnvironmentId = "TEST_operationalEnvironmentId"; + private final String vnfOperationalEnvironmentId = "VNF_operationalEnvironmentId"; + private final CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private final String workloadContext = "TEST_workloadContext"; + private final String recoveryActionRetry = "RETRY"; + private final String recoveryActionAbort = "ABORT"; + private final String recoveryActionSkip = "SKIP"; + private final String serviceModelVersionId = "TEST_serviceModelVersionId"; + private final String serviceModelVersionId1 = "TEST_serviceModelVersionId1"; + private final int retryCountThree = 3; + private final int retryCountTwo = 2; + private final int retryCountZero = 0; + private final String sdcDistributionId1 = "TEST_distributionId1"; + private final String sdcDistributionId = "TEST_distributionId"; + private final String statusOk = Status.DISTRIBUTION_COMPLETE_OK.toString(); + private final String statusError = DistributionStatus.DISTRIBUTION_COMPLETE_ERROR.toString(); + private final String statusSent = "SENT"; + String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; + + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + public void checkOrUpdateOverallStatusTest_Ok() throws Exception { + + // two entries, both status Ok & retry 0 + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusOk); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId1); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusOk); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); + + // overall is success + } + + @Test + public void checkOrUpdateOverallStatusTest_Error() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); try { activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - - } - - @Test - public void checkOrUpdateOverallStatusTest_Waiting() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountTwo); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); - } - - @Test - public void executionTest_Ok() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusSent); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusSent); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - } - - @Test - public void executionTest_ERROR_Status_And_RETRY() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - - // prepare new distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - distribution.setErrorReason("Unable to process."); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - // prepare sdc return data - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId1); - - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - } - - @Test - public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountZero); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - + + } + + @Test + public void checkOrUpdateOverallStatusTest_Waiting() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountTwo); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + activateVnfStatus.checkOrUpdateOverallStatus(operationalEnvironmentId, requestIdOrig); + } + + @Test + public void executionTest_Ok() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusSent); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusSent); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"RETRY\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/aai/" + AAIVersion.LATEST + + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(put(urlPathEqualTo("/aai/" + AAIVersion.LATEST + + "/cloud-infrastructure/operational-environments/operational-environment/VNF_operationalEnvironmentId")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + } + + @Test + public void executionTest_ERROR_Status_And_RETRY() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare new distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + distribution.setErrorReason("Unable to process."); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + // prepare sdc return data + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId1); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\",\"distributionIdErrorReason\":\"Unable to process.\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).willReturn(aResponse() + .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + } + + @Test + public void executionTest_ERROR_Status_And_RETRY_And_RetryZero() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountZero); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"SENT\",\"recoveryAction\":\"RETRY\",\"retryCount\":2,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"handler\":{}}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - - } - - @Test - public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - distribution.setErrorReason("Unable to process."); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - // ERROR in sdc - JSONObject jsonMessages = new JSONObject(); - jsonMessages.put("statusCode", "409"); - jsonMessages.put("message", "Undefined Error Message!"); - jsonMessages.put("messageId", "SVC4675"); - jsonMessages.put("text", "Error: Service state is invalid for this action."); - JSONObject jsonServException = new JSONObject(); - jsonServException.put("serviceException", jsonMessages); - JSONObject jsonErrorRequest = new JSONObject(); - jsonErrorRequest.put("requestError", jsonServException); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString()).withStatus(HttpStatus.SC_CONFLICT))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - try { + + } + + @Test + public void executionTest_ERROR_Status_And_RETRY_And_ErrorSdc() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + distribution.setErrorReason("Unable to process."); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + // ERROR in sdc + JSONObject jsonMessages = new JSONObject(); + jsonMessages.put("statusCode", "409"); + jsonMessages.put("message", "Undefined Error Message!"); + jsonMessages.put("messageId", "SVC4675"); + jsonMessages.put("text", "Error: Service state is invalid for this action."); + JSONObject jsonServException = new JSONObject(); + jsonServException.put("serviceException", jsonMessages); + JSONObject jsonErrorRequest = new JSONObject(); + jsonErrorRequest.put("requestError", jsonServException); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("operationalEnvId\":\"VNF_operationalEnvironmentId\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonMessages.toString()) + .withStatus(HttpStatus.SC_CONFLICT))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e.getMessage(), startsWith("Failure calling SDC: statusCode: ")); assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); } - } - - @Test - public void executionTest_ERROR_Status_And_SKIP() throws Exception { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionSkip); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - // prepare distribution obj - OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId,operationalEnvironmentId,serviceModelVersionId); - distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name()); - - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(equalTo("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(equalTo("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - activateVnfStatus.execute(requestId, request); - - } - - @Test - public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException { - - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionAbort); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusError); - serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusError); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestIdOrig); - iar.setRequestStatus("PENDING"); - - stubFor(get(urlPathEqualTo("/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(serviceModelDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/"+sdcDistributionId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(distributionDb)) - .withStatus(HttpStatus.SC_OK))); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestIdOrig)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")) - .withRequestBody(containing("{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")) - .withRequestBody(containing("{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - + } + + @Test + public void executionTest_ERROR_Status_And_SKIP() throws Exception { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionSkip); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + // prepare distribution obj + OperationalEnvDistributionStatus distributionStatus = new OperationalEnvDistributionStatus(sdcDistributionId, + operationalEnvironmentId, serviceModelVersionId); + distributionStatus.setDistributionIdStatus(Status.DISTRIBUTION_COMPLETE_ERROR.name()); + + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(equalTo( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"recoveryAction\":\"SKIP\",\"retryCount\":0,\"workloadContext\":\"TEST_workloadContext\",\"createTime\":null,\"modifyTime\":null,\"vnfOperationalEnvId\":\"VNF_operationalEnvironmentId\"}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(equalTo( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_OK\",\"distributionIdErrorReason\":\"\",\"createTime\":null,\"modifyTime\":null}")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + activateVnfStatus.execute(requestId, request); + + } + + @Test + public void executionTest_ERROR_Status_And_ABORT() throws JsonProcessingException { + + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionAbort); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusError); + serviceModelDb.setVnfOperationalEnvId(vnfOperationalEnvironmentId); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusError); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_ERROR); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestIdOrig); + iar.setRequestStatus("PENDING"); + + wireMockServer.stubFor(get(urlPathEqualTo( + "/operationalEnvServiceModelStatus/search/findOneByOperationalEnvIdAndServiceModelVersionIdAndRequestId")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(serviceModelDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/operationalEnvDistributionStatus/" + sdcDistributionId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(distributionDb)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestIdOrig)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvDistributionStatus/")).withRequestBody(containing( + "{\"distributionId\":\"TEST_distributionId\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"requestId\":\"TEST_requestIdOrig\",\"distributionIdStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(post(urlPathEqualTo("/operationalEnvServiceModelStatus/")).withRequestBody(containing( + "{\"requestId\":\"TEST_requestIdOrig\",\"operationalEnvId\":\"TEST_operationalEnvironmentId\",\"serviceModelVersionId\":\"TEST_serviceModelVersionId\",\"serviceModelVersionDistrStatus\":\"DISTRIBUTION_COMPLETE_ERROR\"")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + try { activateVnfStatus.execute(requestId, request); - }catch(ApiException e) { - assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); - assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); - assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); - } - - } - - @Test - @Ignore - public void callSDClientForRetryTest_202() throws Exception { - OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); - serviceModelDb.setRequestId(requestIdOrig); - serviceModelDb.setServiceModelVersionId(serviceModelVersionId); - serviceModelDb.setWorkloadContext(workloadContext); - serviceModelDb.setRecoveryAction(recoveryActionRetry); - serviceModelDb.setOperationalEnvId(operationalEnvironmentId); - serviceModelDb.setRetryCount(retryCountThree); - serviceModelDb.setServiceModelVersionDistrStatus(statusSent); - - OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); - distributionDb.setDistributionId(sdcDistributionId); - distributionDb.setRequestId(requestIdOrig); - distributionDb.setOperationalEnvId(operationalEnvironmentId); - distributionDb.setDistributionIdStatus(statusSent); - distributionDb.setServiceModelVersionId(serviceModelVersionId); - distributionDb.setDistributionIdErrorReason(null); - - - - JSONObject jsonObject = new JSONObject(); - jsonObject.put("statusCode", "202"); - jsonObject.put("message", "Success"); - jsonObject.put("distributionId", sdcDistributionId1); - - // prepare distribution obj - Distribution distribution = new Distribution(); - distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); - request.setDistribution(distribution); - request.setDistributionId(sdcDistributionId); - request.setOperationalEnvironmentId(operationalEnvironmentId); - - stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()).withStatus(HttpStatus.SC_ACCEPTED))); - - JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution); - - assertEquals("TEST_distributionId1", jsonResponse.get("distributionId")); - assertEquals("Success", jsonResponse.get("message")); - assertEquals("202", jsonResponse.get("statusCode")); - - } + } catch (ApiException e) { + assertThat(e.getMessage(), startsWith("Overall Activation process is a Failure. ")); + assertEquals(e.getHttpResponseCode(), HttpStatus.SC_BAD_REQUEST); + assertEquals(e.getMessageID(), ErrorNumbers.SVC_DETAILED_SERVICE_ERROR); + } + + } + + @Test + @Ignore + public void callSDClientForRetryTest_202() throws Exception { + OperationalEnvServiceModelStatus serviceModelDb = new OperationalEnvServiceModelStatus(); + serviceModelDb.setRequestId(requestIdOrig); + serviceModelDb.setServiceModelVersionId(serviceModelVersionId); + serviceModelDb.setWorkloadContext(workloadContext); + serviceModelDb.setRecoveryAction(recoveryActionRetry); + serviceModelDb.setOperationalEnvId(operationalEnvironmentId); + serviceModelDb.setRetryCount(retryCountThree); + serviceModelDb.setServiceModelVersionDistrStatus(statusSent); + + OperationalEnvDistributionStatus distributionDb = new OperationalEnvDistributionStatus(); + distributionDb.setDistributionId(sdcDistributionId); + distributionDb.setRequestId(requestIdOrig); + distributionDb.setOperationalEnvId(operationalEnvironmentId); + distributionDb.setDistributionIdStatus(statusSent); + distributionDb.setServiceModelVersionId(serviceModelVersionId); + distributionDb.setDistributionIdErrorReason(null); + + + + JSONObject jsonObject = new JSONObject(); + jsonObject.put("statusCode", "202"); + jsonObject.put("message", "Success"); + jsonObject.put("distributionId", sdcDistributionId1); + + // prepare distribution obj + Distribution distribution = new Distribution(); + distribution.setStatus(Status.DISTRIBUTION_COMPLETE_OK); + request.setDistribution(distribution); + request.setDistributionId(sdcDistributionId); + request.setOperationalEnvironmentId(operationalEnvironmentId); + + wireMockServer.stubFor(post(urlPathMatching("/sdc/v1/catalog/services/TEST_serviceModelVersionId/distr.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(jsonObject.toString()) + .withStatus(HttpStatus.SC_ACCEPTED))); + + JSONObject jsonResponse = activateVnfStatus.callSDClientForRetry(distributionDb, serviceModelDb, distribution); + + assertEquals("TEST_distributionId1", jsonResponse.get("distributionId")); + assertEquals("Success", jsonResponse.get("message")); + assertEquals("202", jsonResponse.get("statusCode")); + + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java index 65ec5fade6..3114f91096 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateEcompOperationalEnvironmentTest.java @@ -20,12 +20,18 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; import static org.junit.Assert.assertThat; import java.util.UUID; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Test; import org.onap.so.apihandler.common.ErrorNumbers; @@ -43,90 +49,93 @@ import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.logger.ErrorCode; import org.onap.so.logger.MessageEnum; import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +public class CreateEcompOperationalEnvironmentTest extends BaseTest { + + @Autowired + private CreateEcompOperationalEnvironment createEcompOpEn; + private final ObjectMapper mapper = new ObjectMapper(); + + public CloudOrchestrationRequest getCloudOrchestrationRequest() { + CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + RequestDetails reqDetails = new RequestDetails(); + RequestInfo reqInfo = new RequestInfo(); + RequestParameters reqParams = new RequestParameters(); + reqParams.setTenantContext("TEST"); + reqParams.setWorkloadContext("ECOMP_TEST"); + reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); + reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); + reqDetails.setRequestInfo(reqInfo); + reqDetails.setRequestParameters(reqParams); + request.setRequestDetails(reqDetails); + request.setOperationalEnvironmentId("operationalEnvId"); + + return request; + } + + @Test + public void testProcess() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId("123"); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/123")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")).withRequestBody(containing( + "{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + createEcompOpEn.execute("123", getCloudOrchestrationRequest()); + } -public class CreateEcompOperationalEnvironmentTest extends BaseTest{ - - @Autowired - private CreateEcompOperationalEnvironment createEcompOpEn; - private final ObjectMapper mapper = new ObjectMapper(); + @Test + public void testProcessException() throws JsonProcessingException { + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/events/.*")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); + ErrorLoggerInfo errorLoggerInfo = + new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); + ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap", + HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo).build(); - public CloudOrchestrationRequest getCloudOrchestrationRequest() { - CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - RequestDetails reqDetails = new RequestDetails(); - RequestInfo reqInfo = new RequestInfo(); - RequestParameters reqParams = new RequestParameters(); - reqParams.setTenantContext("TEST"); - reqParams.setWorkloadContext("ECOMP_TEST"); - reqParams.setOperationalEnvironmentType(OperationalEnvironment.ECOMP); - reqInfo.setInstanceName("TEST_ECOMP_ENVIRONMENT"); - reqDetails.setRequestInfo(reqInfo); - reqDetails.setRequestParameters(reqParams); - request.setRequestDetails(reqDetails); - request.setOperationalEnvironmentId("operationalEnvId"); - - return request; - } - - @Test - public void testProcess() throws ApiException, JsonProcessingException { - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/events/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId("123"); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/123")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\"123\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL, operationalEnvironmentId - operationalEnvId; Success Message: SUCCESSFULLY Created ECOMP OperationalEnvironment.\",\"rollbackStatusMessage\":null,\"flowStatus\":null,\"retryStatusMessage\":null,\"progress\":100")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - createEcompOpEn.execute("123", getCloudOrchestrationRequest()); - } - - @Test - public void testProcessException() throws JsonProcessingException { - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/events/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_NOT_FOUND))); - ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.DataError).build(); - ValidateException expectedException = new ValidateException.Builder("Could not publish DMaap", HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER) - .errorInfo(errorLoggerInfo).build(); - InfraActiveRequests iar = new InfraActiveRequests(); String uuid = UUID.randomUUID().toString(); - iar.setRequestId(uuid); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+uuid)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+uuid+ "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); + iar.setRequestId(uuid); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + uuid)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + uuid + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE, operationalEnvironmentId - operationalEnvId; Error message:")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); - try { + try { createEcompOpEn.execute(uuid, getCloudOrchestrationRequest()); - }catch(ApiException e){ + } catch (ApiException e) { assertThat(e, sameBeanAs((ApiException) expectedException).ignoring("cause")); } - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java index ac274dc8dc..ebed4fa16b 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/CreateVnfOperationalEnvironmentTest.java @@ -20,15 +20,20 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; - import java.io.File; import java.nio.file.Files; import java.util.List; import java.util.UUID; - -import com.fasterxml.jackson.core.JsonProcessingException; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Test; @@ -41,144 +46,155 @@ import org.onap.so.client.grm.beans.Property; import org.onap.so.client.grm.beans.ServiceEndPointList; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; - +import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; +public class CreateVnfOperationalEnvironmentTest extends BaseTest { + + private CloudOrchestrationRequest request; + private ServiceEndPointList serviceEndpoints; + private ServiceEndPointList serviceEndpoints2; + + @Autowired + private CreateVnfOperationalEnvironment createVnfOpEnv; + + @Before + public void testSetUp() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json"); + request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class); + String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json"); + serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class); + String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json"); + serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class); + } + + @Test + public void testGetEcompManagingEnvironmentId() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId()); + } + + @Test + public void testGetTenantContext() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("Test", createVnfOpEnv.getTenantContext()); + } + + @Test + public void testGetEnvironmentName() { + createVnfOpEnv.setRequest(request); + List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties(); + assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); + } + + @Test + public void testGetEnvironmentNameEndpointListBeginWithUpperCase() { + createVnfOpEnv.setRequest(request); + List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties(); + assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); + } + + @Test + public void testBuildServiceNameForVnf() throws Exception { + createVnfOpEnv.setRequest(request); + assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory")); + } + + @Test + public void testGetSearchKey() { + createVnfOpEnv.setRequest(request); + OperationalEnvironment ecompEnv = new OperationalEnvironment(); + ecompEnv.setTenantContext("Test"); + ecompEnv.setWorkloadContext("ECOMPL_PSL"); + assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv)); + } + + public String getFileContentsAsString(String fileName) { + String content = ""; + try { + ClassLoader classLoader = this.getClass().getClassLoader(); + File file = new File(classLoader.getResource(fileName).getFile()); + content = new String(Files.readAllBytes(file.toPath())); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); + } + return content; + } + + @Test + public void testExecute() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + String requestId = UUID.randomUUID().toString(); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + ObjectMapper mapper = new ObjectMapper(); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + createVnfOpEnv.execute(requestId, request); + } + + @Test + public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException { + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withBodyFile("vnfoperenv/ecompOperationalEnvironment.json") + .withStatus(HttpStatus.SC_ACCEPTED))); + String requestId = UUID.randomUUID().toString(); + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + ObjectMapper mapper = new ObjectMapper(); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); -public class CreateVnfOperationalEnvironmentTest extends BaseTest{ - - private CloudOrchestrationRequest request; - private ServiceEndPointList serviceEndpoints; - private ServiceEndPointList serviceEndpoints2; - - @Autowired - private CreateVnfOperationalEnvironment createVnfOpEnv; - - @Before - public void testSetUp() throws Exception { - ObjectMapper mapper = new ObjectMapper(); - String jsonRequest = getFileContentsAsString("__files/vnfoperenv/createVnfOperationalEnvironmentRequest.json"); - request = mapper.readValue(jsonRequest, CloudOrchestrationRequest.class); - String jsonServiceEndpoints = getFileContentsAsString("__files/vnfoperenv/endpoints.json"); - serviceEndpoints = mapper.readValue(jsonServiceEndpoints, ServiceEndPointList.class); - String jsonServiceEndpoints2 = getFileContentsAsString("__files/vnfoperenv/endpoints2.json"); - serviceEndpoints2 = mapper.readValue(jsonServiceEndpoints2, ServiceEndPointList.class); - } - @Test - public void testGetEcompManagingEnvironmentId() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("ff305d54-75b4-431b-adb2-eb6b9e5ff000", createVnfOpEnv.getEcompManagingEnvironmentId()); - } - - @Test - public void testGetTenantContext() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("Test", createVnfOpEnv.getTenantContext()); - } - - @Test - public void testGetEnvironmentName() { - createVnfOpEnv.setRequest(request); - List<Property> props = serviceEndpoints.getServiceEndPointList().get(0).getProperties(); - assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); - } - - @Test - public void testGetEnvironmentNameEndpointListBeginWithUpperCase() { - createVnfOpEnv.setRequest(request); - List<Property> props = serviceEndpoints2.getServiceEndPointList().get(0).getProperties(); - assertEquals("DEV", createVnfOpEnv.getEnvironmentName(props)); - } - - @Test - public void testBuildServiceNameForVnf() throws Exception { - createVnfOpEnv.setRequest(request); - assertEquals("Test.VNF_E2E-IST.Inventory", createVnfOpEnv.buildServiceNameForVnf("TEST.ECOMP_PSL.Inventory")); - } - - @Test - public void testGetSearchKey() { - createVnfOpEnv.setRequest(request); - OperationalEnvironment ecompEnv = new OperationalEnvironment(); - ecompEnv.setTenantContext("Test"); - ecompEnv.setWorkloadContext("ECOMPL_PSL"); - assertEquals("Test.ECOMPL_PSL.*", createVnfOpEnv.getSearchKey(ecompEnv)); - } - - public String getFileContentsAsString(String fileName) { - String content = ""; - try { - ClassLoader classLoader = this.getClass().getClassLoader(); - File file = new File(classLoader.getResource(fileName).getFile()); - content = new String(Files.readAllBytes(file.toPath())); - } - catch(Exception e) { - e.printStackTrace(); - System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); - } - return content; - } - - @Test - public void testExecute() throws ApiException, JsonProcessingException { - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints.json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - String requestId = UUID.randomUUID().toString(); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - ObjectMapper mapper = new ObjectMapper(); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - createVnfOpEnv.execute(requestId, request); - } - - @Test - public void testExecuteEndpointsListBeginWithUppercase() throws ApiException, JsonProcessingException { - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/endpoints2.json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBodyFile("vnfoperenv/ecompOperationalEnvironment.json").withStatus(HttpStatus.SC_ACCEPTED))); - String requestId = UUID.randomUUID().toString(); - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - ObjectMapper mapper = new ObjectMapper(); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - createVnfOpEnv.execute(requestId, request); - } + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + createVnfOpEnv.execute(requestId, request); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java index 7c24050775..16738e9799 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolation/process/DeactivateVnfOperationalEnvironmentTest.java @@ -20,12 +20,18 @@ package org.onap.so.apihandlerinfra.tenantisolation.process; -import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.containing; +import static com.github.tomakehurst.wiremock.client.WireMock.get; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.put; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.startsWith; - -import com.fasterxml.jackson.databind.ObjectMapper; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; import org.apache.http.HttpStatus; import org.junit.Before; import org.junit.Rule; @@ -38,130 +44,140 @@ import org.onap.so.apihandlerinfra.tenantisolation.CloudOrchestrationRequest; import org.onap.so.client.aai.AAIVersion; import org.onap.so.db.request.beans.InfraActiveRequests; import org.springframework.beans.factory.annotation.Autowired; +import com.fasterxml.jackson.databind.ObjectMapper; -import javax.ws.rs.core.HttpHeaders; -import javax.ws.rs.core.MediaType; - -public class DeactivateVnfOperationalEnvironmentTest extends BaseTest{ +public class DeactivateVnfOperationalEnvironmentTest extends BaseTest { @Rule public ExpectedException thrown = ExpectedException.none(); - @Autowired - private DeactivateVnfOperationalEnvironment deactivate; - - private CloudOrchestrationRequest request = new CloudOrchestrationRequest(); - private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff"; - private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe"; - - private ObjectMapper mapper = new ObjectMapper(); - - @Before - public void init(){ - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); - } - @Test - public void testDeactivateOperationalEnvironment() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"ACTIVE\"}"; - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - stubFor(post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateInvalidStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"SUCCESS\"}"; - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); + @Autowired + private DeactivateVnfOperationalEnvironment deactivate; + + private CloudOrchestrationRequest request = new CloudOrchestrationRequest(); + private String operationalEnvironmentId = "ff3514e3-5a33-55df-13ab-12abad84e7ff"; + private String requestId = "ff3514e3-5a33-55df-13ab-12abad84e7fe"; + + private ObjectMapper mapper = new ObjectMapper(); + + @Before + public void init() { + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"COMPLETE\",\"statusMessage\":\"SUCCESSFUL")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + } + + @Test + public void testDeactivateOperationalEnvironment() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"ACTIVE\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + put(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + wireMockServer.stubFor( + post(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json") + .withStatus(HttpStatus.SC_ACCEPTED))); + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + deactivate.execute(requestId, request); + } + + @Test + public void testDeactivateInvalidStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"SUCCESS\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("Invalid OperationalEnvironmentStatus on OperationalEnvironmentId: ")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); - + + InfraActiveRequests iar = new InfraActiveRequests(); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); + wireMockServer.stubFor(post(urlPathEqualTo("/infraActiveRequests/")) + .withRequestBody(containing("{\"requestId\":\"" + requestId + + "\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withStatus(HttpStatus.SC_OK))); + + deactivate.execute(requestId, request); + } + + @Test + public void testDeactivateInactiveStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); + InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - stubFor(post(urlPathEqualTo("/infraActiveRequests/")) - .withRequestBody(containing("{\"requestId\":\""+ requestId+"\",\"clientRequestId\":null,\"action\":null,\"requestStatus\":\"FAILED\",\"statusMessage\":\"FAILURE")) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withStatus(HttpStatus.SC_OK))); + iar.setRequestId(requestId); + iar.setOperationalEnvName("myOpEnv"); + iar.setRequestScope("create"); + iar.setRequestStatus("PENDING"); + iar.setRequestAction("UNKNOWN"); + wireMockServer.stubFor(get(urlPathEqualTo("/infraActiveRequests/" + requestId)) + .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) + .withBody(mapper.writeValueAsString(iar)).withStatus(HttpStatus.SC_OK))); deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateInactiveStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"INACTIVE\"}"; - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); - - InfraActiveRequests iar = new InfraActiveRequests(); - iar.setRequestId(requestId); - iar.setOperationalEnvName("myOpEnv"); - iar.setRequestScope("create"); - iar.setRequestStatus("PENDING"); - iar.setRequestAction("UNKNOWN"); - stubFor(get(urlPathEqualTo("/infraActiveRequests/"+requestId)) - .willReturn(aResponse().withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON) - .withBody(mapper.writeValueAsString(iar)) - .withStatus(HttpStatus.SC_OK))); - - deactivate.execute(requestId, request); - } - - @Test - public void testDeactivateNullStatus() throws Exception { - request.setOperationalEnvironmentId(operationalEnvironmentId); - request.setRequestDetails(null); - - String json = "{\"operational-environment-status\" : \"\"}"; - - stubFor(get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) - .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json).withStatus(HttpStatus.SC_ACCEPTED))); + } + + @Test + public void testDeactivateNullStatus() throws Exception { + request.setOperationalEnvironmentId(operationalEnvironmentId); + request.setRequestDetails(null); + + String json = "{\"operational-environment-status\" : \"\"}"; + + wireMockServer.stubFor( + get(urlPathMatching("/aai/" + AAIVersion.LATEST + "/cloud-infrastructure/operational-environments/.*")) + .willReturn(aResponse().withHeader("Content-Type", "application/json").withBody(json) + .withStatus(HttpStatus.SC_ACCEPTED))); thrown.expect(ValidateException.class); thrown.expectMessage(startsWith("OperationalEnvironmentStatus is null on OperationalEnvironmentId: ")); thrown.expect(hasProperty("httpResponseCode", is(HttpStatus.SC_BAD_REQUEST))); thrown.expect(hasProperty("messageID", is(ErrorNumbers.SVC_DETAILED_SERVICE_ERROR))); deactivate.execute(requestId, request); - } + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java index 8236e6766f..fdc84966e6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/tenantisolationbeans/TenantIsolationBeansTest.java @@ -22,12 +22,9 @@ package org.onap.so.apihandlerinfra.tenantisolationbeans; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; - import java.util.List; - import org.junit.Test; import org.onap.so.apihandlerinfra.BaseTest; - import com.openpojo.reflection.PojoClass; import com.openpojo.reflection.filters.FilterPackageInfo; import com.openpojo.reflection.impl.PojoClassFactory; @@ -39,49 +36,44 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; -public class TenantIsolationBeansTest extends BaseTest{ - - private static final int EXPECTED_CLASS_COUNT = 25; - private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans"; +public class TenantIsolationBeansTest extends BaseTest { + + private static final int EXPECTED_CLASS_COUNT = 25; + private static final String POJO_PACKAGE = "org.onap.so.apihandlerinfra.tenantisolationbeans"; + + @Test + public void ensureExpectedPojoCount() { + List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses(POJO_PACKAGE, new FilterPackageInfo()); + Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); + } + + @Test + public void testPojoStructureAndBehavior() { + Validator validator = ValidatorBuilder.create().with(new GetterMustExistRule()).with(new SetterMustExistRule()) + .with(new SetterTester()).with(new GetterTester()).build(); + + validator.validate(POJO_PACKAGE, new FilterPackageInfo()); + } + + @Test + public void testTenantIsolationToString() { + TenantIsolationRequest request = new TenantIsolationRequest(); + request.setRequestId("requestId"); + request.setRequestScope("scope"); + request.setRequestType("type"); + request.setStartTime("time"); + request.setRequestDetails(new RequestDetails()); + request.setRequestStatus(new RequestStatus()); - @Test - public void ensureExpectedPojoCount() { - List<PojoClass> pojoClasses = PojoClassFactory.getPojoClasses( POJO_PACKAGE, - new FilterPackageInfo()); - Affirm.affirmEquals("Classes added / removed?", EXPECTED_CLASS_COUNT, pojoClasses.size()); - } + assertNotNull(request.toString()); + } - @Test - public void testPojoStructureAndBehavior() { - Validator validator = ValidatorBuilder.create() - .with(new GetterMustExistRule()) - .with(new SetterMustExistRule()) - .with(new SetterTester()) - .with(new GetterTester()) - .build(); + @Test + public void testRequestListToString() { + RequestList list = new RequestList(); + list.setRequest(new Request()); + list.setRequestStatus(new RequestStatus()); - validator.validate(POJO_PACKAGE, new FilterPackageInfo()); - } - - @Test - public void testTenantIsolationToString() { - TenantIsolationRequest request = new TenantIsolationRequest(); - request.setRequestId("requestId"); - request.setRequestScope("scope"); - request.setRequestType("type"); - request.setStartTime("time"); - request.setRequestDetails(new RequestDetails()); - request.setRequestStatus(new RequestStatus()); - - assertNotNull(request.toString()); - } - - @Test - public void testRequestListToString() { - RequestList list = new RequestList(); - list.setRequest(new Request()); - list.setRequestStatus(new RequestStatus()); - - assertNotNull(list.toString()); - } + assertNotNull(list.toString()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java new file mode 100644 index 0000000000..0ea35a5b8c --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/CustomWorkflowValidationTest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 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.validation; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import org.junit.Test; +import org.onap.so.apihandlerinfra.Action; +import org.onap.so.apihandlerinfra.BaseTest; +import org.onap.so.exceptions.ValidationException; +import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CustomWorkflowValidationTest extends BaseTest { + + @Test + public void testCustomWorkflowValidation() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.inPlaceSoftwareUpdate, 1, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vnf"); + + CustomWorkflowValidation validation = new CustomWorkflowValidation(); + validation.validate(info); + + assertEquals(info.getSir().getRequestDetails().getCloudConfiguration().getCloudOwner(), "att-aic"); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java index 02fd7a1aca..54da0baa92 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RelatedInstancesValidationTest.java @@ -21,35 +21,33 @@ package org.onap.so.apihandlerinfra.validation; import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Test; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class RelatedInstancesValidationTest extends BaseTest{ +public class RelatedInstancesValidationTest extends BaseTest { + + @Test + public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vnf"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); + RelatedInstancesValidation validation = new RelatedInstancesValidation(); + validation.validate(info); - @Test - public void testCreateVnfNetworkInstanceGroup() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RelatedInstances/v7CreateVnfNetworkInstanceGroup.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vnf"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - sir.getRequestDetails().getModelInfo().setModelCustomizationName("name"); - RelatedInstancesValidation validation = new RelatedInstancesValidation(); - validation.validate(info); - - assertEquals(info.getVnfType(), "Test/name"); - } + assertEquals(info.getVnfType(), "Test/name"); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java index bd9b95dc12..4f5209d8b4 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/RequestParametersValidationTest.java @@ -22,148 +22,153 @@ package org.onap.so.apihandlerinfra.validation; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; - import org.junit.Test; import org.onap.so.apihandlerinfra.Action; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class RequestParametersValidationTest extends BaseTest{ +public class RequestParametersValidationTest extends BaseTest { + + @Test + public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithNoALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters()); + info.setRequestScope("vfModule"); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithFalseALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithNoALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertFalse(info.getReqParameters().getUsePreload()); + } + + @Test + public void testServiceWithTrueALaCarte() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes(Paths + .get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 6, true, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } - @Test - public void testVfModuleWithFalseALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithNoALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithTrueALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, true, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testVfModuleWithReqVersionBelow4() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 3, false, sir.getRequestDetails().getRequestParameters()); - info.setRequestScope("vfModule"); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithFalseALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithNoALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersNoALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - sir.getRequestDetails().getRequestParameters().setSubscriptionServiceType("subscriptionServiceType"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertFalse(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertFalse(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithTrueALaCarte() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleRequestParametersIsALaCarte.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 6, true, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } - - @Test - public void testServiceWithReqVersionBelow4() throws IOException, ValidationException { - String requestJson = new String(Files.readAllBytes(Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); - sir.getRequestDetails().getRequestParameters().setUsePreload(null); - ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), Action.createInstance, - 3, false, sir.getRequestDetails().getRequestParameters()); - sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); - info.setRequestScope("service"); - RequestParametersValidation validation = new RequestParametersValidation(); - validation.validate(info); - assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); - assertTrue(info.getReqParameters().getUsePreload()); - } + @Test + public void testServiceWithReqVersionBelow4() throws IOException, ValidationException { + String requestJson = new String(Files.readAllBytes( + Paths.get("src/test/resources/MsoRequestTest/RequestParameters/VfModuleModelVersionId.json"))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(requestJson, ServiceInstancesRequest.class); + sir.getRequestDetails().getRequestParameters().setUsePreload(null); + ValidationInformation info = new ValidationInformation(sir, new HashMap<String, String>(), + Action.createInstance, 3, false, sir.getRequestDetails().getRequestParameters()); + sir.setServiceInstanceId("0fd90c0c-0e3a-46e2-abb5-4c4820d5985b"); + info.setRequestScope("service"); + RequestParametersValidation validation = new RequestParametersValidation(); + validation.validate(info); + assertTrue(sir.getRequestDetails().getRequestParameters().getUsePreload()); + assertTrue(info.getReqParameters().getUsePreload()); + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java index c1c4915672..ba02254ad8 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/validation/UserParamsValidationTest.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; - import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -32,78 +31,94 @@ import org.onap.so.apihandlerinfra.Action; import org.onap.so.exceptions.ValidationException; import org.onap.so.serviceinstancebeans.Service; import org.onap.so.serviceinstancebeans.ServiceInstancesRequest; - import com.fasterxml.jackson.databind.ObjectMapper; -public class UserParamsValidationTest{ - - UserParamsValidation validation = new UserParamsValidation(); - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - public ValidationInformation setupValidationInformation(String path) throws IOException{ - String jsonInput = new String(Files.readAllBytes(Paths.get(path))); - ObjectMapper mapper = new ObjectMapper(); - ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); - ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, sir.getRequestDetails().getRequestParameters()); - for(Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()){ - ObjectMapper obj = new ObjectMapper(); - String input = obj.writeValueAsString(params.get("service")); - Service validate = obj.readValue(input, Service.class); - info.setUserParams(validate); - break; - } - info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); - return info; - } - - @Test - public void validateModelTypeExceptionTest() throws IOException, ValidationException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("No valid modelType in userParams service modelInfo is specified"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json")); - } - @Test - public void validateInstanceNameExceptionTest() throws IOException, ValidationException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json")); - } - @Test - public void validateModelTypeTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json")); - } - @Test - public void validateModelInvariantIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json")); - } - @Test - public void validateModelVersionIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json")); - } - @Test - public void validateModelNameTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json")); - } - @Test - public void validateModelVersionTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json")); - } - @Test - public void validateModelCustomizationIdTest() throws ValidationException, IOException{ - thrown.expect(ValidationException.class); - thrown.expectMessage("modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service"); - validation.validate(setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json")); - } -}
\ No newline at end of file +public class UserParamsValidationTest { + + UserParamsValidation validation = new UserParamsValidation(); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + public ValidationInformation setupValidationInformation(String path) throws IOException { + String jsonInput = new String(Files.readAllBytes(Paths.get(path))); + ObjectMapper mapper = new ObjectMapper(); + ServiceInstancesRequest sir = mapper.readValue(jsonInput, ServiceInstancesRequest.class); + ValidationInformation info = new ValidationInformation(sir, null, Action.createInstance, 7, false, + sir.getRequestDetails().getRequestParameters()); + for (Map<String, Object> params : sir.getRequestDetails().getRequestParameters().getUserParams()) { + ObjectMapper obj = new ObjectMapper(); + String input = obj.writeValueAsString(params.get("service")); + Service validate = obj.readValue(input, Service.class); + info.setUserParams(validate); + break; + } + info.setRequestInfo(sir.getRequestDetails().getRequestInfo()); + return info; + } + + @Test + public void validateModelTypeExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("No valid modelType in userParams service modelInfo is specified"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/UserParamsValidation/ModelInfoNoModelType.json")); + } + + @Test + public void validateInstanceNameExceptionTest() throws IOException, ValidationException { + thrown.expect(ValidationException.class); + thrown.expectMessage("instanceName in requestInfo does not match instanceName in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/MacroRequest.json")); + } + + @Test + public void validateModelTypeTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelType in modelInfo does not match modelType in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelType.json")); + } + + @Test + public void validateModelInvariantIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelInvariantId in modelInfo does not match modelInvariantId in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelInvariantId.json")); + } + + @Test + public void validateModelVersionIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelVersionId in modelInfo does not match modelVersionId in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersionId.json")); + } + + @Test + public void validateModelNameTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelName in modelInfo does not match modelName in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelName.json")); + } + + @Test + public void validateModelVersionTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage("modelVersion in modelInfo does not match modelVersion in userParams service"); + validation.validate( + setupValidationInformation("src/test/resources/Validation/UserParamsValidation/ModelVersion.json")); + } + + @Test + public void validateModelCustomizationIdTest() throws ValidationException, IOException { + thrown.expect(ValidationException.class); + thrown.expectMessage( + "modelCustomizationId in modelInfo does not match modelCustomizationId in userParams service"); + validation.validate(setupValidationInformation( + "src/test/resources/Validation/UserParamsValidation/ModelCustomizationId.json")); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java new file mode 100644 index 0000000000..e208a38f47 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/apihandlerinfra/workflowspecificationbeans/WorkflowSpecificationBeansTest.java @@ -0,0 +1,39 @@ +/*- + * ============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.workflowspecificationbeans; + +import org.junit.Test; +import org.onap.so.apihandlerinfra.BaseTest; +import com.openpojo.reflection.filters.FilterPackageInfo; +import com.openpojo.validation.Validator; +import com.openpojo.validation.ValidatorBuilder; +import com.openpojo.validation.rule.impl.GetterMustExistRule; +import com.openpojo.validation.rule.impl.SetterMustExistRule; +import com.openpojo.validation.test.impl.GetterTester; +import com.openpojo.validation.test.impl.SetterTester; + +public class WorkflowSpecificationBeansTest extends BaseTest { + @Test + public void validateGettersAndSetters() { + Validator validator = ValidatorBuilder.create().with(new SetterMustExistRule(), new GetterMustExistRule()) + .with(new SetterTester(), new GetterTester()).build(); + validator.validate("org.onap.so.apihandlerinfra.tasksbeans", new FilterPackageInfo()); + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java index 6555a9a66e..f178a3c0cb 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java +++ b/mso-api-handlers/mso-api-handler-infra/src/test/java/org/onap/so/client/grm/GRMClientTest.java @@ -25,21 +25,16 @@ import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; -import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; -import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; - import java.io.File; import java.nio.file.Files; import java.util.List; import java.util.Map; - import javax.ws.rs.core.MediaType; - import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -47,126 +42,116 @@ import org.junit.rules.ExpectedException; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.apihandlerinfra.BaseTest; import org.onap.so.apihandlerinfra.TestAppender; -import org.onap.so.client.grm.GRMClient; import org.onap.so.client.grm.beans.ServiceEndPoint; import org.onap.so.client.grm.beans.ServiceEndPointList; import org.onap.so.client.grm.beans.ServiceEndPointLookupRequest; import org.onap.so.client.grm.beans.ServiceEndPointRequest; import org.onap.so.client.grm.exceptions.GRMClientCallFailed; import org.slf4j.MDC; - import ch.qos.logback.classic.spi.ILoggingEvent; -public class GRMClientTest extends BaseTest{ - - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - private static final String uuidRegex = "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$"; - - @BeforeClass - public static void setUp() throws Exception { - System.setProperty("mso.config.path", "src/test/resources"); - } - - @Test - public void testFind() throws Exception { +public class GRMClientTest extends BaseTest { + + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + private static final String uuidRegex = + "(?i)^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-5][0-9a-f]{3}-?[089ab][0-9a-f]{3}-?[0-9a-f]{12}$"; + + @BeforeClass + public static void setUp() throws Exception { + System.setProperty("mso.config.path", "src/test/resources"); + } + + @Test + public void testFind() throws Exception { TestAppender.events.clear(); - String endpoints = getFileContentsAsString("__files/grm/endpoints.json"); - stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(200) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(endpoints))); - - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test"); - GRMClient client = new GRMClient(); - ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - List<ServiceEndPoint> list = sel.getServiceEndPointList(); - assertEquals(3, list.size()); - - boolean foundInvoke = false; - boolean foundInvokeReturn = false; - for(ILoggingEvent logEvent : TestAppender.events) - if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE") - ){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + String endpoints = getFileContentsAsString("__files/grm/endpoints.json"); + wireMockServer + .stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody(endpoints))); + + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, "/test"); + GRMClient client = new GRMClient(); + ServiceEndPointList sel = client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); + List<ServiceEndPoint> list = sel.getServiceEndPointList(); + assertEquals(3, list.size()); + + boolean foundInvoke = false; + boolean foundInvokeReturn = false; + for (ILoggingEvent logEvent : TestAppender.events) + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("GRM",mdc.get("TargetEntity")); - assertEquals("INPROGRESS",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvoke=true; - }else if(logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") && - logEvent.getMarker()!= null && logEvent.getMarker().getName().equals("INVOKE_RETURN")){ - Map<String,String> mdc = logEvent.getMDCPropertyMap(); + assertEquals("GRM", mdc.get("TargetEntity")); + assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + foundInvoke = true; + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.JaxRsClientLogging") + && logEvent.getMarker() != null && logEvent.getMarker().getName().equals("INVOKE_RETURN")) { + Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("200",mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("COMPLETED",mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - foundInvokeReturn=true; + assertEquals("200", mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); + assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + foundInvokeReturn = true; } - - if(!foundInvoke) + + if (!foundInvoke) fail("INVOKE Marker not found"); - - if(!foundInvokeReturn) + + if (!foundInvokeReturn) fail("INVOKE RETURN Marker not found"); - - verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) + + wireMockServer.verify(postRequestedFor(urlEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) .withHeader(ONAPLogConstants.Headers.INVOCATION_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) - .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); + .withHeader(ONAPLogConstants.Headers.REQUEST_ID.toString(), matching(uuidRegex)) + .withHeader(ONAPLogConstants.Headers.PARTNER_NAME.toString(), equalTo("SO"))); TestAppender.events.clear(); - } - - @Test - public void testFindFail() throws Exception { - stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")) - .willReturn(aResponse() - .withStatus(400) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody(""))); - - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); - } - - @Test - public void testAddFail() throws Exception { - stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")) - .willReturn(aResponse() - .withStatus(404) - .withHeader("Content-Type", MediaType.APPLICATION_JSON) - .withBody("test"))); - ServiceEndPointRequest request = new ServiceEndPointRequest(); - GRMClient client = new GRMClient(); - thrown.expect(GRMClientCallFailed.class); - client.addServiceEndPoint(request); - } - - @Test - public void testBuildServiceEndPointLookupRequest() { - GRMClient client = new GRMClient(); - ServiceEndPointLookupRequest request = client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV"); - assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName()); - assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor())); - assertEquals("DEV", request.getEnv()); - - } - - protected String getFileContentsAsString(String fileName) { - String content = ""; - try { - ClassLoader classLoader = this.getClass().getClassLoader(); - File file = new File(classLoader.getResource(fileName).getFile()); - content = new String(Files.readAllBytes(file.toPath())); - } - catch(Exception e) { - e.printStackTrace(); - System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); - } - return content; - } + } + + @Test + public void testFindFail() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/findRunning")).willReturn( + aResponse().withStatus(400).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody(""))); + + GRMClient client = new GRMClient(); + thrown.expect(GRMClientCallFailed.class); + client.findRunningServices("TEST.ECOMP_PSL.*", 1, "TEST"); + } + + @Test + public void testAddFail() throws Exception { + wireMockServer.stubFor(post(urlPathEqualTo("/GRMLWPService/v1/serviceEndPoint/add")).willReturn( + aResponse().withStatus(404).withHeader("Content-Type", MediaType.APPLICATION_JSON).withBody("test"))); + ServiceEndPointRequest request = new ServiceEndPointRequest(); + GRMClient client = new GRMClient(); + thrown.expect(GRMClientCallFailed.class); + client.addServiceEndPoint(request); + } + + @Test + public void testBuildServiceEndPointLookupRequest() { + GRMClient client = new GRMClient(); + ServiceEndPointLookupRequest request = + client.buildServiceEndPointlookupRequest("TEST.ECOMP_PSL.Inventory", 1, "DEV"); + assertEquals("TEST.ECOMP_PSL.Inventory", request.getServiceEndPoint().getName()); + assertEquals(Integer.valueOf(1), Integer.valueOf(request.getServiceEndPoint().getVersion().getMajor())); + assertEquals("DEV", request.getEnv()); + + } + + protected String getFileContentsAsString(String fileName) { + String content = ""; + try { + ClassLoader classLoader = this.getClass().getClassLoader(); + File file = new File(classLoader.getResource(fileName).getFile()); + content = new String(Files.readAllBytes(file.toPath())); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Exception encountered reading " + fileName + ". Error: " + e.getMessage()); + } + return content; + } } diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json new file mode 100644 index 0000000000..611ccb3c66 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/MsoRequestTest/SuccessfulValidation/v1ExecuteCustomWorkflow.json @@ -0,0 +1,18 @@ +{ + "requestDetails": { + "cloudConfiguration": { + "cloudOwner": "att-aic", + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "requestParameters": { + "userParams": [ + { + "existing_software_version": "3.1", + "new_software_version": "3.2", + "operations_timeout": "3600" + } + ] + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json new file mode 100644 index 0000000000..611ccb3c66 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/ServiceInstanceTest/ExecuteCustomWorkflow.json @@ -0,0 +1,18 @@ +{ + "requestDetails": { + "cloudConfiguration": { + "cloudOwner": "att-aic", + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "requestParameters": { + "userParams": [ + { + "existing_software_version": "3.1", + "new_software_version": "3.2", + "operations_timeout": "3600" + } + ] + } + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json new file mode 100644 index 0000000000..3192865b52 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowActivitySpecSequence_Response.json @@ -0,0 +1,432 @@ +{ + "_embedded": { + + "workflowActivitySpecSequence": [ + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + } + ] + +} +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json new file mode 100644 index 0000000000..5556c602be --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecifications.json @@ -0,0 +1,113 @@ +{ + "workflowSpecificationList": [ + { + "workflowSpecification": { + "artifactInfo": { + "artifactType": "workflow", + "artifactUuid": "ab6478e4-ea33-3346-ac12-ab121484a333", + "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", + "artifactVersion": "1.0", + "artifactDescription": "xyz xyz", + "workflowName": "inPlaceSoftwareUpdate", + "operationName": "inPlaceSoftwareUpdate", + "workflowSource": "sdc", + "workflowResourceTarget": "vnf" + }, + "activitySequence": [ + { + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF" + }, + { + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF" + }, + { + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow" + } + ], + "workflowInputParameters": [ + { + "label": "Operations Timeout", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "50", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "operations_timeout", + "soPayloadLocation": "userParams" + }, + { + "label": "Existing Software Version", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "50", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "existing_software_version", + "soPayloadLocation": "userParams" + }, + { + "label": "Cloud Owner", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "7", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "cloudOwner", + "soPayloadLocation": "cloudConfiguration" + }, + { + "label": "Tenant/Project ID", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "36", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "tenantId", + "soPayloadLocation": "cloudConfiguration" + }, + { + "label": "New Software Version", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "50", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "new_software_version", + "soPayloadLocation": "userParams" + }, + { + "label": "Cloud Region ID", + "inputType": "text", + "required": true, + "validation": [ + { + "maxLength": "7", + "allowableChars": "someRegEx" + } + ], + "soFieldName": "lcpCloudRegionId", + "soPayloadLocation": "cloudConfiguration" + } + ] + } + } + ] +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json new file mode 100644 index 0000000000..c12365649e --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/WorkflowSpecificationsQuery_Response.json @@ -0,0 +1,468 @@ +{ + "_embedded": { + "workflows" :[ + { + "artifactUUID": "ab6478e4-ea33-3346-ac12-ab121484a333", + "artifactName": "inPlaceSoftwareUpdate-1_0.bpmn", + "name": "inPlaceSoftwareUpdate", + "operationName": "inPlaceSoftwareUpdate", + "version": 1, + "description": "xyz xyz", + "body": null, + "resourceTarget": "vnf", + "source": "sdc", + "timeoutMinutes": null, + "artifactChecksum": null, + "created": null, + "vnfResourceWorkflow": null, + "workflowActivitySpecSequence": [ + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFQuiesceTrafficActivity", + "description": "Activity to QuiesceTraffic on VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID[?]vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "VNFHealthCheckActivity", + "description": "Activity to HealthCheck VNF", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + }, + { + "activitySpecId": null, + "workflowId": null, + "activitySpec": { + "name": "FlowCompleteActivity", + "description": "Activity to Complete the BPMN Flow", + "version": null, + "created": null, + "workflowActivitySpecSequence": null, + "activitySpecActivitySpecCategories": null, + "activitySpecUserParameters": [ + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "operations_timeout", + "payloadLocation": "userParams", + "label": "Operations Timeout", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "existing_software_version", + "payloadLocation": "userParams", + "label": "Existing Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "cloudOwner", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Owner", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "tenantId", + "payloadLocation": "cloudConfiguration", + "label": "Tenant/Project ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 36, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "new_software_version", + "payloadLocation": "userParams", + "label": "New Software Version", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 50, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + }, + { + "activitySpecId": null, + "userParametersId": null, + "activitySpec": null, + "userParameters": { + "name": "lcpCloudRegionId", + "payloadLocation": "cloudConfiguration", + "label": "Cloud Region ID", + "type": "text", + "description": null, + "isRequried": true, + "maxLength": 7, + "allowableChars": "someRegEx", + "created": null, + "activitySpecUserParameters": null, + "id": null + }, + "id": null + } + ], + "activitySpecActivitySpecParameters": null, + "id": null + }, + "workflow": null, + "id": null, + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } + } + ], + "id": null, + + "_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/1/workflowActivitySpecSequence" + } + + } + + } +] +}, +"_links": { + "self": { + "href": "http://localhost:8090/workflow/search/findWorkflowByModelUUID?vnfResourceModelUUID=b5fa707a-f55a-11e7-a796-005056856d52" + }, + "workflowActivitySpecSequence": { + "href": "http://localhost:8090/workflow/b5fa707a-f55a-11e7-a796-005056856d52/workflowActivitySpecSequence" + } + + } +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationPCM_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationPCM_Response.json index 895c905ec9..4e760b71f1 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationPCM_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationPCM_Response.json @@ -1,4 +1,5 @@ { + "id" : 2, "modelCustomizationUUID": "b4ea86b4-253f-11e7-93ae-92361f002672", "label": "PCM", "minInstances": 0, @@ -8,19 +9,19 @@ "created": "2017-05-26 09:38:23.000", "_links": { "self": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModuleCustomization/2" }, "vfModuleCustomization": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModuleCustomization/2" }, "volumeHeatEnv": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/volumeHeatEnv" + "href": "http://localhost:8090/vfModuleCustomization/2/volumeHeatEnv" }, "heatEnvironment": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/heatEnvironment" + "href": "http://localhost:8090/vfModuleCustomization/2/heatEnvironment" }, "vfModule": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/vfModule" + "href": "http://localhost:8090/vfModuleCustomization/2/vfModule" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationVolGrp_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationVolGrp_Response.json index dd7fbe1a84..9ffd759416 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationVolGrp_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationVolGrp_Response.json @@ -1,4 +1,5 @@ { + "id": 1, "modelCustomizationUUID": "b4ea86b4-253f-11e7-93ae-92361f002671", "label": "PCM", "minInstances": 0, @@ -8,19 +9,19 @@ "created": "2017-05-26 09:38:23.000", "_links": { "self": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "vfModuleCustomization": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "volumeHeatEnv": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/volumeHeatEnv" + "href": "http://localhost:8090/vfModuleCustomization/1/volumeHeatEnv" }, "vfModule": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/vfModule" + "href": "http://localhost:8090/vfModuleCustomization/1/vfModule" }, "heatEnvironment": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002671/heatEnvironment" + "href": "http://localhost:8090/vfModuleCustomization/1/heatEnvironment" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomization_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomization_Response.json index a3ace2b24c..c23471fd31 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomization_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomization_Response.json @@ -1,4 +1,5 @@ { + "id" : 1, "modelCustomizationUUID": "cb82ffd8-252a-11e7-93ae-92361f002671", "label": "base", "minInstances": 0, @@ -8,19 +9,19 @@ "created": "2017-05-26 09:38:23.000", "_links": { "self": { - "href": "http://localhost:8090/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "vfModuleCustomization": { - "href": "http://localhost:8090/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "volumeHeatEnv": { - "href": "http://localhost:8090/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/volumeHeatEnv" + "href": "http://localhost:8090/vfModuleCustomization/1/volumeHeatEnv" }, "vfModule": { - "href": "http://localhost:8090/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/vfModule" + "href": "http://localhost:8090/vfModuleCustomization/1/vfModule" }, "heatEnvironment": { - "href": "http://localhost:8090/vfModuleCustomization/cb82ffd8-252a-11e7-93ae-92361f002671/heatEnvironment" + "href": "http://localhost:8090/vfModuleCustomization/1/heatEnvironment" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationsPCM_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationsPCM_Response.json index 4743bd39b2..5f7399ee26 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationsPCM_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModuleCustomizationsPCM_Response.json @@ -2,6 +2,7 @@ "_embedded": { "vfModuleCustomization": [ { + "id" : "1", "modelCustomizationUUID": "b4ea86b4-253f-11e7-93ae-92361f002672", "label": "PCM", "minInstances": 0, @@ -11,19 +12,19 @@ "created": "2017-05-26 09:38:23.000", "_links": { "self": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "vfModuleCustomization": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModuleCustomization/1" }, "volumeHeatEnv": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/volumeHeatEnv" + "href": "http://localhost:8090/vfModuleCustomization/1/volumeHeatEnv" }, "heatEnvironment": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/heatEnvironment" + "href": "http://localhost:8090/vfModuleCustomization/1/heatEnvironment" }, "vfModule": { - "href": "http://localhost:8090/vfModuleCustomization/b4ea86b4-253f-11e7-93ae-92361f002672/vfModule" + "href": "http://localhost:8090/vfModuleCustomization/1/vfModule" } } } @@ -31,7 +32,7 @@ }, "_links": { "self": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vfModuleCustomizations" + "href": "http://localhost:8090/vnfResourceCustomization/1/vfModuleCustomizations" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModulePCM_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModulePCM_Response.json index d4693bd075..8f717da9c6 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModulePCM_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vfModulePCM_Response.json @@ -1,4 +1,5 @@ { + "id" : 2, "modelUUID": "066de97e-253e-11e7-93ae-92361f002672", "modelInvariantUUID": "64efd51a-2544-11e7-93ae-92361f002671", "modelName": "test::PCM::module-1", @@ -9,22 +10,22 @@ "heatFiles": [], "_links": { "self": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModule/2" }, "vfModule": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672" + "href": "http://localhost:8090/vfModule/2" }, "vfModuleCustomization": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672/vfModuleCustomization" + "href": "http://localhost:8090/vfModule/2/vfModuleCustomization" }, "volumeHeatTemplate": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672/volumeHeatTemplate" + "href": "http://localhost:8090/vfModule/2/volumeHeatTemplate" }, "vnfResources": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672/vnfResources" + "href": "http://localhost:8090/vfModule/2/vnfResources" }, "moduleHeatTemplate": { - "href": "http://localhost:8090/vfModule/066de97e-253e-11e7-93ae-92361f002672/moduleHeatTemplate" + "href": "http://localhost:8090/vfModule/2/moduleHeatTemplate" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomizationForVfModule_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomizationForVfModule_Response.json index 85a02e76ba..ae46c418af 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomizationForVfModule_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomizationForVfModule_Response.json @@ -1,4 +1,5 @@ { + "id" : 3, "modelCustomizationUUID": "68dc9a92-214c-11e7-93ae-92361f002673", "modelInstanceName": "test", "created": "2017-05-26 09:38:24.000", @@ -13,20 +14,20 @@ "creationTimestamp": "2017-05-26T09:38:24.000+0000", "_links": { "self": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673" + "href": "http://localhost:8090/vnfResourceCustomization/3" }, "vnfResourceCustomization": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673{?projection}", + "href": "http://localhost:8090/vnfResourceCustomization/3{?projection}", "templated": true }, "vnfResources": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vnfResources" + "href": "http://localhost:8090/vnfResourceCustomization/3/vnfResources" }, "vfModuleCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vfModuleCustomizations" + "href": "http://localhost:8090/vnfResourceCustomization/3/vfModuleCustomizations" }, "vnfcInstanceGroupCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002673/vnfcInstanceGroupCustomizations" + "href": "http://localhost:8090/vnfResourceCustomization/3/vnfcInstanceGroupCustomizations" } } }
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_ReplaceVnf_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_ReplaceVnf_Response.json index 97e2be4a6a..0b7752d2dc 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_ReplaceVnf_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_ReplaceVnf_Response.json @@ -1,4 +1,7 @@ { + "_embedded": { + "vnfResourceCustomization": [{ + "id" : 1, "modelCustomizationUUID": "68dc9a92-214c-11e7-93ae-92361f002671", "modelInstanceName": "v10 1", "created": "2017-05-26 09:38:24.000", @@ -13,20 +16,22 @@ "creationTimestamp": "2017-05-26T09:38:24.000+0000", "_links": { "self": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671" + "href": "http://localhost:8090/vnfResourceCustomization/1" }, "vnfResourceCustomization": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671{?projection}", + "href": "http://localhost:8090/vnfResourceCustomization/1{?projection}", "templated": true }, "vnfResources": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671/vnfResources" + "href": "http://localhost:8090/vnfResourceCustomization/1/vnfResources" }, "vfModuleCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671/vfModuleCustomizations" + "href": "http://localhost:8090/vnfResourceCustomization/1/vfModuleCustomizations" }, "vnfcInstanceGroupCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002671/vnfcInstanceGroupCustomizations" + "href": "http://localhost:8090/vnfResourceCustomization/1/vnfcInstanceGroupCustomizations" } } -}
\ No newline at end of file +}] + } +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_Response.json index e83ad10245..b5e9999d03 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_Response.json +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/vnfResourceCustomization_Response.json @@ -1,32 +1,39 @@ { - "modelCustomizationUUID": "68dc9a92-214c-11e7-93ae-92361f002674", - "modelInstanceName": "test", - "created": "2017-05-26 09:38:24.000", - "minInstances": 0, - "maxInstances": 0, - "availabilityZoneMaxCount": 0, - "nfFunction": "", - "nfType": "", - "nfRole": "TEST", - "nfNamingCode": "", - "multiStageDesign": null, - "creationTimestamp": "2017-05-26T09:38:24.000+0000", - "_links": { - "self": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674" - }, - "vnfResourceCustomization": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674{?projection}", - "templated": true - }, - "vnfcInstanceGroupCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfcInstanceGroupCustomizations" - }, - "vnfResources": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vnfResources" - }, - "vfModuleCustomizations": { - "href": "http://localhost:8090/vnfResourceCustomization/68dc9a92-214c-11e7-93ae-92361f002674/vfModuleCustomizations" - } + "_embedded": { + "vnfResourceCustomization": [ + { + "_links": { + "self": { + "href": "http://localhost:8090/vnfResourceCustomization/4" + }, + "vfModuleCustomizations": { + "href": "http://localhost:8090/vnfResourceCustomization/4/vfModuleCustomizations" + }, + "vnfResourceCustomization": { + "href": "http://localhost:8090/vnfResourceCustomization/4{?projection}", + "templated": true + }, + "vnfResources": { + "href": "http://localhost:8090/vnfResourceCustomization/4/vnfResources" + }, + "vnfcInstanceGroupCustomizations": { + "href": "http://localhost:8090/vnfResourceCustomization/4/vnfcInstanceGroupCustomizations" + } + }, + "availabilityZoneMaxCount": 0, + "created": "2017-05-26 09:38:24.000", + "creationTimestamp": "2017-05-26T09:38:24.000+0000", + "id": 4, + "maxInstances": 0, + "minInstances": 0, + "modelCustomizationUUID": "68dc9a92-214c-11e7-93ae-92361f002674", + "modelInstanceName": "test", + "multiStageDesign": null, + "nfFunction": "", + "nfNamingCode": "", + "nfRole": "TEST", + "nfType": "" + } + ] } -}
\ No newline at end of file +} diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json new file mode 100644 index 0000000000..6e358f7e17 --- /dev/null +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/__files/catalogdb/workflow_Response.json @@ -0,0 +1,4 @@ +{ + "artifactUUID": "71526781-e55c-4cb7-adb3-97e09d9c76be", + "artifactName": "testingWorkflow" +}
\ No newline at end of file diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/data.sql b/mso-api-handlers/mso-api-handler-infra/src/test/resources/data.sql index 765b8cf75e..22f68e0579 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/data.sql +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/data.sql @@ -90,109 +90,9 @@ INSERT INTO service_recipe(ID, ACTION, VERSION_STR, DESCRIPTION, ORCHESTRATION_U ('37', 'unassignInstance', '1.0', 'Unassign ServiceInstance', '/mso/async/services/UnassignServiceInstance', NULL, '180', NULL, '2016-09-13 15:06:18', 'ff3514e3-5a33-55df-13ab-12abad84e7ff'), ('41', 'createInstance', '1', 'Create ServiceRequest', '/mso/async/services/CreateMacroServiceNetworkVnf', null, '180', '0', '2017-04-14 19:18:20', '109a153e-325f-4df5-8161-edd91314daee'); -INSERT INTO heat_template(ARTIFACT_UUID, NAME, VERSION, DESCRIPTION, BODY, TIMEOUT_MINUTES, ARTIFACT_CHECKSUM, CREATION_TIMESTAMP) VALUES -('ff874603-4222-11e7-9252-005056850d2e', 'module_mns_zrdm3frwl01exn_01_rgvm_1.yml', '1', 'created from csar', 'heat_template_version: 2013-05-23 description: heat template that creates TEST VNF parameters: TEST_server_name: type: string label: TEST server name description: TEST server name TEST_image_name: type: string label: image name description: TEST image name TEST_flavor_name: type: string label: TEST flavor name description: flavor name of TEST instance TEST_Role_net_name: type: string label: TEST network name description: TEST network name TEST_vnf_id: type: string label: TEST VNF Id description: TEST VNF Id resources:TEST: type: OS::Nova::Server properties: name: { get_param: TEST_server_name } image: { get_param: TEST_image_name } flavor: { get_param: TEST_flavor_name } networks: - port: { get_resource: TEST_port_0} metadata: vnf_id: {get_param: TEST_vnf_id} TEST_port_0: type: OS::Neutron::Port properties: network: { get_param: TEST_Role_net_name }', '60', 'MANUAL RECORD', '2017-01-21 23:26:56'), -('ff87482f-4222-11e7-9252-005056850d2e', 'module_mns_zrdm3frwl01exn_01_rgvm_1.yml', '1', 'created from csar', 'heat_template_version: 2013-05-23 description: heat template that creates TEST VNF parameters: TEST_server_name: type: string label: TEST server name description: TEST server name TEST_image_name: type: string label: image name description: TEST image name TEST_flavor_name: type: string label: TEST flavor name description: flavor name of TEST instance TEST_Role_net_name: type: string label: TEST network name description: TEST network name TEST_vnf_id: type: string label: TEST VNF Id description: TEST VNF Id resources:TEST: type: OS::Nova::Server properties: name: { get_param: TEST_server_name } image: { get_param: TEST_image_name } flavor: { get_param: TEST_flavor_name } networks: - port: { get_resource: TEST_port_0} metadata: vnf_id: {get_param: TEST_vnf_id} TEST_port_0: type: OS::Neutron::Port properties: network: { get_param: TEST_Role_net_name }', '60', 'MANUAL RECORD', '2017-01-21 23:26:56'), -('aa874603-4222-11e7-9252-005056850d2e', 'module_mns_zrdm3frwl01exn_01_rgvm_1.yml', '1', 'created from csar', 'heat_template_version: 2013-05-23 description: heat template that creates TEST VNF parameters: TEST_server_name: type: string label: TEST server name description: TEST server name TEST_image_name: type: string label: image name description: TEST image name TEST_flavor_name: type: string label: TEST flavor name description: flavor name of TEST instance TEST_Role_net_name: type: string label: TEST network name description: TEST network name TEST_vnf_id: type: string label: TEST VNF Id description: TEST VNF Id resources:TEST: type: OS::Nova::Server properties: name: { get_param: TEST_server_name } image: { get_param: TEST_image_name } flavor: { get_param: TEST_flavor_name } networks: - port: { get_resource: TEST_port_0} metadata: vnf_id: {get_param: TEST_vnf_id} TEST_port_0: type: OS::Neutron::Port properties: network: { get_param: TEST_Role_net_name }', '60', 'MANUAL RECORD', '2017-01-21 23:26:56'); - - -INSERT INTO heat_template_params(HEAT_TEMPLATE_ARTIFACT_UUID, PARAM_NAME, IS_REQUIRED, PARAM_TYPE, PARAM_ALIAS) VALUES -('ff874603-4222-11e7-9252-005056850d2e', 'availability_zone_0', 1, 'string', ''), -('ff874603-4222-11e7-9252-005056850d2e', 'exn_direct_net_fqdn', 1, 'string', ''), -('ff874603-4222-11e7-9252-005056850d2e', 'exn_hsl_net_fqdn', 1, 'string', ''); - - -INSERT INTO heat_environment(ARTIFACT_UUID, NAME, VERSION, DESCRIPTION, BODY, ARTIFACT_CHECKSUM, CREATION_TIMESTAMP) VALUES -('fefb1601-4222-11e7-9252-005056850d2e', 'module_nso.env', '2', 'Auto-generated HEAT Environment deployment artifact', 'parameters:\n availability_zone_0: \"alln-zone-1\"\n nso_flavor_name: \"citeis.1vCPUx2GB\"\n nso_image_name: \"RHEL-6.8-BASE-20160912\"\n nso_name_0: \"zrdm3vamp01nso001\"\n nso_oam_ip_0: \"172.18.25.175\"\n nso_oam_net_gw: \"172.18.25.1\"\n nso_oam_net_mask: \"255.255.255.0\"\n nso_sec_grp_id: \"36f48d82-f099-4437-bfbc-70d9e5d420d1\"\n nso_srv_grp_id: \"e431c477-5bd1-476a-bfa9-e4ce16b8356b\"\n oam_net_id: \"nso_oam\"\n vf_module_id: \"145cd730797234b4a40aa99335abc143\"\n vnf_id: \"730797234b4a40aa99335157b02871cd\"\n vnf_name: \"Mobisupport\"\n', 'MWI2ODY0Yjc1NDJjNWU1NjdkMTAyMjVkNzFmZDU0MzA=', '2017-11-27 08:42:58'), -('fefb1751-4333-11e7-9252-005056850d2e', 'module_nso.env', '2', 'Auto-generated HEAT Environment deployment artifact', 'parameters:\n availability_zone_0: \"alln-zone-1\"\n nso_flavor_name: \"citeis.1vCPUx2GB\"\n nso_image_name: \"RHEL-6.8-BASE-20160912\"\n nso_name_0: \"zrdm3vamp01nso001\"\n nso_oam_ip_0: \"172.18.25.175\"\n nso_oam_net_gw: \"172.18.25.1\"\n nso_oam_net_mask: \"255.255.255.0\"\n nso_sec_grp_id: \"36f48d82-f099-4437-bfbc-70d9e5d420d1\"\n nso_srv_grp_id: \"e431c477-5bd1-476a-bfa9-e4ce16b8356b\"\n oam_net_id: \"nso_oam\"\n vf_module_id: \"145cd730797234b4a40aa99335abc143\"\n vnf_id: \"730797234b4a40aa99335157b02871cd\"\n vnf_name: \"Mobisupport\"\n', 'MWI2ODY0Yjc1NDJjNWU1NjdkMTAyMjVkNzFmZDU0MzA=', '2017-11-27 08:42:58'); - -INSERT INTO vnf_resource(ORCHESTRATION_MODE, DESCRIPTION, CREATION_TIMESTAMP, MODEL_UUID, AIC_VERSION_MIN, AIC_VERSION_MAX, MODEL_INVARIANT_UUID, MODEL_VERSION, MODEL_NAME, TOSCA_NODE_TYPE, HEAT_TEMPLATE_ARTIFACT_UUID) VALUES -('HEAT', '1607 v10 - inherent network', '2017-04-14 21:46:28', 'ff2ae348-214a-11e7-93ae-92361f002672', '', '', '2fff5b20-214b-11e7-93ae-92361f002671', '2.0', 'v10', 'VF', null), -('HEAT', '1607 v10 - inherent network', '2017-04-14 21:46:28', 'fe6478e4-ea33-3346-ac12-ab121484a3fe', '', '', 'ff5256d1-5a33-55df-13ab-12abad84e7ff', '2.0', 'v12', 'VF', null), -('HEAT', '1607 v10 - inherent network', '2017-04-14 21:46:28', 'ff2ae348-214a-11e7-93ae-92361f002671', '', '', '2fff5b20-214b-11e7-93ae-92361f002671', '1.0', 'v10', 'VF', null), -('HEAT', '1607 vSAMP10a - inherent network', '2017-04-14 21:46:28', 'fe6478e4-ea33-3346-ac12-ab121484a3fw', '', '', '2fff5b20-214b-11e7-93ae-92361f002671', '1.0', 'vSAMP10a', 'VF', null); - -INSERT INTO vnf_resource_customization(MODEL_CUSTOMIZATION_UUID, MODEL_INSTANCE_NAME, MIN_INSTANCES, MAX_INSTANCES, AVAILABILITY_ZONE_MAX_COUNT, NF_TYPE, NF_ROLE, NF_FUNCTION, NF_NAMING_CODE, CREATION_TIMESTAMP, VNF_RESOURCE_MODEL_UUID, MULTI_STAGE_DESIGN) VALUES -('68dc9a92-214c-11e7-93ae-92361f002671', 'v10 1', '0', '0', '0', 'vSAMP', 'vSAMP', 'vSAMP', 'vSAMP', '2017-05-26 15:08:24', 'ff2ae348-214a-11e7-93ae-92361f002671', null), -('f78914d9-423b-11e7-93f8-0050569a7967', 'test', '0', '0', '0', 'vSAMP', 'vSAMP', 'vSAMP', 'vSAMP', '2017-05-26 15:08:24', 'f78914d9-423b-11e7-93f8-0050569a7967', null), -('68dc9a92-214c-11e7-93ae-92361f002672', 'test', '0', '0', '0', 'vSAMP', 'vSAMP', 'vSAMP', 'vSAMP', '2017-05-26 15:08:24', 'ff2ae348-214a-11e7-93ae-92361f002672', null), -('68dc9a92-214c-11e7-93ae-92361f002673', 'test', '0', '0', '0', 'vSAMP', 'vSAMP', 'vSAMP', 'vSAMP', '2017-05-26 15:08:24', 'fe6478e4-ea33-3346-ac12-ab121484a3fe', null), -('68dc9a92-214c-11e7-93ae-92361f002674', 'test', '0', '0', '0', '', 'TEST', '', '', '2017-05-26 15:08:24', 'fe6478e4-ea33-3346-ac12-ab121484a3fw', null); - - - -INSERT INTO vf_module(MODEL_UUID, MODEL_INVARIANT_UUID, MODEL_VERSION, MODEL_NAME, DESCRIPTION, IS_BASE, HEAT_TEMPLATE_ARTIFACT_UUID, VOL_HEAT_TEMPLATE_ARTIFACT_UUID, CREATION_TIMESTAMP, VNF_RESOURCE_MODEL_UUID) VALUES - -('20c4431c-246d-11e7-93ae-92361f002671', '78ca26d0-246d-11e7-93ae-92361f002671', '2', 'test::base::module-0', 'v10 DEV Base', '1', 'ff874603-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002671'), -('066de97e-253e-11e7-93ae-92361f002671', '64efd51a-2544-11e7-93ae-92361f002671', '2', 'test::PCM::module-1', 'v10 DEV PCM', '0', 'ff87482f-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002671'); - - -INSERT INTO vf_module_customization(MODEL_CUSTOMIZATION_UUID, LABEL, INITIAL_COUNT, MIN_INSTANCES, MAX_INSTANCES, AVAILABILITY_ZONE_COUNT, HEAT_ENVIRONMENT_ARTIFACT_UUID, VOL_ENVIRONMENT_ARTIFACT_UUID, CREATION_TIMESTAMP, VF_MODULE_MODEL_UUID) VALUES -('cb82ffd8-252a-11e7-93ae-92361f002671', 'base', '1', '0', '0', '0', 'fefb1601-4222-11e7-9252-005056850d2e', null, '2017-05-26 15:08:23', '20c4431c-246d-11e7-93ae-92361f002671'), -('b4ea86b4-253f-11e7-93ae-92361f002671', 'PCM', '0', '0', '0', '0', 'fefb1751-4333-11e7-9252-005056850d2e', null, '2017-05-26 15:08:23', '066de97e-253e-11e7-93ae-92361f002671'); - - -INSERT INTO vnf_res_custom_to_vf_module_custom(VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID, VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID, CREATION_TIMESTAMP) VALUES -('68dc9a92-214c-11e7-93ae-92361f002671', 'cb82ffd8-252a-11e7-93ae-92361f002671', '2017-05-26 15:08:24'), -('68dc9a92-214c-11e7-93ae-92361f002671', 'b4ea86b4-253f-11e7-93ae-92361f002671', '2017-05-26 15:08:24'); - -INSERT INTO allotted_resource(MODEL_UUID, MODEL_INVARIANT_UUID, MODEL_VERSION, MODEL_NAME, TOSCA_NODE_TYPE, SUBCATEGORY, DESCRIPTION, CREATION_TIMESTAMP) VALUES -('f6b7d4c6-e8a4-46e2-81bc-31cad5072842', 'b7a1b78e-6b6b-4b36-9698-8c9530da14af', '1.0', 'Tunnel_Xconn', '', '', '', '2017-05-26 15:08:24'); - -INSERT INTO allotted_resource_customization(MODEL_CUSTOMIZATION_UUID, MODEL_INSTANCE_NAME, PROVIDING_SERVICE_MODEL_INVARIANT_UUID, TARGET_NETWORK_ROLE, NF_TYPE, NF_ROLE, NF_FUNCTION, NF_NAMING_CODE, MIN_INSTANCES, MAX_INSTANCES, AR_MODEL_UUID, CREATION_TIMESTAMP) VALUES -('367a8ba9-057a-4506-b106-fbae818597c6', 'Sec_Tunnel_Xconn 11', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 'f6b7d4c6-e8a4-46e2-81bc-31cad5072842', TIMESTAMP '2017-01-20 16:14:20.0'); - - -INSERT INTO network_resource(MODEL_UUID, MODEL_NAME, MODEL_INVARIANT_UUID, DESCRIPTION, HEAT_TEMPLATE_ARTIFACT_UUID, NEUTRON_NETWORK_TYPE, MODEL_VERSION, TOSCA_NODE_TYPE, AIC_VERSION_MIN, AIC_VERSION_MAX, ORCHESTRATION_MODE, CREATION_TIMESTAMP) VALUES -('10b36f65-f4e6-4be6-ae49-9596dc1c47fc', 'CONTRAIL30_GNDIRECT', 'ce4ff476-9641-4e60-b4d5-b4abbec1271d', 'Contrail 30 GNDIRECT NW', 'aa874603-4222-11e7-9252-005056850d2e', 'BASIC', '1.0', '', '3.0', '', 'HEAT', '2017-01-17 20:35:05'); - -INSERT INTO network_resource_customization(MODEL_CUSTOMIZATION_UUID, MODEL_INSTANCE_NAME, NETWORK_TECHNOLOGY, NETWORK_TYPE, NETWORK_ROLE, NETWORK_SCOPE, CREATION_TIMESTAMP, NETWORK_RESOURCE_MODEL_UUID) VALUES -('3bdbb104-476c-483e-9f8b-c095b3d308ac', 'CONTRAIL30_GNDIRECT 9', '', '', '', '', '2017-04-19 14:28:32', '10b36f65-f4e6-4be6-ae49-9596dc1c47fc'); --second service insert - - - - -INSERT INTO vf_module(MODEL_UUID, MODEL_INVARIANT_UUID, MODEL_VERSION, MODEL_NAME, DESCRIPTION, IS_BASE, HEAT_TEMPLATE_ARTIFACT_UUID, VOL_HEAT_TEMPLATE_ARTIFACT_UUID, CREATION_TIMESTAMP, VNF_RESOURCE_MODEL_UUID) VALUES - -('20c4431c-246d-11e7-93ae-92361f002672', '78ca26d0-246d-11e7-93ae-92361f002671', '2', 'test::base::module-0', 'v10 DEV Base', '1', 'ff874603-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002671'), -('066de97e-253e-11e7-93ae-92361f002672', '64efd51a-2544-11e7-93ae-92361f002671', '2', 'test::PCM::module-1', 'v10 DEV PCM', '0', 'ff87482f-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002671'), -('test', '64efd51a-2544-11e7-93ae-92361f002671', '2', 'test::PCM::module-1', 'v10 DEV PCM', '1', 'ff87482f-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002672'), -('test1', 'b4ea86b4-253f-11e7-93ae-92361f002672', '2', 'test::PCM::module-1', 'v10 DEV PCM', '1', 'ff87482f-4222-11e7-9252-005056850d2e', null, '2016-09-14 18:19:56', 'ff2ae348-214a-11e7-93ae-92361f002672'); - -INSERT INTO vf_module_customization(MODEL_CUSTOMIZATION_UUID, LABEL, INITIAL_COUNT, MIN_INSTANCES, MAX_INSTANCES, AVAILABILITY_ZONE_COUNT, HEAT_ENVIRONMENT_ARTIFACT_UUID, VOL_ENVIRONMENT_ARTIFACT_UUID, CREATION_TIMESTAMP, VF_MODULE_MODEL_UUID) VALUES -('cb82ffd8-252a-11e7-93ae-92361f002672', 'base', '1', '0', '0', '0', 'fefb1601-4222-11e7-9252-005056850d2e', null, '2017-05-26 15:08:23', '20c4431c-246d-11e7-93ae-92361f002672'), -('b4ea86b4-253f-11e7-93ae-92361f002672', 'PCM', '0', '0', '0', '0', 'fefb1751-4333-11e7-9252-005056850d2e', null, '2017-05-26 15:08:23', '066de97e-253e-11e7-93ae-92361f002672'); - - -INSERT INTO vnf_res_custom_to_vf_module_custom(VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID, VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID, CREATION_TIMESTAMP) VALUES -('68dc9a92-214c-11e7-93ae-92361f002672', 'cb82ffd8-252a-11e7-93ae-92361f002672', '2017-05-26 15:08:24'), -('68dc9a92-214c-11e7-93ae-92361f002672', 'b4ea86b4-253f-11e7-93ae-92361f002672', '2017-05-26 15:08:24'), -('68dc9a92-214c-11e7-93ae-92361f002673', 'b4ea86b4-253f-11e7-93ae-92361f002672', '2017-05-26 15:08:24'); - - -INSERT INTO vf_module_to_heat_files(VF_MODULE_MODEL_UUID, HEAT_FILES_ARTIFACT_UUID) VALUES -('20c4431c-246d-11e7-93ae-92361f002671', '00535bdd-0878-4478-b95a-c575c742bfb0'), -('066de97e-253e-11e7-93ae-92361f002671', '00535bdd-0878-4478-b95a-c575c742bfb0'); - - -insert into network_resource_customization_to_service(service_model_uuid, resource_model_customization_uuid) values -('5df8b6de-2083-11e7-93ae-92361f002671', '3bdbb104-476c-483e-9f8b-c095b3d308ac'), -('5df8b6de-2083-11e7-93ae-92361f002672', '3bdbb104-476c-483e-9f8b-c095b3d308ac'); - - -insert into vnf_resource_customization_to_service(service_model_uuid, resource_model_customization_uuid) values -('5df8b6de-2083-11e7-93ae-92361f002671', '68dc9a92-214c-11e7-93ae-92361f002671'), -('f78914d9-423b-11e7-93f8-0050569a7965', 'f78914d9-423b-11e7-93f8-0050569a7967'), -('5df8b6de-2083-11e7-93ae-92361f002672', '68dc9a92-214c-11e7-93ae-92361f002672'); - -insert into allotted_resource_customization_to_service(service_model_uuid, resource_model_customization_uuid) values -('5df8b6de-2083-11e7-93ae-92361f002671', '367a8ba9-057a-4506-b106-fbae818597c6'), -('5df8b6de-2083-11e7-93ae-92361f002672', '367a8ba9-057a-4506-b106-fbae818597c6'); - - INSERT INTO vnf_recipe(ID, nf_role, ACTION, SERVICE_TYPE, VERSION_STR, DESCRIPTION, ORCHESTRATION_URI, VNF_PARAM_XSD, RECIPE_TIMEOUT, CREATION_TIMESTAMP, VF_MODULE_ID) VALUES ('77', 'VID_DEFAULT', 'createInstance', '', '1', 'VID_DEFAULT recipe to create VNF if no custom BPMN flow is found', '/mso/async/services/CreateVnfInfra', '', '180', '2016-09-14 19:18:20', ''), ('78', 'VID_DEFAULT', 'deleteInstance', '', '1', 'VID_DEFAULT recipe to delete VNF if no custom BPMN flow is found', '/mso/async/services/DeleteVnfInfra', '', '180', '2016-09-14 19:18:20', ''), diff --git a/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml b/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml index 4da57a15f9..5e6b88c039 100644 --- a/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml +++ b/mso-api-handlers/mso-api-handler-infra/src/test/resources/logback-test.xml @@ -38,4 +38,4 @@ <logger name="wiremock.org" level="ERROR" /> -</configuration>
\ No newline at end of file +</configuration> 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 fddd7adbf4..2c03173b16 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 @@ -1,836 +1,1247 @@ --------START Catalog DB SCHEMA -------- use catalogdb; -create table `allotted_resource` ( - `model_uuid` varchar(200) not null, - `model_invariant_uuid` varchar(200) not null, - `model_version` varchar(20) not null, - `model_name` varchar(200) not null, - `tosca_node_type` varchar(200) default null, - `subcategory` varchar(200) default null, - `description` varchar(1200) default null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`model_uuid`) -) engine=innodb default charset=latin1; - - - - -create table `allotted_resource_customization` ( - `model_customization_uuid` varchar(200) not null, - `model_instance_name` varchar(200) not null, - `providing_service_model_uuid` varchar(200) default null, - `providing_service_model_invariant_uuid` varchar(200) default null, - `providing_service_model_name` varchar(200) default null, - `target_network_role` varchar(200) default null, - `nf_type` varchar(200) default null, - `nf_role` varchar(200) default null, - `nf_function` varchar(200) default null, - `nf_naming_code` varchar(200) default null, - `min_instances` int(11) default null, - `max_instances` int(11) default null, - `ar_model_uuid` varchar(200) not null, - `resource_input` varchar(20000) default null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`model_customization_uuid`), - key `fk_allotted_resource_customization__allotted_resource1_idx` (`ar_model_uuid`), - constraint `fk_allotted_resource_customization__allotted_resource1` foreign key (`ar_model_uuid`) references `allotted_resource` (`model_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - - -create table `heat_environment` ( - `artifact_uuid` varchar(200) not null, - `name` varchar(100) not null, - `version` varchar(20) not null, - `description` varchar(1200) default null, - `body` longtext not null, - `artifact_checksum` varchar(200) not null default 'manual record', - `creation_timestamp` datetime not null default current_timestamp, - primary key (`artifact_uuid`) -) engine=innodb default charset=latin1; - - - -create table `heat_files` ( - `artifact_uuid` varchar(200) not null, - `name` varchar(200) not null, - `version` varchar(20) not null, - `description` varchar(1200) default null, - `body` longtext not null, - `artifact_checksum` varchar(200) not null default 'manual record', - `creation_timestamp` datetime not null default current_timestamp, - primary key (`artifact_uuid`) -) engine=innodb default charset=latin1; - - - - -create table `heat_template` ( - `artifact_uuid` varchar(200) not null, - `name` varchar(200) not null, - `version` varchar(20) not null, - `description` varchar(1200) default null, - `body` longtext not null, - `timeout_minutes` int(11) default null, - `artifact_checksum` varchar(200) not null default 'manual record', - `creation_timestamp` datetime not null default current_timestamp, - primary key (`artifact_uuid`) -) engine=innodb default charset=latin1; - - - -create table `heat_nested_template` ( - `parent_heat_template_uuid` varchar(200) not null, - `child_heat_template_uuid` varchar(200) not null, - `provider_resource_file` varchar(100) default null, - primary key (`parent_heat_template_uuid`,`child_heat_template_uuid`), - key `fk_heat_nested_template__heat_template2_idx` (`child_heat_template_uuid`), - constraint `fk_heat_nested_template__child_heat_temp_uuid__heat_template1` foreign key (`child_heat_template_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade, - constraint `fk_heat_nested_template__parent_heat_temp_uuid__heat_template1` foreign key (`parent_heat_template_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - - -create table `heat_template_params` ( - `heat_template_artifact_uuid` varchar(200) not null, - `param_name` varchar(100) not null, - `is_required` bit(1) not null, - `param_type` varchar(20) default null, - `param_alias` varchar(45) default null, - primary key (`heat_template_artifact_uuid`,`param_name`), - constraint `fk_heat_template_params__heat_template1` foreign key (`heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - -create table `network_recipe` ( - `id` int(11) not null auto_increment, - `model_name` varchar(20) not null, - `action` varchar(50) not null, - `description` varchar(1200) default null, - `orchestration_uri` varchar(256) not null, - `network_param_xsd` varchar(2048) default null, - `recipe_timeout` int(11) default null, - `service_type` varchar(45) default null, - `creation_timestamp` datetime not null default current_timestamp, - `version_str` varchar(20) not null, - primary key (`id`), - unique key `uk_rl4f296i0p8lyokxveaiwkayi` (`model_name`,`action`,`version_str`) -) engine=innodb auto_increment=178 default charset=latin1; - - - - -create table `temp_network_heat_template_lookup` ( - `network_resource_model_name` varchar(200) not null, - `heat_template_artifact_uuid` varchar(200) not null, - `aic_version_min` varchar(20) not null, - `aic_version_max` varchar(20) default null, - primary key (`network_resource_model_name`), - key `fk_temp_network_heat_template_lookup__heat_template1_idx` (`heat_template_artifact_uuid`), - constraint `fk_temp_network_heat_template_lookup__heat_template1` foreign key (`heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete no action on update cascade -) engine=innodb default charset=latin1; - - - -create table `network_resource` ( - `model_uuid` varchar(200) not null, - `model_name` varchar(200) not null, - `model_invariant_uuid` varchar(200) default null, - `description` varchar(1200) default null, - `heat_template_artifact_uuid` varchar(200) null, - `neutron_network_type` varchar(20) default null, - `model_version` varchar(20) default null, - `tosca_node_type` varchar(200) default null, - `aic_version_min` varchar(20) null, - `aic_version_max` varchar(20) default null, - `orchestration_mode` varchar(20) default 'heat', - `resource_category` varchar(20) default null, - `resource_sub_category` varchar(20) default null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`model_uuid`), - key `fk_network_resource__temp_network_heat_template_lookup1_idx` (`model_name`), - key `fk_network_resource__heat_template1_idx` (`heat_template_artifact_uuid`), - constraint `fk_network_resource__heat_template1` foreign key (`heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete no action on update cascade -) engine=innodb default charset=latin1; - - - - - -create table `network_resource_customization` ( - `model_customization_uuid` varchar(200) not null, - `model_instance_name` varchar(200) not null, - `network_technology` varchar(45) default null, - `network_type` varchar(45) default null, - `network_role` varchar(200) default null, - `network_scope` varchar(45) default null, - `creation_timestamp` datetime not null default current_timestamp, - `network_resource_model_uuid` varchar(200) not null, - `resource_input` varchar(20000) default null, - primary key (`model_customization_uuid`), - key `fk_network_resource_customization__network_resource1_idx` (`network_resource_model_uuid`), - constraint `fk_network_resource_customization__network_resource1` foreign key (`network_resource_model_uuid`) references `network_resource` (`model_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - - - -create table `tosca_csar` ( - `artifact_uuid` varchar(200) not null, - `name` varchar(200) not null, - `version` varchar(20) not null, - `description` varchar(1200) default null, - `artifact_checksum` varchar(200) not null, - `url` varchar(200) not null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`artifact_uuid`) -) engine=innodb default charset=latin1; - - - - -create table `service` ( - `model_uuid` varchar(200) not null, - `model_name` varchar(200) not null, - `model_invariant_uuid` varchar(200) not null, - `model_version` varchar(20) not null, - `description` varchar(1200) default null, - `creation_timestamp` datetime not null default current_timestamp, - `tosca_csar_artifact_uuid` varchar(200) default null, - `service_type` varchar(200) default null, - `service_role` varchar(200) default null, - `environment_context` varchar(200) default null, - `workload_context` varchar(200) default null, - `service_category` varchar(200) default null, - `resource_order` varchar(200) default null, - primary key (`model_uuid`), - key `fk_service__tosca_csar1_idx` (`tosca_csar_artifact_uuid`), - constraint `fk_service__tosca_csar1` foreign key (`tosca_csar_artifact_uuid`) references `tosca_csar` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - -create table `service_recipe` ( - `id` int(11) not null auto_increment, - `action` varchar(50) not null, - `version_str` varchar(20) default null, - `description` varchar(1200) default null, - `orchestration_uri` varchar(256) not null, - `service_param_xsd` varchar(2048) default null, - `recipe_timeout` int(11) default null, - `service_timeout_interim` int(11) default null, - `creation_timestamp` datetime not null default current_timestamp, - `service_model_uuid` varchar(200) not null, - primary key (`id`), - unique key `uk_7fav5dkux2v8g9d2i5ymudlgc` (`service_model_uuid`,`action`), - key `fk_service_recipe__service1_idx` (`service_model_uuid`), - constraint `fk_service_recipe__service1` foreign key (`service_model_uuid`) references `service` (`model_uuid`) on delete cascade on update cascade -) engine=innodb auto_increment=86 default charset=latin1; - - - -create table `vnf_resource` ( - `orchestration_mode` varchar(20) not null default 'heat', - `description` varchar(1200) default null, - `creation_timestamp` datetime not null default current_timestamp, - `model_uuid` varchar(200) not null, - `aic_version_min` varchar(20) default null, - `aic_version_max` varchar(20) default null, - `model_invariant_uuid` varchar(200) default null, - `model_version` varchar(20) not null, - `model_name` varchar(200) default null, - `tosca_node_type` varchar(200) default null, - `resource_category` varchar(200) default null, - `resource_sub_category` varchar(200) default null, - `heat_template_artifact_uuid` varchar(200) default null, - primary key (`model_uuid`), - key `fk_vnf_resource__heat_template1` (`heat_template_artifact_uuid`), - constraint `fk_vnf_resource__heat_template1` foreign key (`heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - - -create table `vf_module` ( - `model_uuid` varchar(200) not null, - `model_invariant_uuid` varchar(200) default null, - `model_version` varchar(20) not null, - `model_name` varchar(200) not null, - `description` varchar(1200) default null, - `is_base` int(11) not null, - `heat_template_artifact_uuid` varchar(200) default null, - `vol_heat_template_artifact_uuid` varchar(200) default null, - `creation_timestamp` datetime not null default current_timestamp, - `vnf_resource_model_uuid` varchar(200) not null, - primary key (`model_uuid`,`vnf_resource_model_uuid`), - key `fk_vf_module__vnf_resource1_idx` (`vnf_resource_model_uuid`), - key `fk_vf_module__heat_template_art_uuid__heat_template1_idx` (`heat_template_artifact_uuid`), - key `fk_vf_module__vol_heat_template_art_uuid__heat_template2_idx` (`vol_heat_template_artifact_uuid`), - constraint `fk_vf_module__heat_template_art_uuid__heat_template1` foreign key (`heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade, - constraint `fk_vf_module__vnf_resource1` foreign key (`vnf_resource_model_uuid`) references `vnf_resource` (`model_uuid`) on delete cascade on update cascade, - constraint `fk_vf_module__vol_heat_template_art_uuid__heat_template2` foreign key (`vol_heat_template_artifact_uuid`) references `heat_template` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - -/*!40101 set @saved_cs_client = @@character_set_client */; -/*!40101 set character_set_client = utf8 */; -create table `vf_module_customization` ( - `model_customization_uuid` varchar(200) not null, - `label` varchar(200) default null, - `initial_count` int(11) default '0', - `min_instances` int(11) default '0', - `max_instances` int(11) default null, - `availability_zone_count` int(11) default null, - `heat_environment_artifact_uuid` varchar(200) default null, - `vol_environment_artifact_uuid` varchar(200) default null, - `creation_timestamp` datetime not null default current_timestamp, - `vf_module_model_uuid` varchar(200) not null, - primary key (`model_customization_uuid`), - key `fk_vf_module_customization__vf_module1_idx` (`vf_module_model_uuid`), - key `fk_vf_module_customization__heat_env__heat_environment1_idx` (`heat_environment_artifact_uuid`), - key `fk_vf_module_customization__vol_env__heat_environment2_idx` (`vol_environment_artifact_uuid`), - constraint `fk_vf_module_customization__heat_env__heat_environment1` foreign key (`heat_environment_artifact_uuid`) references `heat_environment` (`artifact_uuid`) on delete cascade on update cascade, - constraint `fk_vf_module_customization__vf_module1` foreign key (`vf_module_model_uuid`) references `vf_module` (`model_uuid`) on delete cascade on update cascade, - constraint `fk_vf_module_customization__vol_env__heat_environment2` foreign key (`vol_environment_artifact_uuid`) references `heat_environment` (`artifact_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; -/*!40101 set character_set_client = @saved_cs_client */; - --- --- table structure for table `vf_module_to_heat_files` --- - - -/*!40101 set @saved_cs_client = @@character_set_client */; -/*!40101 set character_set_client = utf8 */; -create table `vf_module_to_heat_files` ( - `vf_module_model_uuid` varchar(200) not null, - `heat_files_artifact_uuid` varchar(200) not null, - primary key (`vf_module_model_uuid`,`heat_files_artifact_uuid`), - key `fk_vf_module_to_heat_files__heat_files__artifact_uuid1_idx` (`heat_files_artifact_uuid`), - constraint `fk_vf_module_to_heat_files__heat_files__artifact_uuid1` foreign key (`heat_files_artifact_uuid`) references `heat_files` (`artifact_uuid`) on delete cascade on update cascade, - constraint `fk_vf_module_to_heat_files__vf_module__model_uuid1` foreign key (`vf_module_model_uuid`) references `vf_module` (`model_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1 comment='il fait ce qu''il dit'; -/*!40101 set character_set_client = @saved_cs_client */; - --- --- table structure for table `vnf_components` --- - - -/*!40101 set @saved_cs_client = @@character_set_client */; -/*!40101 set character_set_client = utf8 */; -create table `vnf_components` ( - `vnf_id` int(11) not null, - `component_type` varchar(20) not null, - `heat_template_id` int(11) default null, - `heat_environment_id` int(11) default null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`vnf_id`,`component_type`) -) engine=innodb default charset=latin1; -/*!40101 set character_set_client = @saved_cs_client */; - --- --- table structure for table `vnf_components_recipe` --- - - - -create table `vnf_components_recipe` ( - `id` int(11) not null auto_increment, - `vnf_type` varchar(200) default null, - `vnf_component_type` varchar(45) not null, - `action` varchar(50) not null, - `service_type` varchar(45) default null, - `version` varchar(20) not null, - `description` varchar(1200) default null, - `orchestration_uri` varchar(256) not null, - `vnf_component_param_xsd` varchar(2048) default null, - `recipe_timeout` int(11) default null, - `creation_timestamp` datetime default current_timestamp, - `vf_module_model_uuid` varchar(200) default null, - primary key (`id`), - unique key `uk_4dpdwddaaclhc11wxsb7h59ma` (`vf_module_model_uuid`,`vnf_component_type`,`action`,`version`) -) engine=innodb auto_increment=26 default charset=latin1; - - - - -create table `vnf_recipe` ( - `id` int(11) not null auto_increment, - `nf_role` varchar(200) default null, - `action` varchar(50) not null, - `service_type` varchar(45) default null, - `version_str` varchar(20) not null, - `description` varchar(1200) default null, - `orchestration_uri` varchar(256) not null, - `vnf_param_xsd` varchar(2048) default null, - `recipe_timeout` int(11) default null, - `creation_timestamp` datetime default current_timestamp, - `vf_module_id` varchar(100) default null, - primary key (`id`), - unique key `uk_f3tvqau498vrifq3cr8qnigkr` (`vf_module_id`,`action`,`version_str`) -) engine=innodb auto_increment=10006 default charset=latin1; - - - - - - - - -create table `vnf_resource_customization` ( - `model_customization_uuid` varchar(200) not null, - `model_instance_name` varchar(200) not null, - `min_instances` int(11) default null, - `max_instances` int(11) default null, - `availability_zone_max_count` int(11) default null, - `nf_type` varchar(200) default null, - `nf_role` varchar(200) default null, - `nf_function` varchar(200) default null, - `nf_naming_code` varchar(200) default null, - `creation_timestamp` datetime not null default current_timestamp, - `vnf_resource_model_uuid` varchar(200) not null, - `multi_stage_design` varchar(20) default null, - `resource_input` varchar(20000) default null, - primary key (`model_customization_uuid`), - key `fk_vnf_resource_customization__vnf_resource1_idx` (`vnf_resource_model_uuid`), - constraint `fk_vnf_resource_customization__vnf_resource1` foreign key (`vnf_resource_model_uuid`) references `vnf_resource` (`model_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - - - -create table `vnf_res_custom_to_vf_module_custom` ( - `vnf_resource_cust_model_customization_uuid` varchar(200) not null, - `vf_module_cust_model_customization_uuid` varchar(200) not null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`vnf_resource_cust_model_customization_uuid`,`vf_module_cust_model_customization_uuid`), - key `fk_vnf_res_custom_to_vf_module_custom__vf_module_customizat_idx` (`vf_module_cust_model_customization_uuid`), - constraint `fk_vnf_res_custom_to_vf_module_custom__vf_module_customization1` foreign key (`vf_module_cust_model_customization_uuid`) references `vf_module_customization` (`model_customization_uuid`) on delete cascade on update cascade, - constraint `fk_vnf_res_custom_to_vf_module_custom__vnf_resource_customiza1` foreign key (`vnf_resource_cust_model_customization_uuid`) references `vnf_resource_customization` (`model_customization_uuid`) on delete cascade on update cascade -) engine=innodb default charset=latin1; - - -create table if not exists `external_service_to_internal_model_mapping` ( -id int(11) not null, -service_name varchar(200) not null, -product_flavor varchar(200) null, -subscription_service_type varchar(200) not null, -service_model_uuid varchar(200) not null, -primary key (id), -unique index uk_external_service_to_internal_model_mapping -(service_name asc, product_flavor asc, service_model_uuid asc)); - -create table if not exists `collection_resource` ( - model_uuid varchar(200) not null, - model_name varchar(200) not null, - model_invariant_uuid varchar(200) not null, - model_version varchar(20) not null, - tosca_node_type varchar(200) not null, - description varchar(200), - creation_timestamp datetime not null default current_timestamp, - primary key (`model_uuid`) -)engine=innodb default charset=latin1; - -create table if not exists `collection_resource_customization` ( - model_customization_uuid varchar(200) not null, - model_instance_name varchar(200) not null, - role varchar(200) NULL, - object_type varchar(200) not null, - function varchar(200) NULL, - collection_resource_type varchar(200) NULL, - creation_timestamp datetime not null default current_timestamp, - cr_model_uuid varchar(200) not null, - primary key (`model_customization_uuid`) -)engine=innodb default charset=latin1; - -create table if not exists `instance_group` ( - model_uuid varchar(200) not null, - model_name varchar(200) not null, - model_invariant_uuid varchar(200) not null, - model_version varchar(20) not null, - tosca_node_type varchar(200) NULL, - role varchar(200) not null, - object_type varchar(200) not null, - creation_timestamp datetime not null default current_timestamp, - cr_model_uuid varchar(200) not null, - instance_group_type varchar(200) not null, - primary key (`model_uuid`) -)engine=innodb default charset=latin1; - - -create table if not exists `collection_resource_instance_group_customization` ( - `collection_resource_customization_model_uuid` varchar(200) not null, - `instance_group_model_uuid` varchar(200) not null, - `function` varchar(200) null, - `description` varchar(1200) null, - `subinterface_network_quantity` int(11) null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`collection_resource_customization_model_uuid`, `instance_group_model_uuid`), - index `fk_collection_resource_instance_group_customization__instan_idx` (`instance_group_model_uuid` asc), - constraint `fk_collection_resource_instance_group_customization__collecti1` - foreign key (`collection_resource_customization_model_uuid`) - references `collection_resource_customization` (`model_customization_uuid`) - on delete cascade - on update cascade, - constraint `fk_collection_resource_instance_group_customization__instance1` - foreign key (`instance_group_model_uuid`) - references `instance_group` (`model_uuid`) - on delete cascade - on update cascade) -engine = innodb -default character set = latin1; - -create table if not exists `vnfc_instance_group_customization` ( - `vnf_resource_customization_model_uuid` varchar(200) not null, - `instance_group_model_uuid` varchar(200) not null, - `function` varchar(200) null, - `description` varchar(1200) null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`vnf_resource_customization_model_uuid`, `instance_group_model_uuid`), - index `fk_vnfc_instance_group_customization__instance_group1_idx` (`instance_group_model_uuid` asc), - constraint `fk_vnfc_instance_group_customization__vnf_resource_customizat1` - foreign key (`vnf_resource_customization_model_uuid`) - references `vnf_resource_customization` (`model_customization_uuid`) - on delete cascade - on update cascade, - constraint `fk_vnfc_instance_group_customization__instance_group1` - foreign key (`instance_group_model_uuid`) - references `instance_group` (`model_uuid`) - on delete cascade - on update cascade) -engine = innodb -default character set = latin1; - - create table if not exists `configuration` - ( `model_uuid` varchar(200) not null, - `model_invariant_uuid` varchar(200) not null, - `model_version` varchar(20) not null, - `model_name` varchar(200) not null, - `tosca_node_type` varchar(200) not null, - `description` varchar(1200) null, - `creation_timestamp` datetime not null default current_timestamp, - primary key (`model_uuid`)) - engine = innodb auto_increment = 20654 - default character set = latin1; - - CREATE TABLE IF NOT EXISTS `service_proxy_customization` ( - `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, - `MODEL_UUID` VARCHAR(200) NOT NULL, - `MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, - `MODEL_VERSION` VARCHAR(20) NOT NULL, - `MODEL_NAME` VARCHAR(200) NOT NULL, - `TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, - `DESCRIPTION` VARCHAR(1200) NULL, - `SOURCE_SERVICE_MODEL_UUID` VARCHAR(200) NOT NULL, - `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, +set foreign_key_checks=0; +DROP TABLE IF EXISTS `allotted_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `allotted_resource` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `SUBCATEGORY` varchar(200) DEFAULT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `allotted_resource_customization` +-- + +DROP TABLE IF EXISTS `allotted_resource_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `allotted_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `PROVIDING_SERVICE_MODEL_UUID` varchar(200) DEFAULT NULL, + `PROVIDING_SERVICE_MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `PROVIDING_SERVICE_MODEL_NAME` varchar(200) DEFAULT NULL, + `TARGET_NETWORK_ROLE` varchar(200) DEFAULT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `MIN_INSTANCES` int(11) DEFAULT NULL, + `MAX_INSTANCES` int(11) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `AR_MODEL_UUID` varchar(200) NOT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_allotted_resource_customization__allotted_resource1_idx` (`AR_MODEL_UUID`), + CONSTRAINT `fk_allotted_resource_customization__allotted_resource1` FOREIGN KEY (`AR_MODEL_UUID`) REFERENCES `allotted_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `allotted_resource_customization_to_service` +-- + +DROP TABLE IF EXISTS `allotted_resource_customization_to_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `allotted_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + KEY `RESOURCE_MODEL_CUSTOMIZATION_UUID` (`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `allotted_resource_customization_to_service_ibfk_1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE, + CONSTRAINT `allotted_resource_customization_to_service_ibfk_2` FOREIGN KEY (`RESOURCE_MODEL_CUSTOMIZATION_UUID`) REFERENCES `allotted_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ar_recipe` +-- + +DROP TABLE IF EXISTS `ar_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ar_recipe` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_NAME` varchar(200) NOT NULL, + `ACTION` varchar(200) NOT NULL, + `VERSION_STR` varchar(200) NOT NULL, + `SERVICE_TYPE` varchar(200) DEFAULT NULL, + `DESCRIPTION` varchar(200) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(200) NOT NULL, + `AR_PARAM_XSD` varchar(200) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE KEY `uk_ar_recipe` (`MODEL_NAME`,`ACTION`,`VERSION_STR`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `building_block_detail` +-- + +DROP TABLE IF EXISTS `building_block_detail`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `building_block_detail` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `BUILDING_BLOCK_NAME` varchar(200) NOT NULL, + `RESOURCE_TYPE` varchar(25) NOT NULL, + `TARGET_ACTION` varchar(25) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_building_block_name` (`BUILDING_BLOCK_NAME`) +) ENGINE=InnoDB AUTO_INCREMENT=104 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cloud_sites` +-- + +DROP TABLE IF EXISTS `cloud_sites`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cloud_sites` ( + `ID` varchar(50) NOT NULL, + `REGION_ID` varchar(11) DEFAULT NULL, + `IDENTITY_SERVICE_ID` varchar(50) DEFAULT NULL, + `CLOUD_VERSION` varchar(20) DEFAULT NULL, + `CLLI` varchar(11) DEFAULT NULL, + `CLOUDIFY_ID` varchar(50) DEFAULT NULL, + `PLATFORM` varchar(50) DEFAULT NULL, + `ORCHESTRATOR` varchar(50) DEFAULT NULL, + `LAST_UPDATED_BY` varchar(120) DEFAULT NULL, + `CREATION_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `UPDATE_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + KEY `FK_cloud_sites_identity_services` (`IDENTITY_SERVICE_ID`), + CONSTRAINT `FK_cloud_sites_identity_services` FOREIGN KEY (`IDENTITY_SERVICE_ID`) REFERENCES `identity_services` (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cloudify_managers` +-- + +DROP TABLE IF EXISTS `cloudify_managers`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cloudify_managers` ( + `ID` varchar(50) NOT NULL, + `CLOUDIFY_URL` varchar(200) DEFAULT NULL, + `USERNAME` varchar(255) DEFAULT NULL, + `PASSWORD` varchar(255) DEFAULT NULL, + `VERSION` varchar(20) DEFAULT NULL, + `LAST_UPDATED_BY` varchar(120) DEFAULT NULL, + `CREATION_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `UPDATE_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `collection_network_resource_customization` +-- + +DROP TABLE IF EXISTS `collection_network_resource_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collection_network_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NETWORK_TECHNOLOGY` varchar(45) DEFAULT NULL, + `NETWORK_TYPE` varchar(45) DEFAULT NULL, + `NETWORK_ROLE` varchar(200) DEFAULT NULL, + `NETWORK_SCOPE` varchar(45) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `NETWORK_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `INSTANCE_GROUP_MODEL_UUID` varchar(200) DEFAULT NULL, + `CRC_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`,`CRC_MODEL_CUSTOMIZATION_UUID`), + KEY `fk_collection_net_resource_customization__network_resource1_idx` (`NETWORK_RESOURCE_MODEL_UUID`), + KEY `fk_collection_net_resource_customization__instance_group1_idx` (`INSTANCE_GROUP_MODEL_UUID`), + KEY `fk_col_net_res_customization__collection_res_customization_idx` (`CRC_MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `fk_collection_net_resource_customization__instance_group10` FOREIGN KEY (`INSTANCE_GROUP_MODEL_UUID`) REFERENCES `instance_group` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_collection_net_resource_customization__network_resource10` FOREIGN KEY (`NETWORK_RESOURCE_MODEL_UUID`) REFERENCES `network_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_collection_network_resource_customization__collection_reso1` FOREIGN KEY (`CRC_MODEL_CUSTOMIZATION_UUID`) REFERENCES `collection_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `collection_resource` +-- + +DROP TABLE IF EXISTS `collection_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collection_resource` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `collection_resource_customization` +-- + +DROP TABLE IF EXISTS `collection_resource_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collection_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `role` varchar(200) DEFAULT NULL, + `object_type` varchar(200) NOT NULL, + `function` varchar(200) DEFAULT NULL, + `collection_resource_type` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CR_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `CR_MODEL_UUID` (`CR_MODEL_UUID`), + CONSTRAINT `collection_resource_customization_ibfk_1` FOREIGN KEY (`CR_MODEL_UUID`) REFERENCES `collection_resource` (`MODEL_UUID`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `collection_resource_customization_to_service` +-- + +DROP TABLE IF EXISTS `collection_resource_customization_to_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collection_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + KEY `RESOURCE_MODEL_CUSTOMIZATION_UUID` (`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `collection_resource_customization_to_service_ibfk_1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE, + CONSTRAINT `collection_resource_customization_to_service_ibfk_2` FOREIGN KEY (`RESOURCE_MODEL_CUSTOMIZATION_UUID`) REFERENCES `collection_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `collection_resource_instance_group_customization` +-- + +DROP TABLE IF EXISTS `collection_resource_instance_group_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collection_resource_instance_group_customization` ( + `COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID` varchar(200) NOT NULL, + `INSTANCE_GROUP_MODEL_UUID` varchar(200) NOT NULL, + `FUNCTION` varchar(200) DEFAULT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `SUBINTERFACE_NETWORK_QUANTITY` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID`,`INSTANCE_GROUP_MODEL_UUID`), + KEY `fk_collection_resource_instance_group_customization__instan_idx` (`INSTANCE_GROUP_MODEL_UUID`), + CONSTRAINT `fk_collection_resource_instance_group_customization__collecti1` FOREIGN KEY (`COLLECTION_RESOURCE_CUSTOMIZATION_MODEL_UUID`) REFERENCES `collection_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_collection_resource_instance_group_customization__instance1` FOREIGN KEY (`INSTANCE_GROUP_MODEL_UUID`) REFERENCES `instance_group` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `configuration` +-- + +DROP TABLE IF EXISTS `configuration`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `configuration` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `configuration_customization` +-- + +DROP TABLE IF EXISTS `configuration_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `configuration_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `CONFIGURATION_TYPE` varchar(200) DEFAULT NULL, + `CONFIGURATION_ROLE` varchar(200) DEFAULT NULL, + `CONFIGURATION_FUNCTION` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` varchar(200) NOT NULL, + `SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID` varchar(200) DEFAULT NULL, + `CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_configuration_customization__configuration_idx` (`CONFIGURATION_MODEL_UUID`), + KEY `fk_configuration_customization__service_proxy_customization_idx` (`SERVICE_PROXY_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID`), + KEY `fk_configuration_customization__configuration_customization_idx` (`CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `fk_configuration_customization__configuration_customization1` FOREIGN KEY (`CONFIGURATION_CUSTOMIZATION_MODEL_CUSTOMIZATION_UUID`) REFERENCES `configuration_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_configuration_resource_customization__configuration_resour1` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `configuration_customization_to_service` +-- + +DROP TABLE IF EXISTS `configuration_customization_to_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `configuration_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `controller_selection_reference` +-- + +DROP TABLE IF EXISTS `controller_selection_reference`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `controller_selection_reference` ( + `VNF_TYPE` varchar(50) NOT NULL, + `CONTROLLER_NAME` varchar(100) NOT NULL, + `ACTION_CATEGORY` varchar(15) NOT NULL, + PRIMARY KEY (`VNF_TYPE`,`CONTROLLER_NAME`,`ACTION_CATEGORY`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cvnfc_configuration_customization` +-- + +DROP TABLE IF EXISTS `cvnfc_configuration_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cvnfc_configuration_customization` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `CONFIGURATION_TYPE` varchar(200) DEFAULT NULL, + `CONFIGURATION_ROLE` varchar(200) DEFAULT NULL, + `CONFIGURATION_FUNCTION` varchar(200) DEFAULT NULL, + `POLICY_NAME` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CONFIGURATION_MODEL_UUID` varchar(200) NOT NULL, + `CVNFC_CUSTOMIZATION_ID` int(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + KEY `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID`), + CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) REFERENCES `configuration` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=20655 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `cvnfc_customization` +-- + +DROP TABLE IF EXISTS `cvnfc_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cvnfc_customization` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `NFC_FUNCTION` varchar(200) DEFAULT NULL, + `NFC_NAMING_CODE` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VNFC_CUST_MODEL_CUSTOMIZATION_UUID` varchar(200) DEFAULT NULL, + `VF_MODULE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + PRIMARY KEY (`ID`), + KEY `fk_cvnfc_customization__vnfc_customization1_idx` (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID`), + KEY `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_cvnfc_customization_to_vf_module_resource_customization` (`VF_MODULE_CUSTOMIZATION_ID`), + CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_cvnfc_customization_to_vf_module_resource_customization` FOREIGN KEY (`VF_MODULE_CUSTOMIZATION_ID`) REFERENCES `vf_module_customization` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=20655 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `external_service_to_internal_model_mapping` +-- + +DROP TABLE IF EXISTS `external_service_to_internal_model_mapping`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `external_service_to_internal_model_mapping` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `SERVICE_NAME` varchar(200) NOT NULL, + `PRODUCT_FLAVOR` varchar(200) DEFAULT NULL, + `SUBSCRIPTION_SERVICE_TYPE` varchar(200) NOT NULL, + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_external_service_to_internal_model_mapping` (`SERVICE_NAME`,`PRODUCT_FLAVOR`,`SERVICE_MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `flyway_schema_history` +-- + +DROP TABLE IF EXISTS `flyway_schema_history`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `flyway_schema_history` ( + `installed_rank` int(11) NOT NULL, + `version` varchar(50) DEFAULT NULL, + `description` varchar(200) NOT NULL, + `type` varchar(20) NOT NULL, + `script` varchar(1000) NOT NULL, + `checksum` int(11) DEFAULT NULL, + `installed_by` varchar(100) NOT NULL, + `installed_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `execution_time` int(11) NOT NULL, + `success` tinyint(1) NOT NULL, + PRIMARY KEY (`installed_rank`), + KEY `flyway_schema_history_s_idx` (`success`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `heat_environment` +-- + +DROP TABLE IF EXISTS `heat_environment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `heat_environment` ( + `ARTIFACT_UUID` varchar(200) NOT NULL, + `NAME` varchar(100) NOT NULL, + `VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `BODY` longtext NOT NULL, + `ARTIFACT_CHECKSUM` varchar(200) NOT NULL DEFAULT 'MANUAL RECORD', + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ARTIFACT_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `heat_files` +-- + +DROP TABLE IF EXISTS `heat_files`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `heat_files` ( + `ARTIFACT_UUID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `BODY` longtext NOT NULL, + `ARTIFACT_CHECKSUM` varchar(200) NOT NULL DEFAULT 'MANUAL RECORD', + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ARTIFACT_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `heat_nested_template` +-- + +DROP TABLE IF EXISTS `heat_nested_template`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `heat_nested_template` ( + `PARENT_HEAT_TEMPLATE_UUID` varchar(200) NOT NULL, + `CHILD_HEAT_TEMPLATE_UUID` varchar(200) NOT NULL, + `PROVIDER_RESOURCE_FILE` varchar(100) DEFAULT NULL, + PRIMARY KEY (`PARENT_HEAT_TEMPLATE_UUID`,`CHILD_HEAT_TEMPLATE_UUID`), + KEY `fk_heat_nested_template__heat_template2_idx` (`CHILD_HEAT_TEMPLATE_UUID`), + CONSTRAINT `fk_heat_nested_template__child_heat_temp_uuid__heat_template1` FOREIGN KEY (`CHILD_HEAT_TEMPLATE_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_heat_nested_template__parent_heat_temp_uuid__heat_template1` FOREIGN KEY (`PARENT_HEAT_TEMPLATE_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `heat_template` +-- + +DROP TABLE IF EXISTS `heat_template`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `heat_template` ( + `ARTIFACT_UUID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `BODY` longtext NOT NULL, + `TIMEOUT_MINUTES` int(11) DEFAULT NULL, + `ARTIFACT_CHECKSUM` varchar(200) NOT NULL DEFAULT 'MANUAL RECORD', + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ARTIFACT_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `heat_template_params` +-- + +DROP TABLE IF EXISTS `heat_template_params`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `heat_template_params` ( + `HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) NOT NULL, + `PARAM_NAME` varchar(100) NOT NULL, + `IS_REQUIRED` bit(1) NOT NULL, + `PARAM_TYPE` varchar(20) DEFAULT NULL, + `PARAM_ALIAS` varchar(45) DEFAULT NULL, + PRIMARY KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`,`PARAM_NAME`), + CONSTRAINT `fk_heat_template_params__heat_template1` FOREIGN KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `identity_services` +-- + +DROP TABLE IF EXISTS `identity_services`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `identity_services` ( + `ID` varchar(50) NOT NULL, + `IDENTITY_URL` varchar(200) DEFAULT NULL, + `MSO_ID` varchar(255) DEFAULT NULL, + `MSO_PASS` varchar(255) DEFAULT NULL, + `ADMIN_TENANT` varchar(50) DEFAULT NULL, + `MEMBER_ROLE` varchar(50) DEFAULT NULL, + `TENANT_METADATA` tinyint(1) DEFAULT '0', + `IDENTITY_SERVER_TYPE` varchar(50) DEFAULT NULL, + `IDENTITY_AUTHENTICATION_TYPE` varchar(50) DEFAULT NULL, + `LAST_UPDATED_BY` varchar(120) DEFAULT NULL, + `CREATION_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `UPDATE_TIMESTAMP` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `PROJECT_DOMAIN_NAME` varchar(255) DEFAULT NULL, + `USER_DOMAIN_NAME` varchar(255) DEFAULT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `instance_group` +-- + +DROP TABLE IF EXISTS `instance_group`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `instance_group` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `ROLE` varchar(200) NOT NULL, + `OBJECT_TYPE` varchar(200) NOT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `CR_MODEL_UUID` varchar(200) DEFAULT NULL, + `INSTANCE_GROUP_TYPE` varchar(200) NOT NULL, + PRIMARY KEY (`MODEL_UUID`), + KEY `CR_MODEL_UUID` (`CR_MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `model` +-- + +DROP TABLE IF EXISTS `model`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `model` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_ID` varchar(40) DEFAULT NULL, + `MODEL_CUSTOMIZATION_NAME` varchar(40) DEFAULT NULL, + `MODEL_INVARIANT_ID` varchar(40) DEFAULT NULL, + `MODEL_NAME` varchar(40) DEFAULT NULL, + `MODEL_TYPE` varchar(20) DEFAULT NULL, + `MODEL_VERSION` varchar(20) DEFAULT NULL, + `MODEL_VERSION_ID` varchar(40) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `RECIPE` int(11) DEFAULT NULL, + PRIMARY KEY (`ID`), + UNIQUE KEY `uk1_model` (`MODEL_TYPE`,`MODEL_VERSION_ID`), + KEY `RECIPE` (`RECIPE`), + CONSTRAINT `model_ibfk_1` FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `model_recipe` +-- + +DROP TABLE IF EXISTS `model_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `model_recipe` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_ID` int(11) DEFAULT NULL, + `ACTION` varchar(40) DEFAULT NULL, + `SCHEMA_VERSION` varchar(40) DEFAULT NULL, + `DESCRIPTION` varchar(40) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(20) DEFAULT NULL, + `MODEL_PARAM_XSD` varchar(20) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ID`), + UNIQUE KEY `uk1_model_recipe` (`MODEL_ID`,`ACTION`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `network_recipe` +-- + +DROP TABLE IF EXISTS `network_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `network_recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `MODEL_NAME` varchar(20) NOT NULL, + `ACTION` varchar(50) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(256) NOT NULL, + `NETWORK_PARAM_XSD` varchar(2048) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `SERVICE_TYPE` varchar(45) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VERSION_STR` varchar(20) NOT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_rl4f296i0p8lyokxveaiwkayi` (`MODEL_NAME`,`ACTION`,`VERSION_STR`) +) ENGINE=InnoDB AUTO_INCREMENT=181 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `network_resource` +-- + +DROP TABLE IF EXISTS `network_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `network_resource` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) NULL, + `NEUTRON_NETWORK_TYPE` varchar(20) DEFAULT NULL, + `MODEL_VERSION` varchar(20) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `AIC_VERSION_MIN` varchar(20) NULL, + `AIC_VERSION_MAX` varchar(20) DEFAULT NULL, + `ORCHESTRATION_MODE` varchar(20) DEFAULT 'HEAT', + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`), + KEY `fk_network_resource__temp_network_heat_template_lookup1_idx` (`MODEL_NAME`), + KEY `fk_network_resource__heat_template1_idx` (`HEAT_TEMPLATE_ARTIFACT_UUID`), + CONSTRAINT `fk_network_resource__heat_template1` FOREIGN KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_network_resource__temp_network_heat_template_lookup__mod_nm1` FOREIGN KEY (`MODEL_NAME`) REFERENCES `temp_network_heat_template_lookup` (`NETWORK_RESOURCE_MODEL_NAME`) ON DELETE NO ACTION ON UPDATE NO ACTION +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `network_resource_customization` +-- + +DROP TABLE IF EXISTS `network_resource_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `network_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NETWORK_TECHNOLOGY` varchar(45) DEFAULT NULL, + `NETWORK_TYPE` varchar(45) DEFAULT NULL, + `NETWORK_ROLE` varchar(200) DEFAULT NULL, + `NETWORK_SCOPE` varchar(45) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `NETWORK_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_network_resource_customization__network_resource1_idx` (`NETWORK_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_network_resource_customization__network_resource1` FOREIGN KEY (`NETWORK_RESOURCE_MODEL_UUID`) REFERENCES `network_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `network_resource_customization_to_service` +-- + +DROP TABLE IF EXISTS `network_resource_customization_to_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `network_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + KEY `RESOURCE_MODEL_CUSTOMIZATION_UUID` (`RESOURCE_MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `network_resource_customization_to_service_ibfk_1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE, + CONSTRAINT `network_resource_customization_to_service_ibfk_2` FOREIGN KEY (`RESOURCE_MODEL_CUSTOMIZATION_UUID`) REFERENCES `network_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `northbound_request_ref_lookup` +-- + +DROP TABLE IF EXISTS `northbound_request_ref_lookup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `northbound_request_ref_lookup` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `REQUEST_SCOPE` varchar(200) NOT NULL, + `MACRO_ACTION` varchar(200) NOT NULL, + `ACTION` varchar(200) NOT NULL, + `IS_ALACARTE` tinyint(1) NOT NULL DEFAULT '0', + `MIN_API_VERSION` double NOT NULL, + `MAX_API_VERSION` double DEFAULT NULL, + `IS_TOPLEVELFLOW` tinyint(1) DEFAULT NULL, + `CLOUD_OWNER` varchar(200) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_northbound_request_ref_lookup` (`MIN_API_VERSION`,`REQUEST_SCOPE`,`ACTION`,`IS_ALACARTE`,`MACRO_ACTION`,`CLOUD_OWNER`) +) ENGINE=InnoDB AUTO_INCREMENT=86 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `orchestration_flow_reference` +-- + +DROP TABLE IF EXISTS `orchestration_flow_reference`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `orchestration_flow_reference` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `COMPOSITE_ACTION` varchar(200) NOT NULL, + `SEQ_NO` int(11) NOT NULL, + `FLOW_NAME` varchar(200) NOT NULL, + `FLOW_VERSION` double NOT NULL, + `NB_REQ_REF_LOOKUP_ID` int(11) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_orchestration_flow_reference` (`COMPOSITE_ACTION`,`FLOW_NAME`,`SEQ_NO`,`NB_REQ_REF_LOOKUP_ID`), + KEY `fk_orchestration_flow_reference__northbound_req_ref_look_idx` (`NB_REQ_REF_LOOKUP_ID`), + KEY `fk_orchestration_flow_reference__building_block_detail` (`FLOW_NAME`), + CONSTRAINT `fk_orchestration_flow_reference__northbound_request_ref_look1` FOREIGN KEY (`NB_REQ_REF_LOOKUP_ID`) REFERENCES `northbound_request_ref_lookup` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=398 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `orchestration_status_state_transition_directive` +-- + +DROP TABLE IF EXISTS `orchestration_status_state_transition_directive`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `orchestration_status_state_transition_directive` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `RESOURCE_TYPE` varchar(25) NOT NULL, + `ORCHESTRATION_STATUS` varchar(25) NOT NULL, + `TARGET_ACTION` varchar(25) NOT NULL, + `FLOW_DIRECTIVE` varchar(25) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_orchestration_status_state_transition_directive` (`RESOURCE_TYPE`,`ORCHESTRATION_STATUS`,`TARGET_ACTION`) +) ENGINE=InnoDB AUTO_INCREMENT=686 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `rainy_day_handler_macro` +-- + +DROP TABLE IF EXISTS `rainy_day_handler_macro`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `rainy_day_handler_macro` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `FLOW_NAME` varchar(200) NOT NULL, + `SERVICE_TYPE` varchar(200) NOT NULL, + `VNF_TYPE` varchar(200) NOT NULL, + `ERROR_CODE` varchar(200) NOT NULL, + `WORK_STEP` varchar(200) NOT NULL, + `POLICY` varchar(200) NOT NULL, + `SECONDARY_POLICY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `service` +-- + +DROP TABLE IF EXISTS `service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `service` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `TOSCA_CSAR_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `SERVICE_TYPE` varchar(200) DEFAULT NULL, + `SERVICE_ROLE` varchar(200) DEFAULT NULL, + `ENVIRONMENT_CONTEXT` varchar(200) DEFAULT NULL, + `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, + `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_ORDER` varchar(200) default NULL, + PRIMARY KEY (`MODEL_UUID`), + KEY `fk_service__tosca_csar1_idx` (`TOSCA_CSAR_ARTIFACT_UUID`), + CONSTRAINT `fk_service__tosca_csar1` FOREIGN KEY (`TOSCA_CSAR_ARTIFACT_UUID`) REFERENCES `tosca_csar` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `service_proxy_customization` +-- + +DROP TABLE IF EXISTS `service_proxy_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `service_proxy_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `SOURCE_SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), - INDEX `fk_service_proxy_customization__service1_idx` (`SOURCE_SERVICE_MODEL_UUID` ASC), - UNIQUE INDEX `UK_service_proxy_customization` (`MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_service_proxy_customization__serv_prox_to_serv` (`MODEL_CUSTOMIZATION_UUID` ASC), - CONSTRAINT `fk_service_proxy_resource_customization__service1` - FOREIGN KEY (`SOURCE_SERVICE_MODEL_UUID`) - REFERENCES `service` (`MODEL_UUID`) - ON DELETE CASCADE - ON UPDATE CASCADE) -ENGINE = InnoDB -AUTO_INCREMENT = 20654 -DEFAULT CHARACTER SET = latin1; - -create table if not exists `configuration_customization` ( -`model_customization_uuid` varchar(200) not null, -`model_instance_name` varchar(200) not null, -`configuration_type` varchar(200) null, -`configuration_role` varchar(200) null, -`configuration_function` varchar(200) null, -`creation_timestamp` datetime not null default current_timestamp, -`configuration_model_uuid` varchar(200) not null, -`service_proxy_customization_model_customization_uuid` varchar(200) null, -`configuration_customization_model_customization_uuid` varchar(200) null, -primary key (`model_customization_uuid`), -index `fk_configuration_customization__configuration_idx` (`configuration_model_uuid` asc), -index `fk_configuration_customization__configuration_customization_idx` -(`configuration_customization_model_customization_uuid` asc), -constraint `fk_configuration_resource_customization__configuration_resour1` -foreign key (`configuration_model_uuid`) references `configuration` (`model_uuid`) -on delete cascade on update cascade, -constraint `fk_configuration_customization__configuration_customization1` -foreign key (`configuration_customization_model_customization_uuid`) references -`configuration_customization` (`model_customization_uuid`) -on delete cascade on update cascade) -engine = innodb -auto_increment =20654 -default character set = latin1; - - -create table `service_proxy_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - - -create table `configuration_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - - -create table if not exists `collection_resource_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - - -create table `network_resource_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - -create table `vnf_resource_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - -create table `allotted_resource_customization_to_service` ( - `service_model_uuid` varchar(200) not null, - `resource_model_customization_uuid` varchar(200) not null, - primary key (`service_model_uuid`,`resource_model_customization_uuid`) -)engine=innodb default charset=latin1; - - - -create table ar_recipe ( - ID INT(11) not null auto_increment, - MODEL_NAME VARCHAR(200) NOT NULL, - `ACTION` VARCHAR(200) NOT NULL, - VERSION_STR VARCHAR(200) NOT NULL, - SERVICE_TYPE VARCHAR(200), - DESCRIPTION VARCHAR(200), - ORCHESTRATION_URI VARCHAR(200) NOT NULL, - AR_PARAM_XSD VARCHAR(200), - RECIPE_TIMEOUT INT(10), - CREATION_TIMESTAMP DATETIME NOT NULL default current_timestamp, - primary key (ID), - unique key `uk_ar_recipe` (`model_name`,`action`,`version_str`) + KEY `fk_service_proxy_customization__service1_idx` (`SOURCE_SERVICE_MODEL_UUID`), + CONSTRAINT `fk_service_proxy_resource_customization__service1` FOREIGN KEY (`SOURCE_SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `service_proxy_customization_to_service` +-- + +DROP TABLE IF EXISTS `service_proxy_customization_to_service`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `service_proxy_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `service_recipe` +-- -alter table collection_resource_customization -add foreign key ( cr_model_uuid) -references collection_resource(model_uuid) -on delete cascade; - -alter table vnf_resource_customization -add column -instance_group_model_uuid varchar(200); - -alter table network_resource_customization -add column -instance_group_model_uuid varchar(200); - - -alter table network_resource_customization -add foreign key ( instance_group_model_uuid) -references instance_group(model_uuid) -on delete cascade; - -alter table collection_resource_customization_to_service -add foreign key (service_model_uuid) -references service(model_uuid) -on delete cascade; - -alter table allotted_resource_customization_to_service -add foreign key (service_model_uuid) -references service(model_uuid) -on delete cascade; - - -alter table vnf_resource_customization_to_service -add foreign key (service_model_uuid) -references service(model_uuid) -on delete cascade; - - -alter table network_resource_customization_to_service -add foreign key (service_model_uuid) -references service(model_uuid) -on delete cascade; - - -alter table network_resource_customization_to_service -add foreign key (resource_model_customization_uuid) -references network_resource_customization(model_customization_uuid) -on delete cascade; - -alter table vnf_resource_customization_to_service -add foreign key (resource_model_customization_uuid) -references vnf_resource_customization(model_customization_uuid) -on delete cascade; - -alter table allotted_resource_customization_to_service -add foreign key (resource_model_customization_uuid) -references allotted_resource_customization(model_customization_uuid) -on delete cascade; - -alter table collection_resource_customization_to_service -add foreign key (resource_model_customization_uuid) -references collection_resource_customization(model_customization_uuid) -on delete cascade; - - -create table if not exists `collection_network_resource_customization` ( -`model_customization_uuid` varchar(200) not null, -`model_instance_name` varchar(200) not null, -`network_technology` varchar(45) null, -`network_type` varchar(45) null, -`network_role` varchar(200) null, -`network_scope` varchar(45) null, -`creation_timestamp` datetime not null default current_timestamp, -`network_resource_model_uuid` varchar(200) not null, `instance_group_model_uuid` varchar(200) null, -`crc_model_customization_uuid` varchar(200) not null, primary key -(`model_customization_uuid`, `crc_model_customization_uuid`), -index `fk_collection_net_resource_customization__network_resource1_idx` -(`network_resource_model_uuid` asc), index -`fk_collection_net_resource_customization__instance_group1_idx` -(`instance_group_model_uuid` asc), index -`fk_col_net_res_customization__collection_res_customization_idx` -(`crc_model_customization_uuid` asc), constraint -`fk_collection_net_resource_customization__network_resource10` foreign -key (`network_resource_model_uuid`) references -`network_resource` (`model_uuid`) on delete cascade on -update cascade, constraint -`fk_collection_net_resource_customization__instance_group10` foreign key -(`instance_group_model_uuid`) references `instance_group` -(`model_uuid`) on delete cascade on update cascade, constraint -`fk_collection_network_resource_customization__collection_reso1` foreign -key (`crc_model_customization_uuid`) references -`collection_resource_customization` -(`model_customization_uuid`) on delete cascade on update cascade) engine -= innodb default character set = latin1; - -CREATE TABLE IF NOT EXISTS `rainy_day_handler_macro` ( -`id` INT(11) NOT NULL AUTO_INCREMENT, -`FLOW_NAME` VARCHAR(200) NOT NULL, -`SERVICE_TYPE` VARCHAR(200) NOT NULL, -`VNF_TYPE` VARCHAR(200) NOT NULL, -`ERROR_CODE` VARCHAR(200) NOT NULL, -`WORK_STEP` VARCHAR(200) NOT NULL, -`POLICY` VARCHAR(200) NOT NULL, -PRIMARY KEY (`id`)) -ENGINE = InnoDB -DEFAULT CHARACTER SET = latin1; - -CREATE TABLE IF NOT EXISTS `northbound_request_ref_lookup` ( -`id` INT(11) NOT NULL AUTO_INCREMENT, -`REQUEST_SCOPE` VARCHAR(200) NOT NULL, -`ACTION` VARCHAR(200) NOT NULL, -`MACRO_ACTION` VARCHAR(200) NOT NULL, -`IS_ALACARTE` TINYINT(1) NOT NULL DEFAULT 0, -`IS_TOPLEVELFLOW` TINYINT(1) NOT NULL DEFAULT 0, -`MIN_API_VERSION` DOUBLE NOT NULL, -`MAX_API_VERSION` DOUBLE NULL, -PRIMARY KEY (`id`), -UNIQUE INDEX `UK_northbound_request_ref_lookup` (`MIN_API_VERSION` ASC, `REQUEST_SCOPE` ASC, `ACTION` ASC, `IS_ALACARTE` ASC)) -ENGINE = InnoDB -DEFAULT CHARACTER SET = latin1; - -CREATE TABLE IF NOT EXISTS `orchestration_flow_reference` ( -`id` INT(11) NOT NULL AUTO_INCREMENT, -`COMPOSITE_ACTION` VARCHAR(200) NOT NULL, -`SEQ_NO` INT(11) NOT NULL, -`FLOW_NAME` VARCHAR(200) NOT NULL, -`FLOW_VERSION` DOUBLE NOT NULL, -`NB_REQ_REF_LOOKUP_ID` INT(11) NOT NULL, -PRIMARY KEY (`id`), -INDEX `fk_orchestration_flow_reference__northbound_req_ref_look_idx` (`NB_REQ_REF_LOOKUP_ID` ASC), -UNIQUE INDEX `UK_orchestration_flow_reference` (`COMPOSITE_ACTION` ASC, `FLOW_NAME` ASC, `SEQ_NO` ASC, `NB_REQ_REF_LOOKUP_ID` ASC), -CONSTRAINT `fk_orchestration_flow_reference__northbound_request_ref_look1` -FOREIGN KEY (`NB_REQ_REF_LOOKUP_ID`) REFERENCES `northbound_request_ref_lookup` (`id`) -ON DELETE CASCADE ON UPDATE CASCADE) -ENGINE = InnoDB DEFAULT CHARACTER SET = latin1; - -CREATE TABLE IF NOT EXISTS vnfc_customization ( -`MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, -`MODEL_UUID` VARCHAR(200) NOT NULL, -`MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, -`MODEL_VERSION` VARCHAR(20) NOT NULL, -`MODEL_NAME` VARCHAR(200) NOT NULL, -`TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, -`DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, -`CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`)) -ENGINE = InnoDB -AUTO_INCREMENT = 20654 -DEFAULT CHARACTER SET = latin1; - -CREATE TABLE IF NOT EXISTS cvnfc_customization ( -`ID` INT(11) NOT NULL AUTO_INCREMENT, -`MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, -`MODEL_UUID` VARCHAR(200) NOT NULL, -`MODEL_INVARIANT_UUID` VARCHAR(200) NOT NULL, -`MODEL_VERSION` VARCHAR(20) NOT NULL, -`MODEL_NAME` VARCHAR(200) NOT NULL, -`TOSCA_NODE_TYPE` VARCHAR(200) NOT NULL, -`DESCRIPTION` VARCHAR(1200) NULL DEFAULT NULL, -`NFC_FUNCTION` VARCHAR(200) NULL, -`NFC_NAMING_CODE` VARCHAR(200) NULL, -`CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, -`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, -`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, PRIMARY KEY (`ID`), INDEX `fk_cvnfc_customization__vf_module_customization1_idx` (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnfc_customization1_idx` (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_resource_customization1_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), UNIQUE INDEX `UK_cvnfc_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID` ASC, `MODEL_CUSTOMIZATION_UUID` ASC), INDEX `fk_cvnfc_customization__vnf_vfmod_cvnfc_config_cust1_idx` (`MODEL_CUSTOMIZATION_UUID` ASC), CONSTRAINT `fk_cvnfc_customization__vf_module_customization1` FOREIGN KEY (`VF_MODULE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnfc_customization1` FOREIGN KEY (`VNFC_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE, CONSTRAINT `fk_cvnfc_customization__vnf_resource_customization1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) ON -DELETE CASCADE ON -UPDATE CASCADE) ENGINE = InnoDB AUTO_INCREMENT = 20654 DEFAULT CHARACTER SET = latin1; - -CREATE TABLE IF NOT EXISTS vnf_vfmodule_cvnfc_configuration_customization ( - `ID` INT(11) NOT NULL AUTO_INCREMENT, - `MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `VF_MODULE_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `CVNFC_MODEL_CUSTOMIZATION_UUID` VARCHAR(200) NOT NULL, - `MODEL_INSTANCE_NAME` VARCHAR(200) NOT NULL, - `CONFIGURATION_TYPE` VARCHAR(200) NULL, - `CONFIGURATION_ROLE` VARCHAR(200) NULL, - `CONFIGURATION_FUNCTION` VARCHAR(200) NULL, - `POLICY_NAME` VARCHAR(200) NULL, - `CREATION_TIMESTAMP` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, - `CONFIGURATION_MODEL_UUID` VARCHAR(200) NOT NULL, - PRIMARY KEY (`ID`), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__configuration_idx` (`CONFIGURATION_MODEL_UUID` ASC), - UNIQUE INDEX `UK_vnf_vfmodule_cvnfc_configuration_customization` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC , `VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC , `CVNFC_MODEL_CUSTOMIZATION_UUID` ASC , `MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__cvnfc_cust1_idx` (`CVNFC_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vf_module_cust_idx` (`VF_MODULE_MODEL_CUSTOMIZATION_UUID` ASC), - INDEX `fk_vnf_vfmodule_cvnfc_config_cust__vnf_res_cust_idx` (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID` ASC), - CONSTRAINT `fk_vnf_vfmod_cvnfc_config_cust__configuration_resource` FOREIGN KEY (`CONFIGURATION_MODEL_UUID`) - REFERENCES `configuration` (`MODEL_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_cvnfc_configuration_customization__cvnfc_customization1` FOREIGN KEY (`CVNFC_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `cvnfc_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vnf_configuration_cvnfc_customization__vf_module_customiza1` FOREIGN KEY (`VF_MODULE_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vf_module_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_vfmodule_cvnfc_configuration_customization__vnf_resource_c1` FOREIGN KEY (`VNF_RESOURCE_CUST_MODEL_CUSTOMIZATION_UUID`) - REFERENCES `vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`) - ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=INNODB AUTO_INCREMENT=20654 DEFAULT CHARACTER SET=LATIN1; +DROP TABLE IF EXISTS `service_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `service_recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `ACTION` varchar(50) NOT NULL, + `VERSION_STR` varchar(20) DEFAULT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(256) NOT NULL, + `SERVICE_PARAM_XSD` varchar(2048) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `SERVICE_TIMEOUT_INTERIM` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_7fav5dkux2v8g9d2i5ymudlgc` (`SERVICE_MODEL_UUID`,`ACTION`), + KEY `fk_service_recipe__service1_idx` (`SERVICE_MODEL_UUID`), + CONSTRAINT `fk_service_recipe__service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `temp_network_heat_template_lookup` +-- + +DROP TABLE IF EXISTS `temp_network_heat_template_lookup`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `temp_network_heat_template_lookup` ( + `NETWORK_RESOURCE_MODEL_NAME` varchar(200) NOT NULL, + `HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) NULL, + `AIC_VERSION_MIN` varchar(20) NULL, + `AIC_VERSION_MAX` varchar(20) DEFAULT NULL, + PRIMARY KEY (`NETWORK_RESOURCE_MODEL_NAME`), + KEY `fk_temp_network_heat_template_lookup__heat_template1_idx` (`HEAT_TEMPLATE_ARTIFACT_UUID`), + CONSTRAINT `fk_temp_network_heat_template_lookup__heat_template1` FOREIGN KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `tosca_csar` +-- +DROP TABLE IF EXISTS `tosca_csar`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tosca_csar` ( + `ARTIFACT_UUID` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `ARTIFACT_CHECKSUM` varchar(200) NOT NULL, + `URL` varchar(200) NOT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`ARTIFACT_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vf_module` +-- + +DROP TABLE IF EXISTS `vf_module`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vf_module` ( + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `IS_BASE` tinyint(1) NOT NULL, + `HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `VOL_HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`MODEL_UUID`,`VNF_RESOURCE_MODEL_UUID`), + KEY `fk_vf_module__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), + KEY `fk_vf_module__heat_template_art_uuid__heat_template1_idx` (`HEAT_TEMPLATE_ARTIFACT_UUID`), + KEY `fk_vf_module__vol_heat_template_art_uuid__heat_template2_idx` (`VOL_HEAT_TEMPLATE_ARTIFACT_UUID`), + CONSTRAINT `fk_vf_module__heat_template_art_uuid__heat_template1` FOREIGN KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module__vnf_resource1` FOREIGN KEY (`VNF_RESOURCE_MODEL_UUID`) REFERENCES `vnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module__vol_heat_template_art_uuid__heat_template2` FOREIGN KEY (`VOL_HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vf_module_customization` +-- + +DROP TABLE IF EXISTS `vf_module_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vf_module_customization` ( + `ID` int(13) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `LABEL` varchar(200) DEFAULT NULL, + `INITIAL_COUNT` int(11) DEFAULT '0', + `MIN_INSTANCES` int(11) DEFAULT '0', + `MAX_INSTANCES` int(11) DEFAULT NULL, + `AVAILABILITY_ZONE_COUNT` int(11) DEFAULT NULL, + `HEAT_ENVIRONMENT_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `VOL_ENVIRONMENT_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, + `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) DEFAULT NULL, + PRIMARY KEY (`ID`), + KEY `fk_vf_module_customization__vf_module1_idx` (`VF_MODULE_MODEL_UUID`), + KEY `fk_vf_module_customization__heat_env__heat_environment1_idx` (`HEAT_ENVIRONMENT_ARTIFACT_UUID`), + KEY `fk_vf_module_customization__vol_env__heat_environment2_idx` (`VOL_ENVIRONMENT_ARTIFACT_UUID`), + KEY `fk_vf_module_customization_to_vnf_resource_customization` (`VNF_RESOURCE_CUSTOMIZATION_ID`), + KEY `vf_module_customization_model_cust_uuid_idx` (`MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `fk_vf_module_customization__heat_env__heat_environment1` FOREIGN KEY (`HEAT_ENVIRONMENT_ARTIFACT_UUID`) REFERENCES `heat_environment` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module_customization__vf_module1` FOREIGN KEY (`VF_MODULE_MODEL_UUID`) REFERENCES `vf_module` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module_customization__vol_env__heat_environment2` FOREIGN KEY (`VOL_ENVIRONMENT_ARTIFACT_UUID`) REFERENCES `heat_environment` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module_customization_to_vnf_resource_customization` FOREIGN KEY (`VNF_RESOURCE_CUSTOMIZATION_ID`) REFERENCES `vnf_resource_customization` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vf_module_to_heat_files` +-- + +DROP TABLE IF EXISTS `vf_module_to_heat_files`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vf_module_to_heat_files` ( + `VF_MODULE_MODEL_UUID` varchar(200) NOT NULL, + `HEAT_FILES_ARTIFACT_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`VF_MODULE_MODEL_UUID`,`HEAT_FILES_ARTIFACT_UUID`), + KEY `fk_vf_module_to_heat_files__heat_files__artifact_uuid1_idx` (`HEAT_FILES_ARTIFACT_UUID`), + CONSTRAINT `fk_vf_module_to_heat_files__heat_files__artifact_uuid1` FOREIGN KEY (`HEAT_FILES_ARTIFACT_UUID`) REFERENCES `heat_files` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vf_module_to_heat_files__vf_module__model_uuid1` FOREIGN KEY (`VF_MODULE_MODEL_UUID`) REFERENCES `vf_module` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='il fait ce qu''il dit'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnf_components` +-- + +DROP TABLE IF EXISTS `vnf_components`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnf_components` ( + `VNF_ID` int(11) NOT NULL, + `COMPONENT_TYPE` varchar(20) NOT NULL, + `HEAT_TEMPLATE_ID` int(11) DEFAULT NULL, + `HEAT_ENVIRONMENT_ID` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`VNF_ID`,`COMPONENT_TYPE`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnf_components_recipe` +-- + +DROP TABLE IF EXISTS `vnf_components_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnf_components_recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `VNF_TYPE` varchar(200) DEFAULT NULL, + `VNF_COMPONENT_TYPE` varchar(45) NOT NULL, + `ACTION` varchar(50) NOT NULL, + `SERVICE_TYPE` varchar(45) DEFAULT NULL, + `VERSION` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(256) NOT NULL, + `VNF_COMPONENT_PARAM_XSD` varchar(2048) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime DEFAULT CURRENT_TIMESTAMP, + `VF_MODULE_MODEL_UUID` varchar(200) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_4dpdwddaaclhc11wxsb7h59ma` (`VF_MODULE_MODEL_UUID`,`VNF_COMPONENT_TYPE`,`ACTION`,`VERSION`) +) ENGINE=InnoDB AUTO_INCREMENT=38 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnf_recipe` +-- + +DROP TABLE IF EXISTS `vnf_recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnf_recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `NF_ROLE` varchar(200) DEFAULT NULL, + `ACTION` varchar(50) NOT NULL, + `SERVICE_TYPE` varchar(45) DEFAULT NULL, + `VERSION_STR` varchar(20) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `ORCHESTRATION_URI` varchar(256) NOT NULL, + `VNF_PARAM_XSD` varchar(2048) DEFAULT NULL, + `RECIPE_TIMEOUT` int(11) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime DEFAULT CURRENT_TIMESTAMP, + `VF_MODULE_ID` varchar(100) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UK_f3tvqau498vrifq3cr8qnigkr` (`VF_MODULE_ID`,`ACTION`,`VERSION_STR`) +) ENGINE=InnoDB AUTO_INCREMENT=10015 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnf_resource` +-- + +DROP TABLE IF EXISTS `vnf_resource`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnf_resource` ( + `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEL_UUID` varchar(200) NOT NULL, + `AIC_VERSION_MIN` varchar(20) DEFAULT NULL, + `AIC_VERSION_MAX` varchar(20) DEFAULT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `HEAT_TEMPLATE_ARTIFACT_UUID` varchar(200) DEFAULT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`), + KEY `fk_vnf_resource__heat_template1` (`HEAT_TEMPLATE_ARTIFACT_UUID`), + CONSTRAINT `fk_vnf_resource__heat_template1` FOREIGN KEY (`HEAT_TEMPLATE_ARTIFACT_UUID`) REFERENCES `heat_template` (`ARTIFACT_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnf_resource_customization` +-- + +DROP TABLE IF EXISTS `vnf_resource_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnf_resource_customization` ( + `ID` int(13) NOT NULL AUTO_INCREMENT, + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `MIN_INSTANCES` int(11) DEFAULT NULL, + `MAX_INSTANCES` int(11) DEFAULT NULL, + `AVAILABILITY_ZONE_MAX_COUNT` int(11) DEFAULT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `MULTI_STAGE_DESIGN` varchar(20) DEFAULT NULL, + `RESOURCE_INPUT` varchar(20000) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) default null, + `CDS_BLUEPRINT_VERSION` varchar(20) default null, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `VNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`ID`), + UNIQUE KEY `UK_vnf_resource_customization` (`MODEL_CUSTOMIZATION_UUID`,`SERVICE_MODEL_UUID`), + KEY `fk_vnf_resource_customization__vnf_resource1_idx` (`VNF_RESOURCE_MODEL_UUID`), + KEY `fk_vnf_resource_customization_to_service` (`SERVICE_MODEL_UUID`), + KEY `vnf_resource_customization_mod_cust_uuid_idx` (`MODEL_CUSTOMIZATION_UUID`), + CONSTRAINT `fk_vnf_resource_customization__vnf_resource1` FOREIGN KEY (`VNF_RESOURCE_MODEL_UUID`) REFERENCES `vnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vnf_resource_customization_to_service` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnfc_customization` +-- + +DROP TABLE IF EXISTS `vnfc_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnfc_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) NOT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) NOT NULL, + `TOSCA_NODE_TYPE` varchar(200) NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vnfc_instance_group_customization` +-- + +DROP TABLE IF EXISTS `vnfc_instance_group_customization`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vnfc_instance_group_customization` ( + `ID` int(13) NOT NULL AUTO_INCREMENT PRIMARY KEY, + `VNF_RESOURCE_CUSTOMIZATION_ID` int(13) NOT NULL, + `INSTANCE_GROUP_MODEL_UUID` varchar(200) NOT NULL, + `FUNCTION` varchar(200) DEFAULT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + KEY `fk_vnfc_instance_group_customization__instance_group1_idx` (`INSTANCE_GROUP_MODEL_UUID`), + CONSTRAINT `fk_vnfc_instance_group_customization__instance_group1` FOREIGN KEY (`INSTANCE_GROUP_MODEL_UUID`) REFERENCES `instance_group` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `fk_vnfc_instance_group_customization_vnf_customization` FOREIGN KEY (`VNF_RESOURCE_CUSTOMIZATION_ID`) REFERENCES `vnf_resource_customization` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; +set foreign_key_checks=1; + +CREATE TABLE IF NOT EXISTS `pnf_resource` ( + `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `MULTI_STAGE_DESIGN` varchar(20) DEFAULT NULL, + `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +)ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource` ( + `ORCHESTRATION_MODE` varchar(20) NOT NULL DEFAULT 'HEAT', + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `MODEL_UUID` varchar(200) NOT NULL, + `MODEL_INVARIANT_UUID` varchar(200) DEFAULT NULL, + `MODEL_VERSION` varchar(20) NOT NULL, + `MODEL_NAME` varchar(200) DEFAULT NULL, + `TOSCA_NODE_TYPE` varchar(200) DEFAULT NULL, + `RESOURCE_CATEGORY` varchar(200) DEFAULT NULL, + `RESOURCE_SUB_CATEGORY` varchar(200) DEFAULT NULL, + PRIMARY KEY (`MODEL_UUID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization` ( + `MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + `MODEL_INSTANCE_NAME` varchar(200) NOT NULL, + `NF_TYPE` varchar(200) DEFAULT NULL, + `NF_ROLE` varchar(200) DEFAULT NULL, + `NF_FUNCTION` varchar(200) DEFAULT NULL, + `NF_NAMING_CODE` varchar(200) DEFAULT NULL, + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `PNF_RESOURCE_MODEL_UUID` varchar(200) NOT NULL, + `MULTI_STAGE_DESIGN` varchar(20) DEFAULT NULL, + `RESOURCE_INPUT` varchar(2000) DEFAULT NULL, + `CDS_BLUEPRINT_NAME` varchar(200) DEFAULT NULL, + `CDS_BLUEPRINT_VERSION` varchar(20) DEFAULT NULL, + PRIMARY KEY (`MODEL_CUSTOMIZATION_UUID`), + KEY `fk_pnf_resource_customization__pnf_resource1_idx` (`PNF_RESOURCE_MODEL_UUID`), + CONSTRAINT `fk_pnf_resource_customization__pnf_resource1` FOREIGN KEY (`PNF_RESOURCE_MODEL_UUID`) REFERENCES `pnf_resource` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `pnf_resource_customization_to_service` ( + `SERVICE_MODEL_UUID` varchar(200) NOT NULL, + `RESOURCE_MODEL_CUSTOMIZATION_UUID` varchar(200) NOT NULL, + PRIMARY KEY (`SERVICE_MODEL_UUID`,`RESOURCE_MODEL_CUSTOMIZATION_UUID`) +)ENGINE=InnoDB DEFAULT CHARSET=latin1; --------START Request DB SCHEMA -------- CREATE DATABASE requestdb; USE requestdb; @@ -1055,4 +1466,27 @@ create table if not exists model ( PRIMARY KEY (`ID`), CONSTRAINT uk1_model UNIQUE (`MODEL_TYPE`, `MODEL_VERSION_ID`), FOREIGN KEY (`RECIPE`) REFERENCES `model_recipe` (`MODEL_ID`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=latin1;
\ No newline at end of file +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + +CREATE TABLE IF NOT EXISTS `workflow` ( + `ID` int(11) NOT NULL AUTO_INCREMENT, + `ARTIFACT_UUID` varchar(200) NOT NULL, + `ARTIFACT_NAME` varchar(200) NOT NULL, + `NAME` varchar(200) NOT NULL, + `OPERATION_NAME` varchar(200) DEFAULT NULL, + `VERSION` double NOT NULL, + `DESCRIPTION` varchar(1200) DEFAULT NULL, + `BODY` longtext DEFAULT NULL, + `RESOURCE_TARGET` varchar(200) NOT NULL, + `SOURCE` varchar(200) NOT NULL, + `TIMEOUT_MINUTES` int(11) DEFAULT NULL, + `ARTIFACT_CHECKSUM` varchar(200) DEFAULT 'MANUAL RECORD', + `CREATION_TIMESTAMP` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`ID`), + UNIQUE KEY `UK_workflow` (`ARTIFACT_UUID`,`NAME`,`VERSION`,`SOURCE`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1; + + + + + |